OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[GGUF] Add lossless Q8_1 weight support (#39226)
Maxim Vafin943c5ececbcf
diff --git a/src/frontends/gguf/docs/quantization.md b/src/frontends/gguf/docs/quantization.mdindex ff7a6f380be..e1d9a5a1aaa 100644--- a/src/frontends/gguf/docs/quantization.md+++ b/src/frontends/gguf/docs/quantization.md@@ -29,7 +29,7 @@ Q4_1/Q4_K are backing buffers for eight nibbles per word; their graph ConstantsUnpacking into `u2` or `i4` therefore does not mean allocating one byte per weight.The usual graph is `Convert -> [Subtract] -> Multiply -> Reshape -> Convert(F32)`. Decompression-uses the scale's element type, normally F16. Q6_K and formats with fractional F16 zero points+uses the scale's element type, normally F16. Q6_K, Q8_1 and formats with fractional F16 zero pointsand code widths of at least four bits instead perform subtraction/multiplication in F32.Q8_K uses F32 scales and thus F32 arithmetic. MXFP4 uses an F16 multiply. A final F32 outputdoes not undo rounding in earlier F16 operations, and does not imply that a full F32 weight@@ -70,6 +70,7 @@ The type columns describe stored Constants; their decompression or Convert outpu| Q5_K, fractional zero point | 256 | 176 | `u8` | `f16` | `f16` | `256 + 16 + 16` = 288 | +63.6% || Q6_K | 256 | 210 | `i8` | `f16` | — | `256 + 32` = 288 | +37.1% || Q8_0 | 32 | 34 | `i8` | `f16` | — | `32 + 2` = 34 | 0% |+| Q8_1 | 32 | 36 | `i8` | `f16` | — | `32 + 2` = 34 | -5.6% || Q8_K | 256 | 292 | `i8` | `f32` | — | `256 + 4` = 260 | -11.0% || MXFP4 | 32 | 17 | `f4e2m1` | `f8e8m0` | — | `16 + 1` = 17 | 0% |@@ -213,11 +214,25 @@ Code values are preserved, but widening to eight bits and expanding sub-scales iF32 graph arithmetic avoids an F16 multiply, but the combined scales have already been roundedto F16 at import.-### Q8_0 and Q8_K+### Q8_0, Q8_1 and Q8_KQ8_0 directly copies 32 `i8` codes and one F16 scale per block. There is no code expansion,requantization or extra metadata; its usual decompression multiply is F16.+Q8_1 (type 9) uses the current ggml layout `F16 d | F16 s | 32 i8 codes`, totaling 36 bytes.+Import copies `d` and the codes unchanged and omits `s`, a precomputed `d * sum(codes)` used+by ggml dot-product kernels. It is not an additive weight offset or zero point. OpenVINO+stores 34 bytes per block, 5.6% less than the GGUF payload. Legacy 40-byte blocks with F32+`d` and `s` are not supported; the frontend does not infer that layout from padded tensor spans.++Both input paths keep the original per-32 F16 scales for every Q8_1 weight name, including+embedding/output tensors. The graph converts codes and scales to F32 before multiplying,+preserving finite reconstructed weight values exactly without F16 multiplication rounding or+requantization. The stored Constants remain i8 and F16; no full F32 weight Constant is required+at import. Device compilation can still expand the weights or select different execution+precision, so the compact payload and exact graph reconstruction do not guarantee runtime+memory usage or bit-exact inference.+Q8_K copies 256 `i8` codes and an F32 scale unchanged. Each GGUF block contains 256 code bytes,four scale bytes and 32 bytes of precomputed sums (`16` values of type `i16`), totaling 292bytes. OpenVINO omits the sums, leaving 260 bytes: a reduction of `32/292`, or 11.0%.@@ -228,7 +243,7 @@ or precision is lost by omitting them: reconstruction remains `weight[i] = scalein F32, without requantization. The sums can be regenerated exactly from the retained codesif a future kernel or GGUF exporter needs them. Preserving them would add unused storage tothe current representation. OpenVINO does not reproduce GGML's partial-sum kernel through-this representation. Q8_1 has no implemented native weight unpacking path.+this representation.## Affine K formats@@ -299,7 +314,8 @@ currently differs as follows:|---|---|---|| Q4_1, Q5_1 | Full F32 Constant decoded with `d*q + m` before other format handling | 128 bytes per 32 weights: +540% for Q4_1, +433.3% for Q5_1 || Q1_0, including embedding/output | Packed `u1` plus per-128 F16 scales, as in native loading | Requires plugin binary decompression support to remain packed at execution |-| Quantized `token_embd.weight` / `output.weight`, except Q1_0 and the Q4_1/Q5_1 cases above | Channel-wise Q8_0_C: `i8` codes with one F16 scale per row | Additional lossy quantization; low-bit sources usually expand |+| Q8_1, including embedding/output | Original `i8` codes plus per-32 F16 scales, with F32 graph multiplication, as in native loading | Device compilation determines execution storage and precision |+| Quantized `token_embd.weight` / `output.weight`, except Q1_0/Q8_1 and the Q4_1/Q5_1 cases above | Channel-wise Q8_0_C: `i8` codes with one F16 scale per row | Additional lossy quantization; low-bit sources usually expand || Q5_K ordinary matrices | The same channel-wise Q8_0_C representation | Additional lossy quantization; different scale grouping from native Q5_K || Q4_K/Q5_K/Q6_K selected for Q8_0_C | Stream original F32-dequantized rows directly into channel-wise quantization | Per-worker F32 row scratch; avoids allocating a full temporary F32 matrix || Rank greater than two MXFP4 experts | Packed `u8` blocks retaining scale/code interleaving; expert selection and decompression happen on the graph | Different graph layout; device fusion and temporary storage depend on expert execution |diff --git a/src/frontends/gguf/docs/testing.md b/src/frontends/gguf/docs/testing.mdindex 3143866a8fa..185eb713fc4 100644--- a/src/frontends/gguf/docs/testing.md+++ b/src/frontends/gguf/docs/testing.md@@ -44,6 +44,18 @@ the standard `split.no` (u16), `split.count` (u16) and `split.tensors.count` (i3## Fixtures and oracles+Regenerate the Q8_1 weight fixtures with a clean llama.cpp checkout at+`476c01efe88aad7880a8132d5d3a415f2ca75139` and its freshly built `libggml-base`:++```sh+python3 src/frontends/gguf/tests/gen_q8_1_accuracy.py \+ --llama-cpp /path/to/llama.cpp --library /path/to/libggml-base.so+```++The generator calls ggml's Q8_1 reference quantizer, then copies each block's F16 scale+and signed codes into Q8_0 blocks for real ggml dequantization. Q8_1 has no `to_float`+callback. The committed arrays and provenance JSON require no ggml dependency in unit tests.+Small NPZ/NPY numerical references are committed and work offline. Missing numerical referencesfail their tests. Architecture header fixtures are generated separately; if none are present,`GGUFArchConversion` skips, while a partially generated set fails. Generate them before claimingdiff --git a/src/frontends/gguf/src/quant/gguf.cpp b/src/frontends/gguf/src/quant/gguf.cppindex 8c505dffac3..2395dfa73c6 100644--- a/src/frontends/gguf/src/quant/gguf.cpp+++ b/src/frontends/gguf/src/quant/gguf.cpp@@ -69,7 +69,7 @@ TypeTraits type_traits(uint32_t type) {case GGUF_TYPE_Q8_0:return {32, 34};case GGUF_TYPE_Q8_1:- return {32, 40};+ return {32, 36};case GGUF_TYPE_Q2_K:return {256, 84};case GGUF_TYPE_Q2_0:@@ -129,6 +129,7 @@ std::optional<QuantLayout> quant_layout(uint32_t type, const std::string& name)return QuantLayout{ov::element::i4, 1, ov::element::f16, 16, symmetric};case GGUF_TYPE_Q5_0:case GGUF_TYPE_Q8_0:+ case GGUF_TYPE_Q8_1:return QuantLayout{ov::element::i8, 1, ov::element::f16, 32, symmetric};case GGUF_TYPE_Q6_K:return QuantLayout{ov::element::i8, 1, ov::element::f16, 16, symmetric};diff --git a/src/frontends/gguf/src/quant/gguf.hpp b/src/frontends/gguf/src/quant/gguf.hppindex 967f2e262a4..e29329fe5cf 100644--- a/src/frontends/gguf/src/quant/gguf.hpp+++ b/src/frontends/gguf/src/quant/gguf.hpp@@ -95,7 +95,7 @@ using GGUFLoad = std::tuple<std::unordered_map<std::string, GGUFMetaData>,std::vector<std::shared_ptr<ov::MappedMemory>>>;// Fill pre-allocated weights and f16 scales from a symmetric GGUF tensor-// (Q8_0/Q5_0/Q6_K: i8 weights; Q4_0/Q3_K: i4 weights; Q1_0: u1 weights).+// (Q8_0/Q8_1/Q5_0/Q6_K: i8 weights; Q4_0/Q3_K: i4 weights; Q1_0: u1 weights).// Integer weights are centered during unpacking; Q1_0 keeps binary codes and applies 2 * bit - 1 in the graph.void gguf_fill_sym(const GgufTensor& tensor, ov::Tensor& weights, ov::Tensor& scales);diff --git a/src/frontends/gguf/src/quant/gguf_quants.cpp b/src/frontends/gguf/src/quant/gguf_quants.cppindex bd097a69abb..eac74b796a6 100644--- a/src/frontends/gguf/src/quant/gguf_quants.cpp+++ b/src/frontends/gguf/src/quant/gguf_quants.cpp@@ -305,6 +305,27 @@ void fill_q8_0(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& sc});}+void fill_q8_1(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr) {+ constexpr size_t weights_per_block = 32;+ constexpr size_t bytes_per_block = 36;+ OPENVINO_ASSERT(tensor.num_weights % weights_per_block == 0 && weights_arr.get_size() == tensor.num_weights &&+ scales_arr.get_size() == tensor.num_weights / weights_per_block,+ "[GGUF] invalid Q8_1 output sizes");+ OPENVINO_ASSERT(tensor.bsize % bytes_per_block == 0 && tensor.bsize / bytes_per_block == scales_arr.get_size(),+ "[GGUF] invalid Q8_1 payload size");+ const auto* data = static_cast<const uint8_t*>(tensor.weights_data);+ auto* weights = weights_arr.data<int8_t>();+ auto* scales = scales_arr.data<ov::float16>();+ ov::parallel_for(scales_arr.get_size(), [&](size_t i) {+ const auto* block = data + i * bytes_per_block;+ uint16_t scale_bits;+ std::memcpy(&scale_bits, block, sizeof(scale_bits));+ scales[i] = ov::float16::from_bits(scale_bits);+ // The second F16 field is a dot-product sum, not a weight offset.+ std::memcpy(weights + i * weights_per_block, block + 4, weights_per_block);+ });+}+// Q5_0 symmetric: block = |f16 scale d|32-bit qh|16 bytes ql (32x4bit low)|.// weight = lo|(hi<<4) in [0..31]; dequant = d*(w - 16). Output: i8 weights [-16..15].void fill_q5_0(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr) {@@ -935,7 +956,7 @@ void gguf_fill_q2_0(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tenso});}-// Symmetric types (Q1_0, Q4_0, Q8_0, Q5_0, Q6_K, Q3_K): fill weights + scales (f16), no+// Symmetric types (Q1_0, Q4_0, Q8_0, Q8_1, Q5_0, Q6_K, Q3_K): fill weights + scales (f16), no// zero-point. Q8_K uses f32 scales and is handled by a separate overload dispatched on// tensor.type.void gguf_fill_sym(const GgufTensor& tensor, ov::Tensor& weights, ov::Tensor& scales) {@@ -946,6 +967,8 @@ void gguf_fill_sym(const GgufTensor& tensor, ov::Tensor& weights, ov::Tensor& screturn fill_q4_0(tensor, weights, scales);case GGUF_TYPE_Q8_0:return fill_q8_0(tensor, weights, scales);+ case GGUF_TYPE_Q8_1:+ return fill_q8_1(tensor, weights, scales);case GGUF_TYPE_Q5_0:return fill_q5_0(tensor, weights, scales);case GGUF_TYPE_Q6_K:diff --git a/src/frontends/gguf/src/quant/weights.cpp b/src/frontends/gguf/src/quant/weights.cppindex d9253238d98..0aebf37910d 100644--- a/src/frontends/gguf/src/quant/weights.cpp+++ b/src/frontends/gguf/src/quant/weights.cpp@@ -14,6 +14,7 @@#include <cstdlib>#include <cstring>#include <iostream>+#include <limits>#include <mutex>#include <vector>@@ -73,6 +74,7 @@ WeightFormat get_weight_format(GgufTensorType qtype) {return {FillKind::SYMMETRIC, 16, ov::element::i4};case GGUF_TYPE_Q5_0:case GGUF_TYPE_Q8_0:+ case GGUF_TYPE_Q8_1:return {FillKind::SYMMETRIC, 32, ov::element::i8};case GGUF_TYPE_Q6_K:return {FillKind::SYMMETRIC, 16, ov::element::i8};@@ -369,7 +371,8 @@ bool is_embedding_or_output(const std::string& name) {// Decide whether a weight is requantized to Q8_0_C, mirroring llama.cpp's// ggml_openvino_get_requant_type for the CPU/GPU (non-NPU) path.bool needs_q8_0_c_requant(const std::string& name, GgufTensorType qtype) {- return qtype != GGUF_TYPE_Q1_0 && (is_embedding_or_output(name) || qtype == GGUF_TYPE_Q5_K);+ return qtype != GGUF_TYPE_Q1_0 && qtype != GGUF_TYPE_Q8_1 &&+ (is_embedding_or_output(name) || qtype == GGUF_TYPE_Q5_K);}// Keep an exact-decode escape hatch for strict validation against ggml's original Q4_K / Q4_1 values.@@ -492,12 +495,13 @@ std::shared_ptr<ov::Node> make_weight_node(const WeightTensors& tensors,} else {const auto node_et = format.node_element_type();// Explicit f32 arithmetic instead of the low-precision decomposition when:- // - Q6_K, to preserve the reference dequantization accuracy; or+ // - Q6_K/Q8_1, to preserve the reference dequantization accuracy; or// - a 4-/8-bit weight carries a FRACTIONAL f16 zero-point, which cannot fold into a// compressed FullyConnected anyway, so the exact f32 form costs nothing.// The 2-bit formats (Q2_K/Q2_0) always stay on the decomposition.const bool fractional_zp = tensors.zero_point && tensors.zero_point.get_element_type() == ov::element::f16;- const bool explicit_f32 = qtype == GGUF_TYPE_Q6_K || (fractional_zp && node_et.bitwidth() >= 4);+ const bool explicit_f32 =+ qtype == GGUF_TYPE_Q6_K || qtype == GGUF_TYPE_Q8_1 || (fractional_zp && node_et.bitwidth() >= 4);node = make_compressed(tensors, node_et, explicit_f32);}node->set_friendly_name(name);@@ -505,25 +509,12 @@ std::shared_ptr<ov::Node> make_weight_node(const WeightTensors& tensors,}GgufTensorType gguf_type_from_name(const std::string& quant_type) {- static const std::unordered_map<std::string, GgufTensorType> names = {{"F32", GGUF_TYPE_F32},- {"F16", GGUF_TYPE_F16},- {"BF16", GGUF_TYPE_BF16},- {"Q4_0", GGUF_TYPE_Q4_0},- {"Q4_1", GGUF_TYPE_Q4_1},- {"Q5_0", GGUF_TYPE_Q5_0},- {"Q5_1", GGUF_TYPE_Q5_1},- {"Q8_0", GGUF_TYPE_Q8_0},- {"Q2_K", GGUF_TYPE_Q2_K},- {"Q3_K", GGUF_TYPE_Q3_K},- {"Q4_K", GGUF_TYPE_Q4_K},- {"Q5_K", GGUF_TYPE_Q5_K},- {"Q6_K", GGUF_TYPE_Q6_K},- {"Q8_K", GGUF_TYPE_Q8_K},- {"MXFP4", GGUF_TYPE_MXFP4},- {"Q1_0", GGUF_TYPE_Q1_0},- {"Q2_0", GGUF_TYPE_Q2_0},- {"PQ2_0", GGUF_TYPE_PQ2_0},- {"PTQ1_0", GGUF_TYPE_PTQ1_0}};+ static const std::unordered_map<std::string, GgufTensorType> names = {+ {"F32", GGUF_TYPE_F32}, {"F16", GGUF_TYPE_F16}, {"BF16", GGUF_TYPE_BF16}, {"Q4_0", GGUF_TYPE_Q4_0},+ {"Q4_1", GGUF_TYPE_Q4_1}, {"Q5_0", GGUF_TYPE_Q5_0}, {"Q5_1", GGUF_TYPE_Q5_1}, {"Q8_0", GGUF_TYPE_Q8_0},+ {"Q8_1", GGUF_TYPE_Q8_1}, {"Q2_K", GGUF_TYPE_Q2_K}, {"Q3_K", GGUF_TYPE_Q3_K}, {"Q4_K", GGUF_TYPE_Q4_K},+ {"Q5_K", GGUF_TYPE_Q5_K}, {"Q6_K", GGUF_TYPE_Q6_K}, {"Q8_K", GGUF_TYPE_Q8_K}, {"MXFP4", GGUF_TYPE_MXFP4},+ {"Q1_0", GGUF_TYPE_Q1_0}, {"Q2_0", GGUF_TYPE_Q2_0}, {"PQ2_0", GGUF_TYPE_PQ2_0}, {"PTQ1_0", GGUF_TYPE_PTQ1_0}};// Accept ggml's lowercase type names ("q4_0", "q6_K", "f16", ...) as well as the// canonical uppercase form.auto it = names.find(ov::util::to_upper(quant_type));@@ -635,6 +626,14 @@ std::shared_ptr<ov::Node> make_weight_node(const ov::Tensor& data,const size_t cols = logical_shape[1];const GgufTensorType qtype = gguf_type_from_name(quant_type);+ if (qtype == GGUF_TYPE_Q8_1) {+ OPENVINO_ASSERT(cols != 0 && cols % 32 == 0, "[GGUF] Q8_1 columns must be a nonzero multiple of 32");+ OPENVINO_ASSERT(rows <= std::numeric_limits<size_t>::max() / cols, "[GGUF] Q8_1 weight count overflow");+ const size_t blocks = rows * (cols / 32);+ OPENVINO_ASSERT(blocks <= std::numeric_limits<size_t>::max() / 36, "[GGUF] Q8_1 payload size overflow");+ OPENVINO_ASSERT(data.get_byte_size() == blocks * 36, "[GGUF] invalid Q8_1 payload size");+ }+if (qtype == GGUF_TYPE_Q4_1 || qtype == GGUF_TYPE_Q5_1) {ov::Tensor decoded(ov::element::f32, logical_shape);auto* out = decoded.data<float>();diff --git a/src/frontends/gguf/tests/gen_q8_1_accuracy.py b/src/frontends/gguf/tests/gen_q8_1_accuracy.pynew file mode 100644index 00000000000..4c60447a793--- /dev/null+++ b/src/frontends/gguf/tests/gen_q8_1_accuracy.py@@ -0,0 +1,78 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++"""Generate Q8_1 fixtures with pinned ggml and its Q8_0 dequantization oracle."""++import argparse+import ctypes+import hashlib+import json+import subprocess+from pathlib import Path++import numpy as np+++LLAMA_CPP_COMMIT = "476c01efe88aad7880a8132d5d3a415f2ca75139"+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--llama-cpp", type=Path, required=True, help="Pinned llama.cpp checkout")+ parser.add_argument("--library", type=Path, required=True, help="Its built libggml-base shared library")+ parser.add_argument("--output", type=Path, default=Path(__file__).parent / "test_data")+ args = parser.parse_args()+ revision = subprocess.check_output(+ ["git", "-C", str(args.llama_cpp), "rev-parse", "HEAD"], text=True+ ).strip()+ if revision != LLAMA_CPP_COMMIT:+ parser.error(f"llama.cpp must be at {LLAMA_CPP_COMMIT}, got {revision}")+ subprocess.run(+ ["git", "-C", str(args.llama_cpp), "diff", "--exit-code", LLAMA_CPP_COMMIT, "--", "ggml"],+ check=True,+ stdout=subprocess.DEVNULL,+ )+ library = ctypes.CDLL(str(args.library.resolve()))+ library.ggml_type_size.argtypes = [ctypes.c_int]+ library.ggml_type_size.restype = ctypes.c_size_t+ library.ggml_blck_size.argtypes = [ctypes.c_int]+ library.ggml_blck_size.restype = ctypes.c_int64+ if library.ggml_type_size(9) != 36 or library.ggml_blck_size(9) != 32:+ parser.error("The ggml library must use 36-byte, 32-element Q8_1 blocks")+ if library.ggml_type_size(8) != 34 or library.ggml_blck_size(8) != 32:+ parser.error("The ggml library must use 34-byte, 32-element Q8_0 blocks")++ quantize = library.quantize_row_q8_1_ref+ dequantize = library.dequantize_row_q8_0+ for function in (quantize, dequantize):+ function.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64]+ function.restype = None+ seed = 20261026+ values = (np.random.default_rng(seed).normal(0, 0.4, (4, 256)) + np.linspace(-0.2, 0.3, 256)).astype(+ np.float32+ )+ packed = np.empty((values.size // 32, 36), dtype=np.uint8)+ quantize(values.ctypes.data, packed.ctypes.data, values.size)+ surrogate = np.empty((values.size // 32, 34), dtype=np.uint8)+ surrogate[:, :2] = packed[:, :2]+ surrogate[:, 2:] = packed[:, 4:]+ reference = np.empty(values.size, dtype=np.float32)+ dequantize(surrogate.ctypes.data, reference.ctypes.data, reference.size)++ args.output.mkdir(parents=True, exist_ok=True)+ np.save(args.output / "q8_1_qbytes.npy", packed.reshape(-1))+ np.save(args.output / "q8_1_deq.npy", reference)+ provenance = {+ "llama_cpp_commit": revision,+ "shape": list(values.shape),+ "seed": seed,+ "quantizer": "quantize_row_q8_1_ref",+ "oracle": "dequantize_row_q8_0 after copying Q8_1 d and qs into Q8_0 blocks",+ "qbytes_sha256": hashlib.sha256(packed.tobytes()).hexdigest(),+ "deq_sha256": hashlib.sha256(reference.tobytes()).hexdigest(),+ }+ (args.output / "q8_1_fixture.json").write_text(json.dumps(provenance, indent=2) + "\n")+++if __name__ == "__main__":+ main()diff --git a/src/frontends/gguf/tests/test_data/q8_1_deq.npy b/src/frontends/gguf/tests/test_data/q8_1_deq.npynew file mode 100644index 00000000000..0723364b96eBinary files /dev/null and b/src/frontends/gguf/tests/test_data/q8_1_deq.npy differdiff --git a/src/frontends/gguf/tests/test_data/q8_1_fixture.json b/src/frontends/gguf/tests/test_data/q8_1_fixture.jsonnew file mode 100644index 00000000000..01ef8383f92--- /dev/null+++ b/src/frontends/gguf/tests/test_data/q8_1_fixture.json@@ -0,0 +1,12 @@+{+ "llama_cpp_commit": "476c01efe88aad7880a8132d5d3a415f2ca75139",+ "shape": [+ 4,+ 256+ ],+ "seed": 20261026,+ "quantizer": "quantize_row_q8_1_ref",+ "oracle": "dequantize_row_q8_0 after copying Q8_1 d and qs into Q8_0 blocks",+ "qbytes_sha256": "3096f2df8e8dff60a332c546ca71750dfbfe71321b04da9bdf066ef21caa2840",+ "deq_sha256": "cac9fc77b618a9756c059948fdc95f18ad56e6f43cdfa55de620a5b52b3e0838"+}diff --git a/src/frontends/gguf/tests/test_data/q8_1_qbytes.npy b/src/frontends/gguf/tests/test_data/q8_1_qbytes.npynew file mode 100644index 00000000000..125df3c54a0Binary files /dev/null and b/src/frontends/gguf/tests/test_data/q8_1_qbytes.npy differdiff --git a/src/frontends/gguf/tests/test_dequant_vs_ggml.cpp b/src/frontends/gguf/tests/test_dequant_vs_ggml.cppindex ca2c9184e9b..bc2c58f9507 100644--- a/src/frontends/gguf/tests/test_dequant_vs_ggml.cpp+++ b/src/frontends/gguf/tests/test_dequant_vs_ggml.cpp@@ -87,6 +87,8 @@ const char* type_name(uint32_t type) {return "Q5_1";case GGUF_TYPE_Q8_0:return "Q8_0";+ case GGUF_TYPE_Q8_1:+ return "Q8_1";case GGUF_TYPE_Q2_K:return "Q2_K";case GGUF_TYPE_Q3_K:@@ -167,6 +169,11 @@ TEST_P(DequantVsGGML, MatchesGgmlToFloat) {const auto ours = frontend_dequant(c.type, qbytes, kRows, kCols);ASSERT_EQ(ours.size(), ref.size());+ if (c.tol == 0.f) {+ for (size_t i = 0; i < ref.size(); ++i)+ EXPECT_EQ(ours[i], ref[i]) << "element " << i;+ return;+ }EXPECT_LE(max_abs_diff(ours, ref), c.tol)<< c.stem << ": frontend dequant diverges from ggml to_float beyond tolerance";}@@ -238,6 +245,7 @@ INSTANTIATE_TEST_SUITE_P(AllQuantTypes,DeqCase{"q5_0", GGUF_TYPE_Q5_0, kTolFaithful},DeqCase{"q5_1", GGUF_TYPE_Q5_1, kTolFaithful},DeqCase{"q8_0", GGUF_TYPE_Q8_0, kTolFaithful},+ DeqCase{"q8_1", GGUF_TYPE_Q8_1, kTolExact},DeqCase{"q2_k", GGUF_TYPE_Q2_K, kTolFaithful},DeqCase{"q3_k", GGUF_TYPE_Q3_K, kTolFaithful},DeqCase{"q4_k", GGUF_TYPE_Q4_K, kTolU4Requant},@@ -338,6 +346,44 @@ TEST(GGUFDequant, IntegerZeroPointRequantizationTracksGgml) {}}+TEST(DequantVsGGML, Q8_1PreservesFiniteScaleRangeAndIgnoresSum) {+ const std::vector<uint16_t> scale_bits{0, 0x8000, 0xbc00, 1, 0x7bff, 0x3555};+ std::vector<uint8_t> bytes(scale_bits.size() * 36);+ std::vector<float> reference(scale_bits.size() * 32);+ for (size_t group = 0; group < scale_bits.size(); ++group) {+ std::memcpy(bytes.data() + group * 36, &scale_bits[group], sizeof(uint16_t));+ const uint16_t sum_bits = group % 2 == 0 ? 0x7c00 : 0x7e00;+ std::memcpy(bytes.data() + group * 36 + 2, &sum_bits, sizeof(sum_bits));+ const float scale = static_cast<float>(ov::float16::from_bits(scale_bits[group]));+ for (size_t k = 0; k < 32; ++k) {+ const int8_t code = k == 0 ? -128 : k == 1 ? 127 : static_cast<int8_t>(static_cast<int>(k) - 16);+ std::memcpy(bytes.data() + group * 36 + 4 + k, &code, sizeof(code));+ reference[group * 32 + k] = static_cast<float>(code) * scale;+ }+ }+ const auto values = frontend_dequant(GGUF_TYPE_Q8_1, bytes, 1, reference.size());+ ASSERT_EQ(values.size(), reference.size());+ for (size_t i = 0; i < reference.size(); ++i) {+ EXPECT_TRUE(std::isfinite(values[i]));+ EXPECT_EQ(values[i], reference[i]) << "element " << i;+ }+ const size_t rounding_trap = (scale_bits.size() - 1) * 32 + 1;+ EXPECT_NE(reference[rounding_trap], static_cast<float>(ov::float16(reference[rounding_trap])));+}++TEST(DequantVsGGML, Q8_1RejectsInvalidDimensionsAndPayloadSizes) {+ const std::vector<uint8_t> block(36);+ for (const uint64_t cols : {0, 31, 33}) {+ SCOPED_TRACE(cols);+ EXPECT_THROW(frontend_dequant(GGUF_TYPE_Q8_1, block, 1, cols), ov::Exception);+ }+ for (const size_t size : {35, 37, 40, 71, 73, 80}) {+ SCOPED_TRACE(size);+ const uint64_t rows = size < 64 ? 1 : 2;+ EXPECT_THROW(frontend_dequant(GGUF_TYPE_Q8_1, std::vector<uint8_t>(size), rows, 32), ov::Exception);+ }+}+TEST(GGUFQ5KRequant, SymmetricGroupsTrackRealGgml) {const auto bytes = load_npy<uint8_t>("q5_k_qbytes");const auto reference = load_npy<float>("q5_k_deq");diff --git a/src/frontends/gguf/tests/test_parser.cpp b/src/frontends/gguf/tests/test_parser.cppindex d9a2d25d367..6f2eb8fc681 100644--- a/src/frontends/gguf/tests/test_parser.cpp+++ b/src/frontends/gguf/tests/test_parser.cpp@@ -3,6 +3,7 @@//#include <array>+#include <cmath>#include <filesystem>#include <fstream>#include <tuple>@@ -37,7 +38,8 @@ protected:uint64_t cols,uint64_t rows,const std::vector<uint8_t>& data = {},- const std::string& architecture = {}) {+ const std::string& architecture = {},+ const std::vector<uint64_t>& extra_dims = {}) {std::ofstream out(m_path, std::ios::binary);ASSERT_TRUE(out);const auto put = [&out](auto value) {@@ -57,9 +59,11 @@ protected:}put(uint64_t{name.size()});out.write(name.data(), name.size());- put(uint32_t{2});+ put(static_cast<uint32_t>(2 + extra_dims.size()));put(cols);put(rows);+ for (const auto dim : extra_dims)+ put(dim);put(static_cast<uint32_t>(type));put(uint64_t{0}); // tensor offsetwhile (static_cast<size_t>(out.tellp()) % 32 != 0) {@@ -74,6 +78,114 @@ protected:std::string m_path;};+TEST_F(GGUFParser, Q8_1PreservesCodesScalesAndIgnoresSumForAllWeightNames) {+ auto bytes = load_npy<uint8_t>("q8_1_qbytes");+ const auto reference = load_npy<float>("q8_1_deq");+ ASSERT_EQ(bytes.size(), 4 * 256 / 32 * 36);+ ASSERT_EQ(reference.size(), 4 * 256);+ for (size_t group = 0; group < bytes.size() / 36; ++group) {+ const uint16_t sum_bits = 0x7c00;+ std::memcpy(bytes.data() + group * 36 + 2, &sum_bits, sizeof(sum_bits));+ }+ for (const std::string name : {"blk.0.attn_q", "token_embd", "output"}) {+ SCOPED_TRACE(name);+ ASSERT_NO_FATAL_FAILURE(write_tensor(name + ".weight", GGUF_TYPE_Q8_1, 256, 4, bytes));+ const auto loaded = get_gguf_data(m_path);+ const auto& arrays = std::get<1>(loaded);+ EXPECT_EQ(std::get<2>(loaded).at(name + ".qtype"), GGUF_TYPE_Q8_1);+ const auto& weights = arrays.at(name + ".weight");+ const auto& scales = arrays.at(name + ".scales");+ ASSERT_EQ(weights.get_element_type(), ov::element::i8);+ ASSERT_EQ(scales.get_element_type(), ov::element::f16);+ EXPECT_EQ(weights.get_shape(), (ov::Shape{4, 256}));+ EXPECT_EQ(scales.get_shape(), (ov::Shape{4, 8}));+ EXPECT_EQ(weights.get_byte_size() + scales.get_byte_size(), 4 * 256 / 32 * 34);+ EXPECT_EQ(arrays.count(name + ".zp"), 0);+ for (size_t group = 0; group < scales.get_size(); ++group) {+ uint16_t bits;+ std::memcpy(&bits, bytes.data() + group * 36, sizeof(bits));+ EXPECT_EQ(scales.data<const ov::float16>()[group].to_bits(), bits);+ EXPECT_EQ(std::memcmp(weights.data<const int8_t>() + group * 32, bytes.data() + group * 36 + 4, 32), 0);+ }+ const auto node = make_weight_node({weights, scales, {}}, GGUF_TYPE_Q8_1, name + ".weight");+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{node}, ov::ParameterVector{});+ const auto output = run_on_cpu(model, {});+ ASSERT_EQ(output.get_size(), reference.size());+ for (size_t i = 0; i < reference.size(); ++i)+ EXPECT_EQ(output.data<const float>()[i], reference[i]);+ }+}++TEST_F(GGUFParser, Q8_1KeepsHigherRankGroups) {+ const auto bytes = load_npy<uint8_t>("q8_1_qbytes");+ const auto reference = load_npy<float>("q8_1_deq");+ ASSERT_NO_FATAL_FAILURE(write_tensor("experts.weight", GGUF_TYPE_Q8_1, 256, 2, bytes, {}, {2}));+ const auto loaded = get_gguf_data(m_path);+ const auto& arrays = std::get<1>(loaded);+ const auto& weights = arrays.at("experts.weight");+ const auto& scales = arrays.at("experts.scales");+ EXPECT_EQ(weights.get_shape(), (ov::Shape{2, 2, 256}));+ EXPECT_EQ(scales.get_shape(), (ov::Shape{2, 2, 8}));+ const auto node = make_weight_node({weights, scales, {}}, GGUF_TYPE_Q8_1, "experts.weight");+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{node}, ov::ParameterVector{});+ const auto output = run_on_cpu(model, {});+ EXPECT_EQ(output.get_shape(), (ov::Shape{2, 2, 256}));+ ASSERT_EQ(output.get_size(), reference.size());+ for (size_t i = 0; i < reference.size(); ++i)+ EXPECT_EQ(output.data<const float>()[i], reference[i]);+}++TEST_F(GGUFParser, Q8_1ExtractedBuffersPreserveFiniteScaleRangeAfterParserRelease) {+ const std::array<uint16_t, 6> scale_bits{0, 0x8000, 0xbc00, 1, 0x7bff, 0x3555};+ std::vector<uint8_t> bytes(scale_bits.size() * 36);+ std::vector<float> reference(scale_bits.size() * 32);+ for (size_t group = 0; group < scale_bits.size(); ++group) {+ std::memcpy(bytes.data() + group * 36, &scale_bits[group], sizeof(uint16_t));+ const uint16_t sum_bits = 0x7c00;+ std::memcpy(bytes.data() + group * 36 + 2, &sum_bits, sizeof(sum_bits));+ const float scale = static_cast<float>(ov::float16::from_bits(scale_bits[group]));+ for (size_t k = 0; k < 32; ++k) {+ const int8_t code = k % 2 == 0 ? -128 : 127;+ std::memcpy(bytes.data() + group * 36 + 4 + k, &code, sizeof(code));+ reference[group * 32 + k] = static_cast<float>(code) * scale;+ }+ }+ ASSERT_NO_FATAL_FAILURE(write_tensor("output.weight", GGUF_TYPE_Q8_1, reference.size(), 1, bytes));+ WeightTensors tensors;+ {+ const auto loaded = get_gguf_data(m_path);+ const auto& arrays = std::get<1>(loaded);+ tensors = {arrays.at("output.weight"), arrays.at("output.scales"), {}};+ ASSERT_EQ(tensors.scales.get_size(), scale_bits.size());+ for (size_t group = 0; group < scale_bits.size(); ++group)+ EXPECT_EQ(tensors.scales.data<const ov::float16>()[group].to_bits(), scale_bits[group]);+ }+ const auto node = make_weight_node(tensors, GGUF_TYPE_Q8_1, "output.weight");+ tensors = {};+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{node}, ov::ParameterVector{});+ const auto output = run_on_cpu(model, {});+ ASSERT_EQ(output.get_size(), reference.size());+ for (size_t i = 0; i < reference.size(); ++i) {+ EXPECT_TRUE(std::isfinite(output.data<const float>()[i]));+ EXPECT_EQ(output.data<const float>()[i], reference[i]);+ }+ EXPECT_NE(reference.back(), static_cast<float>(ov::float16(reference.back())));+}++TEST_F(GGUFParser, Q8_1RejectsInvalidDimensionsAndTruncatedPayload) {+ for (const uint64_t cols : {31, 33}) {+ SCOPED_TRACE(cols);+ ASSERT_NO_FATAL_FAILURE(write_tensor("invalid.weight", GGUF_TYPE_Q8_1, cols, 1, std::vector<uint8_t>(36)));+ EXPECT_THROW(get_gguf_data(m_path), ov::Exception);+ }+ for (const uint64_t rows : {1, 2}) {+ SCOPED_TRACE(rows);+ ASSERT_NO_FATAL_FAILURE(+ write_tensor("truncated.weight", GGUF_TYPE_Q8_1, 32, rows, std::vector<uint8_t>(rows * 36 - 1)));+ EXPECT_THROW(get_gguf_data(m_path), ov::Exception);+ }+}+TEST_F(GGUFParser, Q1_0PreservesBinaryStorageAndScaleValues) {const auto bytes = load_npy<uint8_t>("q1_0_qbytes");const auto reference = load_npy<float>("q1_0_deq");@@ -234,6 +346,7 @@ TEST_F(GGUFParser, AcceptsEmptyQuantizedTensors) {std::pair{"Q5_0", GGUF_TYPE_Q5_0},std::pair{"Q5_1", GGUF_TYPE_Q5_1},std::pair{"Q8_0", GGUF_TYPE_Q8_0},+ std::pair{"Q8_1", GGUF_TYPE_Q8_1},std::pair{"Q2_K", GGUF_TYPE_Q2_K},std::pair{"Q2_0", GGUF_TYPE_Q2_0},std::pair{"Q3_K", GGUF_TYPE_Q3_K},diff --git a/src/frontends/gguf/tests/test_weights.cpp b/src/frontends/gguf/tests/test_weights.cppindex efead58903d..691dc1c6c0e 100644--- a/src/frontends/gguf/tests/test_weights.cpp+++ b/src/frontends/gguf/tests/test_weights.cpp@@ -19,6 +19,8 @@#include "common_test_utils/file_utils.hpp"#include "op_test_utils.hpp"#include "openvino/op/constant.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/matmul.hpp"#include "quant/gguf.hpp"#include "quant/weights.hpp"@@ -76,6 +78,11 @@ TEST_P(GGUFWeight, MatchesGgmlToFloat) {float max_diff = 0.f;for (size_t i = 0; i < ref.size(); ++i)max_diff = std::max(max_diff, std::fabs(a[i] - ref[i]));+ if (c.tol == 0.f) {+ for (size_t i = 0; i < ref.size(); ++i)+ EXPECT_EQ(a[i], ref[i]) << "element " << i;+ return;+ }EXPECT_LE(max_diff, c.tol) << c.stem << ": frontend weight dequant diverges from ggml to_float";}@@ -86,6 +93,7 @@ INSTANTIATE_TEST_SUITE_P(AllQuantTypes,WeightCase{"q5_0", "Q5_0", kTolFaithful},WeightCase{"q5_1", "Q5_1", kTolFaithful},WeightCase{"q8_0", "Q8_0", kTolFaithful},+ WeightCase{"q8_1", "Q8_1", 0.f},WeightCase{"q2_k", "Q2_K", kTolFaithful},WeightCase{"q3_k", "Q3_K", kTolFaithful},WeightCase{"q4_k", "Q4_K", kTolU4Requant},@@ -99,6 +107,113 @@ INSTANTIATE_TEST_SUITE_P(AllQuantTypes,return std::string(i.param.stem);});+TEST(GGUFWeight, Q8_1KeepsCodesAndScaleBitsForAllWeightNames) {+ const auto bytes = load_npy<uint8_t>("q8_1_qbytes");+ ASSERT_EQ(bytes.size(), kRows * kCols / 32 * 36);+ for (const std::string name : {"blk.0.attn_q.weight", "token_embd.weight", "output.weight"}) {+ SCOPED_TRACE(name);+ const auto node = make_weight_node(bytes_to_u8_tensor(bytes), "Q8_1", {kRows, kCols}, name);+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{node}, ov::ParameterVector{});+ size_t payload_bytes = 0;+ size_t weight_constants = 0;+ size_t scale_constants = 0;+ for (const auto& op : model->get_ordered_ops()) {+ EXPECT_STRNE(op->get_type_name(), "Subtract");+ if (std::string(op->get_type_name()) == "Multiply") {+ EXPECT_EQ(op->get_output_element_type(0), ov::element::f32);+ }+ const auto constant = ov::as_type_ptr<ov::op::v0::Constant>(op);+ if (!constant || constant->get_element_type() == ov::element::i64)+ continue;+ payload_bytes += constant->get_byte_size();+ if (constant->get_element_type() == ov::element::i8) {+ ++weight_constants;+ ASSERT_EQ(ov::shape_size(constant->get_shape()), kRows * kCols);+ for (size_t i = 0; i < ov::shape_size(constant->get_shape()); ++i) {+ int8_t code;+ std::memcpy(&code, bytes.data() + (i / 32) * 36 + 4 + i % 32, sizeof(code));+ EXPECT_EQ(constant->get_data_ptr<int8_t>()[i], code);+ }+ } else {+ ASSERT_EQ(constant->get_element_type(), ov::element::f16);+ ++scale_constants;+ ASSERT_EQ(ov::shape_size(constant->get_shape()), kRows * kCols / 32);+ for (size_t group = 0; group < ov::shape_size(constant->get_shape()); ++group) {+ uint16_t bits;+ std::memcpy(&bits, bytes.data() + group * 36, sizeof(bits));+ EXPECT_EQ(constant->get_data_ptr<ov::float16>()[group].to_bits(), bits);+ }+ }+ }+ EXPECT_EQ(weight_constants, 1);+ EXPECT_EQ(scale_constants, 1);+ EXPECT_EQ(payload_bytes, kRows * kCols / 32 * 34);+ }+}++TEST(GGUFWeight, Q8_1SuppliedDecoderPreservesHigherRankShape) {+ const auto bytes = load_npy<uint8_t>("q8_1_qbytes");+ const auto reference = load_npy<float>("q8_1_deq");+ std::vector<uint8_t> storage(bytes.size() + 1);+ std::memcpy(storage.data() + 1, bytes.data(), bytes.size());+ const ov::Tensor unaligned(ov::element::u8, {bytes.size()}, storage.data() + 1);+ const auto model = SingleOpBuilder()+ .op("GGML_OP_NONE")+ .output("output.weight", ov::element::f32, {2, 2, kCols})+ .attr<ov::Tensor>("data", unaligned)+ .attr<std::string>("quant_type", "q8_1")+ .build();+ EXPECT_EQ(model->get_output_shape(0), (ov::Shape{2, 2, kCols}));+ const auto output = run_on_cpu(model, {});+ ASSERT_EQ(output.get_size(), reference.size());+ for (size_t i = 0; i < reference.size(); ++i)+ EXPECT_EQ(output.data<const float>()[i], reference[i]);+}++TEST(GGUFWeight, Q8_1CpuMatmulAndGatherMatchRepresentedWeights) {+ const auto bytes = load_npy<uint8_t>("q8_1_qbytes");+ const auto reference = load_npy<float>("q8_1_deq");+ ASSERT_EQ(reference.size(), kRows * kCols);+ const std::vector<int64_t> selected_rows{3, 0, 2, 1};+ ov::Tensor one_hot(ov::element::f32, {kCols, kCols});+ std::fill_n(one_hot.data<float>(), one_hot.get_size(), 0.f);+ for (size_t i = 0; i < kCols; ++i)+ one_hot.data<float>()[i * kCols + i] = 1.f;+ ov::Core core;+ for (const std::string name : {"blk.0.attn_q.weight", "token_embd.weight", "output.weight"}) {+ SCOPED_TRACE(name);+ const auto weight = make_weight_node(bytes_to_u8_tensor(bytes), "Q8_1", {kRows, kCols}, name);+ const auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{kCols, kCols});+ const auto indices = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{kRows});+ const auto matmul = std::make_shared<ov::op::v0::MatMul>(input, weight, false, true);+ const auto gather =+ std::make_shared<ov::op::v8::Gather>(weight,+ indices,+ ov::op::v0::Constant::create(ov::element::i64, {}, {0}));+ const auto model =+ std::make_shared<ov::Model>(ov::OutputVector{matmul, gather}, ov::ParameterVector{input, indices});+ auto request = core.compile_model(model,+ "CPU",+ ov::hint::inference_precision(ov::element::f32),+ ov::hint::dynamic_quantization_group_size(0))+ .create_infer_request();+ request.set_input_tensor(0, one_hot);+ request.set_input_tensor(1, make_i64_tensor({kRows}, selected_rows));+ request.infer();+ const auto products = request.get_output_tensor(0);+ const auto embeddings = request.get_output_tensor(1);+ ASSERT_EQ(products.get_shape(), (ov::Shape{kCols, kRows}));+ ASSERT_EQ(embeddings.get_shape(), (ov::Shape{kRows, kCols}));+ for (size_t row = 0; row < kRows; ++row) {+ for (size_t col = 0; col < kCols; ++col) {+ EXPECT_EQ(products.data<const float>()[col * kRows + row], reference[row * kCols + col]);+ EXPECT_EQ(embeddings.data<const float>()[row * kCols + col],+ reference[selected_rows[row] * kCols + col]);+ }+ }+ }+}+TEST(GGUFWeight, Q1_0KeepsBinaryCodesForAllWeightNames) {const auto bytes = load_npy<uint8_t>("q1_0_qbytes");const auto reference = load_npy<float>("q1_0_deq");@@ -307,7 +422,7 @@ TEST(GGUFFusedQkvBias, SplitsIntoExpectedRanges) {}}-TEST(GGUFFusedQkvWeight, PreservesScalesForMxfp4AndQ8K) {+TEST(GGUFFusedQkvWeight, PreservesScalesForGroupedFormats) {const auto check = [](ov::frontend::gguf::GgufTensorType qtype,const ov::element::Type& weight_type,const ov::element::Type& scale_type,@@ -335,6 +450,7 @@ TEST(GGUFFusedQkvWeight, PreservesScalesForMxfp4AndQ8K) {check(ov::frontend::gguf::GGUF_TYPE_MXFP4, ov::element::f4e2m1, ov::element::f8e8m0, 8);check(ov::frontend::gguf::GGUF_TYPE_Q1_0, ov::element::u1, ov::element::f16, 2);+ check(ov::frontend::gguf::GGUF_TYPE_Q8_1, ov::element::i8, ov::element::f16, 8);check(ov::frontend::gguf::GGUF_TYPE_Q8_K, ov::element::i8, ov::element::f32, 1);}