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] Fix TinyLlama and Hunyuan frontend accuracy (#37924)
Maxim Vafin469d2b98bd84
diff --git a/.github/workflows/job_gguf_llamacpp_validation.yml b/.github/workflows/job_gguf_llamacpp_validation.ymlindex 44fde3552cb..888a0f0acff 100644--- a/.github/workflows/job_gguf_llamacpp_validation.yml+++ b/.github/workflows/job_gguf_llamacpp_validation.yml@@ -86,10 +86,9 @@ jobs:- name: Run llama.cpp tests against the ggml-openvino backendenv:- # Q4_K's zero-point defaults to an integer (u8) constant for production (genai) speed.- # llama.cpp's test-backend-ops compares against an f32 CPU reference within a tolerance- # the rounded u8 zero-point can miss, so request the faithful f16 zero-point here. See- # gguf_zero_point_type in src/frontends/gguf/src/quant/weights.cpp.+ # The production Q4_K path requantizes weights to OpenVINO u4 and is necessarily lossy.+ # llama.cpp's test-backend-ops uses a strict f32-oracle tolerance, so validate the+ # frontend's faithful Q4_K decode path here. The requantized path has dedicated tests.OV_GGUF_Q4_K_ZP_F16: "1"run: |source ${{ env.INSTALL_DIR }}/setupvars.shdiff --git a/src/frontends/gguf/docs/supported_models.md b/src/frontends/gguf/docs/supported_models.mdindex fa3132d62d0..e6842dfc100 100644--- a/src/frontends/gguf/docs/supported_models.md+++ b/src/frontends/gguf/docs/supported_models.md@@ -64,7 +64,7 @@ The builder's accept-list is the union of two sets, both defined inAnything not in either set is rejected with an explicit `OPENVINO_ASSERT` at load timerather than converting into a silently wrong graph.-### `verified_archs()` — 10 architectures+### `verified_archs()` — 11 architectures| Architecture | Notes ||---|---|@@ -73,13 +73,14 @@ rather than converting into a silently wrong graph.| `qwen3` | QK-norm || `phi3` | fused QKV || `minicpm` | NORMAL rope + scalar embedding/residual/logit scales |+| `hunyuan-dense` | NEOX rope + learned per-head Q/K norm after RoPE || `olmoe` | OLMoE 1B-7B (MoE) || `qwen35` | Qwen3.5/3.6 (and the Ternary-Bonsai backbone): hybrid Gated-DeltaNet + full attention, M-RoPE, interleaved query+gate projection. Greedy / batch 1 only || `gpt-oss` | MoE + attention sinks + SWA + OAI gated activation || `gemma3` | post-norms + final logit soft-cap || `gemma4` | SWA, per-layer embeddings, shared KV |-### `experimental_archs()` — 20 architectures+### `experimental_archs()` — 19 architectures| Architecture | Notes ||---|---|@@ -99,7 +100,6 @@ rather than converting into a silently wrong graph.| `mellum` | JetBrains Mellum: pure MoE || `deepseek2-ocr` | DeepSeekOCR: dense lead layers + MoE || `jais2` | JAIS-2: dense (biases auto-detected) |-| `hunyuan-dense` | Demoted from `verified_archs()`: degenerate output through the builder (see below) || `qwen3moe` | Qwen3 MoE; same topology as `olmoe`. Demoted: degenerate output through the builder || `gemma` | Gemma 2B / 7B. Demoted: throws through the builder (see below) || `gemma2` | post-norms + attention soft-cap. Demoted: degenerate output through the builder |@@ -124,7 +124,7 @@ model/checkpoint that is simply weak on the prompt.| `qwen3` | verified | Qwen3-0.6B Q8_0 | generates (reasoning preamble) | same || `phi3` | verified | Phi-3-mini-4k-instruct Q4 | generates | generates || `minicpm` | verified | MiniCPM-2B-dpo Q4_K_M | generates | generates |-| `hunyuan-dense` | experimental | Hunyuan-0.5B-Instruct Q4_K_M | **degenerate** | generates |+| `hunyuan-dense` | verified | Hunyuan-0.5B-Instruct Q8_0 | matches reference | same || `olmoe` | verified | OLMoE-1B-7B-Instruct Q4_K_M | generates | generates || `qwen3moe` | experimental | Qwen3-0.9B-A0.6B Q4_K_M | **degenerate** | generates || `gpt-oss` | verified | gpt-oss-20b MXFP4 | generates (harmony format) | same |@@ -156,10 +156,10 @@ greedy completion is expected of it, not a defect. `gemma` (v1 base) and `plamo3instruct) are degenerate on the reference too, so those rows are checkpoint/prompt artifactsrather than frontend bugs.-That leaves **5 architectures that generate correctly under llama.cpp but not through the-builder** — `hunyuan-dense`, `qwen3moe`, `gemma2`, `exaone4` and `ernie4_5-moe` (blank output) —+That leaves **4 architectures that generate correctly under llama.cpp but not through the+builder** — `qwen3moe`, `gemma2`, `exaone4` and `ernie4_5-moe` (blank output) —i.e. real conversion defects, plus `gemma`, which throws instead of converting cleanly.-`hunyuan-dense`, `qwen3moe`, `gemma2` and `gemma` were previously misclassified as+`qwen3moe`, `gemma2` and `gemma` were previously misclassified as`verified_archs()`; they have been moved to `experimental_archs()` (and now emit the one-time`OPENVINO_WARN`) until the underlying defects are fixed and re-verified.diff --git a/src/frontends/gguf/src/builder/arch_registry.cpp b/src/frontends/gguf/src/builder/arch_registry.cppindex d213b97d692..400271d1a76 100644--- a/src/frontends/gguf/src/builder/arch_registry.cpp+++ b/src/frontends/gguf/src/builder/arch_registry.cpp@@ -31,9 +31,10 @@ const std::set<std::string>& verified_archs() {"llama", // llama-2 / llama-3"qwen2", // qwen2 / qwen2.5"qwen3",- "phi3", // phi-3 (fused QKV)- "minicpm", // NORMAL rope + scalar scales- "olmoe", // OLMoE 1B-7B (MoE)+ "phi3", // phi-3 (fused QKV)+ "minicpm", // NORMAL rope + scalar scales+ "hunyuan-dense", // NEOX rope + per-head QK-norm after RoPE+ "olmoe", // OLMoE 1B-7B (MoE)// Qwen3.5/3.6 hybrid: Gated-DeltaNet linear attention on 3 of every 4 layers, full// attention with M-RoPE and an interleaved query+gate projection on the rest. Verified// token-exact against llama.cpp on Qwen3.5-0.8B-Q8_0 and Ternary-Bonsai-27B-Q2_g64.@@ -75,7 +76,6 @@ const std::set<std::string>& experimental_archs() {// Demoted from verified_archs(): the GenAI-vs-llama.cpp measured status (see// docs/supported_models.md) found these produce degenerate output (or, for `gemma`,// throw) through the native builder despite passing conversion. Re-promote once fixed.- "hunyuan-dense","qwen3moe", // Qwen3 MoE: same topology as olmoe"gemma", // Gemma 2B / 7B"gemma2", // Gemma 2: post-norms + attention soft-capdiff --git a/src/frontends/gguf/src/builder/blocks/attention.cpp b/src/frontends/gguf/src/builder/blocks/attention.cppindex a020cb5436e..f959f319df3 100644--- a/src/frontends/gguf/src/builder/blocks/attention.cpp+++ b/src/frontends/gguf/src/builder/blocks/attention.cpp@@ -107,7 +107,7 @@ std::string attention(GraphEmitter& e,v = e.add_op("GGML_OP_RESHAPE", p + "Vcur_r", {v}, ps({1, T, n_head_kv_l, head_size_l}), f32, 1);// per-head q_norm / k_norm (qwen3, hunyuan, gemma4)- if (cfg.has_qk_norm && !cfg.qk_norm_full) {+ if (cfg.has_qk_norm && !cfg.qk_norm_full && !cfg.qk_norm_after_rope) {q = rms_norm(e, q, p + "attn_q_norm.weight", p + "Qcur_normed", cfg.rms_eps);k = rms_norm(e, k, p + "attn_k_norm.weight", p + "Kcur_normed", cfg.rms_eps);}@@ -151,6 +151,12 @@ std::string attention(GraphEmitter& e,{{"rope_config", rope_config_l}});}+ // Hunyuan differs from Qwen/Gemma: its learned per-head Q/K RMSNorm follows RoPE.+ if (cfg.has_qk_norm && !cfg.qk_norm_full && cfg.qk_norm_after_rope) {+ q = rms_norm(e, q, p + "attn_q_norm.weight", p + "Qcur_normed", cfg.rms_eps);+ k = rms_norm(e, k, p + "attn_k_norm.weight", p + "Kcur_normed", cfg.rms_eps);+ }+// ---- KV cache store ----// Gemma4: layers with shared_kv_layers have no K/V of their own; they reuse the KV// from the last layer of the same SWA type that has its own KV cache. SWA layersdiff --git a/src/frontends/gguf/src/builder/decoder_config.cpp b/src/frontends/gguf/src/builder/decoder_config.cppindex 0a8aba6f475..6965670f34d 100644--- a/src/frontends/gguf/src/builder/decoder_config.cpp+++ b/src/frontends/gguf/src/builder/decoder_config.cpp@@ -78,6 +78,10 @@ DecoderConfig::DecoderConfig(const std::map<std::string, GGUFMetaData>& config,const size_t qn = weights.at("blk.0.attn_q_norm.weight").get_shape()[0];qk_norm_full = (arch != "gemma4") && (qn != static_cast<size_t>(head_size));}+ // Hunyuan's graph applies RoPE before its learned per-head Q/K RMSNorm. This order is+ // architecture-specific and cannot be inferred from the identical tensor shapes used by+ // Qwen3/Gemma, which normalize before RoPE.+ qk_norm_after_rope = arch == "hunyuan-dense" || arch == "hunyuan-moe";n_dense_lead = cfg_i("n_layer_dense_lead");// Detect MoE from the first non-dense-lead layer (layer 0 may be dense even in MoE models).{diff --git a/src/frontends/gguf/src/builder/decoder_config.hpp b/src/frontends/gguf/src/builder/decoder_config.hppindex 15bacf2cc93..3663e5fcec9 100644--- a/src/frontends/gguf/src/builder/decoder_config.hpp+++ b/src/frontends/gguf/src/builder/decoder_config.hpp@@ -48,7 +48,8 @@ struct DecoderConfig {// ---- auto-detected per-architecture structure ----bool has_qk_norm = false;- bool qk_norm_full = false; // norm width is n_head*head_size (OLMoE) rather than per-head+ bool qk_norm_full = false; // norm width is n_head*head_size (OLMoE) rather than per-head+ bool qk_norm_after_rope = false; // Hunyuan applies learned per-head Q/K norm after RoPEbool has_qkv_bias = false;bool has_attn_out_bias = false;bool has_rope_freqs = false;diff --git a/src/frontends/gguf/src/pass/lower_set_rows_stateless.cpp b/src/frontends/gguf/src/pass/lower_set_rows_stateless.cppindex 639e609c28b..bdd3ecf8cb2 100644--- a/src/frontends/gguf/src/pass/lower_set_rows_stateless.cpp+++ b/src/frontends/gguf/src/pass/lower_set_rows_stateless.cpp@@ -5,6 +5,7 @@#include "pass/lower_set_rows_stateless.hpp"#include <memory>+#include <vector>#include "openvino/core/graph_util.hpp"#include "openvino/core/rt_info.hpp"@@ -12,6 +13,7 @@#include "openvino/op/constant.hpp"#include "openvino/op/reshape.hpp"#include "openvino/op/scatter_update.hpp"+#include "openvino/op/shape_of.hpp"#include "openvino/pass/pattern/op/wrap_type.hpp"namespace ov {@@ -31,22 +33,26 @@ LowerSetRowsStateless::LowerSetRowsStateless() {auto indices = set_rows->input_value(1); // squeezed row indicesauto dst = set_rows->input_value(2); // destination tensor (Parameter for a KV cache)+ // SET_ROWS indices address the flattened context/head row axis. Flatten the destination+ // the same way translate_set_rows flattened the updates; with a one-token cache the two+ // layouts happen to coincide, which previously hid this mismatch until the second step.+ const auto dst_shape = dst.get_partial_shape();+ OPENVINO_ASSERT(dst_shape.rank().is_static() && dst_shape[dst_shape.rank().get_length() - 1].is_static(),+ "SET_ROWS requires a static destination row size");+ const auto row_size = dst_shape[dst_shape.rank().get_length() - 1].get_length();+ auto flat_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{0, 1, -1, row_size});+ auto flat_dst = std::make_shared<ov::op::v1::Reshape>(dst, flat_shape, true);auto axes = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {2});- std::shared_ptr<ov::Node> res = std::make_shared<ov::op::v3::ScatterUpdate>(dst, indices, data, axes);+ std::shared_ptr<ov::Node> res = std::make_shared<ov::op::v3::ScatterUpdate>(flat_dst, indices, data, axes);++ ov::Output<ov::Node> output_shape = std::make_shared<ov::op::v3::ShapeOf>(dst, ov::element::i64);// Multi-sequence: if the destination is a Reshape, reshape the scatter result back to the// original [1, n_seq, ctx_per_seq, emb] layout (ctx_per_seq stays dynamic for llama-bench).if (auto dst_reshape = ov::as_type_ptr<ov::op::v1::Reshape>(dst.get_node_shared_ptr())) {- auto dst_ps = dst_reshape->get_input_partial_shape(0);- // -1 for any dynamic dim; get_length() throws on dynamic.- auto dim_or_dynamic = [&](size_t i) -> int64_t {- return dst_ps[i].is_static() ? dst_ps[i].get_length() : -1;- };- std::vector<int64_t> shape = {dim_or_dynamic(0), dim_or_dynamic(1), dim_or_dynamic(2), dim_or_dynamic(3)};- res = std::make_shared<ov::op::v1::Reshape>(res,- ov::op::v0::Constant::create(ov::element::i64, {4}, shape),- false);+ output_shape = std::make_shared<ov::op::v3::ShapeOf>(dst_reshape->input_value(0), ov::element::i64);}+ res = std::make_shared<ov::op::v1::Reshape>(res, output_shape, false);res->set_friendly_name(set_rows->get_friendly_name());ov::copy_runtime_info(set_rows, res);diff --git a/src/frontends/gguf/src/quant/gguf.cpp b/src/frontends/gguf/src/quant/gguf.cppindex 40cbb9c535d..e9699b8d1cf 100644--- a/src/frontends/gguf/src/quant/gguf.cpp+++ b/src/frontends/gguf/src/quant/gguf.cpp@@ -427,8 +427,7 @@ GGUFLoad get_gguf_data(const std::string& file) {// Helper: for a quantized tensor, compute (weights_bytes, scale_bytes, zp_bytes).// Symmetric types (Q4_0, Q8_0, Q5_0, Q6_K): zp_bytes = 0.- // Asymmetric types (Q4_1, Q4_K): zp u4 packed (same count as scales, half the bytes).- // Asymmetric Q5_K: zp u8 (one byte per sub-block, same count as scales).+ // Asymmetric types: zero-points use the element type selected by gguf_zero_point_type.//// Every dim comes straight from the file, so shape products (and the total below) use// ov::util::mul_overflow/add_overflow instead of raw `*=`/`+=`: wrapped products could@@ -522,15 +521,16 @@ GGUFLoad get_gguf_data(const std::string& file) {const size_t s_nelems = size_prod(scale_shape);const size_t s_bytes = s_nelems * sizeof(uint16_t);- // Zero-point bytes:- // Symmetric (Q4_0, Q8_0, Q5_0, Q6_K): no zp.- // Q4_1, Q4_K: u4 zp — same element count as scales, packed 2/byte.- // Q5_K, Q5_1: u8 zp — one byte per sub-block.+ // Zero-point bytes. Symmetric formats have none; asymmetric formats use the same+ // element count as scales and the representation selected by gguf_zero_point_type.size_t z_bytes = 0;- if (ti.type == GGUF_TYPE_Q4_1 || ti.type == GGUF_TYPE_Q4_K) {- z_bytes = (s_nelems + 1) / 2; // u4 packed- } else if (ti.type == GGUF_TYPE_Q5_K || ti.type == GGUF_TYPE_Q5_1) {- z_bytes = s_nelems; // u8+ if (ti.type == GGUF_TYPE_Q4_1 || ti.type == GGUF_TYPE_Q4_K || ti.type == GGUF_TYPE_Q5_K ||+ ti.type == GGUF_TYPE_Q5_1) {+ OPENVINO_ASSERT(+ !ov::util::mul_overflow(s_nelems,+ gguf_zero_point_type(ti.name, static_cast<GgufTensorType>(ti.type)).size(),+ z_bytes),+ "[load_gguf] zero-point byte count overflows size_t");}return {w_bytes, s_bytes, z_bytes};};@@ -760,9 +760,8 @@ GGUFLoad get_gguf_data(const std::string& file) {qtype.emplace(name_prefix + ".qtype", static_cast<GgufTensorType>(ti.type));} else if (ti.type == GGUF_TYPE_Q4_1 || ti.type == GGUF_TYPE_Q4_K || ti.type == GGUF_TYPE_Q5_K ||ti.type == GGUF_TYPE_Q5_1) {- // Asymmetric: weights + f16 scales + integer zp.- // 4-bit (Q4_1, Q4_K): u32-packed u4 weights, u4 zp.- // 8-bit (Q5_K, Q5_1): i8 weights, u8 zp.+ // Asymmetric: weights + f16 scales + zero-point. Q4_K matmul weights are decoded and+ // requantized group-wise to u4 with an integer zero-point; Q8_0_C sources keep f16.auto [wb, sb, zb] = quant_sizes(ti);char* buf_ptr = quant_buf->get_ptr<char>();@@ -787,9 +786,9 @@ GGUFLoad get_gguf_data(const std::string& file) {// Both ingest paths must agree on the zero-point representation; see// gguf_zero_point_type in quant/weights.hpp for why it matters.const auto zp_elem = gguf_zero_point_type(name, static_cast<GgufTensorType>(ti.type));- // Only Q4_K's integer zp actually rounds: Q2_0's zero-point is the exact integer 1.+ // Q4_K performs a real group-wise requantization; Q2_0's integer zero-point is exact.if (zp_elem == ov::element::u8 && ti.type == GGUF_TYPE_Q4_K) {- notify_lossy_weight_approximation(LossyWeightApproximation::INTEGER_ZERO_POINT);+ notify_lossy_weight_approximation(LossyWeightApproximation::Q4_K_REQUANT);}ov::Tensor zp(zp_elem, scale_shape);quant_offset += zb;diff --git a/src/frontends/gguf/src/quant/gguf_quants.cpp b/src/frontends/gguf/src/quant/gguf_quants.cppindex 2aaf99c86f5..19dbecf9b70 100644--- a/src/frontends/gguf/src/quant/gguf_quants.cpp+++ b/src/frontends/gguf/src/quant/gguf_quants.cpp@@ -6,9 +6,11 @@#include <cmath>#include <cstdint>#include <cstring>+#include <limits>#include <memory>#include <numeric>#include <sstream>+#include <utility>#include "gguf.hpp"#include "openvino/core/parallel.hpp"@@ -27,6 +29,7 @@ static constexpr uint64_t kQ6K_BLOCK_BYTES = 128 + 64 + 16 + 2; // ql + qh// Round a fractional zero-point to u8, clamping to avoid a modulo-256 wrap when min/scale > 255.static inline uint8_t quantize_zp_u8(float zpval) {+ OPENVINO_ASSERT(std::isfinite(zpval), "[GGUF] cannot quantize a non-finite zero-point");long r = std::lround(zpval);return static_cast<uint8_t>(std::min<long>(255, std::max<long>(0, r)));}@@ -133,13 +136,15 @@ void unpack_256_4(const uint8_t* data, uint8_t* dst) {// Q4_K asymmetric: super-block = |f16 d|f16 dmin|12 bytes scales/mins|128 bytes ql|.// 8 sub-blocks of 32 with 6-bit scale and 6-bit min each.// Outputs: u32-packed u4 weights + f16 scales + zp (one per sub-block).-// Dequant is w = scale*q - min, scale = d*sc_raw, min = dmin*m_raw, expressed as scale*(q - zp).-// The zp element type selects the representation:-// - u8 -> INTEGER zp = round(min/scale): forces min to a multiple of scale (injects a small-// per-weight rounding error) but keeps the low-precision form the CPU plugin fuses-// into the MatMul -- this is what the original ggml-openvino backend does.-// - f16 -> FRACTIONAL zp = min/scale: faithful, used on the requant path (token_embd/output)-// where the dequant is re-quantized channel-wise rather than fed to the MatMul.+// Dequant is w = scale*q - min, scale = d*sc_raw, min = dmin*m_raw.+//+// With an f16 zp, preserve the source nibbles and express the exact affine offset as min/scale.+// With a u8 zp, faithfully decode one 32-value group to f32 and requantize it to a NEW u4 grid.+// The latter follows NNCF's data-free INT4_ASYM baseline (range includes zero, min/max scale,+// integral clipped zp), followed by one cheap least-squares scale refinement. Candidate errors+// are evaluated with the actually stored f16 scale. A candidate is used only when it reduces+// squared error without increasing the maximum error versus the former rounded-zp representation.+// Only 32 f32 values are live per worker.void fill_q4_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr, ov::Tensor& zp_arr) {const uint64_t bytes_per_block = kQ4K_BLOCK_BYTES;const uint64_t n_super_block = tensor.bsize / bytes_per_block;@@ -154,6 +159,10 @@ void fill_q4_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scconst uint8_t* block_data = data + i * bytes_per_block;const float d = static_cast<float>(ov::float16::from_bits(*((uint16_t*)block_data)));const float dmin = static_cast<float>(ov::float16::from_bits(*((uint16_t*)block_data + 1)));+ OPENVINO_ASSERT(std::isfinite(d) && std::isfinite(dmin),+ "[GGUF] Q4_K block ",+ i,+ " has non-finite scale metadata");const uint8_t* qs1 = block_data + 4;// 8 sub-blocks: 6-bit scale and 6-bit min packed in 12 bytes.@@ -168,14 +177,110 @@ void fill_q4_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scfor (int j = 0; j < 8; ++j) {const float sc = d * sc_raw[j];const float mn = dmin * m_raw[j];- scales[i * 8 + j] = ov::float16(sc);- const float zpval = (sc != 0.f) ? (mn / sc) : 0.f;- if (int_zp)- zp_u8[i * 8 + j] = quantize_zp_u8(zpval);- else+ if (!int_zp) {+ scales[i * 8 + j] = ov::float16(sc);+ const float zpval = (sc != 0.f) ? (mn / sc) : 0.f;zp_f16[i * 8 + j] = ov::float16(zpval);+ continue;+ }++ float values[32];+ uint8_t source_q[32];+ const uint8_t* source = block_data + 16 + (j / 2) * 32;+ float min_value = 0.0f;+ float max_value = 0.0f;+ for (int k = 0; k < 32; ++k) {+ const uint8_t q = (j % 2 == 0) ? (source[k] & 0x0F) : (source[k] >> 4);+ source_q[k] = q;+ values[k] = sc * static_cast<float>(q) - mn;+ min_value = std::min(min_value, values[k]);+ max_value = std::max(max_value, values[k]);+ }++ struct Error {+ double squared;+ float max_abs;+ };+ const auto measure = [&](float runtime_scale, uint8_t zp, const uint8_t* quantized) {+ Error error{0.0, 0.0f};+ for (int k = 0; k < 32; ++k) {+ const float diff = values[k] - runtime_scale * (static_cast<int>(quantized[k]) - zp);+ error.squared += static_cast<double>(diff) * diff;+ error.max_abs = std::max(error.max_abs, std::fabs(diff));+ }+ return error;+ };++ // Start from the previous compressed-FC representation. Requantization must not+ // regress either its total error or its worst reconstructed value.+ uint8_t best_q[32];+ std::copy_n(source_q, 32, best_q);+ ov::float16 best_scale(sc);+ uint8_t best_zp = quantize_zp_u8((sc != 0.0f) ? (mn / sc) : 0.0f);+ Error best_error = measure(static_cast<float>(best_scale), best_zp, best_q);+ const float fallback_max_error = best_error.max_abs;++ float initial_scale = (max_value - min_value) / 15.0f;+ if (std::fabs(initial_scale) < std::numeric_limits<float>::epsilon()) {+ initial_scale = std::numeric_limits<float>::epsilon();+ }+ const auto rounded_zp = static_cast<long>(std::nearbyint(-min_value / initial_scale));+ const uint8_t zp = static_cast<uint8_t>(std::min<long>(15, std::max<long>(0, rounded_zp)));++ const auto evaluate = [&](float scale_candidate, uint8_t* quantized) {+ const ov::float16 scale_f16(scale_candidate);+ const float runtime_scale = static_cast<float>(scale_f16);+ if (!(runtime_scale > 0.0f) || !std::isfinite(runtime_scale)) {+ return std::make_pair(+ scale_f16,+ Error{std::numeric_limits<double>::infinity(), std::numeric_limits<float>::infinity()});+ }+ for (int k = 0; k < 32; ++k) {+ const long rounded = static_cast<long>(std::nearbyint(values[k] / runtime_scale)) + zp;+ quantized[k] = static_cast<uint8_t>(std::min<long>(15, std::max<long>(0, rounded)));+ }+ return std::make_pair(scale_f16, measure(runtime_scale, zp, quantized));+ };++ const auto accept = [&](const std::pair<ov::float16, Error>& candidate, const uint8_t* candidate_q) {+ if (candidate.second.squared < best_error.squared && candidate.second.max_abs <= fallback_max_error) {+ best_scale = candidate.first;+ best_zp = zp;+ best_error = candidate.second;+ std::copy_n(candidate_q, 32, best_q);+ }+ };++ uint8_t candidate_q[32];+ auto candidate = evaluate(initial_scale, candidate_q);+ accept(candidate, candidate_q);++ // With the min/max assignments fixed, this is the least-squares optimal scale for+ // x ~= scale * (q-zp). Requantize once more with it and retain it only if the actual+ // f16-scale reconstruction improves both criteria versus the retained representation.+ double numerator = 0.0;+ double denominator = 0.0;+ for (int k = 0; k < 32; ++k) {+ const int centered = static_cast<int>(candidate_q[k]) - zp;+ numerator += static_cast<double>(values[k]) * centered;+ denominator += static_cast<double>(centered) * centered;+ }+ if (denominator != 0.0) {+ candidate = evaluate(static_cast<float>(numerator / denominator), candidate_q);+ accept(candidate, candidate_q);+ }++ scales[i * 8 + j] = best_scale;+ zp_u8[i * 8 + j] = best_zp;+ uint8_t* destination = weights + i * 128 + j * 16;+ std::fill_n(destination, 16, 0);+ for (int k = 0; k < 32; ++k) {+ destination[k / 2] |= static_cast<uint8_t>(best_q[k] << (4 * (k % 2)));+ }+ }+ if (!int_zp) {+ unpack_256_4(block_data + 16, weights + i * 128);}- unpack_256_4(block_data + 16, weights + i * 128);});}@@ -196,7 +301,7 @@ static inline void get_scale_min_k4(int j, const uint8_t* q, uint8_t* d, uint8_t// ports of ggml's dequantize_row_q{4,5,6}_K: they compute w = (d*sc)*q - (dmin*m) with the products// kept in f32 (d/dmin are the f16 super-block scales widened to f32), matching what the upstream// backend feeds into its Q8_0_C requant. This is NOT the general dequant path -- the compressed-// matmul weights still go through fill_*/make_int4 (f16 scales, integer zp) unchanged. Each function+// matmul weights still go through fill_*/make_int4 unchanged. Each function// fills ONE row (`cols` floats) so the caller never materializes the whole f32 weight.static void dequant_row_q4_k_f32(const uint8_t* row, size_t cols, float* y) {const uint64_t bpb = kQ4K_BLOCK_BYTES;@@ -709,7 +814,7 @@ void gguf_fill_sym(const GgufTensor& tensor, ov::Tensor& weights, ov::Tensor& sc}}-// Asymmetric types (Q4_1, Q4_K, Q5_K, Q5_1, Q2_K): fill weights + scales + integer zero-points.+// Asymmetric types (Q4_1, Q4_K, Q5_K, Q5_1, Q2_K): fill weights, scales, and zero-points.void gguf_fill_asym(const GgufTensor& tensor, ov::Tensor& weights, ov::Tensor& scales, ov::Tensor& zp) {if (tensor.type == GGUF_TYPE_Q4_1) {fill_q4_1(tensor, weights, scales, zp);diff --git a/src/frontends/gguf/src/quant/weights.cpp b/src/frontends/gguf/src/quant/weights.cppindex 798ccbd3324..ecc932fbd3e 100644--- a/src/frontends/gguf/src/quant/weights.cpp+++ b/src/frontends/gguf/src/quant/weights.cpp@@ -477,17 +477,11 @@ bool needs_q8_0_c_requant(const std::string& name, GgufTensorType qtype) {return qtype == GGUF_TYPE_Q5_K;}-// Opt-in switch: represent Q4_K's asymmetric zero-point as a faithful f16 constant instead of-// the default integer (u8) one. Left unset, production (genai) keeps the u8 zero-point for the-// ~2x faster compressed-FC dequant; llama.cpp's test-backend-ops compares against an f32-// reference with a tolerance the rounded u8 zero-point can miss, so its CI sets this to trade-// that speedup for exact accuracy. See gguf_zero_point_type.+// Keep an exact-decode escape hatch for strict validation against ggml's original Q4_K values.+// Production leaves this unset and uses the compressed-FC-friendly u4 requantization.bool q4_k_f16_zero_point_enabled() {- static const bool enabled = [] {- const char* env = std::getenv("OV_GGUF_Q4_K_ZP_F16");- return env != nullptr && *env != '\0' && std::strcmp(env, "0") != 0;- }();- return enabled;+ const char* env = std::getenv("OV_GGUF_Q4_K_ZP_F16");+ return env != nullptr && *env != '\0' && std::strcmp(env, "0") != 0;}} // namespace@@ -513,12 +507,12 @@ void notify_lossy_weight_approximation(LossyWeightApproximation kind) {<< std::endl;});break;- case LossyWeightApproximation::INTEGER_ZERO_POINT:+ case LossyWeightApproximation::Q4_K_REQUANT:std::call_once(zero_point_once, [] {- std::cerr << "[GGUF] accuracy notice: Q4_K weights use an integer (u8) zero-point, which rounds each "- "sub-block's minimum to a multiple of its scale. This is lossy, so results may differ "- "slightly from the original GGUF weights. It keeps the dequantization foldable into an "- "int8 MatMul, which is roughly twice as fast at prefill. Reported once per process."+ std::cerr << "[GGUF] accuracy notice: Q4_K weights are faithfully decoded and requantized group-wise "+ "to OpenVINO u4. This adds a small quantization error, so results may differ slightly "+ "from the original GGUF weights. The integer zero-point keeps decompression foldable "+ "into a compressed FullyConnected operation. Reported once per process."<< std::endl;});break;@@ -527,12 +521,12 @@ void notify_lossy_weight_approximation(LossyWeightApproximation kind) {ov::element::Type gguf_zero_point_type(const std::string& name, GgufTensorType qtype) {// The CPU compressed-FullyConnected fast path only folds the dequant when the zero-point is an- // INTEGER constant; a fractional f16 one leaves a ~2x slower kernel. Q4_K carries the matmul- // weights of modern models and Q2_0's zp is the exact integer 1, so both use u8 by default. The- // others keep a faithful f16 zp: their zp = min/scale can exceed u8 range, and rounding it- // injects error into every weight. Tensors that are requantized to Q8_0_C are excluded --- // their dequant feeds the channel-wise path, not a compressed FC. Q4_K's u8 zp can be switched- // back to a faithful f16 one via OV_GGUF_Q4_K_ZP_F16 (see q4_k_f16_zero_point_enabled).+ // INTEGER constant; a fractional f16 one leaves a ~2x slower kernel. Q4_K matmul weights are+ // decoded and requantized to an OpenVINO u4 grid with an integer zero-point. Strict oracle+ // validation can request Q4_K's faithful f16 zero-point via OV_GGUF_Q4_K_ZP_F16. Q2_0's+ // zero-point is exactly 1, so u8 is faithful there. Other asymmetric formats keep f16 because+ // their zero-point can exceed u8 range. Tensors selected for Q8_0_C are excluded because their+ // faithful dequantization feeds that separate requantization path.const bool integer_zp = qtype == GGUF_TYPE_Q2_0 || (qtype == GGUF_TYPE_Q4_K && !q4_k_f16_zero_point_enabled());return (integer_zp && !needs_q8_0_c_requant(name, qtype)) ? ov::element::u8 : ov::element::f16;}@@ -766,9 +760,8 @@ std::shared_ptr<ov::Node> make_weight_node(const ov::Tensor& data,// Asymmetric zero-points. The CPU plugin only folds the dequant into the MatMul when the// zp is an INTEGER (u8) low-precision constant; a fractional f16 zp leaves a standalone- // dequant MatMul (~2x slower prefill). Q4_K is the asymmetric type that appears as MatMul- // weights in modern models (Q4_K_M = Q4_K + symmetric Q6_K), so it uses integer zp to match- // the original ggml-openvino backend; Q2_0's zp is the exact integer 1, so it does too.+ // dequant MatMul (~2x slower prefill). Q4_K is decoded to f32 one 32-element group at a time+ // and requantized to an integer-zp u4 grid. Q2_0's zp is exactly 1, so it also uses u8.// The legacy Q4_1/Q5_1/Q2_K types keep a faithful f16 zp:// they are not perf-critical here, and their zp = -min/scale can fall outside u8 range. The// requant path (token_embd/output) also keeps f16 -- its dequant feeds channel-wise Q8_0_C.@@ -777,9 +770,9 @@ std::shared_ptr<ov::Node> make_weight_node(const ov::Tensor& data,if (requant) {notify_lossy_weight_approximation(LossyWeightApproximation::Q8_0_C_REQUANT);}- // Only Q4_K's integer zp actually rounds: Q2_0's zero-point is the exact integer 1.+ // Q4_K performs a real group-wise requantization; Q2_0's integer zero-point is exact.if (zp_type == ov::element::u8 && qtype == GGUF_TYPE_Q4_K) {- notify_lossy_weight_approximation(LossyWeightApproximation::INTEGER_ZERO_POINT);+ notify_lossy_weight_approximation(LossyWeightApproximation::Q4_K_REQUANT);}// K-quant requant sources: the fused dequant -> Q8_0_C streams from the raw bytes, so skip thediff --git a/src/frontends/gguf/src/quant/weights.hpp b/src/frontends/gguf/src/quant/weights.hppindex 18aadd171bb..9185659af10 100644--- a/src/frontends/gguf/src/quant/weights.hpp+++ b/src/frontends/gguf/src/quant/weights.hpp@@ -19,9 +19,9 @@ namespace ov::frontend::gguf {// Element type of the zero-point constant for an asymmetric quantized weight. Both ingest// paths must agree on this: it decides whether the CPU folds the dequant into the MatMul.-// Q4_K defaults to an integer (u8) zero-point (faster, lossy); set the environment variable-// OV_GGUF_Q4_K_ZP_F16=1 to use a faithful f16 zero-point instead (llama.cpp's test-backend-ops-// CI does this to meet its accuracy tolerance).+// Q4_K matmul weights are faithfully decoded and requantized to u4 with an integer zero-point,+// which keeps the CPU compressed-FullyConnected path available. Q4_K tensors selected for the+// channel-wise Q8_0_C path retain an f16 zero-point while feeding that separate requantization.ov::element::Type gguf_zero_point_type(const std::string& name, GgufTensorType qtype);// A lossy weight approximation the frontend deliberately makes, reported to the user once so a@@ -29,9 +29,8 @@ ov::element::Type gguf_zero_point_type(const std::string& name, GgufTensorType qenum class LossyWeightApproximation {// token_embd / output / Q6_K / Q5_K tensors requantized channel-wise to Q8_0_C.Q8_0_C_REQUANT,- // Q4_K asymmetric weights expressed with an INTEGER (u8) zero-point, which forces each- // sub-block's min to a multiple of its scale.- INTEGER_ZERO_POINT,+ // Q4_K asymmetric weights faithfully decoded and requantized group-wise to OpenVINO u4.+ Q4_K_REQUANT,};// Warn -- ONCE per process and per approximation kind -- that weights are being converted with adiff --git a/src/frontends/gguf/tests/test_arch_conversion.cpp b/src/frontends/gguf/tests/test_arch_conversion.cppindex 8adcaa2b657..2ce0f29f5db 100644--- a/src/frontends/gguf/tests/test_arch_conversion.cpp+++ b/src/frontends/gguf/tests/test_arch_conversion.cpp@@ -43,8 +43,10 @@#include <filesystem>#include <fstream>#include <map>+#include <set>#include <sstream>#include <string>+#include <utility>#include <vector>#include "common_test_utils/common_utils.hpp"@@ -178,22 +180,65 @@ struct Fingerprint {const std::map<std::string, Fingerprint>& fingerprints() {static const std::map<std::string, Fingerprint> fp{- {"bailingmoe2-moe.gguf.hdr", {457, 10}}, {"ernie4_5-moe-moe.gguf.hdr", {431, 10}},- {"exaone4-dense.gguf.hdr", {402, 11}}, {"gemma-dense.gguf.hdr", {349, 10}},- {"gemma2-dense.gguf.hdr", {399, 11}}, {"glm4moe-moe.gguf.hdr", {469, 10}},- {"gpt-oss-moe.gguf.hdr", {558, 11}}, {"hunyuan-dense-dense.gguf.hdr", {400, 10}},- {"hunyuan-moe-moe.gguf.hdr", {518, 10}}, {"llama-dense.gguf.hdr", {384, 10}},- {"llama-moe.gguf.hdr", {490, 10}}, {"maincoder-dense.gguf.hdr", {416, 10}},- {"minicpm-dense.gguf.hdr", {382, 10}}, {"minicpm-moe.gguf.hdr", {488, 10}},- {"minimax-m2-moe.gguf.hdr", {518, 10}}, {"mistral3-dense.gguf.hdr", {384, 10}},- {"mistral3-moe.gguf.hdr", {490, 10}}, {"olmoe-moe.gguf.hdr", {518, 10}},- {"phi3-dense.gguf.hdr", {364, 10}}, {"qwen2-dense.gguf.hdr", {352, 10}},- {"qwen3-dense.gguf.hdr", {400, 10}}, {"qwen3moe-moe.gguf.hdr", {534, 10}},- {"qwen35-dense.gguf.hdr", {387, 10}}, {"smollm3-dense.gguf.hdr", {368, 10}},+ {"bailingmoe2-moe.gguf.hdr", {473, 10}}, {"ernie4_5-moe-moe.gguf.hdr", {447, 10}},+ {"exaone4-dense.gguf.hdr", {418, 11}}, {"gemma-dense.gguf.hdr", {365, 10}},+ {"gemma2-dense.gguf.hdr", {415, 11}}, {"glm4moe-moe.gguf.hdr", {485, 10}},+ {"gpt-oss-moe.gguf.hdr", {574, 11}}, {"hunyuan-dense-dense.gguf.hdr", {416, 10}},+ {"hunyuan-moe-moe.gguf.hdr", {534, 10}}, {"llama-dense.gguf.hdr", {400, 10}},+ {"llama-moe.gguf.hdr", {506, 10}}, {"maincoder-dense.gguf.hdr", {432, 10}},+ {"minicpm-dense.gguf.hdr", {398, 10}}, {"minicpm-moe.gguf.hdr", {504, 10}},+ {"minimax-m2-moe.gguf.hdr", {534, 10}}, {"mistral3-dense.gguf.hdr", {400, 10}},+ {"mistral3-moe.gguf.hdr", {506, 10}}, {"olmoe-moe.gguf.hdr", {534, 10}},+ {"phi3-dense.gguf.hdr", {380, 10}}, {"qwen2-dense.gguf.hdr", {368, 10}},+ {"qwen3-dense.gguf.hdr", {416, 10}}, {"qwen3moe-moe.gguf.hdr", {550, 10}},+ {"qwen35-dense.gguf.hdr", {395, 10}}, {"smollm3-dense.gguf.hdr", {384, 10}},};return fp;}+using GraphDependency = std::pair<std::string, std::string>;++const std::map<std::string, std::vector<GraphDependency>>& graph_dependencies() {+ static const std::map<std::string, std::vector<GraphDependency>> dependencies{+ {"hunyuan-dense-dense.gguf.hdr", {{"blk.0.Qcur_rope", "blk.0.Qcur_normed"}}},+ {"hunyuan-moe-moe.gguf.hdr", {{"blk.0.Qcur_rope", "blk.0.Qcur_normed"}}},+ {"qwen3-dense.gguf.hdr", {{"blk.0.Qcur_normed", "blk.0.Qcur_rope"}}},+ {"qwen3moe-moe.gguf.hdr", {{"blk.0.Qcur_normed", "blk.0.Qcur_rope"}}},+ };+ return dependencies;+}++std::shared_ptr<ov::Node> find_node(const std::shared_ptr<ov::Model>& model, const std::string& name) {+ const auto ops = model->get_ordered_ops();+ const auto it = std::find_if(ops.begin(), ops.end(), [&](const std::shared_ptr<ov::Node>& node) {+ const auto& friendly_name = node->get_friendly_name();+ return friendly_name.find(name) != std::string::npos && friendly_name.find(name + ".") == std::string::npos;+ });+ return it == ops.end() ? nullptr : *it;+}++bool is_ancestor(const std::shared_ptr<ov::Node>& ancestor, const std::shared_ptr<ov::Node>& descendant) {+ std::vector<std::shared_ptr<ov::Node>> pending;+ for (const auto& input : descendant->input_values()) {+ pending.push_back(input.get_node_shared_ptr());+ }+ std::set<const ov::Node*> visited;+ while (!pending.empty()) {+ const auto node = pending.back();+ pending.pop_back();+ if (node == ancestor) {+ return true;+ }+ if (!visited.insert(node.get()).second) {+ continue;+ }+ for (const auto& input : node->input_values()) {+ pending.push_back(input.get_node_shared_ptr());+ }+ }+ return false;+}+// A scratch directory that outlives one test, so the reconstructed .gguf can be written once per// test and removed afterwards without leaving multi-MB files behind on failure.class ScratchDir {@@ -246,6 +291,17 @@ TEST_P(GGUFArchConversion, MatchesManifestExpectation) {<< "update fingerprints() -- and say why in the commit message.";EXPECT_EQ(model->inputs().size(), it->second.inputs)<< "graph input count for " << fixture.header_file << " changed; see fingerprints().";+ if (const auto dependency_it = graph_dependencies().find(fixture.header_file);+ dependency_it != graph_dependencies().end()) {+ for (const auto& dependency : dependency_it->second) {+ const auto producer = find_node(model, dependency.first);+ const auto consumer = find_node(model, dependency.second);+ ASSERT_TRUE(producer) << fixture.header_file << " has no expected producer " << dependency.first;+ ASSERT_TRUE(consumer) << fixture.header_file << " has no expected consumer " << dependency.second;+ EXPECT_TRUE(is_ancestor(producer, consumer))+ << fixture.header_file << ": " << dependency.second << " must depend on " << dependency.first;+ }+ }break;}case Expectation::Reject: {diff --git a/src/frontends/gguf/tests/test_dequant_vs_ggml.cpp b/src/frontends/gguf/tests/test_dequant_vs_ggml.cppindex 795592eb06d..84c948fe507 100644--- a/src/frontends/gguf/tests/test_dequant_vs_ggml.cpp+++ b/src/frontends/gguf/tests/test_dequant_vs_ggml.cpp@@ -98,6 +98,16 @@ float max_abs_diff(const std::vector<float>& a, const std::vector<float>& b) {return m;}+float mean_squared_error(const std::vector<float>& a, const std::vector<float>& b) {+ EXPECT_EQ(a.size(), b.size());+ double sum = 0.0;+ for (size_t i = 0; i < a.size() && i < b.size(); ++i) {+ const double diff = static_cast<double>(a[i]) - b[i];+ sum += diff * diff;+ }+ return static_cast<float>(sum / a.size());+}+// One case: stem (test_data file prefix) + ggml quant enum + tolerance. rows/cols match the// generator. Q5_K/Q6_K go through the channel-wise Q8_0_C requantization (matching the// llama.cpp ggml-openvino CPU/GPU backend), so they diverge from ggml's faithful to_float by@@ -112,10 +122,9 @@ constexpr uint64_t kRows = 4;constexpr uint64_t kCols = 256;constexpr float kTolFaithful = 3e-3f; // f16-scale dequant noiseconstexpr float kTolRequant = 1.5e-2f; // channel-wise Q8_0_C requant round-off-// Q4_K uses an INTEGER (u8) zero-point so the CPU plugin fuses the dequant into the MatMul-// (matching the original ggml-openvino backend). The integer zp rounds min to a multiple of-// scale, so the dequant diverges from ggml's faithful to_float by up to ~0.045 per weight.-constexpr float kTolIntZp = 5e-2f;+// Q4_K is faithfully decoded and then requantized in its native 32-value groups to OpenVINO u4.+// Keep its worst error below the former rounded-zero-point path's 5e-2 tolerance.+constexpr float kTolU4Requant = 4e-2f;// Q2_0: (code - 1) * d on both sides and the zero-point of 1 is exact, so hold it to bit-equality.constexpr float kTolExact = 0.0f;@@ -136,6 +145,30 @@ TEST_P(DequantVsGGML, MatchesGgmlToFloat) {<< c.stem << ": frontend dequant diverges from ggml to_float beyond tolerance";}+// Guard both aggregate quality and the worst outlier against the real ggml CPU oracle. The+// previous SSE-only candidate selection lowered MSE but raised max error above 5e-2.+TEST(DequantVsGGML, Q4KRequantizationImprovesWithoutOutliers) {+ const auto qbytes = load_npy<uint8_t>("q4_k_qbytes");+ const auto ref = load_npy<float>("q4_k_deq");+ const auto ours = frontend_dequant(GGUF_TYPE_Q4_K, qbytes, kRows, kCols);++ ASSERT_EQ(ours.size(), ref.size());+ EXPECT_LE(mean_squared_error(ours, ref), 2.8e-4f);+ EXPECT_LE(max_abs_diff(ours, ref), kTolU4Requant);+}++TEST(DequantVsGGML, Q4KRejectsNonFiniteScaleMetadata) {+ const auto valid = load_npy<uint8_t>("q4_k_qbytes");+ constexpr uint16_t inf_f16 = 0x7c00;+ constexpr uint16_t nan_f16 = 0x7e00;++ for (const auto& [offset, bits] : {std::pair<size_t, uint16_t>{0, inf_f16}, {2, nan_f16}}) {+ auto malformed = valid;+ std::memcpy(malformed.data() + offset, &bits, sizeof(bits));+ EXPECT_ANY_THROW(frontend_dequant(GGUF_TYPE_Q4_K, malformed, kRows, kCols));+ }+}+// The faithful per-row K-quant dequant used as the Q8_0_C requant source must match ggml's// to_float almost exactly (f16 super-scale widening only): assert tight agreement with the ggml// reference. A loose result here means a byte-layout/index bug (which would silently corrupt the@@ -181,7 +214,7 @@ INSTANTIATE_TEST_SUITE_P(AllQuantTypes,DeqCase{"q8_0", GGUF_TYPE_Q8_0, kTolFaithful},DeqCase{"q2_k", GGUF_TYPE_Q2_K, kTolFaithful},DeqCase{"q3_k", GGUF_TYPE_Q3_K, kTolFaithful},- DeqCase{"q4_k", GGUF_TYPE_Q4_K, kTolIntZp},+ DeqCase{"q4_k", GGUF_TYPE_Q4_K, kTolU4Requant},DeqCase{"q5_k", GGUF_TYPE_Q5_K, kTolRequant},DeqCase{"q6_k", GGUF_TYPE_Q6_K, kTolRequant},// Q2_0 is bit-exact: both sides compute (code - 1) * ddiff --git a/src/frontends/gguf/tests/test_ops.cpp b/src/frontends/gguf/tests/test_ops.cppindex fb3b060b0cf..66cb471aefd 100644--- a/src/frontends/gguf/tests/test_ops.cpp+++ b/src/frontends/gguf/tests/test_ops.cpp@@ -1284,6 +1284,33 @@ TEST(GGUFOps, SetRowsFlattenedCache) {expect_near(out, expected, 0.0f);}+// Real KV layout is [batch, context, heads, head_size], while SET_ROWS indices address the+// flattened context/head rows. Append one token's two heads at context slot 1 and preserve slot 0.+TEST(GGUFOps, SetRowsAppendsToKvCache) {+ constexpr size_t context = 2, heads = 2, head_size = 2;+ auto model = SingleOpBuilder()+ .op("GGML_OP_SET_ROWS")+ .input("data", ov::element::f32, {1, 1, heads, head_size})+ .input("ind", ov::element::i64, {1, 1, 1, heads})+ .input("dst", ov::element::f32, {1, context, heads, head_size})+ .output("out", ov::element::f32, {1, context, heads, head_size})+ .build();++ std::vector<float> data{10, 11, 20, 21};+ std::vector<int64_t> ind{2, 3};+ std::vector<float> dst{1, 2, 3, 4, -1, -1, -1, -1};++ ov::Tensor ind_t(ov::element::i64, ov::Shape{1, 1, 1, heads});+ std::copy(ind.begin(), ind.end(), ind_t.data<int64_t>());+ auto out = run_on_cpu(model,+ {{"data", make_f32_tensor({1, 1, heads, head_size}, data)},+ {"ind", ind_t},+ {"dst", make_f32_tensor({1, context, heads, head_size}, dst)}});++ std::vector<float> expected{1, 2, 3, 4, 10, 11, 20, 21};+ expect_near(out, expected, 0.0f);+}+// Reference for the frontend's make_sin_cos on the NEOX (non-imrope) path: for a single position p,// theta[j] = p * freq_scale * factor[j], factor[0]=1, factor[j]=theta_scale^j,// theta_scale = freq_base^(-2/n_dims); cos/sin scaled by attn_factor. ext_factor is 0 here.diff --git a/src/frontends/gguf/tests/test_weights.cpp b/src/frontends/gguf/tests/test_weights.cppindex ef9e0cb1fbc..d2ac87bdc35 100644--- a/src/frontends/gguf/tests/test_weights.cpp+++ b/src/frontends/gguf/tests/test_weights.cpp@@ -29,10 +29,8 @@ constexpr size_t kRows = 4;constexpr size_t kCols = 256;constexpr float kTolFaithful = 3e-3f;constexpr float kTolRequant = 1.5e-2f;-// Q4_K uses an INTEGER (u8) zero-point so the CPU plugin fuses the dequant into the MatMul-// (matching the original ggml-openvino backend); the integer zp diverges from ggml's faithful-// to_float by up to ~0.045 per weight.-constexpr float kTolIntZp = 5e-2f;+// Native Q4_K group-wise requantization improves on the former 5e-2 integer-zp tolerance.+constexpr float kTolU4Requant = 4e-2f;struct WeightCase {const char* stem; // test_data prefix@@ -85,7 +83,7 @@ INSTANTIATE_TEST_SUITE_P(AllQuantTypes,WeightCase{"q8_0", "Q8_0", kTolFaithful},WeightCase{"q2_k", "Q2_K", kTolFaithful},WeightCase{"q3_k", "Q3_K", kTolFaithful},- WeightCase{"q4_k", "Q4_K", kTolIntZp},+ WeightCase{"q4_k", "Q4_K", kTolU4Requant},WeightCase{"q5_k", "Q5_K", kTolRequant},WeightCase{"q6_k", "Q6_K", kTolRequant},WeightCase{"q2_0", "Q2_0", kTolFaithful}),@@ -296,3 +294,11 @@ TEST(GGUFWeight, RejectsMissingAuxiliaryTensors) {WeightTensors without_zero_point{ov::Tensor(ov::element::u32, {1, 4}), ov::Tensor(ov::element::f16, {1, 1}), {}};EXPECT_THROW(make_weight_node(without_zero_point, GGUF_TYPE_Q4_K), ov::Exception);}++TEST(GGUFWeight, UsesIntegerZeroPointForQ4KMatmulWeights) {+ using namespace ov::frontend::gguf;++ EXPECT_EQ(gguf_zero_point_type("blk.0.attn_q.weight", GGUF_TYPE_Q4_K), ov::element::u8);+ EXPECT_EQ(gguf_zero_point_type("token_embd.weight", GGUF_TYPE_Q4_K), ov::element::f16);+ EXPECT_EQ(gguf_zero_point_type("blk.0.attn_q.weight", GGUF_TYPE_Q2_0), ov::element::u8);+}diff --git a/tests/model_hub_tests/gguf/gguf_models_nightly b/tests/model_hub_tests/gguf/gguf_models_nightlyindex 3694dba5add..2c565ef3567 100644--- a/tests/model_hub_tests/gguf/gguf_models_nightly+++ b/tests/model_hub_tests/gguf/gguf_models_nightly@@ -1,6 +1,6 @@# List of larger models (roughly 7B-30B parameters) used to verify the GGUF frontend converts,-# compiles, and runs a single forward step correctly for each supported architecture that has-# no small (<=4B) checkpoint available.+# compiles, and runs two state-carrying forward steps correctly for each supported architecture+# that has no small (<=4B) checkpoint available.## Format: arch,repo_id,filename[,mark,reason]# arch - architecture name (matches src/frontends/gguf/docs/supported_models.md)diff --git a/tests/model_hub_tests/gguf/gguf_models_precommit b/tests/model_hub_tests/gguf/gguf_models_precommitindex 540ce58288e..40b45c875df 100644--- a/tests/model_hub_tests/gguf/gguf_models_precommit+++ b/tests/model_hub_tests/gguf/gguf_models_precommit@@ -1,5 +1,5 @@# List of small models (roughly <=4B parameters) used to verify the GGUF frontend converts,-# compiles, and runs a single forward step correctly for each supported architecture.+# compiles, and runs two state-carrying forward steps correctly for each supported architecture.## Format: arch,repo_id,filename[,mark,reason]# arch - architecture name (matches src/frontends/gguf/docs/supported_models.md)diff --git a/tests/model_hub_tests/gguf/test_gguf.py b/tests/model_hub_tests/gguf/test_gguf.pyindex 9b7567bb7e1..fdc5de1a30d 100644--- a/tests/model_hub_tests/gguf/test_gguf.py+++ b/tests/model_hub_tests/gguf/test_gguf.py@@ -5,12 +5,10 @@# Verifies the GGUF frontend against real .gguf checkpoints downloaded from the Hugging Face# Hub, one per architecture listed in src/frontends/gguf/docs/supported_models.md.#-# Each test downloads one .gguf file, converts it with core.read_model(), compiles it, and-# runs a single forward step (one new token, no prior context -- see utils.py for why that is-# enough to exercise the frontend's default stateless lowering without extra setup). The-# check is deliberately shallow: a finite, correctly shaped logits tensor. It does not build a-# tokenizer or run more than one step, since this suite is about frontend conversion/inference-# correctness, not generation quality or text coherence (which+# Each test downloads one .gguf file, converts it, compiles it, and runs two forward steps,+# feeding the cache/state outputs of the first step into the second. The checks cover finite,+# correctly shaped logits and populated, changing KV caches. The suite does not build a tokenizer+# because it verifies frontend conversion/inference correctness rather than text coherence (which# src/frontends/gguf/tests/compare_with_llama.py and the GenAI-based harness described in# supported_models.md already cover for the architectures where that matters).#diff --git a/tests/model_hub_tests/gguf/utils.py b/tests/model_hub_tests/gguf/utils.pyindex b2d978af738..f24fa5e09fe 100644--- a/tests/model_hub_tests/gguf/utils.py+++ b/tests/model_hub_tests/gguf/utils.py@@ -54,26 +54,31 @@ def _kv_cache_head_count(compiled_model) -> int:return 1-def build_single_token_inputs(compiled_model, token_id: int = 1, is_imrope: bool = False):+def build_single_token_inputs(+ compiled_model,+ token_id: int = 1,+ position: int = 0,+ state: dict[str, np.ndarray] | None = None,+ is_imrope: bool = False,+ kv_cache_length: int = 1,+):"""Build a minimal, single-new-token input feed for the GGUF frontend's stateless IOcontract (inp_tokens / inp_pos / inp_out_ids / self_kq_mask[_swa] / token_len_per_seq /inp_kv_idx), plus zero-filled tensors for every other input the model declares (per-layerKV caches and, for hybrid/recurrent architectures such as qwen35, the fully-static conv /delta state Parameters).- This deliberately does not model real multi-token generation or attend to any real- prompt/tokenizer: with T=1 (one new token, no prior context) every KV cache write covers- the cache in full, so the frontend's default (caller-extension-free) SetRows lowering- -- a plain ScatterUpdate over the whole cache -- is well-defined without requiring the- caller to also register the MakeStateful extension. That keeps this check to exactly- what "verify basic correctness" needs: the model converts, compiles, and produces a- finite, correctly shaped output for one forward pass.+ state contains cache outputs from a preceding inference step. Passing them back as the+ matching inputs exercises the frontend's stateless state contract on decode. For a decode+ step, kv_cache_length grows the K/V inputs and targets their last slot, preserving every+ earlier slot so attention reads both the history and the new token.is_imrope selects the interleaved M-RoPE position layout (qwen35 / qwen3vl), read fromthe model's "gguf_is_imrope" rt_info by the caller (CompiledModel does not exposert_info, so this must be read from the ov.Model before compiling): such a model expectsinp_pos to carry 4 position sections per token instead of 1."""+ assert kv_cache_length >= 1n_head_kv = _kv_cache_head_count(compiled_model)n_pos_sections = 4 if is_imrope else 1feed = {}@@ -84,11 +89,11 @@ def build_single_token_inputs(compiled_model, token_id: int = 1, is_imrope: boolif name == "inp_tokens":feed[name] = ov.Tensor(np.array([[[[token_id]]]], dtype=np.int32))elif name == "inp_pos":- feed[name] = ov.Tensor(np.zeros((1, 1, 1, n_pos_sections), dtype=np.int32))+ feed[name] = ov.Tensor(np.full((1, 1, 1, n_pos_sections), position, dtype=np.int32))elif name == "inp_out_ids":feed[name] = ov.Tensor(np.array([[[[0]]]], dtype=np.int32))elif name in ("self_kq_mask", "self_kq_mask_swa"):- feed[name] = ov.Tensor(np.zeros((1, 1, 1, 1), dtype=np.float32))+ feed[name] = ov.Tensor(np.zeros((1, 1, 1, kv_cache_length), dtype=np.float32))elif name == "token_len_per_seq":feed[name] = ov.Tensor(np.array([1], dtype=np.int64))elif name == "beam_idx":@@ -96,8 +101,19 @@ def build_single_token_inputs(compiled_model, token_id: int = 1, is_imrope: boolelif name == "inp_kv_idx":# One write index per (new token, kv head): translate_set_rows flattens the new# rows to [.., 1, tokens * n_head_kv, row_size] before the default ScatterUpdate- # lowering, so indices must cover that same flattened extent.- feed[name] = ov.Tensor(np.arange(n_head_kv, dtype=np.int32).reshape(1, 1, 1, n_head_kv))+ # lowering. Target the final context slot while leaving earlier cache rows intact.+ first_index = (kv_cache_length - 1) * n_head_kv+ indices = np.arange(first_index, first_index + n_head_kv, dtype=np.int32)+ feed[name] = ov.Tensor(indices.reshape(1, 1, 1, n_head_kv))+ elif state is not None and name in state:+ value = state[name]+ if name.startswith(("cache_k_", "cache_v_")) and value.shape[1] < kv_cache_length:+ shape = list(value.shape)+ shape[1] = kv_cache_length+ extended = np.zeros(shape, dtype=value.dtype)+ extended[:, : value.shape[1], ...] = value+ value = extended+ feed[name] = ov.Tensor(value)else:# Any other input (a per-layer KV cache, or a recurrent/linear-attention state# such as qwen35's Gated-DeltaNet conv window and delta matrix): zero-fill,@@ -122,8 +138,79 @@ def convert_gguf_model(path: str) -> ov.Model:return fe.convert(fe.load(path))+def _state_outputs(compiled_model, outputs) -> dict[str, np.ndarray]:+ """Copy state outputs and map them back to their corresponding input names."""+ data_input_names = {+ "beam_idx",+ "inp_kv_idx",+ "inp_out_ids",+ "inp_pos",+ "inp_tokens",+ "self_kq_mask",+ "self_kq_mask_swa",+ "token_len_per_seq",+ }+ state_input_names = {+ next(iter(port.get_names()))+ for port in compiled_model.inputs+ if next(iter(port.get_names()), "") not in data_input_names+ }+ state = {}+ for port, value in outputs.items():+ state_name = port.get_node().get_friendly_name()+ if state_name.endswith("_1"):+ state_name = state_name[:-2]+ if state_name.endswith("_out"):+ state_name = state_name[:-4]+ if state_name in state_input_names:+ state[state_name] = np.array(value, copy=True)++ assert state.keys() == state_input_names, "GGUF state outputs do not match state inputs"+ return state+++def _assert_valid_kv_cache(state: dict[str, np.ndarray]):+ kv_tensors = {name: value for name, value in state.items() if name.startswith(("cache_k_", "cache_v_"))}+ assert kv_tensors, "GGUF model exposes no K/V cache tensors"+ for name, value in kv_tensors.items():+ assert value.size > 0, f"{name} is empty"+ assert np.isfinite(value).all(), f"{name} contains NaN/Inf"+ assert np.any(value != 0), f"{name} was not populated"+++def _run_two_steps(compiled_model, is_imrope: bool) -> np.ndarray:+ request = compiled_model.create_infer_request()++ first_feed = build_single_token_inputs(compiled_model, token_id=1, is_imrope=is_imrope)+ first_outputs = request.infer(first_feed)+ first_state = _state_outputs(compiled_model, first_outputs)+ _assert_valid_kv_cache(first_state)++ second_feed = build_single_token_inputs(+ compiled_model,+ token_id=2,+ position=1,+ state=first_state,+ is_imrope=is_imrope,+ kv_cache_length=2,+ )+ second_outputs = request.infer(second_feed)+ second_state = _state_outputs(compiled_model, second_outputs)+ _assert_valid_kv_cache(second_state)++ kv_names = [name for name in first_state if name.startswith(("cache_k_", "cache_v_"))]+ for name in kv_names:+ assert second_state[name].shape[1] == 2, f"{name} did not grow to two context slots"+ assert np.array_equal(first_state[name][:, 0, ...], second_state[name][:, 0, ...]), (+ f"{name} did not preserve the first-step cache slot"+ )+ assert np.any(second_state[name][:, 1, ...] != 0), f"{name} did not populate the second cache slot"++ return second_outputs[compiled_model.output(0)]++def run_gguf_model(repo_id: str, filename: str, device: str = "CPU"):- """Download, convert, compile, and run one forward step of a .gguf model.+ """Download, convert, compile, and run two state-carrying steps of a .gguf model.Returns the raw logits tensor as a numpy array. Raises on any conversion / compilation /inference failure; the caller is expected to additionally sanity-check the result (shape,@@ -136,10 +223,7 @@ def run_gguf_model(repo_id: str, filename: str, device: str = "CPU"):if "gguf_is_imrope" in model.get_rt_info():is_imrope = bool(model.get_rt_info(["gguf_is_imrope"]).get())compiled_model = core.compile_model(model, device)- request = compiled_model.create_infer_request()- feed = build_single_token_inputs(compiled_model, is_imrope=is_imrope)- outputs = request.infer(feed)- return next(iter(outputs.values()))+ return _run_two_steps(compiled_model, is_imrope)def assert_valid_logits(logits: np.ndarray):