Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[GGUF] Preserve packed ternary weights and expose GPU fusion patterns (#39081)

Maxim Vafinc3d58b4dfbe1
diff --git a/src/frontends/gguf/docs/mmproj.md b/src/frontends/gguf/docs/mmproj.md
index 474f0359aff..a96c21f176c 100644
--- a/src/frontends/gguf/docs/mmproj.md
+++ b/src/frontends/gguf/docs/mmproj.md
@@ -31,10 +31,7 @@ numerical fixture checked against the llama.cpp CPU encoder (see
| Audio | `gemma4ua` | raw 640-sample waveform frames |
| Audio | `qwen2a`, `ultravox`, `voxtral`, `musicflamingo`, `meralion`, `glma` | Whisper-derived encoders |
-Bonsai-27B, Ternary-Bonsai-27B and Ternary-Bonsai-2-27B BF16 and Q8_0 projector files are
-supported by the built-in `qwen3vl_merger` projector. They use patch size 16, spatial merge 2,
-output width 5120 and no DeepStack outputs. Load these files directly through the native GGUF
-frontend.
+The built-in `qwen3vl_merger` projector supports BF16 and Q8_0 weights.
InternViT-6B (width 3200, 45 layers) uses RMS norms like the reference, but has no fixture.
diff --git a/src/frontends/gguf/docs/quantization.md b/src/frontends/gguf/docs/quantization.md
index e1d9a5a1aaa..8f4833fb8b3 100644
--- a/src/frontends/gguf/docs/quantization.md
+++ b/src/frontends/gguf/docs/quantization.md
@@ -28,6 +28,13 @@ with the first element in the least significant bits. The loader's `u32` tensors
Q4_1/Q4_K are backing buffers for eight nibbles per word; their graph Constants use `u4`.
Unpacking into `u2` or `i4` therefore does not mean allocating one byte per weight.
+For ternary embedding row lookups, the frontend views the same `u2` buffer as `u8` bytes,
+with four codes in each byte. It gathers the requested code bytes and scales before
+unpacking the selected rows with integer shifts and masks. The dictionary keeps its
+original two-bit storage; it does not expand to an entire floating-point table. The
+selected codes use I32 arithmetic for shifts, then the original F16 dequantization.
+Matrix multiplication consumers keep their `u2` representation, including tied weights.
+
The usual graph is `Convert -> [Subtract] -> Multiply -> Reshape -> Convert(F32)`. Decompression
uses the scale's element type, normally F16. Q6_K, Q8_1 and formats with fractional F16 zero points
and code widths of at least four bits instead perform subtraction/multiplication in F32.
@@ -47,7 +54,7 @@ the weight values and adds quantization error.
but exclude object metadata, shape Constants, allocator alignment and file padding. Each row
compares the same number of logical weights; a negative change means smaller storage.
-The type columns describe stored Constants; their decompression or Convert outputs are F32.
+The type columns describe extracted tensors; their decompression or Convert outputs are F32.
| Format | Weights per GGUF block | GGUF bytes | Weight type (`W`) | Scale type (`S`) | Zero-point type (`Z`) | Native OpenVINO bytes (`W + S + Z`) | Change |
|---|---:|---:|---|---|---|---:|---:|
@@ -55,8 +62,8 @@ The type columns describe stored Constants; their decompression or Convert outpu
| F16, BF16 | 1 | 2 | `f16`, `bf16` respectively | — | — | 2 | 0% |
| Q1_0 | 128 | 18 | `u1` | `f16` | — | `16 + 2` = 18 | 0% |
| Q2_0 (per-64) | 64 | 18 | `u2` | `f16` | `u8` | `16 + 2 + 1` = 19 | +5.6% |
-| PQ2_0 | 128 | 34 | `u2` | `f16` | `u8` | `32 + 2 + 1` = 35 | +2.9% |
-| PTQ1_0 | 128 | 28 | `u2` | `f16` | `u8` | `32 + 2 + 1` = 35 | +25.0% |
+| PQ2_0, ternary codes | 128 | 34 | `u2` | `f16` | scalar `f16` | 34, plus 2 per tensor | 0% group payload |
+| PTQ1_0 | 128 | 28 | `u2` | `f16` | scalar `f16` | 34, plus 2 per tensor | +21.4% group payload |
| Q2_K | 256 | 84 | `u2` | `f16` | `f16` | `64 + 32 + 32` = 128 | +52.4% |
| Q3_K | 256 | 110 | `i4` | `f16` | — | `128 + 32` = 160 | +45.5% |
| Q4_0 | 32 | 18 | `i4` | `f16` | — | `16 + 2` = 18 | 0% |
@@ -84,13 +91,17 @@ Group size remains 32 for all devices.
`token_embd.weight` and `output.weight` use fractional zero points for these affine formats;
Q5_1 and Q2_K also use fractional zero points. See [accuracy controls](#accuracy-controls)
to select fractional zero points for all Q4_1/Q4_K tensors.
-Q2_0/PQ2_0/PTQ1_0 always use a `u8` zero point of 1 in this path, including embeddings.
+Q2_0 uses a `u8` zero point of 1. PQ2_0/PTQ1_0 use F16 zero points of 1,
+including embeddings.
The frontend prints an accuracy notice once per process for each requantization approximation.
-For example, PQ2_0 adds one byte per 128 weights. PTQ1_0 adds six code bytes plus one zero-point
-byte per 128 weights. Their native storage is identical, at `35/128` bytes per weight
-(2.1875 bits per weight including metadata). The repeated zero point is currently allocated
-per group; the table does not assume that a later pass replaces it with a scalar.
+PTQ1_0 adds six code bytes per 128 weights. For PQ2_0/PTQ1_0 containing only codes
+0, 1 and 2, their native storage is identical, at `34/128` bytes per weight
+(2.125 bits per weight including scales), plus one two-byte zero-point Constant per tensor.
+Code 3 retains a grouped Constant and the existing GPU fallback, using 36 bytes per group.
+Projections sharing an activation input retain grouped zero points if any projection needs
+that fallback, including a singleton group. This keeps their layouts compatible with
+horizontal fusion without changing plugins; all-ternary projection groups remain scalar.
## Floating-point formats
@@ -124,12 +135,14 @@ increase execution and compilation memory despite the compact frontend represent
Q2_0 stores `F16 scale | 16 code bytes` for 64 weights. PQ2_0 (type 142) stores
`F16 scale | 32 code bytes` for 128 weights. Both already pack four two-bit codes per byte in
-OpenVINO element order, so the code bytes are copied directly. The scale is separated and
-one `u8` zero point of 1 is written per group. Reconstruction is `(code - 1) * scale`;
+OpenVINO element order, so the code bytes are copied directly. The scale is separated.
+Q2_0 uses a `u8` zero point of 1 per group; PQ2_0 uses an FP16 scalar zero point of 1
+for strictly ternary tensors. Tensors containing
+code 3 retain grouped FP16 zero points. Reconstruction is `(code - 1) * scale`;
codes 0, 1 and 2 represent -1, 0 and +1. A code of 3 reconstructs +2.
-No code or scale requantization is introduced. The extra storage is the repeated zero point.
-Older Bonsai files also use type 42 (`Q2_0`) for per-128 blocks. Native loading identifies
+No code or scale requantization is introduced.
+Legacy files can also use type 42 (`Q2_0`) for per-128 blocks. Native loading identifies
that layout using dimensions and aligned tensor spans and maps it to PQ2_0. Raw-byte callers
must provide the actual format because they do not supply those descriptor spans.
@@ -137,7 +150,7 @@ must provide the actual format because they do not supply those descriptor spans
PTQ1_0 (type 143) stores `26 dense-trit bytes | F16 scale` for 128 weights. The first 16 bytes
encode five trits each, the next eight encode five each, and the last two encode four each:
-`16*5 + 8*5 + 2*4 = 128`. This is Prism's scaled-byte encoding, decoded in the following order:
+`16*5 + 8*5 + 2*4 = 128`. This scaled-byte encoding is decoded in the following order:
```text
for (start, count, trits) in [(0, 16, 5), (16, 8, 5), (24, 2, 4)]:
@@ -157,16 +170,6 @@ Convert/Subtract/Multiply/Reshape decomposition.
The conversion preserves trit values but expands their dense storage to two bits per code.
It also requires more import work than PQ2_0's direct copy.
-### Bonsai-2 Hadamard transforms
-
-Bonsai-2's folded Hadamard weights require the model's `prism.hadamard.*` metadata for
-activation and inverse embedding transforms, even for F16 checkpoints. This is separate from
-unpacking. Each block uses a Walsh–Hadamard butterfly with `log2(block_size)` stages of
-sum/difference operations and a final normalization by `1/sqrt(block_size)`. This avoids a
-dense rotation Constant and reduces arithmetic from quadratic to `O(block_size * log2(block_size))`;
-intermediate activation buffers still depend on device compilation. See
-[Bonsai and Bonsai-2](supported_models.md#bonsai-and-bonsai-2).
-
## Integer formats
### Q4_0
diff --git a/src/frontends/gguf/docs/supported_models.md b/src/frontends/gguf/docs/supported_models.md
index 434f3f4bd24..833beb0b168 100644
--- a/src/frontends/gguf/docs/supported_models.md
+++ b/src/frontends/gguf/docs/supported_models.md
@@ -54,8 +54,8 @@ with the [strict accuracy settings](quantization.md#accuracy-controls) (`OV_GGUF
| `phi3` | Fused QKV | — | |
| `plamo3` | Fused QKV and gate/up, bare post-norms, SWA | plamo-3-nict-2b-base Q4_K_M | 12/13 |
| `qwen2` | qwen2 / qwen2.5 | — | |
-| `qwen3` | QK-norm before RoPE; also Bonsai-8B (Q1_0) | — | |
-| `qwen35` | Hybrid GatedDeltaNet + attention, interleaved M-RoPE; batching and beam search with SDPA and PA; also Bonsai-27B (Q1_0), Ternary-Bonsai-27B (Q2_0 g64) | — | |
+| `qwen3` | QK-norm before RoPE | — | |
+| `qwen35` | Hybrid GatedDeltaNet + attention, interleaved M-RoPE, folded Hadamard weights; batching and beam search with SDPA and PA | — | |
| `qwen35moe` | Hybrid GatedDeltaNet, separate or fused routed experts, shared expert | Qwen3.6-35B-A3B Q4_K_M / Q4_0 | 13/13 / 12/13 |
| `qwen3moe` | NEOX RoPE, per-head QK-norm, normalized experts | Qwen3-0.9B-A0.6B Q4_K_M | 13/13 |
| `smollm3` | NORMAL RoPE, skipped on every fourth layer | SmolLM3-3B Q4_K_M | 12/13 |
@@ -158,32 +158,11 @@ require the `gguf-frontend-mmproj` integration. Older Mimi-based LFM2 speech out
requires a separate codec. Other sizes, quantizations, long contexts,
and downstream fine-tunes require their own checkpoint validation.
-## Bonsai and Bonsai-2
-
-The native GGUF frontend supports the following model families and weight formats:
-
-| Family | Sizes | Architecture | Weight formats |
-|---|---|---|---|
-| Bonsai | 1.7B, 4B, 8B | `qwen3` | Q1_0 |
-| Bonsai | 27B | `qwen35` | Q1_0, F16 |
-| Ternary-Bonsai | 1.7B, 4B, 8B | `qwen3` | F16, Q2_0 per-64/per-128, PQ2_0 |
-| Ternary-Bonsai | 27B | `qwen35` | F16, Q2_0 per-64/per-128, PQ2_0 |
-| Ternary-Bonsai-2 | 27B | `qwen35` | F16, PQ2_0, PTQ1_0, development Q2_0 per-64 |
-
-Bonsai-2 uses folded Hadamard weights, including its F16 checkpoints. Supported metadata is
-version 1 or tied-output version 2, normalized Sylvester, input-last-dimension, identity or
-explicit ±1 signs, and blocks up to 4096. The frontend applies the input activation transform
-for annotated projections and the inverse transform after latent token lookup, preserving
-annotations when splitting QKV and Q/gate weights.
-
-The BF16 and Q8_0 multimodal projector variants are supported directly by the built-in
-`qwen3vl_merger`; see [supported projectors](mmproj.md#supported-projectors).
-
## Block drafters
-| Architecture | Supported models | Features |
-|---|---|---|
-| `dspark` | Bonsai-27B and Ternary-Bonsai-27B BF16/Q4_1 drafts | Noncausal block attention, captured target features, log-SNR conditioning, optional Markov/confidence outputs |
+| Architecture | Features |
+|---|---|
+| `dspark` | Noncausal block attention, captured target features, log-SNR conditioning, optional Markov/confidence outputs |
DSpark accepts a fixed draft block in `inp_tokens` and captured target-layer features in
`dspark_ctx_feat` (`[1,1,context_rows,capture_count*embedding_width]`). Positions and cache-write
diff --git a/src/frontends/gguf/src/builder/blocks/attention.cpp b/src/frontends/gguf/src/builder/blocks/attention.cpp
index 9bed3a4ebf3..8b6ddda245c 100644
--- a/src/frontends/gguf/src/builder/blocks/attention.cpp
+++ b/src/frontends/gguf/src/builder/blocks/attention.cpp
@@ -4,6 +4,7 @@
#include "builder/blocks/attention.hpp"
+#include <algorithm>
#include <map>
#include <vector>
@@ -80,7 +81,16 @@ std::string attention(GraphEmitter& e,
e.add_weight_from(p + "attn_v.weight", p + "attn_k");
}
}
- auto q = e.add_op("GGML_OP_MUL_MAT", p + "Qcur", {p + "attn_q.weight", attn_norm});
+ std::string q, gate;
+ if (e.weight_emitted(p + "attn_q_gate.weight")) {
+ const auto joint = e.add_op("GGML_OP_MUL_MAT", p + "q_gate", {p + "attn_q_gate.weight", attn_norm});
+ const auto projections =
+ split_interleaved_projection(e, joint, {p + "Qcur", p + "attn_gate_joint"}, cfg.n_head, head_size_l);
+ q = projections[0];
+ gate = projections[1];
+ } else {
+ q = e.add_op("GGML_OP_MUL_MAT", p + "Qcur", {p + "attn_q.weight", attn_norm});
+ }
std::string k, v;
if (has_own_kv) {
k = e.add_op("GGML_OP_MUL_MAT", p + "Kcur", {p + "attn_k.weight", attn_norm});
@@ -275,14 +285,47 @@ std::string attention(GraphEmitter& e,
6,
{{"reshape_target", std::vector<int64_t>{0, 1, -1, q_width}}, {"special_zero", true}});
- // muse-glimmer: sigmoid output gate. The gate is a projection of the PRE-attention
- // normed hidden (the same `attn_norm` tensor Q/K/V come from), squashed by sigmoid and
- // multiplied elementwise into the merged attention output before the wo projection.
if (cfg.has_attn_gate) {
- e.add_weight(p + "attn_gate.weight");
- auto gate = e.add_op("GGML_OP_MUL_MAT", p + "attn_gate", {p + "attn_gate.weight", attn_norm});
+ bool rank3_gate;
+ if (!gate.empty()) {
+ rank3_gate = e.weight_tensor(p + "attn_q.weight").get_element_type() != ov::element::u2;
+ gate =
+ e.add_op("GGML_OP_RESHAPE",
+ p + "attn_gate",
+ {gate},
+ 6,
+ {{"reshape_target",
+ rank3_gate ? std::vector<int64_t>{0, -1, q_width} : std::vector<int64_t>{0, 1, -1, q_width}},
+ {"special_zero", true}});
+ } else {
+ e.add_weight(p + "attn_gate.weight");
+ const auto gate_weight = std::find_if(graph.nodes.begin(), graph.nodes.end(), [&](const auto& node) {
+ return node.name == p + "attn_gate.weight";
+ });
+ rank3_gate = gate_weight->attributes.at("gguf.blob.weight").template as<ov::Tensor>().get_element_type() !=
+ ov::element::u2;
+ gate = e.add_op("GGML_OP_MUL_MAT",
+ p + "attn_gate",
+ {p + "attn_gate.weight", attn_norm},
+ 0,
+ {{"activation_rank", rank3_gate ? 3 : 4}});
+ }
gate = e.add_op("GGML_UNARY_OP_SIGMOID", p + "attn_gate_sig", {gate});
- attn_2d = e.add_op("GGML_OP_MUL", p + "kqv_gated", {attn_2d, gate});
+ const auto gate_attention =
+ rank3_gate ? e.add_op("GGML_OP_RESHAPE",
+ p + "kqv_gate_input",
+ {attn_2d},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{0, -1, q_width}}, {"special_zero", true}})
+ : attn_2d;
+ const auto gated = e.add_op("GGML_OP_MUL", p + "kqv_gated", {gate_attention, gate});
+ attn_2d = rank3_gate
+ ? e.add_op("GGML_OP_RESHAPE",
+ p + "kqv_gated_4d",
+ {gated},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{0, 1, -1, q_width}}, {"special_zero", true}})
+ : gated;
}
// output projection (+ optional bias)
diff --git a/src/frontends/gguf/src/builder/blocks/common.cpp b/src/frontends/gguf/src/builder/blocks/common.cpp
index fddf9d628ec..77ac19fcff6 100644
--- a/src/frontends/gguf/src/builder/blocks/common.cpp
+++ b/src/frontends/gguf/src/builder/blocks/common.cpp
@@ -47,6 +47,38 @@ std::string add_bias(GraphEmitter& e, const std::string& x, const std::string& b
return e.add_op("GGML_OP_ADD", name, {x, bias_weight});
}
+std::array<std::string, 2> split_interleaved_projection(GraphEmitter& e,
+ const std::string& input,
+ const std::array<std::string, 2>& names,
+ int64_t groups,
+ int64_t width) {
+ const auto rank = e.value(input).get_partial_shape().rank().get_length();
+ std::vector<int64_t> grouped_shape(rank - 1, 0);
+ grouped_shape.insert(grouped_shape.end(), {groups, 2 * width});
+ const auto grouped = e.add_op("GGML_OP_RESHAPE",
+ input + "_grouped",
+ {input},
+ 6,
+ {{"reshape_target", grouped_shape}, {"special_zero", true}});
+ std::vector<int64_t> output_shape(rank - 1, 0);
+ output_shape.push_back(groups * width);
+ std::array<std::string, 2> outputs;
+ for (size_t i = 0; i < outputs.size(); ++i) {
+ const auto slice =
+ e.add_op("GGML_OP_VIEW",
+ names[i] + "_slice",
+ {grouped},
+ 3,
+ {{"view_slice", std::vector<int64_t>{rank, static_cast<int64_t>(i) * width, width}}});
+ outputs[i] = e.add_op("GGML_OP_RESHAPE",
+ names[i],
+ {slice},
+ 6,
+ {{"reshape_target", output_shape}, {"special_zero", true}});
+ }
+ return outputs;
+}
+
void store_parts(GraphEmitter& e, const std::string& base, const WeightTensors& t, GgufTensorType qtype) {
auto& w = e.weights();
w[base + ".weight"] = t.weight;
diff --git a/src/frontends/gguf/src/builder/blocks/common.hpp b/src/frontends/gguf/src/builder/blocks/common.hpp
index e69769a7f85..acf1962f4a7 100644
--- a/src/frontends/gguf/src/builder/blocks/common.hpp
+++ b/src/frontends/gguf/src/builder/blocks/common.hpp
@@ -4,6 +4,7 @@
#pragma once
+#include <array>
#include <optional>
#include <string>
#include <utility>
@@ -43,6 +44,12 @@ std::string bias_weight_name(const std::string& weight_name);
// Elementwise add of a (broadcast) bias weight: GGML_OP_ADD(x, bias_weight).
std::string add_bias(GraphEmitter& e, const std::string& x, const std::string& bias_weight, const std::string& name);
+std::array<std::string, 2> split_interleaved_projection(GraphEmitter& e,
+ const std::string& input,
+ const std::array<std::string, 2>& names,
+ int64_t groups,
+ int64_t width);
+
// Register the tensors of a derived weight `base` with quant type `qtype`.
void store_parts(GraphEmitter& e, const std::string& base, const WeightTensors& t, GgufTensorType qtype);
diff --git a/src/frontends/gguf/src/builder/blocks/ffn.cpp b/src/frontends/gguf/src/builder/blocks/ffn.cpp
index fc6df11cef8..3944397e6a6 100644
--- a/src/frontends/gguf/src/builder/blocks/ffn.cpp
+++ b/src/frontends/gguf/src/builder/blocks/ffn.cpp
@@ -22,18 +22,31 @@ std::string gated_gate_up(GraphEmitter& e,
const std::string& up_name,
const std::string& glu_name,
bool has_bias) {
- // Separate gate and up matmuls: a merged weight would copy both and keep the originals alive.
e.add_weight(gate_w);
- auto gate = e.add_op("GGML_OP_MUL_MAT", gate_name, {gate_w, ffn_norm});
+ e.add_weight(up_w);
+ const auto& shape = e.value(ffn_norm).get_partial_shape();
+ const bool rank3 = shape.rank() == 4 && shape[1] == 1 && shape[3].is_static() &&
+ e.value(gate_w).get_partial_shape().rank() == 2 && e.value(up_w).get_partial_shape().rank() == 2;
+ const std::map<std::string, ov::Any> attributes{{"activation_rank", rank3 ? 3 : 4}};
+ auto gate = e.add_op("GGML_OP_MUL_MAT", gate_name, {gate_w, ffn_norm}, 0, attributes);
if (has_bias) {
gate = add_bias(e, gate, bias_weight_name(gate_w), gate_name + "_b");
}
- e.add_weight(up_w);
- auto up = e.add_op("GGML_OP_MUL_MAT", up_name, {up_w, ffn_norm});
+ auto up = e.add_op("GGML_OP_MUL_MAT", up_name, {up_w, ffn_norm}, 0, attributes);
if (has_bias) {
up = add_bias(e, up, bias_weight_name(up_w), up_name + "_b");
}
- return e.add_op(glu_op, glu_name, {gate, up}, 0, {{"swapped", false}});
+ auto glu = e.add_op(glu_op, glu_name, {gate, up}, 0, {{"swapped", false}});
+ if (rank3) {
+ glu = e.add_op(
+ "GGML_OP_RESHAPE",
+ glu_name + "_4d",
+ {glu, ffn_norm},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{0, 0, 0, e.value(glu).get_partial_shape().rbegin()->get_length()}},
+ {"shape_axes", std::vector<int64_t>{0, 1, 2, -1}}});
+ }
+ return glu;
}
} // namespace
diff --git a/src/frontends/gguf/src/builder/blocks/ffn.hpp b/src/frontends/gguf/src/builder/blocks/ffn.hpp
index 75335777023..834fa050684 100644
--- a/src/frontends/gguf/src/builder/blocks/ffn.hpp
+++ b/src/frontends/gguf/src/builder/blocks/ffn.hpp
@@ -16,6 +16,15 @@ namespace ov::frontend::gguf::blocks {
// Each returns the sublayer output tensor name,
// before the residual add.
+std::string swiglu_gate_up(GraphEmitter& e,
+ const std::string& gate_w,
+ const std::string& up_w,
+ const std::string& ffn_norm,
+ const std::string& gate_name,
+ const std::string& up_name,
+ const std::string& glu_name,
+ bool has_bias);
+
// Dense SwiGLU FFN (llama/qwen/phi3/minicpm). Supports the fused gate+up projection (phi-3, no
// ffn_gate.weight) and optional per-projection biases (pangu-embedded), both auto-detected from
// the weight table.
diff --git a/src/frontends/gguf/src/builder/blocks/gated_delta_net.cpp b/src/frontends/gguf/src/builder/blocks/gated_delta_net.cpp
index 7130de7285d..3690e265b08 100644
--- a/src/frontends/gguf/src/builder/blocks/gated_delta_net.cpp
+++ b/src/frontends/gguf/src/builder/blocks/gated_delta_net.cpp
@@ -265,8 +265,11 @@ std::string gated_delta_net(GraphEmitter& e, const DecoderConfig& cfg, int il, c
graph.recurrent_states.emplace_back(cs, cs_out);
e.add_named_weight(conv_w);
- auto conv = e.add_op("GGML_OP_SSM_CONV", p + "conv_out", {conv_in, conv_w}, 0, {{"batch_major", true}});
- conv = e.add_op("GGML_UNARY_OP_SILU", p + "conv_silu", {conv});
+ auto conv = e.add_op("GGML_OP_SSM_CONV",
+ p + "conv_silu",
+ {conv_in, conv_w},
+ 0,
+ {{"batch_major", true}, {"fuse_silu", true}});
// ---- split the conv output into q | k | v; the fused op L2-normalizes q/k ----
auto slice_heads = [&](const std::string& name, int64_t off, int64_t width, int64_t heads, int64_t dim) {
diff --git a/src/frontends/gguf/src/builder/blocks/qkv_repack.cpp b/src/frontends/gguf/src/builder/blocks/qkv_repack.cpp
index 42bad3dd201..93642453808 100644
--- a/src/frontends/gguf/src/builder/blocks/qkv_repack.cpp
+++ b/src/frontends/gguf/src/builder/blocks/qkv_repack.cpp
@@ -35,12 +35,8 @@ void register_fused_qkv(GraphEmitter& e, const DecoderConfig& cfg, int il) {
void register_qwen35_q_gate(GraphEmitter& e, const DecoderConfig& cfg, int il) {
const std::string p = "blk." + std::to_string(il) + ".";
- auto parts = split_interleaved_q_gate(p + "attn_q", e.weights(), e.qtypes(), static_cast<size_t>(cfg.head_size));
- const std::array<std::string, 2> names = {p + "attn_q.weight", p + "attn_gate.weight"};
- for (size_t i = 0; i < 2; ++i) {
- e.inherit_hadamard(names[i], p + "attn_q.weight");
- e.emit_weight_op(names[i], parts[i].tensors, parts[i].qtype);
- }
+ e.inherit_hadamard(p + "attn_q_gate.weight", p + "attn_q.weight");
+ e.add_weight_from(p + "attn_q_gate.weight", p + "attn_q");
}
} // namespace ov::frontend::gguf::blocks
diff --git a/src/frontends/gguf/src/builder/blocks/qkv_repack.hpp b/src/frontends/gguf/src/builder/blocks/qkv_repack.hpp
index a2bad382012..803859ab659 100644
--- a/src/frontends/gguf/src/builder/blocks/qkv_repack.hpp
+++ b/src/frontends/gguf/src/builder/blocks/qkv_repack.hpp
@@ -10,19 +10,11 @@
namespace ov::frontend::gguf::blocks {
-// Weight-level repacking that happens before any op is emitted for a layer, so the rest of the
-// attention path only ever sees the plain blk.<il>.attn_{q,k,v}.weight / attn_gate.weight nodes and
-// stays architecture-agnostic.
-
// Split a fused blk.<il>.attn_qkv weight into separate q/k/v weight nodes registered under
// blk.<il>.attn_{q,k,v}.weight. Rows split as [n_head*head_size | n_head_kv*head_size x2].
void register_fused_qkv(GraphEmitter& e, const DecoderConfig& cfg, int il);
-// qwen35 full-attention layers: attn_q packs query and attention-output gate interleaved per head
-// ([q_h0 | gate_h0 | q_h1 | ...], stride 2*head_size). De-interleave into the plain
-// blk.N.attn_q.weight / blk.N.attn_gate.weight the shared attention path expects, so the graph
-// never sees the interleaving. llama.cpp does the same split with two strided views
-// (src/models/qwen35.cpp build_layer_attn).
+// Preserve the interleaved Q/gate weight for a joint projection.
void register_qwen35_q_gate(GraphEmitter& e, const DecoderConfig& cfg, int il);
} // namespace ov::frontend::gguf::blocks
diff --git a/src/frontends/gguf/src/builder/graph_emitter.cpp b/src/frontends/gguf/src/builder/graph_emitter.cpp
index ab9d6a7a4a8..b8017417aa2 100644
--- a/src/frontends/gguf/src/builder/graph_emitter.cpp
+++ b/src/frontends/gguf/src/builder/graph_emitter.cpp
@@ -120,7 +120,8 @@ std::string GraphEmitter::add_op(const std::string& op_type,
prepare_graph_inputs(*m_graph->values, *decoder);
translate_node(std::make_shared<GgufBuilderDecoder>(m_graph, static_cast<int>(m_graph->nodes.size() - 1)),
m_graph->values,
- m_translators);
+ m_translators,
+ m_constant_cache);
return name;
}
diff --git a/src/frontends/gguf/src/builder/graph_emitter.hpp b/src/frontends/gguf/src/builder/graph_emitter.hpp
index 93dfc823326..e351a0bb641 100644
--- a/src/frontends/gguf/src/builder/graph_emitter.hpp
+++ b/src/frontends/gguf/src/builder/graph_emitter.hpp
@@ -127,6 +127,7 @@ private:
std::string m_arch;
std::shared_ptr<GgufGraph> m_graph;
+ std::shared_ptr<ConstantCache> m_constant_cache = std::make_shared<ConstantCache>();
std::unordered_map<std::string, CreatorFunction> m_translators;
// Names of weights already emitted as GGML_OP_NONE leaves, so a weight referenced by several
// ops (or tied, e.g. MQA tie-V) is emitted once.
diff --git a/src/frontends/gguf/src/hadamard_sign_folding.cpp b/src/frontends/gguf/src/hadamard_sign_folding.cpp
new file mode 100644
index 00000000000..8b7e7177395
--- /dev/null
+++ b/src/frontends/gguf/src/hadamard_sign_folding.cpp
@@ -0,0 +1,483 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "hadamard_sign_folding.hpp"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdint>
+#include <cstring>
+#include <set>
+#include <utility>
+
+#include "openvino/core/model.hpp"
+#include "openvino/core/rt_info.hpp"
+#include "openvino/core/runtime_attribute.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/convert_like.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/shape_of.hpp"
+#include "openvino/op/squeeze.hpp"
+#include "openvino/op/subtract.hpp"
+#include "openvino/op/swish.hpp"
+#include "openvino/op/unsqueeze.hpp"
+
+namespace ov::frontend::gguf {
+namespace {
+using Constant = ov::op::v0::Constant;
+using Multiply = ov::op::v1::Multiply;
+using Squeeze = ov::op::v0::Squeeze;
+using Reshape = ov::op::v1::Reshape;
+constexpr char sign_marker[] = "gguf_hadamard_input_sign";
+
+bool is_sign_multiply(const std::shared_ptr<Multiply>& multiply) {
+ if (!multiply)
+ return false;
+ const auto& info = multiply->get_rt_info();
+ const auto marker = info.find(sign_marker);
+ return marker != info.end() && marker->second.is<bool>() && marker->second.as<bool>();
+}
+
+std::shared_ptr<Constant> exact_constant(const ov::Output<ov::Node>& value) {
+ const auto node = value.get_node_shared_ptr();
+ if (const auto constant = ov::as_type_ptr<Constant>(node))
+ return constant;
+ if (!ov::is_type<ov::op::v0::Convert>(node) && !ov::is_type<ov::op::v1::ConvertLike>(node))
+ return nullptr;
+ const auto source = exact_constant(node->input_value(0));
+ if (!source || value.get_element_type().is_dynamic())
+ return nullptr;
+ const auto convert = std::make_shared<ov::op::v0::Convert>(source, value.get_element_type());
+ ov::TensorVector converted{ov::Tensor(value.get_element_type(), source->get_shape())};
+ if (!convert->evaluate(converted, {source->get_tensor_view()}))
+ return nullptr;
+ const auto result = std::make_shared<Constant>(converted.front());
+ const auto reverse = std::make_shared<ov::op::v0::Convert>(result, source->get_element_type());
+ ov::TensorVector restored{ov::Tensor(source->get_element_type(), source->get_shape())};
+ if (!reverse->evaluate(restored, converted) ||
+ std::memcmp(source->get_data_ptr(), restored.front().data(), source->get_byte_size()) != 0)
+ return nullptr;
+ return result;
+}
+
+bool supported_float(const ov::element::Type& type) {
+ return type == ov::element::f16 || type == ov::element::bf16 || type == ov::element::f32 ||
+ type == ov::element::f64;
+}
+
+void collect_constant_sources(const ov::Output<ov::Node>& value, ov::NodeVector& sources) {
+ const auto node = value.get_node_shared_ptr();
+ sources.push_back(node);
+ if (ov::is_type<ov::op::v0::Convert>(node) || ov::is_type<ov::op::v1::ConvertLike>(node))
+ collect_constant_sources(node->input_value(0), sources);
+}
+
+bool preserves_shape(const ov::PartialShape& data,
+ const ov::Shape& constant,
+ const ov::op::AutoBroadcastSpec& broadcast) {
+ if (broadcast.m_type == ov::op::AutoBroadcastType::NONE)
+ return data.is_static() && data.to_shape() == constant;
+ if (broadcast.m_type != ov::op::AutoBroadcastType::NUMPY || data.rank().is_dynamic() ||
+ constant.size() > static_cast<size_t>(data.rank().get_length()))
+ return false;
+ const auto offset = data.size() - constant.size();
+ for (size_t axis = 0; axis < constant.size(); ++axis) {
+ if (constant[axis] != 1 && (!data[offset + axis].is_static() ||
+ data[offset + axis].get_length() != static_cast<int64_t>(constant[axis])))
+ return false;
+ }
+ return true;
+}
+
+std::shared_ptr<Constant> signed_scale(const std::shared_ptr<Constant>& scale, const std::shared_ptr<Constant>& signs) {
+ ov::PartialShape shape = scale->get_shape();
+ if (!ov::PartialShape::broadcast_merge_into(shape, signs->get_shape(), ov::op::AutoBroadcastType::NUMPY) ||
+ ov::shape_size(shape.to_shape()) == 0)
+ return nullptr;
+ const auto values = scale->cast_vector<double>();
+ const auto sign_values = signs->cast_vector<double>();
+ for (const auto value : values)
+ if (!std::isfinite(value))
+ return nullptr;
+ for (const auto sign : sign_values)
+ if (sign != 1.0 && sign != -1.0)
+ return nullptr;
+ // Multiplying a finite value by +-1 is exact, including for f16/bf16 evaluated through f32.
+ ov::TensorVector folded{ov::Tensor(scale->get_element_type(), shape.to_shape())};
+ if (!std::make_shared<Multiply>(scale, signs)
+ ->evaluate(folded, {scale->get_tensor_view(), signs->get_tensor_view()}))
+ return nullptr;
+ return std::make_shared<Constant>(folded.front());
+}
+
+bool merge_info(const ov::NodeVector& sources, const std::shared_ptr<ov::Node>& target) {
+ ov::Node::RTMap plain;
+ for (const auto& source : sources) {
+ for (const auto& [key, value] : source->get_rt_info()) {
+ if (key == sign_marker || key == "opset" || value.is<ov::RuntimeAttribute>())
+ continue;
+ const auto found = plain.find(key);
+ if (found != plain.end() && found->second != value)
+ return false;
+ plain[key] = value;
+ }
+ }
+ ov::copy_runtime_info(sources, target);
+ for (const auto& [key, value] : plain)
+ target->get_rt_info()[key] = value;
+ target->get_rt_info().erase(sign_marker);
+ return true;
+}
+
+bool merge_output_info(const ov::OutputVector& sources, ov::Output<ov::Node> target) {
+ ov::Node::RTMap plain;
+ for (const auto& source : sources) {
+ for (const auto& [key, value] : source.get_rt_info()) {
+ if (value.is<ov::RuntimeAttribute>())
+ continue;
+ const auto found = plain.find(key);
+ if (found != plain.end() && found->second != value)
+ return false;
+ plain[key] = value;
+ }
+ }
+ ov::copy_output_runtime_info(sources, {target});
+ for (const auto& [key, value] : plain)
+ target.get_rt_info()[key] = value;
+ return true;
+}
+
+std::shared_ptr<ov::Node> clone_branch_node(const std::shared_ptr<ov::Node>& source, const ov::OutputVector& inputs) {
+ const auto result = source->clone_with_new_inputs(inputs);
+ result->get_rt_info() = source->get_rt_info();
+ result->set_friendly_name(source->get_friendly_name());
+ result->output(0).get_rt_info() = source->output(0).get_rt_info();
+ result->output(0).set_names(source->output(0).get_names());
+ return result;
+}
+
+bool has_channels(const ov::PartialShape& shape, size_t channels) {
+ return shape.rank().is_static() && shape.size() >= 2 && shape[shape.size() - 1].is_static() &&
+ shape[shape.size() - 1].get_length() == static_cast<int64_t>(channels);
+}
+
+void redirect_shape_queries(const std::shared_ptr<ov::Node>& source, const std::shared_ptr<ov::Node>& replacement) {
+ for (auto input : source->output(0).get_target_inputs())
+ if (input.get_index() == 0 &&
+ (ov::is_type<ov::op::v0::ShapeOf>(input.get_node()) || ov::is_type<ov::op::v3::ShapeOf>(input.get_node())))
+ input.replace_source_output(replacement->output(0));
+}
+
+bool fold_up_projection(const std::shared_ptr<Multiply>& rotation) {
+ std::shared_ptr<Constant> signs;
+ size_t sign_port = 0;
+ for (; sign_port < 2; ++sign_port) {
+ signs = exact_constant(rotation->input_value(sign_port));
+ if (signs)
+ break;
+ }
+ if (!signs || !supported_float(signs->get_element_type()) || signs->get_shape().empty())
+ return false;
+ const auto& sign_shape = signs->get_shape();
+ const auto channels = sign_shape.back();
+ if (channels == 0 || ov::shape_size(sign_shape) != channels)
+ return false;
+ const auto sign_values = signs->cast_vector<double>();
+ if (std::any_of(sign_values.begin(), sign_values.end(), [](double value) {
+ return value != 1.0 && value != -1.0;
+ }))
+ return false;
+ auto data = rotation->input_value(1 - sign_port);
+ if (data.get_element_type() != signs->get_element_type() || !has_channels(data.get_partial_shape(), channels) ||
+ !preserves_shape(data.get_partial_shape(), sign_shape, rotation->get_autob()))
+ return false;
+ ov::NodeVector views;
+ while (ov::is_type<Reshape>(data.get_node()) || ov::is_type<Squeeze>(data.get_node()) ||
+ ov::is_type<ov::op::v0::Unsqueeze>(data.get_node())) {
+ const auto view = data.get_node_shared_ptr();
+ if (view->get_input_size() != 2 || !has_channels(view->get_input_partial_shape(0), channels) ||
+ !has_channels(view->get_output_partial_shape(0), channels))
+ return false;
+ views.push_back(view);
+ data = view->input_value(0);
+ }
+ const auto swiglu = ov::as_type_ptr<Multiply>(data.get_node_shared_ptr());
+ if (!swiglu || is_sign_multiply(swiglu))
+ return false;
+ size_t up_port = 0;
+ std::shared_ptr<ov::op::v0::MatMul> up;
+ for (; up_port < 2; ++up_port) {
+ up = ov::as_type_ptr<ov::op::v0::MatMul>(swiglu->get_input_node_shared_ptr(up_port));
+ if (up && ov::is_type<ov::op::v4::Swish>(swiglu->get_input_node_shared_ptr(1 - up_port)))
+ break;
+ }
+ if (up_port == 2 || !up->get_transpose_b() || !has_channels(up->get_output_partial_shape(0), channels) ||
+ up->get_output_partial_shape(0) != swiglu->get_input_partial_shape(1 - up_port) ||
+ up->get_output_partial_shape(0) != swiglu->get_output_partial_shape(0))
+ return false;
+
+ auto weights = up->input_value(1);
+ std::shared_ptr<ov::op::v0::Convert> output_convert;
+ if ((output_convert = ov::as_type_ptr<ov::op::v0::Convert>(weights.get_node_shared_ptr()))) {
+ const auto type = output_convert->get_destination_type();
+ if (output_convert->get_input_element_type(0) != ov::element::f16 ||
+ (type != ov::element::f16 && type != ov::element::f32 && type != ov::element::f64))
+ return false;
+ weights = output_convert->input_value(0);
+ }
+ const auto weight_view = ov::as_type_ptr<Reshape>(weights.get_node_shared_ptr());
+ if (!weight_view || !weights.get_partial_shape().is_static() || weights.get_shape().size() != 2 ||
+ weights.get_shape()[0] != channels || weights.get_element_type() != ov::element::f16)
+ return false;
+ const auto scaled = ov::as_type_ptr<Multiply>(weight_view->get_input_node_shared_ptr(0));
+ if (!scaled)
+ return false;
+ size_t scale_port = 0;
+ std::shared_ptr<Constant> scale;
+ for (; scale_port < 2; ++scale_port) {
+ scale = exact_constant(scaled->input_value(scale_port));
+ if (scale)
+ break;
+ }
+ if (!scale || scale->get_element_type() != ov::element::f16)
+ return false;
+ const auto subtract = ov::as_type_ptr<ov::op::v1::Subtract>(scaled->get_input_node_shared_ptr(1 - scale_port));
+ if (!subtract)
+ return false;
+ const auto code_convert = ov::as_type_ptr<ov::op::v0::Convert>(subtract->get_input_node_shared_ptr(0));
+ const auto zero_point = exact_constant(subtract->input_value(1));
+ if (!code_convert || code_convert->get_destination_type() != ov::element::f16 || !zero_point ||
+ zero_point->get_element_type() != ov::element::f16)
+ return false;
+ const auto codes = ov::as_type_ptr<Constant>(code_convert->get_input_node_shared_ptr(0));
+ if (!codes || codes->get_element_type() != ov::element::u2 || codes->get_shape().size() < 2 ||
+ codes->get_shape()[0] != channels || ov::shape_size(codes->get_shape()) == 0 ||
+ ov::shape_size(codes->get_shape()) != ov::shape_size(weights.get_shape()) ||
+ !preserves_shape(codes->get_shape(), zero_point->get_shape(), subtract->get_autob()) ||
+ !preserves_shape(codes->get_shape(), scale->get_shape(), scaled->get_autob()))
+ return false;
+ for (const auto value : zero_point->cast_vector<double>())
+ if (value != 1.0)
+ return false;
+ for (const auto value : scale->cast_vector<double>())
+ if (!std::isfinite(value))
+ return false;
+
+ const auto* packed = static_cast<const uint8_t*>(codes->get_data_ptr());
+ const auto count = ov::shape_size(codes->get_shape());
+ if (std::any_of(packed, packed + count / 4, [](uint8_t value) {
+ return (value & (value >> 1) & 0x55) != 0;
+ }))
+ return false;
+ for (size_t i = count / 4 * 4; i < count; ++i)
+ if (((packed[i / 4] >> (2 * (i % 4))) & 3) == 3)
+ return false;
+ ov::Shape row_shape(codes->get_shape().size(), 1);
+ row_shape[0] = channels;
+ const auto row_signs = Constant::create(ov::element::f16, row_shape, sign_values);
+ const auto folded = signed_scale(scale, row_signs);
+ if (!folded || !preserves_shape(codes->get_shape(), folded->get_shape(), scaled->get_autob()))
+ return false;
+ folded->set_friendly_name(scale->get_friendly_name());
+ folded->output(0).get_rt_info() = scale->output(0).get_rt_info();
+ folded->output(0).set_names(scale->output(0).get_names());
+ ov::NodeVector constant_sources;
+ collect_constant_sources(scaled->input_value(scale_port), constant_sources);
+ collect_constant_sources(rotation->input_value(sign_port), constant_sources);
+ if (!merge_info(constant_sources, folded))
+ return false;
+ auto inputs = scaled->input_values();
+ inputs[scale_port] = folded;
+ auto replacement = clone_branch_node(scaled, inputs);
+ replacement = clone_branch_node(weight_view, {replacement, weight_view->input_value(1)});
+ if (output_convert)
+ replacement = clone_branch_node(output_convert, {replacement});
+ replacement = clone_branch_node(up, {up->input_value(0), replacement});
+ std::vector<std::pair<std::shared_ptr<ov::Node>, std::shared_ptr<ov::Node>>> shape_replacements;
+ shape_replacements.reserve(views.size() + 2);
+ shape_replacements.emplace_back(up, replacement);
+ inputs = swiglu->input_values();
+ inputs[up_port] = replacement;
+ replacement = clone_branch_node(swiglu, inputs);
+ shape_replacements.emplace_back(swiglu, replacement);
+ for (auto view = views.rbegin(); view != views.rend(); ++view) {
+ replacement = clone_branch_node(*view, {replacement, (*view)->input_value(1)});
+ shape_replacements.emplace_back(*view, replacement);
+ }
+ const auto original = rotation->input_value(1 - sign_port);
+ if (!merge_info({original.get_node_shared_ptr(), rotation}, replacement) ||
+ !merge_output_info({original, rotation->output(0)}, replacement->output(0)))
+ return false;
+ auto names = original.get_names();
+ const auto& rotation_names = rotation->output(0).get_names();
+ names.insert(rotation_names.begin(), rotation_names.end());
+ replacement->output(0).set_names(names);
+ rotation->output(0).replace(replacement);
+ for (const auto& [source, target] : shape_replacements)
+ redirect_shape_queries(source, target);
+ return true;
+}
+
+bool squeeze_axes(const std::shared_ptr<Squeeze>& squeeze, std::set<size_t>& axes) {
+ const auto input_shape = squeeze->get_input_partial_shape(0);
+ if (input_shape.rank().is_dynamic() || input_shape.size() == 0 || squeeze->get_input_size() != 2)
+ return false;
+ const auto constant = exact_constant(squeeze->input_value(1));
+ if (!constant || ov::shape_size(constant->get_shape()) == 0)
+ return false;
+ const auto rank = static_cast<int64_t>(input_shape.size());
+ for (auto axis : constant->cast_vector<int64_t>()) {
+ if (axis < 0)
+ axis += rank;
+ if (axis < 0 || axis >= rank - 1 || !input_shape[axis].is_static() || input_shape[axis].get_length() != 1)
+ return false;
+ axes.insert(static_cast<size_t>(axis));
+ }
+ ov::PartialShape expected;
+ for (size_t axis = 0; axis < input_shape.size(); ++axis)
+ if (axes.count(axis) == 0)
+ expected.push_back(input_shape[axis]);
+ return squeeze->get_output_partial_shape(0) == expected;
+}
+
+struct SignView {
+ ov::Output<ov::Node> output;
+ std::shared_ptr<Squeeze> squeeze;
+ std::set<size_t> axes;
+ ov::NodeVector rotations;
+};
+
+std::shared_ptr<Constant> lift_signs(const std::shared_ptr<Constant>& signs, const SignView& view, size_t source_rank) {
+ ov::Shape shape(source_rank, 1);
+ const auto& sign_shape = signs->get_shape();
+ const auto view_rank = source_rank - view.axes.size();
+ size_t view_axis = 0;
+ for (size_t axis = 0; axis < source_rank; ++axis) {
+ if (view.axes.count(axis) != 0)
+ continue;
+ if (view_axis >= view_rank - sign_shape.size())
+ shape[axis] = sign_shape[view_axis - (view_rank - sign_shape.size())];
+ ++view_axis;
+ }
+ const auto first = std::find_if(shape.begin(), shape.end(), [](size_t dim) {
+ return dim != 1;
+ });
+ shape.erase(shape.begin(), first);
+ return std::make_shared<Constant>(signs->get_element_type(), shape, signs->get_data_ptr());
+}
+
+void fold_scale(const std::shared_ptr<Multiply>& scaled) {
+ std::shared_ptr<Constant> scale;
+ size_t scale_port = 0;
+ for (; scale_port < 2; ++scale_port) {
+ scale = exact_constant(scaled->input_value(scale_port));
+ if (scale)
+ break;
+ }
+ if (!scale || !supported_float(scale->get_element_type()))
+ return;
+ const auto data = scaled->input_value(1 - scale_port);
+ if (data.get_element_type() != scale->get_element_type() ||
+ !preserves_shape(data.get_partial_shape(), scale->get_shape(), scaled->get_autob()))
+ return;
+
+ std::vector<SignView> views{{scaled->output(0), nullptr, {}, {}}};
+ for (const auto& consumer : scaled->output(0).get_target_inputs()) {
+ const auto squeeze = ov::as_type_ptr<Squeeze>(consumer.get_node()->shared_from_this());
+ if (!squeeze)
+ continue;
+ std::set<size_t> axes;
+ if (consumer.get_index() != 0 || !squeeze_axes(squeeze, axes))
+ return;
+ views.push_back({squeeze->output(0), squeeze, std::move(axes), {}});
+ }
+ ov::NodeVector constant_sources;
+ collect_constant_sources(scaled->input_value(scale_port), constant_sources);
+ std::shared_ptr<Constant> signs;
+ for (auto& view : views) {
+ for (const auto& consumer : view.output.get_target_inputs()) {
+ const auto node = consumer.get_node()->shared_from_this();
+ if (ov::is_type<ov::op::v0::ShapeOf>(node) || ov::is_type<ov::op::v3::ShapeOf>(node) ||
+ (!view.squeeze && ov::is_type<Squeeze>(node)))
+ continue;
+ const auto rotation = ov::as_type_ptr<Multiply>(node);
+ if (!is_sign_multiply(rotation))
+ return;
+ const auto sign_input = rotation->input_value(1 - consumer.get_index());
+ if (sign_input == view.output)
+ return;
+ const auto constant = exact_constant(sign_input);
+ if (!constant || constant->get_element_type() != scale->get_element_type() ||
+ !preserves_shape(view.output.get_partial_shape(), constant->get_shape(), rotation->get_autob()))
+ return;
+ const auto candidate = lift_signs(constant, view, data.get_partial_shape().size());
+ if (signs && (signs->get_shape() != candidate->get_shape() ||
+ std::memcmp(signs->get_data_ptr(), candidate->get_data_ptr(), signs->get_byte_size()) != 0))
+ return;
+ signs = candidate;
+ view.rotations.push_back(node);
+ collect_constant_sources(sign_input, constant_sources);
+ }
+ }
+ if (!signs)
+ return;
+ const auto folded = signed_scale(scale, signs);
+ if (!folded || !preserves_shape(data.get_partial_shape(), folded->get_shape(), scaled->get_autob()))
+ return;
+ const auto replacement = std::make_shared<Multiply>(data, folded, scaled->get_autob());
+ if (!merge_info(constant_sources, folded))
+ return;
+ ov::OutputVector replacements;
+ for (const auto& view : views) {
+ const std::shared_ptr<ov::Node> target =
+ view.squeeze ? std::static_pointer_cast<ov::Node>(
+ std::make_shared<Squeeze>(replacement, view.squeeze->input_value(1)))
+ : replacement;
+ ov::NodeVector sources{view.output.get_node_shared_ptr()};
+ sources.insert(sources.end(), view.rotations.begin(), view.rotations.end());
+ ov::OutputVector output_sources{view.output};
+ for (const auto& rotation : view.rotations)
+ output_sources.push_back(rotation->output(0));
+ if (!merge_info(sources, target) || !merge_output_info(output_sources, target->output(0)))
+ return;
+ target->set_friendly_name(view.output.get_node()->get_friendly_name());
+ auto names = view.output.get_names();
+ for (const auto& rotation : view.rotations) {
+ const auto& output_names = rotation->output(0).get_names();
+ names.insert(output_names.begin(), output_names.end());
+ }
+ target->output(0).set_names(names);
+ replacements.push_back(target->output(0));
+ }
+ for (size_t i = 0; i < views.size(); ++i) {
+ for (const auto& rotation : views[i].rotations)
+ rotation->output(0).replace(replacements[i]);
+ views[i].output.replace(replacements[i]);
+ }
+}
+} // namespace
+
+void fold_hadamard_input_signs(const std::shared_ptr<ov::Model>& model) {
+ std::set<ov::Node*> visited;
+ for (const auto& node : model->get_ordered_ops()) {
+ const auto rotation = ov::as_type_ptr<Multiply>(node);
+ if (!is_sign_multiply(rotation))
+ continue;
+ if (fold_up_projection(rotation))
+ continue;
+ for (const auto& input : rotation->input_values()) {
+ auto source = input.get_node_shared_ptr();
+ if (const auto squeeze = ov::as_type_ptr<Squeeze>(source))
+ source = squeeze->input_value(0).get_node_shared_ptr();
+ const auto scaled = ov::as_type_ptr<Multiply>(source);
+ if (scaled && !is_sign_multiply(scaled) && visited.insert(scaled.get()).second)
+ fold_scale(scaled);
+ }
+ }
+}
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/hadamard_sign_folding.hpp b/src/frontends/gguf/src/hadamard_sign_folding.hpp
new file mode 100644
index 00000000000..5497ca163ed
--- /dev/null
+++ b/src/frontends/gguf/src/hadamard_sign_folding.hpp
@@ -0,0 +1,17 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <memory>
+
+namespace ov {
+class Model;
+}
+
+namespace ov::frontend::gguf {
+
+void fold_hadamard_input_signs(const std::shared_ptr<ov::Model>& model);
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/node_context.hpp b/src/frontends/gguf/src/node_context.hpp
index 7239c0b3a0e..ebd59a80e3d 100644
--- a/src/frontends/gguf/src/node_context.hpp
+++ b/src/frontends/gguf/src/node_context.hpp
@@ -4,22 +4,48 @@
#pragma once
+#include <cmath>
#include <cstdint>
+#include <map>
+#include <memory>
#include <string>
+#include <tuple>
+#include <vector>
#include "openvino/frontend/gguf/decoder.hpp"
#include "openvino/frontend/node_context.hpp"
+#include "openvino/op/constant.hpp"
namespace ov::frontend::gguf {
typedef std::map<std::string, Output<Node>> TensorMap;
+struct ConstantCache {
+ std::map<std::tuple<ov::element::Type_t, ov::Shape, std::vector<int64_t>>, std::shared_ptr<ov::op::v0::Constant>>
+ constants;
+ std::map<std::pair<ov::element::Type_t, size_t>, std::shared_ptr<ov::op::v0::Constant>> hadamard_matrices;
+ std::map<std::tuple<Output<Node>,
+ int64_t,
+ bool,
+ bool,
+ std::vector<int64_t>,
+ ov::element::Type_t,
+ ov::Shape,
+ std::vector<uint8_t>>,
+ Output<Node>>
+ hadamard_outputs;
+ std::map<Output<Node>, Output<Node>> f32_activations;
+ std::map<Output<Node>, Output<Node>> rank3_activations;
+};
class NodeContext : public frontend::NodeContext {
public:
- NodeContext(const std::shared_ptr<GgufDecoder>& decoder, std::shared_ptr<TensorMap>& tensor_map)
+ NodeContext(const std::shared_ptr<GgufDecoder>& decoder,
+ std::shared_ptr<TensorMap>& tensor_map,
+ const std::shared_ptr<ConstantCache>& constant_cache = {})
: ov::frontend::NodeContext(decoder->get_op_type()),
m_decoder(decoder),
- m_tensor_map(tensor_map) {
+ m_tensor_map(tensor_map),
+ m_constant_cache(constant_cache ? constant_cache : std::make_shared<ConstantCache>()) {
m_input_names = decoder->get_input_names();
m_output_names = decoder->get_output_names();
}
@@ -83,9 +109,50 @@ public:
return m_decoder->get_attribute(name);
}
+ std::shared_ptr<ov::op::v0::Constant> get_constant(const ov::element::Type& type,
+ const ov::Shape& shape,
+ const std::vector<int64_t>& values) const {
+ auto& constant = m_constant_cache->constants[{static_cast<ov::element::Type_t>(type), shape, values}];
+ if (!constant)
+ constant = ov::op::v0::Constant::create(type, shape, values);
+ return constant;
+ }
+
+ std::shared_ptr<ov::op::v0::Constant> get_hadamard_matrix(const ov::element::Type& type,
+ size_t block = 1024) const {
+ const auto make_matrix = [&] {
+ const float scale = 1.f / std::sqrt(static_cast<float>(block));
+ std::vector<float> values(block * block);
+ for (size_t row = 0; row < block; ++row) {
+ for (size_t column = 0; column < block; ++column) {
+ bool negative = false;
+ for (auto bits = row & column; bits; bits &= bits - 1)
+ negative = !negative;
+ values[row * block + column] = negative ? -scale : scale;
+ }
+ }
+ return ov::op::v0::Constant::create(type, {block, block}, values);
+ };
+ auto& matrix = m_constant_cache->hadamard_matrices[{static_cast<ov::element::Type_t>(type), block}];
+ if (!matrix)
+ matrix = make_matrix();
+ return matrix;
+ }
+
+ Output<Node>* get_hadamard_cache_entry(const Output<Node>& input,
+ int64_t block,
+ bool inverse,
+ bool matrix_form,
+ const std::vector<int64_t>& heads,
+ const ov::Tensor& signs) const;
+
+ Output<Node> get_f32_activation(const Output<Node>& input) const;
+ Output<Node> get_rank3_activation(const Output<Node>& input) const;
+
private:
std::shared_ptr<GgufDecoder> m_decoder;
std::shared_ptr<TensorMap>& m_tensor_map;
+ std::shared_ptr<ConstantCache> m_constant_cache;
std::vector<std::string> m_input_names;
std::vector<std::string> m_output_names;
};
diff --git a/src/frontends/gguf/src/op/get_rows.cpp b/src/frontends/gguf/src/op/get_rows.cpp
index be72d1a0f1f..9105502193e 100644
--- a/src/frontends/gguf/src/op/get_rows.cpp
+++ b/src/frontends/gguf/src/op/get_rows.cpp
@@ -18,6 +18,7 @@
#include "openvino/op/squeeze.hpp"
#include "openvino/op/subtract.hpp"
#include "openvino/op/unsqueeze.hpp"
+#include "quant/weights.hpp"
#include "utils.hpp"
namespace ov::frontend::gguf::op {
@@ -133,8 +134,7 @@ OutputVector translate_get_rows(const NodeContext& context) {
res = std::make_shared<ov::op::v8::Gather>(data, indices, axis, 1);
}
} else {
- auto axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0});
- res = std::make_shared<ov::op::v8::Gather>(data, indices, axis);
+ res = gather_weight_rows(data, indices);
}
// The two Squeezes above dropped the leading axes; restore ggml's rank-4 form.
diff --git a/src/frontends/gguf/src/op/mulmat.cpp b/src/frontends/gguf/src/op/mulmat.cpp
index 8e68cc6e101..93307aec82e 100644
--- a/src/frontends/gguf/src/op/mulmat.cpp
+++ b/src/frontends/gguf/src/op/mulmat.cpp
@@ -33,7 +33,34 @@ OutputVector translate_mulmat(const NodeContext& context) {
ov::Output<Node> res;
ov::Output<ov::Node> B = context.get_input(0);
ov::Output<ov::Node> A = context.get_input(1);
- A = apply_hadamard(context, A);
+ const auto activation = A;
+ auto weight = B.get_node_shared_ptr();
+ while (weight->get_input_size() > 0)
+ weight = weight->get_input_node_shared_ptr(0);
+ const bool u2_weights =
+ ov::is_type<ov::op::v0::Constant>(weight) && weight->get_output_element_type(0) == ov::element::u2;
+ const auto& shape = A.get_partial_shape();
+ const bool rank3_output = context.get_attribute<int>("activation_rank", 4) == 3;
+ const bool rank3_projection = u2_weights && shape.rank() == 4 && shape[1] == 1 && shape[3].is_static() &&
+ B.get_partial_shape().rank() == 2 && op_case != 3;
+ if (rank3_output) {
+ FRONT_END_OP_CONVERSION_CHECK(shape.rank() == 4 && shape[1] == 1 && shape[3].is_static(),
+ "Rank-3 projection requires [batch, 1, tokens, features] activations");
+ }
+ if (rank3_projection)
+ A = context.get_rank3_activation(A);
+ A = apply_hadamard(context, A, u2_weights);
+ if (rank3_output && !rank3_projection)
+ A = context.get_rank3_activation(A);
+
+ const auto restore_projection = [&](const ov::Output<Node>& output) -> ov::Output<Node> {
+ if (!rank3_projection || rank3_output)
+ return output;
+ const auto restored_shape = std::make_shared<ov::op::v0::Concat>(
+ ov::OutputVector{get_dimensions(activation, {0, 1, 2}), get_dimensions(output, {-1})},
+ 0);
+ return std::make_shared<ov::op::v1::Reshape>(output, restored_shape, false);
+ };
bool transpose_b = true;
if (op_case == 2) {
@@ -44,9 +71,7 @@ OutputVector translate_mulmat(const NodeContext& context) {
A = process_view_input(context, 1);
}
// GGML MUL_MAT produces F32, including when both operands are F16.
- if (A.get_element_type() != ov::element::f32) {
- A = std::make_shared<ov::op::v0::Convert>(A, ov::element::f32);
- }
+ A = context.get_f32_activation(A);
if (B.get_element_type() != ov::element::f32) {
B = std::make_shared<ov::op::v0::Convert>(B, ov::element::f32);
}
@@ -56,8 +81,9 @@ OutputVector translate_mulmat(const NodeContext& context) {
if (A_shape[1].is_dynamic() || B_shape[1].is_dynamic()) {
// Variable encoder grids use equal or singleton batch axes. MatMul validates
// their broadcast compatibility at runtime; do not freeze a grid dimension.
- return rename_outputs_with_suffix({std::make_shared<ov::op::v0::MatMul>(A, B, false, transpose_b)},
- context.get_name());
+ res = std::make_shared<ov::op::v0::MatMul>(A, B, false, transpose_b);
+ res = restore_projection(res);
+ return rename_outputs_with_suffix({res}, context.get_name());
}
int64_t A_batch = A_shape[1].get_length();
int64_t B_batch = B_shape[1].get_length();
@@ -96,6 +122,7 @@ OutputVector translate_mulmat(const NodeContext& context) {
}
res = std::make_shared<ov::op::v0::MatMul>(A, B, false, transpose_b);
+ res = restore_projection(res);
return rename_outputs_with_suffix({std::move(res)}, context.get_name());
}
diff --git a/src/frontends/gguf/src/op/rope.cpp b/src/frontends/gguf/src/op/rope.cpp
index f530210d6b5..afb6e12e87c 100644
--- a/src/frontends/gguf/src/op/rope.cpp
+++ b/src/frontends/gguf/src/op/rope.cpp
@@ -30,6 +30,7 @@
#include "openvino/op/subtract.hpp"
#include "openvino/op/transpose.hpp"
#include "openvino/op/unsqueeze.hpp"
+#include "openvino/op/variadic_split.hpp"
#include "openvino/pass/node_registry.hpp"
#include "utils.hpp"
@@ -236,7 +237,7 @@ OutputVector translate_rope(const NodeContext& context) {
ov::Output<ov::Node> rotated = std::make_shared<ov::op::v1::Add>(y1, y2);
res = n_rot < head_size ? std::make_shared<ov::op::v0::Concat>(ov::OutputVector{rotated, pass_through}, -1)
: rotated;
- } else if (mode == TYPE_NEOX) {
+ } else if (mode == TYPE_NEOX || mode == TYPE_IMROPE) {
// Partial rotary (ggml n_dims < head_dim): only the first n_dims of every head are
// rotated; the remaining tail is passed through unchanged. cos/sin have width n_dims/2,
// so the rotated block must be exactly n_dims wide.
@@ -259,16 +260,7 @@ OutputVector translate_rope(const NodeContext& context) {
}
};
- // Build the canonical NEOX RoPE via the shared decomposition helper, which emits the exact
- // split-halves + Multiply(-1)+Add + Concat pattern that ov::pass::RoPEFusion (specifically
- // RoPEFusionGPTOSS) folds into the fused ov::op::internal::RoPE primitive on CPU/GPU.
- //
- // That matcher only fires when the rotated tensor is [B, H, L, S] and cos/sin are
- // [?, 1, ?, head/2]. Our tensors are ggml-natural: data is [B, L, H, S], cos/sin are
- // [B, L, 1, head/2]. So transpose every operand into [B, H, L, S] (heads on axis 1), run
- // the decomposition there, and transpose the result back. The math is unchanged; the
- // wrapping Transposes are sunk / cancelled against the adjacent PERMUTE during
- // TransposeSinking.
+ // Normalize to [B, H, L, S] for RoPE fusion.
const int64_t n_head_rope = static_cast<int64_t>(output_shape[2].get_length());
const int64_t head_size_rope = static_cast<int64_t>(output_shape[3].get_length());
const auto perm_bhls = ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3});
@@ -286,8 +278,14 @@ OutputVector translate_rope(const NodeContext& context) {
x = std::make_shared<ov::op::v1::Reshape>(x, shape4d, true); // [B, L, H, S]
return std::make_shared<ov::op::v1::Transpose>(x, perm_bhls); // [B, H, L, S]
};
- // cos/sin always arrive rank-4 [B, L, 1, head/2]; just transpose to [B, 1, L, head/2].
+ // Normalize angles to [B, 1, L, head/2].
auto cossin_to_bhls = [&](ov::Output<ov::Node> x) -> ov::Output<ov::Node> {
+ if (mode == TYPE_IMROPE) {
+ x = std::make_shared<ov::op::v1::Reshape>(
+ x,
+ ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{0, -1, 1, n_rot / 2}),
+ true);
+ }
return std::make_shared<ov::op::v1::Transpose>(x, perm_bhls);
};
@@ -300,10 +298,24 @@ OutputVector translate_rope(const NodeContext& context) {
ov::Output<ov::Node> rotary_in;
ov::Output<ov::Node> pass_through;
split_rotary(x_bhls, rotary_in, pass_through);
-
ov::pass::NodeRegistry reg;
- ov::Output<ov::Node> roped =
- ov::decomposition::rope(reg, rotary_in, cos_bhls, sin_bhls, n_rot / 2); // [B, H, L, n_rot]
+ ov::Output<ov::Node> roped;
+ if (mode == TYPE_IMROPE) {
+ auto halves = std::make_shared<ov::op::v1::VariadicSplit>(
+ rotary_in,
+ ov::op::v0::Constant::create(ov::element::i64, {}, {3}),
+ ov::op::v0::Constant::create(ov::element::i64, {2}, std::vector<int64_t>{n_rot / 2, n_rot / 2}));
+ auto negative = std::make_shared<ov::op::v1::Multiply>(
+ halves->output(1),
+ ov::op::v0::Constant::create(rotary_in.get_element_type(), {}, {-1}));
+ auto rotated = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{negative, halves->output(0)}, -1);
+ auto cos_full = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{cos_bhls, cos_bhls}, -1);
+ auto sin_full = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{sin_bhls, sin_bhls}, -1);
+ roped = std::make_shared<ov::op::v1::Add>(std::make_shared<ov::op::v1::Multiply>(rotary_in, cos_full),
+ std::make_shared<ov::op::v1::Multiply>(rotated, sin_full));
+ } else {
+ roped = ov::decomposition::rope(reg, rotary_in, cos_bhls, sin_bhls, n_rot / 2);
+ }
if (n_rot < head_dim) {
roped = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{roped, pass_through}, -1);
}
@@ -313,49 +325,6 @@ OutputVector translate_rope(const NodeContext& context) {
res = std::make_shared<ov::op::v1::Transpose>(
roped,
ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3})); // [B, L, H, S]
- } else if (mode == TYPE_IMROPE) {
- // Partial rotary (ggml n_dims < head_dim): only the first n_rot dims of every head are
- // rotated, the tail is passed through unchanged -- e.g. qwen3.5 has head_dim 256 but
- // rope.dimension_count 64. cos/sin carry width n_rot/2, so the rotated block must be
- // exactly n_rot wide; using the full head here rotates the pass-through tail and corrupts
- // every full-attention layer. (Use output_shape, not data.get_shape() which throws
- // on a dynamic dim.)
- const int64_t head_dim = static_cast<int64_t>(output_shape[3].get_length());
- const int64_t n_rot = rope_config.n_dims > 0 ? rope_config.n_dims : head_dim;
-
- Output<Node> rotary_in = data;
- Output<Node> pass_through;
- if (n_rot < head_dim) {
- auto neg_one = ov::op::v0::Constant::create(ov::element::i64, {1}, {-1});
- auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});
- auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
- auto n_rot_c = ov::op::v0::Constant::create(ov::element::i64, {1}, {n_rot});
- auto head_c = ov::op::v0::Constant::create(ov::element::i64, {1}, {head_dim});
- rotary_in = std::make_shared<ov::op::v8::Slice>(data, zero, n_rot_c, one, neg_one);
- pass_through = std::make_shared<ov::op::v8::Slice>(data, n_rot_c, head_c, one, neg_one);
- }
-
- auto cos_sin_shape = std::make_shared<ov::op::v0::Constant>(ov::element::i64,
- ov::Shape{4},
- std::vector<int64_t>{0, -1, 1, (n_rot >> 1)});
- auto cos_reshaped = std::make_shared<ov::op::v1::Reshape>(cos_theta_node, cos_sin_shape, true);
- auto sin_reshaped = std::make_shared<ov::op::v1::Reshape>(sin_theta_node, cos_sin_shape, true);
-
- auto split_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {3});
- auto split_a = std::make_shared<ov::op::v1::Split>(rotary_in, split_axis, 2);
- auto x0 = split_a->output(0);
- auto x1 = split_a->output(1);
- auto mul_a = std::make_shared<ov::op::v1::Multiply>(x0, cos_reshaped);
- auto mul_b = std::make_shared<ov::op::v1::Multiply>(x1, sin_reshaped);
- auto sub = std::make_shared<ov::op::v1::Subtract>(mul_a, mul_b);
-
- auto mul_c = std::make_shared<ov::op::v1::Multiply>(x0, sin_reshaped);
- auto mul_d = std::make_shared<ov::op::v1::Multiply>(x1, cos_reshaped);
- auto add = std::make_shared<ov::op::v1::Add>(mul_c, mul_d);
-
- Output<Node> rotated = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{sub, add}, 3);
- res = (n_rot < head_dim) ? std::make_shared<ov::op::v0::Concat>(ov::OutputVector{rotated, pass_through}, 3)
- : rotated;
}
// Fail cleanly on an unmapped mode rather than dereferencing a null res downstream.
diff --git a/src/frontends/gguf/src/op/ssm_conv.cpp b/src/frontends/gguf/src/op/ssm_conv.cpp
index 8beddc9c736..0a5a00a5946 100644
--- a/src/frontends/gguf/src/op/ssm_conv.cpp
+++ b/src/frontends/gguf/src/op/ssm_conv.cpp
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
//
+#include <memory>
#include <vector>
#include "node_context.hpp"
@@ -9,6 +10,7 @@
#include "openvino/op/constant.hpp"
#include "openvino/op/group_conv.hpp"
#include "openvino/op/reshape.hpp"
+#include "openvino/op/swish.hpp"
#include "openvino/op/transpose.hpp"
#include "openvino/op/unsqueeze.hpp"
#include "utils.hpp"
@@ -51,6 +53,8 @@ OutputVector translate_ssm_conv(const NodeContext& context) {
// [n_s, d_inner, n_t] -> [n_s, n_t, d_inner]
auto perm = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{0, 2, 1});
auto transposed = std::make_shared<ov::op::v1::Transpose>(conv, perm);
+ if (context.get_attribute<bool>("fuse_silu", false))
+ transposed->set_argument(0, std::make_shared<ov::op::v4::Swish>(conv));
if (context.get_attribute<bool>("batch_major", false)) {
return rename_outputs_with_suffix(
diff --git a/src/frontends/gguf/src/pass/adapt_to_genai.cpp b/src/frontends/gguf/src/pass/adapt_to_genai.cpp
index 4ea9cf16739..dd4d7a097ad 100644
--- a/src/frontends/gguf/src/pass/adapt_to_genai.cpp
+++ b/src/frontends/gguf/src/pass/adapt_to_genai.cpp
@@ -96,6 +96,11 @@ public:
node = convert->input_value(0).get_node_shared_ptr();
}
auto gather = ov::as_type_ptr<v8::Gather>(node);
+ if (const auto reshape = ov::as_type_ptr<v1::Reshape>(node)) {
+ const auto multiply = ov::as_type_ptr<v1::Multiply>(reshape->get_input_node_shared_ptr(0));
+ if (multiply)
+ gather = ov::as_type_ptr<v8::Gather>(multiply->get_input_node_shared_ptr(1));
+ }
if (!gather) {
return false;
}
@@ -681,6 +686,17 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
if ((lm_head = ov::as_type_ptr<v0::MatMul>(node))) {
break;
}
+ if (ov::is_type<v0::Unsqueeze>(node) || ov::is_type<v1::Reshape>(node)) {
+ const auto axes = ov::as_type_ptr<v0::Constant>(node->get_input_node_shared_ptr(1));
+ const bool restored_layout =
+ ov::is_type<v1::Reshape>(node) || (axes && axes->cast_vector<int64_t>() == std::vector<int64_t>{1});
+ const auto head = ov::as_type_ptr<v0::MatMul>(node->get_input_node_shared_ptr(0));
+ if (restored_layout && head && head->get_output_partial_shape(0).rank() == 3) {
+ ov::replace_output_update_name(node->output(0), head->output(0));
+ lm_head = head;
+ }
+ break;
+ }
if (!ov::is_type<v1::Multiply>(node) && !ov::is_type<v0::Tanh>(node)) {
break;
}
@@ -688,15 +704,13 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
out = node->input_value(0);
}
const auto& hidden_ps = lm_head ? lm_head->get_input_partial_shape(0) : ov::PartialShape::dynamic();
- if (lm_head && hidden_ps.rank().is_static() && hidden_ps.size() == 4 && hidden_ps[3].is_static() &&
- lm_head->get_input_partial_shape(1).size() == 2) {
- auto hidden_3d = make_shared<v1::Reshape>(
- lm_head->input_value(0),
- make_shared<v0::Concat>(
- ov::OutputVector{batch_len,
- v0::Constant::create(ov::element::i64, {2}, {int64_t{-1}, hidden_ps[3].get_length()})},
- 0),
- false); // [batch, seq, hidden]
+ if (lm_head && hidden_ps.rank().is_static() && (hidden_ps.size() == 3 || hidden_ps.size() == 4) &&
+ hidden_ps[hidden_ps.size() - 1].is_static() && lm_head->get_input_partial_shape(1).size() == 2) {
+ const auto sequence_and_hidden_dims =
+ v0::Constant::create(ov::element::i64, {2}, {int64_t{-1}, hidden_ps[hidden_ps.size() - 1].get_length()});
+ const auto hidden_3d_shape = make_shared<v0::Concat>(ov::OutputVector{batch_len, sequence_and_hidden_dims}, 0);
+ auto hidden_3d =
+ make_shared<v1::Reshape>(lm_head->input_value(0), hidden_3d_shape, false); // [batch, seq, hidden]
lm_head->input(0).replace_source_output(hidden_3d);
lm_head->revalidate_and_infer_types();
// Softcap (x * (1/cap) -> tanh -> * cap): scalar constants keep the chain rank-3, and the
diff --git a/src/frontends/gguf/src/quant/weights.cpp b/src/frontends/gguf/src/quant/weights.cpp
index 0aebf37910d..a52b911e360 100644
--- a/src/frontends/gguf/src/quant/weights.cpp
+++ b/src/frontends/gguf/src/quant/weights.cpp
@@ -10,24 +10,40 @@
#include "weights.hpp"
+#include <algorithm>
#include <array>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <limits>
+#include <map>
#include <mutex>
+#include <set>
+#include <tuple>
#include <vector>
#include "openvino/core/except.hpp"
+#include "openvino/core/model.hpp"
#include "openvino/core/parallel.hpp"
#include "openvino/core/type/float16.hpp"
#include "openvino/decompositions/low_precision_dequantize.hpp"
+#include "openvino/op/add.hpp"
+#include "openvino/op/bitwise_and.hpp"
+#include "openvino/op/bitwise_right_shift.hpp"
+#include "openvino/op/concat.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/convert.hpp"
+#include "openvino/op/divide.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/matmul.hpp"
#include "openvino/op/multiply.hpp"
#include "openvino/op/reshape.hpp"
+#include "openvino/op/shape_of.hpp"
+#include "openvino/op/split.hpp"
#include "openvino/op/subtract.hpp"
+#include "openvino/op/transpose.hpp"
#include "openvino/util/common_util.hpp"
+#include "utils.hpp"
namespace ov::frontend::gguf {
@@ -204,10 +220,26 @@ std::shared_ptr<ov::Node> make_compressed(const WeightTensors& tensors, ov::elem
// Tensor copies share their shape metadata. View each buffer through a Constant
// without reshaping the caller's tensors: tied K/V projections reuse them.
auto scales_node = make_shared_constant(tensors.scales.get_element_type(), scale_shape, tensors.scales);
- const auto zp_node =
- tensors.zero_point
- ? make_shared_constant(tensors.zero_point.get_element_type(), scale_shape, tensors.zero_point)
- : nullptr;
+ auto zp_node = tensors.zero_point
+ ? make_shared_constant(tensors.zero_point.get_element_type(), scale_shape, tensors.zero_point)
+ : nullptr;
+ if (et == ov::element::u2 && tensors.zero_point) {
+ const auto all_one = [&](const auto* values) {
+ return std::all_of(values, values + tensors.zero_point.get_size(), [](auto value) {
+ return static_cast<float>(value) == 1.f;
+ });
+ };
+ const auto type = tensors.zero_point.get_element_type();
+ const bool uniform = type == ov::element::u8 ? all_one(tensors.zero_point.data<const uint8_t>())
+ : type == ov::element::f16 ? all_one(tensors.zero_point.data<const ov::float16>())
+ : false;
+ const auto* codes = static_cast<const uint8_t*>(tensors.weight.data());
+ if (uniform && std::none_of(codes, codes + tensors.weight.get_byte_size(), [](uint8_t value) {
+ return (value & (value >> 1) & 0x55) != 0;
+ })) {
+ zp_node = ov::op::v0::Constant::create(type, {}, {1});
+ }
+ }
auto final_shape_node =
std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{orig_shape.size()}, orig_shape);
@@ -237,6 +269,13 @@ std::shared_ptr<ov::Node> make_compressed(const WeightTensors& tensors, ov::elem
scales_node->output(0),
zp_node ? zp_node->output(0) : ov::Output<ov::Node>{},
final_shape_node->output(0));
+ if (zp_node && zp_node->get_shape().empty()) {
+ auto multiply = result.get_node_shared_ptr();
+ if (auto reshape = ov::as_type_ptr<ov::op::v1::Reshape>(multiply)) {
+ multiply = reshape->get_input_node_shared_ptr(0);
+ }
+ multiply->get_input_node_shared_ptr(0)->get_rt_info()["gguf_u2_zero_point_shape"] = scale_shape;
+ }
return std::make_shared<ov::op::v0::Convert>(result, ov::element::f32);
}
@@ -387,8 +426,240 @@ bool q4_k_f16_zero_point_enabled() {
return enabled;
}
+class ActivationGroups {
+public:
+ size_t get(const ov::Output<ov::Node>& output) {
+ if (const auto found = m_ids.find(output); found != m_ids.end())
+ return found->second;
+ const auto node = output.get_node_shared_ptr();
+ if (!node->get_control_dependencies().empty() || !node->get_control_dependents().empty())
+ return m_ids[output] = m_next++;
+ std::vector<int64_t> attributes;
+ bool comparable = true;
+ if (const auto reshape = ov::as_type_ptr<ov::op::v1::Reshape>(node)) {
+ const auto& shape = reshape->get_input_partial_shape(0);
+ const auto pattern = ov::as_type_ptr<ov::op::v0::Constant>(reshape->get_input_node_shared_ptr(1));
+ if (pattern && shape.rank().is_static() && shape == output.get_partial_shape() &&
+ (shape.is_static() ||
+ (shape.size() > 0 && std::all_of(shape.begin() + 1, shape.end(), [](const ov::Dimension& dim) {
+ return dim.is_static();
+ }))))
+ return m_ids[output] = get(reshape->input_value(0));
+ attributes.push_back(reshape->get_special_zero());
+ } else if (const auto convert = ov::as_type_ptr<ov::op::v0::Convert>(node)) {
+ if (convert->get_input_element_type(0) == convert->get_element_type())
+ return m_ids[output] = get(convert->input_value(0));
+ attributes.push_back(static_cast<int64_t>(static_cast<ov::element::Type_t>(convert->get_element_type())));
+ } else if (const auto shape = ov::as_type_ptr<ov::op::v3::ShapeOf>(node))
+ attributes.push_back(static_cast<int64_t>(static_cast<ov::element::Type_t>(shape->get_output_type())));
+ else if (const auto split = ov::as_type_ptr<ov::op::v1::Split>(node))
+ attributes.push_back(split->get_num_splits());
+ else if (const auto gather = ov::as_type_ptr<ov::op::v8::Gather>(node))
+ attributes.push_back(gather->get_batch_dims());
+ else if (const auto concat = ov::as_type_ptr<ov::op::v0::Concat>(node))
+ attributes.push_back(concat->get_axis());
+ else if (ov::is_type<ov::op::v1::Add>(node) || ov::is_type<ov::op::v1::Subtract>(node) ||
+ ov::is_type<ov::op::v1::Multiply>(node) || ov::is_type<ov::op::v1::Divide>(node)) {
+ const auto binary = ov::as_type_ptr<ov::op::util::BinaryElementwiseArithmetic>(node);
+ attributes = {static_cast<int64_t>(binary->get_autob().m_type), binary->get_autob().m_axis};
+ } else
+ comparable = ov::is_type<ov::op::v1::Transpose>(node);
+ if (const auto constant = ov::as_type_ptr<ov::op::v0::Constant>(node)) {
+ auto& constants = m_constants[{constant->get_element_type(), constant->get_shape()}];
+ for (const auto& [value, id] : constants) {
+ if (std::memcmp(value->get_data_ptr(), constant->get_data_ptr(), constant->get_byte_size()) == 0)
+ return m_ids[output] = id;
+ }
+ const auto id = m_next++;
+ constants.emplace_back(constant, id);
+ return m_ids[output] = id;
+ }
+ if (!comparable)
+ return m_ids[output] = m_next++;
+ std::vector<size_t> inputs;
+ for (const auto& input : node->input_values())
+ inputs.push_back(get(input));
+ const auto key = std::make_tuple(node->get_type_info(), output.get_index(), inputs, attributes);
+ auto [found, inserted] = m_operations.emplace(key, m_next);
+ if (inserted)
+ ++m_next;
+ return m_ids[output] = found->second;
+ }
+
+private:
+ size_t m_next = 0;
+ std::map<ov::Output<ov::Node>, size_t> m_ids;
+ std::map<std::pair<ov::element::Type, ov::Shape>,
+ std::vector<std::pair<std::shared_ptr<ov::op::v0::Constant>, size_t>>>
+ m_constants;
+ std::map<std::tuple<ov::DiscreteTypeInfo, size_t, std::vector<size_t>, std::vector<int64_t>>, size_t> m_operations;
+};
+
} // namespace
+ov::Output<ov::Node> gather_weight_rows(const ov::Output<ov::Node>& data, const ov::Output<ov::Node>& indices) {
+ const auto axis = ov::op::v0::Constant::create(ov::element::i32, {}, {0});
+ const auto gather = [&]() -> ov::Output<ov::Node> {
+ return std::make_shared<ov::op::v8::Gather>(data, indices, axis);
+ };
+ const auto output_convert = ov::as_type_ptr<ov::op::v0::Convert>(data.get_node_shared_ptr());
+ if (!output_convert || data.get_element_type() != ov::element::f32 || !data.get_partial_shape().is_static() ||
+ data.get_partial_shape().rank() != 2 || indices.get_partial_shape().rank() != 2)
+ return gather();
+ const auto reshape = ov::as_type_ptr<ov::op::v1::Reshape>(output_convert->get_input_node_shared_ptr(0));
+ if (!reshape)
+ return gather();
+ const auto multiply = ov::as_type_ptr<ov::op::v1::Multiply>(reshape->get_input_node_shared_ptr(0));
+ if (!multiply || multiply->get_element_type() != ov::element::f16)
+ return gather();
+ const auto scales = ov::as_type_ptr<ov::op::v0::Constant>(multiply->get_input_node_shared_ptr(1));
+ const auto subtract = ov::as_type_ptr<ov::op::v1::Subtract>(multiply->get_input_node_shared_ptr(0));
+ if (!scales || scales->get_element_type() != ov::element::f16 || !subtract)
+ return gather();
+ const auto convert = ov::as_type_ptr<ov::op::v0::Convert>(subtract->get_input_node_shared_ptr(0));
+ const auto zp_convert = ov::as_type_ptr<ov::op::v0::Convert>(subtract->get_input_node_shared_ptr(1));
+ if (!convert || convert->get_element_type() != ov::element::f16)
+ return gather();
+ const auto weights = ov::as_type_ptr<ov::op::v0::Constant>(convert->get_input_node_shared_ptr(0));
+ const auto zp = ov::as_type_ptr<ov::op::v0::Constant>(zp_convert ? zp_convert->get_input_node_shared_ptr(0)
+ : subtract->get_input_node_shared_ptr(1));
+ if (!weights || weights->get_element_type() != ov::element::u2 || weights->get_shape().size() != 3 ||
+ weights->get_shape().back() % 4 != 0 || !zp ||
+ (zp->get_element_type() != ov::element::u8 && zp->get_element_type() != ov::element::f16) ||
+ !zp->get_shape().empty() || zp->cast_vector<float>()[0] != 1.f)
+ return gather();
+
+ const auto shape = data.get_shape();
+ const auto rows = shape[0];
+ const auto cols = shape[1];
+ if (weights->get_shape()[0] != rows || weights->get_shape()[1] * weights->get_shape()[2] != cols ||
+ scales->get_shape() != ov::Shape{rows, weights->get_shape()[1], 1})
+ return gather();
+ const auto& compressed_shape = weights->get_shape();
+ // Gather packed bytes before unpacking, sharing the original two-bit buffer.
+ auto dictionary =
+ std::make_shared<ov::op::v0::Constant>(ov::element::u8,
+ ov::Shape{rows, compressed_shape[1], compressed_shape[2] / 4},
+ weights->get_data_ptr(),
+ weights);
+ dictionary->set_friendly_name(weights->get_friendly_name() + "_gather_packed_u2");
+ auto selected = std::make_shared<ov::op::v8::Gather>(dictionary, indices, axis);
+ auto packed_values = std::make_shared<ov::op::v0::Convert>(selected, ov::element::i32);
+ auto expanded = std::make_shared<ov::op::v1::Reshape>(
+ packed_values,
+ ov::op::v0::Constant::create(ov::element::i64,
+ {5},
+ std::vector<int64_t>{0,
+ 0,
+ static_cast<int64_t>(compressed_shape[1]),
+ static_cast<int64_t>(compressed_shape[2] / 4),
+ 1}),
+ true);
+ auto shifted = std::make_shared<ov::op::v15::BitwiseRightShift>(
+ expanded,
+ ov::op::v0::Constant::create(ov::element::i32, {4}, {0, 2, 4, 6}));
+ auto codes =
+ std::make_shared<ov::op::v13::BitwiseAnd>(shifted, ov::op::v0::Constant::create(ov::element::i32, {}, {3}));
+ auto grouped = std::make_shared<ov::op::v1::Reshape>(
+ codes,
+ ov::op::v0::Constant::create(ov::element::i64,
+ {4},
+ std::vector<int64_t>{0,
+ 0,
+ static_cast<int64_t>(weights->get_shape()[1]),
+ static_cast<int64_t>(weights->get_shape()[2])}),
+ true);
+ auto values = std::make_shared<ov::op::v0::Convert>(grouped, ov::element::f16);
+ auto signs = std::make_shared<ov::op::v1::Subtract>(values, subtract->input_value(1));
+ auto selected_scales = std::make_shared<ov::op::v8::Gather>(scales, indices, axis);
+ auto dequantized = std::make_shared<ov::op::v1::Multiply>(signs, selected_scales);
+ auto restored = std::make_shared<ov::op::v1::Reshape>(
+ dequantized,
+ ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{0, 0, static_cast<int64_t>(cols)}),
+ true);
+ return std::make_shared<ov::op::v0::Convert>(restored, ov::element::f32);
+}
+
+void normalize_u2_zero_points(const std::shared_ptr<ov::Model>& model) {
+ const auto nodes = model->get_ordered_ops();
+ if (std::none_of(nodes.begin(), nodes.end(), [](const std::shared_ptr<ov::Node>& node) {
+ return node->get_rt_info().count("gguf_u2_zero_point_shape") != 0 ||
+ node->get_rt_info().count("gguf_hadamard_block") != 0;
+ })) {
+ return;
+ }
+ ActivationGroups activations;
+ struct Projection {
+ std::shared_ptr<ov::op::v1::Subtract> subtract;
+ ov::Shape shape;
+ ov::element::Type zp_type;
+ ov::Output<ov::Node> input;
+ };
+ std::map<size_t, std::vector<Projection>> projections;
+ for (const auto& node : nodes) {
+ const auto matmul = ov::as_type_ptr<ov::op::v0::MatMul>(node);
+ if (!matmul)
+ continue;
+ auto weight = matmul->get_input_node_shared_ptr(1);
+ while (ov::is_type<ov::op::v0::Convert>(weight) || ov::is_type<ov::op::v1::Reshape>(weight) ||
+ ov::is_type<ov::op::v1::Transpose>(weight)) {
+ weight = weight->get_input_node_shared_ptr(0);
+ }
+ const auto multiply = ov::as_type_ptr<ov::op::v1::Multiply>(weight);
+ if (!multiply)
+ continue;
+ const auto subtract = ov::as_type_ptr<ov::op::v1::Subtract>(multiply->get_input_node_shared_ptr(0));
+ if (!subtract)
+ continue;
+ const auto convert = ov::as_type_ptr<ov::op::v0::Convert>(subtract->get_input_node_shared_ptr(0));
+ if (!convert || convert->get_input_element_type(0) != ov::element::u2)
+ continue;
+ const auto& rt_info = subtract->get_rt_info();
+ const auto shape = rt_info.find("gguf_u2_zero_point_shape");
+ auto input = matmul->input_value(0);
+ while (ov::is_type<ov::op::v0::Convert>(input.get_node_shared_ptr()))
+ input = input.get_node_shared_ptr()->input_value(0);
+ const auto zp_convert = ov::as_type_ptr<ov::op::v0::Convert>(subtract->get_input_node_shared_ptr(1));
+ const auto zp_type = zp_convert ? zp_convert->get_input_element_type(0) : subtract->get_input_element_type(1);
+ projections[activations.get(input)].push_back(
+ {subtract, shape == rt_info.end() ? ov::Shape{} : shape->second.as<ov::Shape>(), zp_type, input});
+ }
+ std::set<ov::Node*> grouped;
+ for (const auto& [input, group] : projections) {
+ for (const auto& projection : group) {
+ if (projection.shape.empty())
+ grouped.insert(projection.subtract.get());
+ }
+ }
+ bool changed;
+ do {
+ changed = false;
+ for (const auto& [input, group] : projections) {
+ if (std::none_of(group.begin(), group.end(), [&](const Projection& projection) {
+ return grouped.count(projection.subtract.get()) != 0;
+ })) {
+ continue;
+ }
+ for (const auto& projection : group)
+ changed |= grouped.insert(projection.subtract.get()).second;
+ }
+ } while (changed);
+ // Keep shared-input projections uniformly grouped when one needs the code-3 fallback.
+ for (const auto& [input, group] : projections) {
+ for (const auto& projection : group) {
+ if (!grouped.count(projection.subtract.get()))
+ continue;
+ if (!projection.shape.empty()) {
+ auto zp = ov::op::v0::Constant::create(projection.zp_type, projection.shape, {1});
+ projection.subtract->input(1).replace_source_output(
+ std::make_shared<ov::op::v0::Convert>(zp, projection.subtract->get_element_type()));
+ projection.subtract->get_rt_info().erase("gguf_u2_zero_point_shape");
+ }
+ decompose_hadamard(projection.input);
+ }
+ }
+}
+
bool native_q5_k_is_symmetric(const std::string& name) {
return !is_embedding_or_output(name) && ov::util::ends_with(name, ".weight");
}
@@ -454,7 +725,7 @@ ov::element::Type gguf_zero_point_type(const std::string& name, GgufTensorType q
// request the faithful f16 zero-point of both u4 formats 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. token_embd/output keep a faithful f16 zero-point.
- if (qtype == GGUF_TYPE_Q2_0 || qtype == GGUF_TYPE_PQ2_0 || qtype == GGUF_TYPE_PTQ1_0) {
+ if (qtype == GGUF_TYPE_Q2_0) {
return ov::element::u8;
}
const bool requantized = qtype == GGUF_TYPE_Q5_K ||
diff --git a/src/frontends/gguf/src/quant/weights.hpp b/src/frontends/gguf/src/quant/weights.hpp
index dc80d083fc0..fefc2ea40e1 100644
--- a/src/frontends/gguf/src/quant/weights.hpp
+++ b/src/frontends/gguf/src/quant/weights.hpp
@@ -10,13 +10,19 @@
#include <unordered_map>
#include "gguf.hpp"
+#include "openvino/core/node_output.hpp"
namespace ov {
class Node;
-}
+class Model;
+} // namespace ov
namespace ov::frontend::gguf {
+void normalize_u2_zero_points(const std::shared_ptr<ov::Model>& model);
+
+ov::Output<ov::Node> gather_weight_rows(const ov::Output<ov::Node>& data, const ov::Output<ov::Node>& indices);
+
// Element type of the zero-point constant for an asymmetric quantized weight.
// Q2_0 always uses u8. The raw-byte Q8_0_C requantization path separately uses temporary f16
// zero-points for its host dequantizer, including Q2_0 embedding/output tensors.
diff --git a/src/frontends/gguf/src/translate_session.cpp b/src/frontends/gguf/src/translate_session.cpp
index b1054765659..0579bc5c615 100644
--- a/src/frontends/gguf/src/translate_session.cpp
+++ b/src/frontends/gguf/src/translate_session.cpp
@@ -13,6 +13,7 @@
#include <unordered_set>
#include "builder/gguf_builder_decoder.hpp"
+#include "hadamard_sign_folding.hpp"
#include "input_model.hpp"
#include "node_context.hpp"
#include "openvino/core/graph_util.hpp"
@@ -44,6 +45,7 @@
#include "openvino/pass/manager.hpp"
#include "pass/lower_set_rows_stateless.hpp"
#include "pass/prune_orphaned_parameters.hpp"
+#include "quant/weights.hpp"
#include "transformations/common_optimizations/fuse_gated_delta_net.hpp"
#include "transformations/common_optimizations/nop_elimination.hpp"
#include "transformations/common_optimizations/optimize_strided_slice.hpp"
@@ -114,7 +116,8 @@ void prepare_graph_inputs(TensorMap& tensor_map, GgufDecoder& gguf_model_decoder
void translate_node(const std::shared_ptr<GgufDecoder>& decoder,
std::shared_ptr<TensorMap>& tensor_map,
- const std::unordered_map<std::string, CreatorFunction>& translators) {
+ const std::unordered_map<std::string, CreatorFunction>& translators,
+ const std::shared_ptr<ConstantCache>& constant_cache) {
const auto& operation_type = decoder->get_op_type();
if (operation_type == "GGML_OP_NONE") {
// A GGML_OP_NONE leaf is a weight if the decoder marks it as one: either the native
@@ -135,7 +138,7 @@ void translate_node(const std::shared_ptr<GgufDecoder>& decoder,
"Translation for operation type ",
operation_type,
" is not implemented.");
- NodeContext node_context(decoder, tensor_map);
+ NodeContext node_context(decoder, tensor_map, constant_cache);
converted_outputs = it->second(node_context);
const auto& node_output_names = decoder->get_output_names();
@@ -217,8 +220,9 @@ std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputMo
// translate_weight turns into a compressed subgraph during the walk below, which keeps them
// lazy (never materialized to f32) and keeps one weight-loading path for both ingest paths.
+ const auto constant_cache = std::make_shared<ConstantCache>();
auto node_visitor = [&](std::shared_ptr<GgufDecoder> decoder) {
- translate_node(decoder, tensor_map, m_translator_map);
+ translate_node(decoder, tensor_map, m_translator_map, constant_cache);
};
// Build the shared LLM scaffolding (sliced attention mask + rope sin/cos table) once, so all
@@ -397,7 +401,9 @@ std::shared_ptr<Model> TranslateSession::apply_transformations(std::shared_ptr<M
manager.register_pass<pass::PruneParametersOrphanedSince>(live_before_gdn);
}
+ fold_hadamard_input_signs(model);
manager.run_passes(model);
+ normalize_u2_zero_points(model);
return model;
}
diff --git a/src/frontends/gguf/src/translate_session.hpp b/src/frontends/gguf/src/translate_session.hpp
index 354bb389a21..9dd0647fcdd 100644
--- a/src/frontends/gguf/src/translate_session.hpp
+++ b/src/frontends/gguf/src/translate_session.hpp
@@ -13,7 +13,8 @@ namespace ov::frontend::gguf {
void prepare_graph_inputs(TensorMap& values, GgufDecoder& decoder);
void translate_node(const std::shared_ptr<GgufDecoder>& decoder,
std::shared_ptr<TensorMap>& values,
- const std::unordered_map<std::string, CreatorFunction>& translators);
+ const std::unordered_map<std::string, CreatorFunction>& translators,
+ const std::shared_ptr<ConstantCache>& constant_cache = {});
class TranslateSession {
public:
diff --git a/src/frontends/gguf/src/utils.cpp b/src/frontends/gguf/src/utils.cpp
index dbf57810d56..0fe5e8e0cfd 100644
--- a/src/frontends/gguf/src/utils.cpp
+++ b/src/frontends/gguf/src/utils.cpp
@@ -11,7 +11,9 @@
#include <numeric>
#include <string>
+#include "openvino/core/graph_util.hpp"
#include "openvino/core/model.hpp"
+#include "openvino/core/rt_info.hpp"
#include "openvino/op/add.hpp"
#include "openvino/op/clamp.hpp"
#include "openvino/op/concat.hpp"
@@ -21,6 +23,7 @@
#include "openvino/op/cos.hpp"
#include "openvino/op/divide.hpp"
#include "openvino/op/gather.hpp"
+#include "openvino/op/matmul.hpp"
#include "openvino/op/maximum.hpp"
#include "openvino/op/multiply.hpp"
#include "openvino/op/parameter.hpp"
@@ -34,11 +37,97 @@
#include "openvino/op/squeeze.hpp"
#include "openvino/op/subtract.hpp"
#include "openvino/op/transpose.hpp"
+#include "openvino/op/unsqueeze.hpp"
#include "openvino/op/variadic_split.hpp"
+#include "transformations/rt_info/disable_precision_conversion.hpp"
namespace ov::frontend::gguf {
-ov::Output<ov::Node> apply_hadamard(const NodeContext& context, ov::Output<ov::Node> input) {
+namespace {
+constexpr char hadamard_marker[] = "gguf_hadamard_block";
+
+Output<Node> hadamard_butterfly(Output<Node> input,
+ int64_t block,
+ const NodeContext* context = nullptr,
+ bool keep_fp32 = false) {
+ using namespace ov::op;
+ const auto original_type = input.get_element_type();
+ if (keep_fp32 && original_type != ov::element::f32)
+ input = std::make_shared<v0::Convert>(input, ov::element::f32);
+ const auto constant = [&](ov::element::Type type, const ov::Shape& shape, const std::vector<int64_t>& values) {
+ return context ? context->get_constant(type, shape, values) : v0::Constant::create(type, shape, values);
+ };
+ const auto axis = constant(ov::element::i64, {}, {1});
+ for (int64_t stride = 1; stride < block; stride *= 2) {
+ std::vector<int64_t> indices(block), stage_signs(block);
+ for (int64_t i = 0; i < block; ++i) {
+ indices[i] = i ^ stride;
+ stage_signs[i] = (i & stride) == 0 ? 1 : -1;
+ }
+ const auto permuted =
+ std::make_shared<v8::Gather>(input,
+ constant(ov::element::i64, {static_cast<size_t>(block)}, indices),
+ axis);
+ const auto signed_input = std::make_shared<v1::Multiply>(
+ input,
+ constant(input.get_element_type(), {static_cast<size_t>(block)}, stage_signs));
+ input = std::make_shared<v1::Add>(signed_input, permuted);
+ if (keep_fp32) {
+ for (const auto& node : ov::NodeVector{permuted, signed_input, input.get_node_shared_ptr()})
+ ov::disable_conversion(node, ov::element::f16);
+ }
+ }
+ const auto scale = v0::Constant::create(input.get_element_type(), {}, {1.f / std::sqrt(static_cast<float>(block))});
+ input = std::make_shared<v1::Multiply>(input, scale);
+ if (keep_fp32) {
+ ov::disable_conversion(input.get_node_shared_ptr(), ov::element::f16);
+ if (original_type != ov::element::f32)
+ input = std::make_shared<v0::Convert>(input, original_type);
+ }
+ return input;
+}
+} // namespace
+
+Output<Node>* NodeContext::get_hadamard_cache_entry(const Output<Node>& input,
+ int64_t block,
+ bool inverse,
+ bool matrix_form,
+ const std::vector<int64_t>& heads,
+ const ov::Tensor& signs) const {
+ if (signs && !signs.is_continuous())
+ return nullptr;
+ auto type = ov::element::Type_t::dynamic;
+ ov::Shape shape;
+ std::vector<uint8_t> values;
+ if (signs) {
+ type = static_cast<ov::element::Type_t>(signs.get_element_type());
+ shape = signs.get_shape();
+ const auto* bytes = static_cast<const uint8_t*>(signs.data());
+ values.assign(bytes, bytes + signs.get_byte_size());
+ }
+ return &m_constant_cache->hadamard_outputs[{input, block, inverse, matrix_form, heads, type, shape, values}];
+}
+
+Output<Node> NodeContext::get_f32_activation(const Output<Node>& input) const {
+ if (input.get_element_type() == ov::element::f32)
+ return input;
+ auto& output = m_constant_cache->f32_activations[input];
+ if (!output.get_node())
+ output = std::make_shared<ov::op::v0::Convert>(input, ov::element::f32);
+ return output;
+}
+
+Output<Node> NodeContext::get_rank3_activation(const Output<Node>& input) const {
+ auto& output = m_constant_cache->rank3_activations[input];
+ if (!output.get_node()) {
+ const auto width = input.get_partial_shape()[3].get_length();
+ output =
+ std::make_shared<ov::op::v1::Reshape>(input, get_constant(ov::element::i64, {3}, {0, -1, width}), true);
+ }
+ return output;
+}
+
+ov::Output<ov::Node> apply_hadamard(const NodeContext& context, ov::Output<ov::Node> input, bool matrix_form) {
const auto block = context.get_attribute<int64_t>("hadamard_block", 0);
if (block == 0)
return input;
@@ -50,10 +139,18 @@ ov::Output<ov::Node> apply_hadamard(const NodeContext& context, ov::Output<ov::N
FRONT_END_OP_CONVERSION_CHECK(block > 0 && block <= 4096 && (block & (block - 1)) == 0 && width % block == 0,
"Invalid Hadamard block size/width");
const auto pattern = [&](const std::vector<int64_t>& dims) {
- return v0::Constant::create(ov::element::i64, {dims.size()}, dims);
+ return context.get_constant(ov::element::i64, {dims.size()}, dims);
};
- const auto original = std::make_shared<v3::ShapeOf>(input, ov::element::i64);
const auto heads = context.get_attribute<std::vector<int64_t>>("hadamard_gdn_heads", {});
+ const auto signs = context.get_attribute<ov::Tensor>("hadamard_signs", ov::Tensor{});
+ const bool inverse = context.get_attribute<bool>("hadamard_inverse", false);
+ const bool use_matrix =
+ (matrix_form || inverse) && block >= 256 &&
+ (input.get_element_type() == ov::element::f32 || input.get_element_type() == ov::element::f16);
+ auto* cached = context.get_hadamard_cache_entry(input, block, inverse, use_matrix, heads, signs);
+ if (cached && cached->get_node())
+ return *cached;
+ const auto original = std::make_shared<v3::ShapeOf>(input, ov::element::i64);
if (!heads.empty()) {
FRONT_END_OP_CONVERSION_CHECK(heads.size() == 3 && heads[0] * heads[1] * heads[2] == width,
"Invalid Hadamard GDN feature order");
@@ -61,32 +158,55 @@ ov::Output<ov::Node> apply_hadamard(const NodeContext& context, ov::Output<ov::N
input = std::make_shared<v1::Transpose>(input, pattern({0, 2, 1, 3}));
input = std::make_shared<v1::Reshape>(input, original, false);
}
- const auto signs = context.get_attribute<ov::Tensor>("hadamard_signs", ov::Tensor{});
- const bool inverse = context.get_attribute<bool>("hadamard_inverse", false);
ov::Output<ov::Node> sign_node;
if (signs) {
sign_node = std::make_shared<v0::Constant>(signs);
if (sign_node.get_element_type() != input.get_element_type())
sign_node = std::make_shared<v1::ConvertLike>(sign_node, input);
}
- if (signs && !inverse)
+ if (signs && !inverse) {
input = std::make_shared<v1::Multiply>(input, sign_node);
- const auto axis = v0::Constant::create(ov::element::i64, {}, {2});
- for (int64_t stride = 1; stride < block; stride *= 2) {
- auto grouped = std::make_shared<v1::Reshape>(input, pattern({-1, block / (2 * stride), 2, stride}), false);
- auto halves = std::make_shared<v1::Split>(grouped, axis, 2);
- auto sum = std::make_shared<v1::Add>(halves->output(0), halves->output(1));
- auto difference = std::make_shared<v1::Subtract>(halves->output(0), halves->output(1));
- input = std::make_shared<v0::Concat>(ov::OutputVector{sum, difference}, 2);
+ input.get_node_shared_ptr()->get_rt_info()["gguf_hadamard_input_sign"] = true;
+ }
+ input = std::make_shared<v1::Reshape>(input, pattern({-1, block}), false);
+ if (use_matrix) {
+ input = std::make_shared<v0::MatMul>(input,
+ context.get_hadamard_matrix(input.get_element_type(), block),
+ false,
+ false);
+ input.get_node_shared_ptr()->get_rt_info()[hadamard_marker] = block;
+ } else {
+ input = hadamard_butterfly(input, block, &context, block == 1024);
}
- const auto scale = v0::Constant::create(input.get_element_type(), {}, {1.f / std::sqrt(static_cast<float>(block))});
- input = std::make_shared<v1::Multiply>(input, scale);
input = std::make_shared<v1::Reshape>(input, original, false);
if (signs && inverse)
input = std::make_shared<v1::Multiply>(input, sign_node);
+ if (cached)
+ *cached = input;
return input;
}
+void decompose_hadamard(Output<Node> input) {
+ while (ov::is_type<ov::op::v0::Convert>(input.get_node_shared_ptr()) ||
+ ov::is_type<ov::op::v1::Reshape>(input.get_node_shared_ptr()) ||
+ ov::is_type<ov::op::v0::Squeeze>(input.get_node_shared_ptr()) ||
+ ov::is_type<ov::op::v0::Unsqueeze>(input.get_node_shared_ptr())) {
+ input = input.get_node()->input_value(0);
+ }
+ const auto rotation = ov::as_type_ptr<ov::op::v0::MatMul>(input.get_node_shared_ptr());
+ if (!rotation)
+ return;
+ const auto marker = rotation->get_rt_info().find(hadamard_marker);
+ if (marker == rotation->get_rt_info().end() || rotation->output(0).get_target_inputs().empty())
+ return;
+ const auto replacement = hadamard_butterfly(rotation->input_value(0), marker->second.as<int64_t>(), nullptr, true);
+ rotation->get_rt_info().erase(marker);
+ ov::copy_runtime_info(rotation, replacement.get_node_shared_ptr());
+ ov::copy_output_runtime_info({rotation->output(0)}, {replacement});
+ replacement.get_node_shared_ptr()->set_friendly_name(rotation->get_friendly_name());
+ ov::replace_node(rotation, replacement.get_node_shared_ptr());
+}
+
void num_inputs_check(const NodeContext& context, size_t min_inputs, size_t max_inputs) {
auto input_size = context.get_input_size();
FRONT_END_OP_CONVERSION_CHECK(input_size >= min_inputs, "Got less inputs than expected");
diff --git a/src/frontends/gguf/src/utils.hpp b/src/frontends/gguf/src/utils.hpp
index 25337cf7c39..05605b308f4 100644
--- a/src/frontends/gguf/src/utils.hpp
+++ b/src/frontends/gguf/src/utils.hpp
@@ -62,7 +62,8 @@ std::shared_ptr<ov::Node> get_dimensions(const ov::Output<ov::Node>& output, con
// x / max(sqrt(sum(x^2, -1)), eps), matching ggml's l2_norm.
ov::Output<ov::Node> make_l2_norm(const ov::Output<ov::Node>& x, float eps);
-ov::Output<ov::Node> apply_hadamard(const NodeContext& context, ov::Output<ov::Node> input);
+ov::Output<ov::Node> apply_hadamard(const NodeContext& context, ov::Output<ov::Node> input, bool matrix_form = false);
+void decompose_hadamard(ov::Output<ov::Node> input);
/// \brief Give `out`'s producer and its first output tensor the same name.
void name_output(const ov::Output<ov::Node>& out, const std::string& name);
diff --git a/src/frontends/gguf/tests/CMakeLists.txt b/src/frontends/gguf/tests/CMakeLists.txt
index 44e0dc117c5..b600be6ecb0 100644
--- a/src/frontends/gguf/tests/CMakeLists.txt
+++ b/src/frontends/gguf/tests/CMakeLists.txt
@@ -22,6 +22,7 @@ set(FRONTEND_SRCS
"${FE_SRC_DIR}/op_table.cpp"
"${FE_SRC_DIR}/translate_session.cpp"
"${FE_SRC_DIR}/utils.cpp"
+ "${FE_SRC_DIR}/hadamard_sign_folding.cpp"
"${FE_SRC_DIR}/helper_ops/set_rows_op.cpp"
"${FE_SRC_DIR}/pass/adapt_to_genai.cpp"
"${FE_SRC_DIR}/pass/adapt_mmproj_to_genai.cpp"
@@ -116,6 +117,8 @@ set(TEST_SRCS
"${CMAKE_CURRENT_SOURCE_DIR}/test_ops.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/test_parser.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/test_weights.cpp"
+ "${CMAKE_CURRENT_SOURCE_DIR}/test_shared_linear_inputs.cpp"
+ "${CMAKE_CURRENT_SOURCE_DIR}/test_hadamard_sign_folding.cpp"
)
set(GGUF_TEST_DATA_DIR "${CMAKE_CURRENT_SOURCE_DIR}/test_data")
diff --git a/src/frontends/gguf/tests/test_adapt_to_genai.cpp b/src/frontends/gguf/tests/test_adapt_to_genai.cpp
index c5bf9f06dbc..9cc47463922 100644
--- a/src/frontends/gguf/tests/test_adapt_to_genai.cpp
+++ b/src/frontends/gguf/tests/test_adapt_to_genai.cpp
@@ -18,6 +18,7 @@
#include "common_test_utils/node_builders/constant.hpp"
#include "gtest/gtest.h"
+#include "node_context.hpp"
#include "op_test_utils.hpp"
#include "openvino/core/validation_util.hpp"
#include "openvino/core/visibility.hpp"
@@ -53,6 +54,7 @@
#include "openvino/pass/sdpa_to_paged_attention.hpp"
#include "openvino/pass/serialize.hpp"
#include "openvino/runtime/system_conf.hpp"
+#include "quant/weights.hpp"
#include "utils.hpp"
using namespace ov_gguf_test;
@@ -523,6 +525,42 @@ TEST(GGUFAdaptToGenAI, EmbeddingModeMapsGenAIMultimodalPositionsToGGML) {
// translate_get_rows's embedding lookup restores ggml's rank-4 form with Unsqueeze(axis=0),
// pinning the leading axis to a literal 1. AdaptToGenAI moves it to axis 1 so it instead mirrors
// input_ids' own (backend-dependent) leading dim -- see FixEmbdAxis in adapt_to_genai.cpp.
+TEST(GGUFAdaptToGenAI, PackedTernaryEmbeddingAdaptsForBatchedLookup) {
+ constexpr size_t vocab = 4;
+ constexpr size_t hidden = 256;
+ auto m = build_minimal_gguf_model(vocab, hidden);
+ const auto bytes = load_npy<uint8_t>("pq2_0_qbytes");
+ ov::Tensor payload(ov::element::u8, {bytes.size()});
+ std::memcpy(payload.data(), bytes.data(), bytes.size());
+ auto weight = make_weight_node(payload, "PQ2_0", {vocab, hidden});
+ auto decoder = SingleOpBuilder()
+ .op("GGML_OP_GET_ROWS")
+ .input("weight", ov::element::f32, {vocab, hidden})
+ .input("inp_tokens", ov::element::i32, {1, 1, 1, -1})
+ .output("embd", ov::element::f32, {1, 1, -1, hidden})
+ .decoder();
+ auto tensors = std::make_shared<TensorMap>();
+ (*tensors)["weight"] = weight;
+ (*tensors)["inp_tokens"] = m.inp_tokens;
+ NodeContext context(decoder, tensors);
+ auto embedding = op::translate_get_rows(context)[0].get_node_shared_ptr();
+ embedding->set_friendly_name(m.embd->get_friendly_name());
+ embedding->get_rt_info()["gguf.token_embedding"] = true;
+ m.embd->output(0).replace(embedding);
+ AdaptToGenAI pass(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS);
+ ASSERT_TRUE(pass.run_on_model(m.model));
+ const auto lookup = pass.get_embedding_model();
+ ASSERT_TRUE(lookup);
+ const auto reference = load_npy<float>("pq2_0_deq");
+ const auto ids = make_i64_tensor({2, 3}, {3, 0, 1, 2, 1, 3});
+ auto output = run_on_cpu(lookup, {{lookup->input().get_any_name(), ids}});
+ ASSERT_EQ(output.get_shape(), (ov::Shape{2, 3, hidden}));
+ for (size_t i = 0; i < ids.get_size(); ++i) {
+ for (size_t j = 0; j < hidden; ++j)
+ EXPECT_FLOAT_EQ(output.data<float>()[i * hidden + j], reference[ids.data<const int64_t>()[i] * hidden + j]);
+ }
+}
+
TEST(GGUFAdaptToGenAI, FixesEmbdAxisStructurally) {
auto m = build_minimal_gguf_model();
auto embd_gather_input = m.embd->input_value(0); // survives the Unsqueeze replacement
@@ -1065,6 +1103,42 @@ std::shared_ptr<v0::MatMul> find_genai_lm_head(const std::shared_ptr<ov::Model>&
} // namespace
+TEST(GGUFAdaptToGenAI, PackedTernaryEmbeddingSurvivesPagedAttentionPrefill) {
+ constexpr size_t vocab = 4;
+ constexpr size_t hidden = 256;
+ auto model = build_attention_gguf_model(vocab, hidden);
+ const auto bytes = load_npy<uint8_t>("pq2_0_qbytes");
+ ov::Tensor payload(ov::element::u8, {bytes.size()});
+ std::memcpy(payload.data(), bytes.data(), bytes.size());
+ auto weight = make_weight_node(payload, "PQ2_0", {vocab, hidden});
+ std::shared_ptr<ov::Node> old_embedding;
+ for (const auto& node : model->get_ops()) {
+ if (node->get_friendly_name() == "embd")
+ old_embedding = node;
+ }
+ ASSERT_TRUE(old_embedding);
+ const auto indices = old_embedding->input_value(0).get_node_shared_ptr()->input_value(1);
+ auto embedding = std::make_shared<v0::Unsqueeze>(gather_weight_rows(weight, indices),
+ v0::Constant::create(ov::element::i64, {1}, {0}));
+ embedding->set_friendly_name("embd");
+ embedding->get_rt_info()["gguf.token_embedding"] = true;
+ old_embedding->output(0).replace(embedding);
+ ASSERT_TRUE(AdaptToGenAI().run_on_model(model));
+ ASSERT_TRUE(ov::pass::SDPAToPagedAttention().run_on_model(model));
+ auto ids = find_parameter(model, "input_ids");
+ ASSERT_TRUE(ids);
+ ids->set_partial_shape({3});
+ ASSERT_NO_THROW(model->validate_nodes_and_infer_types());
+ size_t attention_count = 0;
+ for (const auto& node : model->get_ops()) {
+ if (auto attention = ov::as_type_ptr<PagedAttentionExtension>(node)) {
+ ++attention_count;
+ EXPECT_EQ(attention->get_input_partial_shape(0), (ov::PartialShape{3, hidden}));
+ }
+ }
+ EXPECT_EQ(attention_count, 1);
+}
+
TEST(GGUFAdaptToGenAI, SurvivesSDPAToPagedAttentionWithRealAttentionBlock) {
const int64_t vocab = 8;
const int64_t hidden = 4;
diff --git a/src/frontends/gguf/tests/test_arch_accuracy.cpp b/src/frontends/gguf/tests/test_arch_accuracy.cpp
index dd547f73d9e..c0d8ef478fb 100644
--- a/src/frontends/gguf/tests/test_arch_accuracy.cpp
+++ b/src/frontends/gguf/tests/test_arch_accuracy.cpp
@@ -13,6 +13,7 @@
#include <tuple>
#include "builder/api/metadata_store.hpp"
+#include "builder/arch/decoder_builder.hpp"
#include "builder/arch/dspark_builder.hpp"
#include "builder/gguf_builder_decoder.hpp"
#include "builder/gguf_graph.hpp"
@@ -31,15 +32,18 @@
#include "openvino/frontend/gguf/make_stateful.hpp"
#include "openvino/op/broadcast.hpp"
#include "openvino/op/constant.hpp"
+#include "openvino/op/matmul.hpp"
#include "openvino/op/multiply.hpp"
#include "openvino/op/paged_attention.hpp"
#include "openvino/op/paged_causal_conv1d.hpp"
#include "openvino/op/paged_gated_delta_net.hpp"
#include "openvino/op/read_value.hpp"
+#include "openvino/op/reshape.hpp"
#include "openvino/op/unsqueeze.hpp"
#include "openvino/openvino.hpp"
#include "openvino/pass/manager.hpp"
#include "openvino/pass/sdpa_to_paged_attention.hpp"
+#include "openvino/util/common_util.hpp"
#include "quant/gguf.hpp"
#include "utils.hpp"
@@ -326,7 +330,7 @@ TEST(GGUFHadamardTypes, ExplicitF32SignsFollowF16Activations) {
class GGUFHadamardAccuracy : public ::testing::TestWithParam<std::tuple<int64_t, bool>> {};
-TEST_P(GGUFHadamardAccuracy, ButterflyPreservesSylvesterOrderSignsAndDynamicShapes) {
+TEST_P(GGUFHadamardAccuracy, PreservesSylvesterOrderSignsAndDynamicShapes) {
const auto block = std::get<0>(GetParam());
const auto inverse = std::get<1>(GetParam());
const auto width = static_cast<size_t>(2 * block);
@@ -351,12 +355,23 @@ TEST_P(GGUFHadamardAccuracy, ButterflyPreservesSylvesterOrderSignsAndDynamicShap
const auto y = ov::frontend::gguf::apply_hadamard(context, x);
const auto model = std::make_shared<ov::Model>(ov::OutputVector{y}, ov::ParameterVector{x});
size_t constant_bytes = 0;
+ size_t stages = 0;
+ size_t matrices = 0;
for (const auto& op : model->get_ordered_ops()) {
- EXPECT_NE(op->get_type_name(), std::string("MatMul"));
+ matrices += op->get_type_name() == std::string("MatMul");
+ EXPECT_NE(op->get_type_name(), std::string("Split"));
+ EXPECT_NE(op->get_type_name(), std::string("Concat"));
+ if (op->get_type_name() == std::string("Gather")) {
+ ++stages;
+ EXPECT_EQ(op->get_output_partial_shape(0).rank(), 2);
+ }
if (const auto constant = ov::as_type_ptr<ov::op::v0::Constant>(op))
constant_bytes += constant->get_byte_size();
}
- EXPECT_LE(constant_bytes, signs.get_byte_size() + 1024);
+ const bool matrix_form = inverse && block >= 256;
+ EXPECT_EQ(matrices, matrix_form ? 1 : 0);
+ EXPECT_EQ(stages, matrix_form ? 0 : static_cast<size_t>(std::log2(block)));
+ EXPECT_LE(constant_bytes, signs.get_byte_size() + stages * block * 12 + matrices * block * block * 4 + 128);
ov::Core core;
auto compiled =
core.compile_model(model, "CPU", ov::hint::inference_precision(ov::element::f32), ov::inference_num_threads(4));
@@ -415,9 +430,83 @@ TEST_P(GGUFHadamardAccuracy, ButterflyPreservesSylvesterOrderSignsAndDynamicShap
INSTANTIATE_TEST_SUITE_P(
BlockSizes,
GGUFHadamardAccuracy,
- ::testing::Combine(::testing::Values(int64_t{1}, int64_t{2}, int64_t{8}, int64_t{64}, int64_t{4096}),
+ ::testing::Combine(::testing::Values(int64_t{1}, int64_t{2}, int64_t{8}, int64_t{64}, int64_t{1024}, int64_t{4096}),
::testing::Bool()));
+TEST(GGUFHadamardTypes, MatrixCacheIsScopedToConversionAndPrecision) {
+ using namespace ov::frontend::gguf;
+ const ov::PartialShape shape{1, -1, 2048};
+ const auto decoder = std::make_shared<ov_gguf_test::SingleOpDecoder>(
+ "GGML_OP_MUL_MAT",
+ std::vector<ov_gguf_test::TensorDesc>{{"x", ov::element::f32, shape}},
+ std::vector<ov_gguf_test::TensorDesc>{},
+ ov_gguf_test::TensorDesc{"y", ov::element::f32, shape},
+ std::map<std::string, ov::Any>{{"hadamard_block", int64_t{1024}}});
+ auto tensor_map = std::make_shared<TensorMap>();
+ const auto cache = std::make_shared<ConstantCache>();
+ const NodeContext first(decoder, tensor_map, cache);
+ const NodeContext second(decoder, tensor_map, cache);
+ const NodeContext separate(decoder, tensor_map, std::make_shared<ConstantCache>());
+ const auto f32 = first.get_hadamard_matrix(ov::element::f32);
+ EXPECT_EQ(f32, second.get_hadamard_matrix(ov::element::f32));
+ EXPECT_NE(f32, separate.get_hadamard_matrix(ov::element::f32));
+ const auto f16 = second.get_hadamard_matrix(ov::element::f16);
+ EXPECT_NE(f32, f16);
+ EXPECT_EQ(f32->get_shape(), (ov::Shape{1024, 1024}));
+ EXPECT_EQ(f16->get_element_type(), ov::element::f16);
+ EXPECT_EQ(f32->cast_vector<float>(), f16->cast_vector<float>());
+ const auto smaller_matrix = first.get_hadamard_matrix(ov::element::f32, 512);
+ EXPECT_NE(f32, smaller_matrix);
+ EXPECT_EQ(smaller_matrix, second.get_hadamard_matrix(ov::element::f32, 512));
+ EXPECT_EQ(smaller_matrix->get_shape(), (ov::Shape{512, 512}));
+ for (const auto type : {ov::element::f32, ov::element::f16}) {
+ const auto x = std::make_shared<ov::op::v0::Parameter>(type, shape);
+ const auto y = apply_hadamard(first, x, true);
+ const auto matmul = y.get_node_shared_ptr()->get_input_node_shared_ptr(0);
+ ASSERT_EQ(matmul->get_type_name(), std::string("MatMul"));
+ EXPECT_EQ(matmul->get_input_node_shared_ptr(1), first.get_hadamard_matrix(type));
+ EXPECT_EQ(y.get_partial_shape(), shape);
+ EXPECT_EQ(y.get_element_type(), type);
+ }
+}
+
+TEST(GGUFHadamardTypes, ConstantsAreSharedWithinEachConversion) {
+ using namespace ov::frontend::gguf;
+ const auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/arch_accuracy/bonsai2-hadamard.npz");
+ const ov_gguf_test::TemporaryGguf temporary(ov_gguf_test::npz_array(arrays, "model"));
+ FrontEnd frontend;
+ auto input_model = frontend.load(temporary.path);
+ const auto first = frontend.convert(input_model);
+ const auto second = frontend.convert(input_model);
+ const auto rotation_constants = [](const std::shared_ptr<ov::Model>& model) {
+ std::set<ov::Node*> constants;
+ size_t stages = 0;
+ for (const auto& node : model->get_ops()) {
+ if (node->get_type_name() != std::string("Gather") || node->get_input_partial_shape(0).rank() != 2)
+ continue;
+ const auto indices = ov::as_type_ptr<ov::op::v0::Constant>(node->get_input_node_shared_ptr(1));
+ if (!indices || indices->get_shape() != ov::Shape{8})
+ continue;
+ const auto values = indices->cast_vector<int64_t>();
+ const auto stride = values[0];
+ bool butterfly = stride > 0 && stride < 8 && (stride & (stride - 1)) == 0;
+ for (int64_t i = 0; i < 8; ++i)
+ butterfly &= values[i] == (i ^ stride);
+ if (butterfly) {
+ ++stages;
+ constants.insert(indices.get());
+ }
+ }
+ EXPECT_GT(stages, 3);
+ EXPECT_EQ(constants.size(), 3);
+ return constants;
+ };
+ const auto first_constants = rotation_constants(first);
+ const auto second_constants = rotation_constants(second);
+ for (auto* constant : first_constants)
+ EXPECT_EQ(second_constants.count(constant), 0);
+}
+
TEST(GGUFDSparkAccuracy, NoncausalDraftBlocksMatchPrismCPU) {
auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/arch_accuracy/dspark.npz");
const ov_gguf_test::TemporaryGguf temporary(ov_gguf_test::npz_array(arrays, "model"));
@@ -557,6 +646,100 @@ TEST(GGUFMultimodalBackboneAdaptation, Lfm2SupportsBatchesAndBeamReordering) {
}
}
+static size_t count_rank3_gates(const std::shared_ptr<ov::Model>& model, const std::string& prefix) {
+ size_t gates = 0;
+ for (const auto& node : model->get_ops()) {
+ const auto& name = node->get_friendly_name();
+ for (const auto* gate : {"attn_gate", "attn_gate_sig", "kqv_gated"}) {
+ if (ov::util::ends_with(name, prefix + gate)) {
+ ++gates;
+ EXPECT_EQ(node->get_output_partial_shape(0).rank(), 3) << name;
+ }
+ }
+ }
+ return gates;
+}
+
+TEST(GGUFMultimodalBackboneAdaptation, TernaryAttentionGatesRestoreRankBeforeSigmoid) {
+ using namespace ov::frontend::gguf;
+ for (const auto type : {ov::element::f32, ov::element::u2}) {
+ const auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/arch_accuracy/muse-glimmer.npz");
+ const ov_gguf_test::TemporaryGguf temporary(ov_gguf_test::npz_array(arrays, "model"));
+ auto loaded = get_gguf_data(temporary.path);
+ auto& weights = std::get<1>(loaded);
+ auto& gate = weights.at("blk.0.attn_gate.weight");
+ gate = ov::Tensor(type, gate.get_shape());
+ const auto& metadata = std::get<0>(loaded);
+ const auto config = decoder_config_from_meta(metadata);
+ DecoderBuilder builder(config, weights, std::get<2>(loaded));
+ const auto graph = builder.build();
+ const auto node = std::find_if(graph->nodes.begin(), graph->nodes.end(), [](const auto& op) {
+ return op.name == "blk.0.attn_gate";
+ });
+ ASSERT_NE(node, graph->nodes.end());
+ EXPECT_EQ(node->attributes.at("activation_rank").as<int>(), type == ov::element::u2 ? 4 : 3);
+ for (const auto* name : {"blk.0.kqv_gate_input", "blk.0.kqv_gated_4d"}) {
+ const auto reshapes = std::count_if(graph->nodes.begin(), graph->nodes.end(), [&](const auto& op) {
+ return op.name == name;
+ });
+ EXPECT_EQ(reshapes, type == ov::element::u2 ? 0 : 1);
+ }
+ }
+}
+
+TEST(GGUFMultimodalBackboneAdaptation, AttentionGatesPreserveBatchAndBeamShapes) {
+ const auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/arch_accuracy/muse-glimmer.npz");
+ const ov_gguf_test::TemporaryGguf temporary(ov_gguf_test::npz_array(arrays, "model"));
+ ov::frontend::gguf::FrontEnd frontend;
+ frontend.add_extension(std::make_shared<ov::frontend::gguf::GenAIExtension>());
+ const auto model = frontend.convert(frontend.load(temporary.path));
+ EXPECT_GT(count_rank3_gates(model, "."), 0);
+ check_batched_decode(model);
+}
+
+TEST(GGUFMultimodalBackboneAdaptation, Rank3HeadRemainsVisibleToGenAI) {
+ using namespace ov::frontend::gguf;
+ for (const auto* family : {"llama", "bonsai2-hadamard", "gemma4-mqa"}) {
+ SCOPED_TRACE(family);
+ const auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/arch_accuracy/" + family + ".npz");
+ const ov_gguf_test::TemporaryGguf temporary(ov_gguf_test::npz_array(arrays, "model"));
+ FrontEnd frontend;
+ frontend.add_extension(
+ std::make_shared<ov::frontend::DecoderTransformationExtension>(pass::GGUFMakeStateful()));
+ const auto model = frontend.convert(frontend.load(temporary.path));
+ std::shared_ptr<ov::op::v0::MatMul> head;
+ for (const auto& node : model->get_ops()) {
+ if (ov::util::ends_with(node->get_friendly_name(), "result_output"))
+ head = ov::as_type_ptr<ov::op::v0::MatMul>(node);
+ }
+ ASSERT_NE(head, nullptr);
+ const auto targets = head->output(0).get_target_inputs();
+ const auto width = head->get_input_partial_shape(0)[3].get_length();
+ head->input(0).replace_source_output(std::make_shared<ov::op::v1::Reshape>(
+ head->input_value(0),
+ ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{0, -1, width}),
+ true));
+ head->revalidate_and_infer_types();
+ const auto restored =
+ std::make_shared<ov::op::v0::Unsqueeze>(head, ov::op::v0::Constant::create(ov::element::i64, {1}, {1}));
+ for (auto target : targets)
+ target.replace_source_output(restored);
+ model->validate_nodes_and_infer_types();
+ ASSERT_TRUE(pass::AdaptToGenAI().run_on_model(model));
+ auto output = model->get_results()[0]->input_value(0);
+ for (size_t depth = 0; output.get_node_shared_ptr() != head && depth < 4; ++depth) {
+ const auto type = std::string(output.get_node()->get_type_name());
+ ASSERT_TRUE(type == "Multiply" || type == "Divide" || type == "Tanh") << type;
+ output = output.get_node()->input_value(0);
+ }
+ EXPECT_EQ(output.get_node_shared_ptr(), head);
+ EXPECT_EQ(head->get_input_partial_shape(0).rank(), 3);
+ ASSERT_NO_THROW(ov::pass::SDPAToPagedAttention().run_on_model(model));
+ ASSERT_NO_THROW(model->reshape({{"input_ids", {5}}, {"position_ids", {5}}}));
+ EXPECT_EQ(model->output().get_partial_shape()[0], 5);
+ }
+}
+
TEST(GGUFMultimodalBackboneAdaptation, QwenAndGemmaSupportBatchesAndPagedAttention) {
for (const auto* family :
{"qwen35", "bonsai2-hadamard", "qwen35moe", "qwen35moe-fused", "gemma4-mqa", "gemma4-moe", "gemma4-ple"}) {
@@ -577,6 +760,10 @@ TEST(GGUFMultimodalBackboneAdaptation, QwenAndGemmaSupportBatchesAndPagedAttenti
ov::frontend::gguf::FrontEnd frontend;
frontend.add_extension(std::make_shared<ov::frontend::gguf::GenAIExtension>());
auto model = frontend.convert(frontend.load(temporary.path));
+ if (std::string(family).find("qwen35") == 0 || std::string(family) == "bonsai2-hadamard") {
+ EXPECT_GT(count_rank3_gates(model, "."), 0);
+ EXPECT_EQ(count_rank3_gates(model, "_blk.3."), 3);
+ }
check_batched_decode(model);
ov::pass::Manager manager;
manager.register_pass<ov::pass::SDPAToPagedAttention>();
diff --git a/src/frontends/gguf/tests/test_arch_conversion.cpp b/src/frontends/gguf/tests/test_arch_conversion.cpp
index 8f4a4afc7ec..cb2c68546e0 100644
--- a/src/frontends/gguf/tests/test_arch_conversion.cpp
+++ b/src/frontends/gguf/tests/test_arch_conversion.cpp
@@ -182,20 +182,20 @@ struct Fingerprint {
const std::map<std::string, Fingerprint>& fingerprints() {
static const std::map<std::string, Fingerprint> fp{
{"mamba2-dense.gguf.hdr", {241, 6}}, {"nemotron_h-dense.gguf.hdr", {254, 8}},
- {"bailingmoe2-moe.gguf.hdr", {489, 10}}, {"ernie4_5-moe-moe.gguf.hdr", {472, 10}},
- {"exaone4-dense.gguf.hdr", {415, 11}}, {"gemma-dense.gguf.hdr", {365, 10}},
- {"gemma2-dense.gguf.hdr", {415, 11}}, {"glm4moe-moe.gguf.hdr", {501, 10}},
- {"gpt-oss-moe.gguf.hdr", {608, 11}}, {"hunyuan-dense-dense.gguf.hdr", {414, 10}},
- {"hunyuan-moe-moe.gguf.hdr", {600, 10}}, {"llama-dense.gguf.hdr", {398, 10}},
- {"lfm2-dense.gguf.hdr", {290, 9}}, {"lfm2moe-moe.gguf.hdr", {373, 8}},
- {"llama-moe.gguf.hdr", {542, 10}}, {"maincoder-dense.gguf.hdr", {430, 10}},
- {"minicpm-dense.gguf.hdr", {396, 10}}, {"minicpm-moe.gguf.hdr", {540, 10}},
- {"minimax-m2-moe.gguf.hdr", {582, 10}}, {"mistral3-dense.gguf.hdr", {398, 10}},
+ {"bailingmoe2-moe.gguf.hdr", {506, 10}}, {"ernie4_5-moe-moe.gguf.hdr", {481, 10}},
+ {"exaone4-dense.gguf.hdr", {432, 11}}, {"gemma-dense.gguf.hdr", {382, 10}},
+ {"gemma2-dense.gguf.hdr", {432, 11}}, {"glm4moe-moe.gguf.hdr", {518, 10}},
+ {"gpt-oss-moe.gguf.hdr", {608, 11}}, {"hunyuan-dense-dense.gguf.hdr", {431, 10}},
+ {"hunyuan-moe-moe.gguf.hdr", {617, 10}}, {"llama-dense.gguf.hdr", {415, 10}},
+ {"lfm2-dense.gguf.hdr", {307, 9}}, {"lfm2moe-moe.gguf.hdr", {382, 8}},
+ {"llama-moe.gguf.hdr", {542, 10}}, {"maincoder-dense.gguf.hdr", {447, 10}},
+ {"minicpm-dense.gguf.hdr", {413, 10}}, {"minicpm-moe.gguf.hdr", {540, 10}},
+ {"minimax-m2-moe.gguf.hdr", {582, 10}}, {"mistral3-dense.gguf.hdr", {415, 10}},
{"mistral3-moe.gguf.hdr", {542, 10}}, {"olmoe-moe.gguf.hdr", {570, 10}},
- {"phi3-dense.gguf.hdr", {368, 10}}, {"qwen2-dense.gguf.hdr", {366, 10}},
- {"qwen3-dense.gguf.hdr", {414, 10}}, {"qwen3moe-moe.gguf.hdr", {582, 10}},
- {"qwen35-dense.gguf.hdr", {360, 10}}, {"qwen35moe-moe.gguf.hdr", {532, 10}},
- {"smollm3-dense.gguf.hdr", {382, 10}}, {"jais2-dense.gguf.hdr", {344, 10}},
+ {"phi3-dense.gguf.hdr", {368, 10}}, {"qwen2-dense.gguf.hdr", {383, 10}},
+ {"qwen3-dense.gguf.hdr", {431, 10}}, {"qwen3moe-moe.gguf.hdr", {582, 10}},
+ {"qwen35-dense.gguf.hdr", {412, 10}}, {"qwen35moe-moe.gguf.hdr", {584, 10}},
+ {"smollm3-dense.gguf.hdr", {399, 10}}, {"jais2-dense.gguf.hdr", {344, 10}},
};
return fp;
}
diff --git a/src/frontends/gguf/tests/test_hadamard_sign_folding.cpp b/src/frontends/gguf/tests/test_hadamard_sign_folding.cpp
new file mode 100644
index 00000000000..d23ea13afbf
--- /dev/null
+++ b/src/frontends/gguf/tests/test_hadamard_sign_folding.cpp
@@ -0,0 +1,601 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <cstring>
+#include <limits>
+
+#include "gtest/gtest.h"
+#include "hadamard_sign_folding.hpp"
+#include "op_test_utils.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/convert_like.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/shape_of.hpp"
+#include "openvino/op/squeeze.hpp"
+#include "openvino/op/subtract.hpp"
+#include "openvino/op/swish.hpp"
+#include "openvino/op/unsqueeze.hpp"
+#include "transformations/rt_info/decompression.hpp"
+
+namespace {
+using Constant = ov::op::v0::Constant;
+using Multiply = ov::op::v1::Multiply;
+using ov::frontend::gguf::fold_hadamard_input_signs;
+
+std::shared_ptr<Multiply> marked_signs(const ov::Output<ov::Node>& data,
+ const ov::Output<ov::Node>& signs,
+ bool reversed = false) {
+ auto result = reversed ? std::make_shared<Multiply>(signs, data) : std::make_shared<Multiply>(data, signs);
+ result->get_rt_info()["gguf_hadamard_input_sign"] = true;
+ return result;
+}
+
+ov::Tensor input_tensor(const ov::element::Type& type) {
+ const std::vector<float> values{1.125f, -2.5f, 3.75f, -4.25f, -5.5f, 6.125f, -7.25f, 8.5f};
+ return type == ov::element::f16 ? ov_gguf_test::make_f16_tensor({2, 4}, values)
+ : ov_gguf_test::make_f32_tensor({2, 4}, values);
+}
+
+ov::TensorVector evaluate(const std::shared_ptr<ov::Model>& model, const ov::Tensor& input) {
+ ov::TensorVector outputs;
+ for (const auto& output : model->outputs())
+ outputs.emplace_back(output.get_element_type(), output.get_shape());
+ EXPECT_TRUE(model->evaluate(outputs, {input}));
+ return outputs;
+}
+
+void expect_identical(const ov::Tensor& actual, const ov::Tensor& expected) {
+ ASSERT_EQ(actual.get_element_type(), expected.get_element_type());
+ ASSERT_EQ(actual.get_shape(), expected.get_shape());
+ EXPECT_EQ(std::memcmp(actual.data(), expected.data(), actual.get_byte_size()), 0);
+}
+
+void expect_identical(const ov::TensorVector& actual, const ov::TensorVector& expected) {
+ ASSERT_EQ(actual.size(), expected.size());
+ for (size_t i = 0; i < actual.size(); ++i) {
+ SCOPED_TRACE(i);
+ expect_identical(actual[i], expected[i]);
+ }
+}
+
+class GGUFHadamardSignFolding : public ::testing::TestWithParam<ov::element::Type> {};
+
+struct UpSignGraph {
+ std::shared_ptr<ov::op::v0::Parameter> input;
+ std::shared_ptr<Constant> codes;
+ std::shared_ptr<Constant> scale;
+ std::shared_ptr<Constant> zero_point;
+ std::shared_ptr<ov::op::v0::Convert> code_convert;
+ std::shared_ptr<ov::op::v1::Subtract> subtract;
+ std::shared_ptr<Multiply> scaled;
+ std::shared_ptr<ov::op::v1::Reshape> weight_view;
+ std::shared_ptr<ov::Node> weights;
+ std::shared_ptr<ov::op::v0::MatMul> up;
+ std::shared_ptr<Multiply> swiglu;
+ std::shared_ptr<ov::op::v1::Reshape> view;
+ std::shared_ptr<Multiply> rotation;
+ std::shared_ptr<ov::op::v0::MatMul> hadamard;
+ std::shared_ptr<ov::Model> model;
+};
+
+UpSignGraph up_sign_graph(const ov::element::Type& type, size_t columns = 4, bool dynamic_tokens = false) {
+ UpSignGraph graph;
+ graph.input = std::make_shared<ov::op::v0::Parameter>(
+ type,
+ ov::PartialShape{dynamic_tokens ? ov::Dimension::dynamic() : ov::Dimension(2), ov::Dimension(columns)});
+ graph.input->output(0).set_names({"x"});
+ std::vector<uint8_t> codes(4 * columns);
+ for (size_t i = 0; i < codes.size(); ++i)
+ codes[i] = static_cast<uint8_t>((i + i / columns) % 3);
+ graph.codes = Constant::create(ov::element::u2, {4, 1, columns}, codes);
+ graph.scale = Constant::create(ov::element::f16, {4, 1, 1}, {0.25f, -0.5f, 0.75f, 1.25f});
+ graph.zero_point = Constant::create(ov::element::f16, {}, {1});
+ graph.code_convert = std::make_shared<ov::op::v0::Convert>(graph.codes, ov::element::f16);
+ ov::mark_as_decompression(graph.code_convert);
+ graph.subtract = std::make_shared<ov::op::v1::Subtract>(graph.code_convert, graph.zero_point);
+ graph.scaled = std::make_shared<Multiply>(graph.subtract, graph.scale);
+ graph.weight_view = std::make_shared<ov::op::v1::Reshape>(
+ graph.scaled,
+ Constant::create(ov::element::i64, {2}, std::vector<int64_t>{4, static_cast<int64_t>(columns)}),
+ false);
+ graph.weights = std::make_shared<ov::op::v0::Convert>(graph.weight_view, type);
+ graph.up = std::make_shared<ov::op::v0::MatMul>(graph.input, graph.weights, false, true);
+ const auto gate_weights = Constant::create(type, {4, columns}, {0.125f});
+ const auto gate = std::make_shared<ov::op::v0::MatMul>(graph.input, gate_weights, false, true);
+ const auto swish = std::make_shared<ov::op::v4::Swish>(gate);
+ graph.swiglu = std::make_shared<Multiply>(swish, graph.up);
+ const auto expanded =
+ std::make_shared<ov::op::v1::Reshape>(graph.swiglu, Constant::create(ov::element::i64, {3}, {-1, 1, 4}), false);
+ graph.view =
+ std::make_shared<ov::op::v1::Reshape>(expanded, Constant::create(ov::element::i64, {2}, {-1, 4}), false);
+ graph.rotation = marked_signs(graph.view, Constant::create(type, {1, 4}, {-1, 1, -1, 1}), true);
+ graph.hadamard = std::make_shared<ov::op::v0::MatMul>(
+ graph.rotation,
+ Constant::create(type, {4, 4}, {1, 1, 1, 1, 1, -1, 1, -1, 1, 1, -1, -1, 1, -1, -1, 1}));
+ graph.model = std::make_shared<ov::Model>(ov::OutputVector{graph.hadamard}, ov::ParameterVector{graph.input});
+ return graph;
+}
+
+std::shared_ptr<ov::op::v0::MatMul> folded_up(const UpSignGraph& graph) {
+ auto data = graph.hadamard->input_value(0);
+ while (ov::is_type<ov::op::v1::Reshape>(data.get_node()) || ov::is_type<ov::op::v0::Squeeze>(data.get_node()) ||
+ ov::is_type<ov::op::v0::Unsqueeze>(data.get_node()))
+ data = data.get_node()->input_value(0);
+ const auto swiglu = ov::as_type_ptr<Multiply>(data.get_node_shared_ptr());
+ return swiglu ? ov::as_type_ptr<ov::op::v0::MatMul>(swiglu->get_input_node_shared_ptr(1)) : nullptr;
+}
+
+void expect_same_floats(const ov::Tensor& actual, const ov::Tensor& expected, float tolerance = 0) {
+ ASSERT_EQ(actual.get_element_type(), expected.get_element_type());
+ ASSERT_EQ(actual.get_shape(), expected.get_shape());
+ const auto value = [](const ov::Tensor& tensor, size_t i) {
+ return tensor.get_element_type() == ov::element::f16 ? static_cast<float>(tensor.data<const ov::float16>()[i])
+ : tensor.data<const float>()[i];
+ };
+ for (size_t i = 0; i < actual.get_size(); ++i)
+ EXPECT_NEAR(value(actual, i), value(expected, i), tolerance) << i;
+}
+
+TEST_P(GGUFHadamardSignFolding, SwiGLURowSignsPreservePackedWeightsNumericsAndMetadata) {
+ auto graph = up_sign_graph(GetParam());
+ graph.code_convert->get_rt_info()["code_metadata"] = 17;
+ graph.code_convert->output(0).get_rt_info()["code_output_metadata"] = 18;
+ graph.rotation->get_rt_info()["rotation_metadata"] = 19;
+ graph.rotation->output(0).get_rt_info()["rotation_output_metadata"] = 20;
+ graph.rotation->output(0).set_names({"rotated"});
+ const auto values = input_tensor(GetParam());
+ const auto expected = evaluate(graph.model, values);
+ const auto cpu_expected = ov_gguf_test::run_on_cpu(graph.model, {{"x", values}});
+ const auto original_codes = graph.codes->cast_vector<uint8_t>();
+
+ fold_hadamard_input_signs(graph.model);
+
+ const auto up = folded_up(graph);
+ ASSERT_NE(up, nullptr);
+ EXPECT_NE(up, graph.up);
+ const auto weight_convert = ov::as_type_ptr<ov::op::v0::Convert>(up->get_input_node_shared_ptr(1));
+ ASSERT_NE(weight_convert, nullptr);
+ const auto weight_view = ov::as_type_ptr<ov::op::v1::Reshape>(weight_convert->get_input_node_shared_ptr(0));
+ ASSERT_NE(weight_view, nullptr);
+ const auto scaled = ov::as_type_ptr<Multiply>(weight_view->get_input_node_shared_ptr(0));
+ ASSERT_NE(scaled, nullptr);
+ const auto scale = ov::as_type_ptr<Constant>(scaled->get_input_node_shared_ptr(1));
+ ASSERT_NE(scale, nullptr);
+ EXPECT_EQ(scale->get_element_type(), ov::element::f16);
+ EXPECT_EQ(scale->cast_vector<float>(), (std::vector<float>{-0.25f, -0.5f, -0.75f, 1.25f}));
+ const auto subtract = ov::as_type_ptr<ov::op::v1::Subtract>(scaled->get_input_node_shared_ptr(0));
+ ASSERT_NE(subtract, nullptr);
+ EXPECT_EQ(subtract->input_value(1), graph.zero_point->output(0));
+ const auto code_convert = ov::as_type_ptr<ov::op::v0::Convert>(subtract->get_input_node_shared_ptr(0));
+ ASSERT_NE(code_convert, nullptr);
+ EXPECT_TRUE(ov::is_decompression(code_convert));
+ EXPECT_EQ(code_convert->get_rt_info().at("code_metadata").as<int>(), 17);
+ EXPECT_EQ(code_convert->output(0).get_rt_info().at("code_output_metadata").as<int>(), 18);
+ const auto codes = ov::as_type_ptr<Constant>(code_convert->get_input_node_shared_ptr(0));
+ ASSERT_NE(codes, nullptr);
+ EXPECT_EQ(codes, graph.codes);
+ EXPECT_EQ(codes->get_element_type(), ov::element::u2);
+ EXPECT_EQ(codes->get_shape(), graph.codes->get_shape());
+ EXPECT_EQ(codes->cast_vector<uint8_t>(), original_codes);
+ EXPECT_EQ(graph.codes->cast_vector<uint8_t>(), original_codes);
+ const auto replacement = graph.hadamard->input_value(0);
+ EXPECT_EQ(replacement.get_node()->get_rt_info().at("rotation_metadata").as<int>(), 19);
+ EXPECT_EQ(replacement.get_rt_info().at("rotation_output_metadata").as<int>(), 20);
+ EXPECT_EQ(replacement.get_names().count("rotated"), 1u);
+ EXPECT_EQ(replacement.get_node()->get_rt_info().count("gguf_hadamard_input_sign"), 0u);
+ expect_same_floats(evaluate(graph.model, values)[0], expected[0]);
+ expect_same_floats(ov_gguf_test::run_on_cpu(graph.model, {{"x", values}}), cpu_expected, 0.002f);
+}
+
+TEST(GGUFHadamardSignFoldingUp, SharedConsumersRemainUnrotatedAndNonByteAlignedRowsFold) {
+ auto graph = up_sign_graph(ov::element::f32, 3);
+ const auto other_signs = marked_signs(graph.view, Constant::create(ov::element::f32, {4}, {1, -1, 1, -1}));
+ graph.model = std::make_shared<ov::Model>(
+ ov::OutputVector{graph.hadamard, graph.up, graph.swiglu, graph.weights, other_signs},
+ ov::ParameterVector{graph.input});
+ const auto values = ov_gguf_test::make_f32_tensor({2, 3}, {1.125f, -2.5f, 3.75f, -4.25f, -5.5f, 6.125f});
+ const auto expected = evaluate(graph.model, values);
+
+ fold_hadamard_input_signs(graph.model);
+
+ EXPECT_NE(graph.hadamard->input_value(0), graph.rotation->output(0));
+ EXPECT_EQ(graph.model->get_results()[1]->input_value(0), graph.up->output(0));
+ EXPECT_EQ(graph.model->get_results()[2]->input_value(0), graph.swiglu->output(0));
+ EXPECT_EQ(graph.model->get_results()[3]->input_value(0), graph.weights->output(0));
+ EXPECT_NE(graph.model->get_results()[4]->input_value(0), other_signs->output(0));
+ const auto actual = evaluate(graph.model, values);
+ for (size_t i = 0; i < actual.size(); ++i)
+ expect_same_floats(actual[i], expected[i]);
+}
+
+TEST(GGUFHadamardSignFoldingUp, SingletonUnsqueezeAndSqueezePreserveNumerics) {
+ auto graph = up_sign_graph(ov::element::f32);
+ const auto axes = Constant::create(ov::element::i64, {1}, {1});
+ const auto expanded = std::make_shared<ov::op::v0::Unsqueeze>(graph.swiglu, axes);
+ const auto squeezed = std::make_shared<ov::op::v0::Squeeze>(expanded, axes);
+ graph.view->set_argument(0, squeezed);
+ graph.model->validate_nodes_and_infer_types();
+ const auto values = input_tensor(ov::element::f32);
+ const auto expected = evaluate(graph.model, values);
+
+ fold_hadamard_input_signs(graph.model);
+
+ ASSERT_NE(folded_up(graph), nullptr);
+ EXPECT_NE(graph.hadamard->input_value(0), graph.rotation->output(0));
+ expect_same_floats(evaluate(graph.model, values)[0], expected[0]);
+}
+
+TEST(GGUFHadamardSignFoldingUp, DynamicShapeQueriesDoNotKeepUnrotatedProjectionsAlive) {
+ auto graph = up_sign_graph(ov::element::f32, 4, true);
+ const auto up_shape = std::make_shared<ov::op::v0::ShapeOf>(graph.up);
+ const auto glu_shape = std::make_shared<ov::op::v3::ShapeOf>(graph.swiglu, ov::element::i64);
+ const auto view_shape = std::make_shared<ov::op::v3::ShapeOf>(graph.view, ov::element::i64);
+ const auto restored = std::make_shared<ov::op::v1::Reshape>(graph.hadamard, view_shape, false);
+ graph.model = std::make_shared<ov::Model>(ov::OutputVector{restored, up_shape, glu_shape, view_shape},
+ ov::ParameterVector{graph.input});
+ const auto values = input_tensor(ov::element::f32);
+ ov::TensorVector expected{ov::Tensor(ov::element::f32, {2, 4}),
+ ov::Tensor(ov::element::i64, {2}),
+ ov::Tensor(ov::element::i64, {2}),
+ ov::Tensor(ov::element::i64, {2})};
+ ASSERT_TRUE(graph.model->evaluate(expected, {values}));
+
+ fold_hadamard_input_signs(graph.model);
+
+ ASSERT_NE(folded_up(graph), nullptr);
+ EXPECT_NE(graph.hadamard->input_value(0), graph.rotation->output(0));
+ EXPECT_EQ(graph.hadamard->get_output_partial_shape(0), (ov::PartialShape{-1, 4}));
+ EXPECT_NE(up_shape->get_input_node_shared_ptr(0), graph.up);
+ EXPECT_NE(glu_shape->get_input_node_shared_ptr(0), graph.swiglu);
+ EXPECT_NE(view_shape->get_input_node_shared_ptr(0), graph.view);
+ const auto operations = graph.model->get_ordered_ops();
+ EXPECT_EQ(std::count_if(operations.begin(),
+ operations.end(),
+ [](const std::shared_ptr<ov::Node>& node) {
+ return ov::is_type<ov::op::v0::MatMul>(node);
+ }),
+ 3);
+ ov::TensorVector actual{ov::Tensor(ov::element::f32, {2, 4}),
+ ov::Tensor(ov::element::i64, {2}),
+ ov::Tensor(ov::element::i64, {2}),
+ ov::Tensor(ov::element::i64, {2})};
+ ASSERT_TRUE(graph.model->evaluate(actual, {values}));
+ expect_same_floats(actual[0], expected[0]);
+ for (size_t i = 1; i < actual.size(); ++i)
+ expect_identical(actual[i], expected[i]);
+}
+
+TEST(GGUFHadamardSignFoldingUp, InvalidCodesZeroPointsScalesSignsViewsConversionsAndMetadataSkip) {
+ for (int invalid = 0; invalid < 12; ++invalid) {
+ SCOPED_TRACE(invalid);
+ auto graph = up_sign_graph(ov::element::f32);
+ if (invalid == 0)
+ graph.code_convert->set_argument(0, Constant::create(ov::element::u2, {4, 1, 4}, {3}));
+ if (invalid == 1)
+ graph.subtract->set_argument(1, Constant::create(ov::element::f16, {}, {0}));
+ if (invalid == 2) {
+ ov::Tensor scale(ov::element::f16, {4, 1, 1});
+ std::fill_n(scale.data<ov::float16>(),
+ scale.get_size(),
+ ov::float16(std::numeric_limits<float>::infinity()));
+ graph.scaled->set_argument(1, std::make_shared<Constant>(scale));
+ }
+ if (invalid == 3)
+ graph.rotation->set_argument(0, Constant::create(ov::element::f32, {1, 4}, {-1.0f, 1.0f, 0.5f, 1.0f}));
+ if (invalid == 4) {
+ const auto mixed = std::make_shared<ov::op::v1::Reshape>(graph.swiglu,
+ Constant::create(ov::element::i64, {2}, {-1, 2}),
+ false);
+ graph.view->set_argument(0, mixed);
+ }
+ if (invalid == 5)
+ graph.rotation->set_argument(0, Constant::create(ov::element::f32, {2, 4}, {-1, 1, -1, 1, 1, -1, 1, -1}));
+ if (invalid == 6) {
+ const auto narrowed = std::make_shared<ov::op::v0::Convert>(graph.weight_view, ov::element::bf16);
+ graph.up->set_argument(1, std::make_shared<ov::op::v0::Convert>(narrowed, ov::element::f32));
+ }
+ if (invalid == 7)
+ graph.rotation->get_rt_info().erase("gguf_hadamard_input_sign");
+ if (invalid == 8) {
+ graph.view->get_rt_info()["conflict"] = 1;
+ graph.rotation->get_rt_info()["conflict"] = 2;
+ }
+ if (invalid == 9) {
+ graph.zero_point = Constant::create(ov::element::u8, {}, {1});
+ graph.subtract->set_argument(1, std::make_shared<ov::op::v0::Convert>(graph.zero_point, ov::element::f16));
+ graph.code_convert->set_argument(0, Constant::create(ov::element::u4, {4, 1, 4}, {1}));
+ }
+ if (invalid == 10)
+ graph.up->set_transpose_b(false);
+ if (invalid == 11)
+ graph.swiglu->set_argument(0, graph.up);
+ graph.model->validate_nodes_and_infer_types();
+ const auto values = input_tensor(ov::element::f32);
+ ov::TensorVector expected;
+ if (invalid != 2)
+ expected = evaluate(graph.model, values);
+
+ fold_hadamard_input_signs(graph.model);
+
+ EXPECT_EQ(graph.hadamard->input_value(0), graph.rotation->output(0));
+ EXPECT_EQ(graph.up->input_value(0), graph.input->output(0));
+ if (invalid != 2)
+ expect_same_floats(evaluate(graph.model, values)[0], expected[0]);
+ }
+}
+
+TEST_P(GGUFHadamardSignFolding, PreservesNumericsSignedZeroSharedConstantsAndMetadata) {
+ const auto type = GetParam();
+ const auto input = std::make_shared<ov::op::v0::Parameter>(type, ov::Shape{2, 4});
+ input->set_friendly_name("x");
+ input->output(0).set_names({"x"});
+ const auto scale = Constant::create(type, {4}, {0.75f, -0.375f, 0.0f, -0.0f});
+ const auto signs = Constant::create(type, {4}, {-1, 1, -1, -1});
+ const auto scaled = std::make_shared<Multiply>(scale, input);
+ const auto rotation = marked_signs(scaled, signs, true);
+ scale->get_rt_info()["scale_constant"] = std::string("scale");
+ signs->get_rt_info()["sign_constant"] = std::string("signs");
+ scaled->get_rt_info()["scale_metadata"] = 42;
+ rotation->get_rt_info()["rotation_metadata"] = 7;
+ scaled->get_rt_info()["common_metadata"] = 11;
+ rotation->get_rt_info()["common_metadata"] = 11;
+ scaled->output(0).get_rt_info()["scale_output_metadata"] = 5;
+ rotation->output(0).get_rt_info()["rotation_output_metadata"] = 6;
+ rotation->output(0).set_names({"rotated"});
+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{rotation, scale}, ov::ParameterVector{input});
+ const auto values = input_tensor(type);
+ const auto expected = evaluate(model, values);
+ const auto cpu_expected = ov_gguf_test::run_on_cpu(model, {{"x", values}});
+
+ fold_hadamard_input_signs(model);
+
+ const auto replacement = ov::as_type_ptr<Multiply>(model->get_results()[0]->input_value(0).get_node_shared_ptr());
+ ASSERT_NE(replacement, nullptr);
+ EXPECT_EQ(replacement->input_value(0), input->output(0));
+ const auto folded = ov::as_type_ptr<Constant>(replacement->input_value(1).get_node_shared_ptr());
+ ASSERT_NE(folded, nullptr);
+ EXPECT_EQ(folded->get_element_type(), type);
+ const auto folded_reference = Constant::create(type, {4}, {-0.75f, -0.375f, -0.0f, 0.0f});
+ expect_identical(folded->get_tensor_view(), folded_reference->get_tensor_view());
+ EXPECT_EQ(model->get_results()[1]->input_value(0), scale->output(0));
+ EXPECT_EQ(replacement->get_rt_info().at("scale_metadata").as<int>(), 42);
+ EXPECT_EQ(replacement->get_rt_info().at("rotation_metadata").as<int>(), 7);
+ EXPECT_EQ(replacement->get_rt_info().at("common_metadata").as<int>(), 11);
+ EXPECT_EQ(replacement->get_rt_info().count("gguf_hadamard_input_sign"), 0u);
+ EXPECT_EQ(folded->get_rt_info().at("scale_constant").as<std::string>(), "scale");
+ EXPECT_EQ(folded->get_rt_info().at("sign_constant").as<std::string>(), "signs");
+ EXPECT_EQ(replacement->output(0).get_rt_info().at("scale_output_metadata").as<int>(), 5);
+ EXPECT_EQ(replacement->output(0).get_rt_info().at("rotation_output_metadata").as<int>(), 6);
+ EXPECT_EQ(replacement->output(0).get_names().count("rotated"), 1u);
+ expect_identical(evaluate(model, values), expected);
+ expect_identical(ov_gguf_test::run_on_cpu(model, {{"x", values}}), cpu_expected);
+}
+
+TEST_P(GGUFHadamardSignFolding, IdenticalSignConsumersAndShapeConsumersShareFoldedScale) {
+ const auto type = GetParam();
+ const auto input = std::make_shared<ov::op::v0::Parameter>(type, ov::Shape{2, 4});
+ const auto scale = Constant::create(type, {}, {0.375f});
+ const auto scaled = std::make_shared<Multiply>(input, scale);
+ const auto first = marked_signs(scaled, Constant::create(type, {4}, {-1, 1, -1, 1}));
+ const auto second = marked_signs(scaled, Constant::create(type, {4}, {-1, 1, -1, 1}), true);
+ const auto shape = std::make_shared<ov::op::v3::ShapeOf>(scaled);
+ const auto old_shape = std::make_shared<ov::op::v0::ShapeOf>(scaled);
+ const auto model =
+ std::make_shared<ov::Model>(ov::OutputVector{first, second, shape, old_shape}, ov::ParameterVector{input});
+ const auto values = input_tensor(type);
+ const auto expected = evaluate(model, values);
+
+ fold_hadamard_input_signs(model);
+
+ const auto replacement = model->get_results()[0]->input_value(0);
+ ASSERT_TRUE(ov::is_type<Multiply>(replacement.get_node()));
+ EXPECT_EQ(model->get_results()[1]->input_value(0), replacement);
+ EXPECT_EQ(shape->input_value(0), replacement);
+ EXPECT_EQ(old_shape->input_value(0), replacement);
+ EXPECT_EQ(replacement.get_node()->input_value(0), input->output(0));
+ EXPECT_EQ(replacement.get_node()->input_value(1).get_shape(), ov::Shape{4});
+ expect_identical(evaluate(model, values), expected);
+}
+
+TEST_P(GGUFHadamardSignFolding, SkipsDifferentSignsUnrotatedAndUnmarkedConsumers) {
+ const auto type = GetParam();
+ for (int consumer = 0; consumer < 3; ++consumer) {
+ SCOPED_TRACE(consumer);
+ const auto input = std::make_shared<ov::op::v0::Parameter>(type, ov::Shape{2, 4});
+ const auto scaled =
+ std::make_shared<Multiply>(input, Constant::create(type, {4}, {0.75f, -0.375f, 2.0f, 3.0f}));
+ const auto first = marked_signs(scaled, Constant::create(type, {4}, {-1, 1, -1, 1}));
+ ov::Output<ov::Node> other = scaled;
+ if (consumer == 0)
+ other = marked_signs(scaled, Constant::create(type, {4}, {-1, 1, 1, 1}));
+ if (consumer == 2)
+ other = std::make_shared<Multiply>(scaled, Constant::create(type, {4}, {-1, 1, -1, 1}));
+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{first, other}, ov::ParameterVector{input});
+ const auto values = input_tensor(type);
+ const auto expected = evaluate(model, values);
+
+ fold_hadamard_input_signs(model);
+
+ EXPECT_EQ(model->get_results()[0]->input_value(0), first->output(0));
+ EXPECT_EQ(first->input_value(0), scaled->output(0));
+ EXPECT_EQ(model->get_results()[1]->input_value(0), other);
+ expect_identical(evaluate(model, values), expected);
+ }
+}
+
+TEST_P(GGUFHadamardSignFolding, SkipsNonUnitSigns) {
+ const auto type = GetParam();
+ for (const float invalid : {0.0f, 0.5f, 2.0f, std::numeric_limits<float>::quiet_NaN()}) {
+ SCOPED_TRACE(invalid);
+ const auto input = std::make_shared<ov::op::v0::Parameter>(type, ov::Shape{2, 4});
+ const auto scaled = std::make_shared<Multiply>(input, Constant::create(type, {}, {0.375f}));
+ const auto rotation = marked_signs(scaled, Constant::create(type, {4}, {-1.0f, 1.0f, invalid, 1.0f}));
+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{rotation}, ov::ParameterVector{input});
+
+ fold_hadamard_input_signs(model);
+
+ EXPECT_EQ(model->get_results()[0]->input_value(0), rotation->output(0));
+ EXPECT_EQ(rotation->input_value(0), scaled->output(0));
+ }
+}
+
+TEST(GGUFHadamardSignFoldingConstants, ExactConvertAndConvertLikeKeepEffectivePrecision) {
+ const auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{2, 4});
+ input->output(0).set_names({"x"});
+ const auto scale_source = Constant::create(ov::element::f16, {4}, {0.75f, -0.375f, 2.0f, 3.0f});
+ const auto scale = std::make_shared<ov::op::v0::Convert>(scale_source, ov::element::f32);
+ const auto scaled = std::make_shared<Multiply>(input, scale);
+ const auto sign_source = Constant::create(ov::element::i8, {4}, {-1, 1, -1, 1});
+ const auto signs = std::make_shared<ov::op::v1::ConvertLike>(sign_source, input);
+ const auto rotation = marked_signs(scaled, signs);
+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{rotation}, ov::ParameterVector{input});
+ const auto values = input_tensor(ov::element::f32);
+ const auto expected = ov_gguf_test::run_on_cpu(model, {{"x", values}});
+
+ fold_hadamard_input_signs(model);
+
+ const auto replacement = ov::as_type_ptr<Multiply>(model->get_results()[0]->input_value(0).get_node_shared_ptr());
+ ASSERT_NE(replacement, nullptr);
+ EXPECT_EQ(replacement->input_value(0), input->output(0));
+ const auto folded = ov::as_type_ptr<Constant>(replacement->input_value(1).get_node_shared_ptr());
+ ASSERT_NE(folded, nullptr);
+ EXPECT_EQ(folded->get_element_type(), ov::element::f32);
+ EXPECT_EQ(folded->cast_vector<float>(), (std::vector<float>{-0.75f, -0.375f, -2, 3}));
+ expect_identical(ov_gguf_test::run_on_cpu(model, {{"x", values}}), expected);
+}
+
+TEST(GGUFHadamardSignFoldingConstants, SkipsLossyConvert) {
+ const auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{2, 4});
+ const auto source = Constant::create(ov::element::f32, {4}, {0.1f, 0.2f, 0.3f, 0.4f});
+ const auto scale = std::make_shared<ov::op::v0::Convert>(source, ov::element::f16);
+ const auto scaled = std::make_shared<Multiply>(input, scale);
+ const auto rotation = marked_signs(scaled, Constant::create(ov::element::f16, {4}, {-1, 1, -1, 1}));
+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{rotation}, ov::ParameterVector{input});
+
+ fold_hadamard_input_signs(model);
+
+ EXPECT_EQ(model->get_results()[0]->input_value(0), rotation->output(0));
+ EXPECT_EQ(rotation->input_value(0), scaled->output(0));
+}
+
+TEST(GGUFHadamardSignFoldingShapes, PreservesDynamicBatchWithoutExpandingShapes) {
+ for (const bool expansion : {false, true}) {
+ SCOPED_TRACE(expansion);
+ const auto input = std::make_shared<ov::op::v0::Parameter>(
+ ov::element::f32,
+ expansion ? ov::PartialShape{ov::Dimension::dynamic(), 1} : ov::PartialShape{ov::Dimension::dynamic(), 4});
+ const auto scaled = std::make_shared<Multiply>(input, Constant::create(ov::element::f32, {}, {0.375f}));
+ const auto rotation = marked_signs(scaled, Constant::create(ov::element::f32, {4}, {-1, 1, -1, 1}));
+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{rotation}, ov::ParameterVector{input});
+
+ fold_hadamard_input_signs(model);
+
+ if (expansion) {
+ EXPECT_EQ(model->get_results()[0]->input_value(0), rotation->output(0));
+ } else {
+ const auto replacement = model->get_results()[0]->input_value(0);
+ EXPECT_EQ(replacement.get_node()->input_value(0), input->output(0));
+ EXPECT_EQ(replacement.get_partial_shape(), input->get_partial_shape());
+ const auto values = input_tensor(ov::element::f32);
+ const auto expected =
+ marked_signs(std::make_shared<Multiply>(input, Constant::create(ov::element::f32, {}, {0.375f})),
+ Constant::create(ov::element::f32, {4}, {-1, 1, -1, 1}));
+ const auto reference = std::make_shared<ov::Model>(ov::OutputVector{expected}, ov::ParameterVector{input});
+ ov::TensorVector before{ov::Tensor(ov::element::f32, {2, 4})};
+ ov::TensorVector after{ov::Tensor(ov::element::f32, {2, 4})};
+ ASSERT_TRUE(reference->evaluate(before, {values}));
+ ASSERT_TRUE(model->evaluate(after, {values}));
+ expect_identical(after, before);
+ }
+ }
+}
+
+TEST(GGUFHadamardSignFoldingShapes, SingletonSqueezeKeepsDynamicTokensNumericsAndSharedSigns) {
+ const auto input = std::make_shared<ov::op::v0::Parameter>(
+ ov::element::f32,
+ ov::PartialShape{ov::Dimension::dynamic(), 1, ov::Dimension::dynamic(), 4});
+ input->output(0).set_names({"x"});
+ const auto scaled =
+ std::make_shared<Multiply>(input, Constant::create(ov::element::f32, {4}, {-0.75f, 1.375f, 0.25f, -2.0f}));
+ const auto squeezed = std::make_shared<ov::op::v0::Squeeze>(scaled, Constant::create(ov::element::i64, {1}, {1}));
+ const auto first = marked_signs(squeezed, Constant::create(ov::element::f32, {4}, {-1, 1, -1, 1}));
+ const auto second = marked_signs(squeezed, Constant::create(ov::element::f32, {1, 1, 4}, {-1, 1, -1, 1}));
+ const auto direct = marked_signs(scaled, Constant::create(ov::element::f32, {1, 1, 1, 4}, {-1, 1, -1, 1}));
+ const auto source_shape = std::make_shared<ov::op::v3::ShapeOf>(scaled);
+ const auto view_shape = std::make_shared<ov::op::v3::ShapeOf>(squeezed);
+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{first, second, direct, source_shape, view_shape},
+ ov::ParameterVector{input});
+ std::vector<float> data(24);
+ for (size_t i = 0; i < data.size(); ++i)
+ data[i] = (static_cast<float>(i) - 11.0f) * 0.375f;
+ const auto values = ov_gguf_test::make_f32_tensor({2, 1, 3, 4}, data);
+ const auto outputs = [] {
+ return ov::TensorVector{ov::Tensor(ov::element::f32, {2, 3, 4}),
+ ov::Tensor(ov::element::f32, {2, 3, 4}),
+ ov::Tensor(ov::element::f32, {2, 1, 3, 4}),
+ ov::Tensor(ov::element::i64, {4}),
+ ov::Tensor(ov::element::i64, {3})};
+ };
+ auto expected = outputs();
+ ASSERT_TRUE(model->evaluate(expected, {values}));
+ const auto cpu_expected = ov_gguf_test::run_on_cpu(model, {{"x", values}});
+
+ fold_hadamard_input_signs(model);
+
+ const auto replacement = model->get_results()[0]->input_value(0);
+ ASSERT_TRUE(ov::is_type<ov::op::v0::Squeeze>(replacement.get_node()));
+ EXPECT_EQ(model->get_results()[1]->input_value(0), replacement);
+ const auto new_scaled = replacement.get_node()->input_value(0);
+ ASSERT_TRUE(ov::is_type<Multiply>(new_scaled.get_node()));
+ EXPECT_EQ(new_scaled.get_node()->input_value(0), input->output(0));
+ EXPECT_EQ(model->get_results()[2]->input_value(0), new_scaled);
+ EXPECT_EQ(source_shape->input_value(0), new_scaled);
+ EXPECT_EQ(view_shape->input_value(0), replacement);
+ EXPECT_EQ(replacement.get_partial_shape(), squeezed->get_output_partial_shape(0));
+ auto actual = outputs();
+ ASSERT_TRUE(model->evaluate(actual, {values}));
+ expect_identical(actual, expected);
+ expect_identical(ov_gguf_test::run_on_cpu(model, {{"x", values}}), cpu_expected);
+}
+
+TEST(GGUFHadamardSignFoldingShapes, DifferentSignsOrUnrotatedSqueezeViewSkipWholeGroup) {
+ for (int consumer = 0; consumer < 3; ++consumer) {
+ SCOPED_TRACE(consumer);
+ const auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{2, 1, 4});
+ const auto scaled = std::make_shared<Multiply>(input, Constant::create(ov::element::f32, {4}, {0.375f}));
+ const auto axes = Constant::create(ov::element::i64, {1}, {1});
+ const auto squeezed = std::make_shared<ov::op::v0::Squeeze>(scaled, axes);
+ const auto first = marked_signs(squeezed, Constant::create(ov::element::f32, {4}, {-1, 1, -1, 1}));
+ ov::Output<ov::Node> other = squeezed;
+ if (consumer == 0)
+ other = marked_signs(squeezed, Constant::create(ov::element::f32, {4}, {-1, 1, 1, 1}));
+ if (consumer == 1) {
+ const auto view = std::make_shared<ov::op::v0::Squeeze>(scaled, axes);
+ other = marked_signs(view, Constant::create(ov::element::f32, {4}, {-1, 1, 1, 1}));
+ }
+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{first, other}, ov::ParameterVector{input});
+ const auto values = ov_gguf_test::make_f32_tensor({2, 1, 4}, {-1, 2, -3, 4, 5, -6, 7, -8});
+ const auto expected = evaluate(model, values);
+
+ fold_hadamard_input_signs(model);
+
+ EXPECT_EQ(model->get_results()[0]->input_value(0), first->output(0));
+ EXPECT_EQ(first->input_value(0), squeezed->output(0));
+ EXPECT_EQ(squeezed->input_value(0), scaled->output(0));
+ EXPECT_EQ(model->get_results()[1]->input_value(0), other);
+ expect_identical(evaluate(model, values), expected);
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(GGUF,
+ GGUFHadamardSignFolding,
+ ::testing::Values(ov::element::f16, ov::element::f32),
+ [](const ::testing::TestParamInfo<ov::element::Type>& value) {
+ return value.param.get_type_name();
+ });
+} // namespace
diff --git a/src/frontends/gguf/tests/test_ops.cpp b/src/frontends/gguf/tests/test_ops.cpp
index 153718ff5e7..6e95a35f3b0 100644
--- a/src/frontends/gguf/tests/test_ops.cpp
+++ b/src/frontends/gguf/tests/test_ops.cpp
@@ -23,6 +23,8 @@
#include "openvino/op/selective_ssm.hpp"
#include "openvino/op/slice.hpp"
#include "openvino/op/topk.hpp"
+#include "openvino/pass/manager.hpp"
+#include "transformations/common_optimizations/fuse_rotary_positional_embeddings.hpp"
#include "transformations/convert_precision.hpp"
#include "transformations/rt_info/disable_precision_conversion.hpp"
#include "utils.hpp"
@@ -1295,6 +1297,38 @@ TEST(GGUFOps, SsmConvRealDims) {
expect_near(out, expected, 1e-4f);
}
+TEST(GGUFOps, SsmConvSiluPreservesBatchesAndLayouts) {
+ const std::vector<float> oracle{1.625f, 11, 24, 2.5625f, 12, 25, 3.5f, 13, 26, 4.4375f, 14, 27, 5.375f, 15, 28};
+ const std::vector<float> filters{0.5f, 0.25f, 0.125f, 0.0625f, 1, 0, 0, 0, 0, 0, 0, 1};
+ std::vector<float> sx(2 * 3 * 8), expected;
+ for (size_t batch = 0; batch < 2; ++batch) {
+ const float scale = batch ? 0.25f : -1.f;
+ for (size_t channel = 0; channel < 3; ++channel)
+ for (size_t t = 0; t < 8; ++t)
+ sx[(batch * 3 + channel) * 8 + t] = scale * (channel * 10 + t + 1);
+ for (const auto value : oracle) {
+ const auto scaled = value * scale;
+ expected.push_back(scaled / (1.f + std::exp(-scaled)));
+ }
+ }
+ for (const bool batch_major : {false, true}) {
+ auto model = SingleOpBuilder()
+ .op("GGML_OP_SSM_CONV")
+ .input("sx", ov::element::f32, {1, 2, 3, 8})
+ .input("c", ov::element::f32, {1, 1, 3, 4})
+ .output("out",
+ ov::element::f32,
+ batch_major ? ov::PartialShape{2, 1, 5, 3} : ov::PartialShape{1, 2, 5, 3})
+ .attr<bool>("batch_major", batch_major)
+ .attr<bool>("fuse_silu", true)
+ .build();
+ const auto output =
+ run_on_cpu(model,
+ {{"sx", make_f32_tensor({1, 2, 3, 8}, sx)}, {"c", make_f32_tensor({1, 1, 3, 4}, filters)}});
+ expect_near(output, expected, 1e-4f);
+ }
+}
+
// Softmax with attention sinks (gpt-oss): a 2nd input shaped [1,1,1,n_head] is a per-head sink,
// NOT a mask. It is appended as one hidden logit column, softmax runs over the widened last axis,
// and the sink column is dropped -- so each row sums to (1 - sink_weight) instead of 1.
@@ -3660,6 +3694,21 @@ TEST(GGUFOps, MultimodalRopeMatchesIndependentSections) {
std::copy(values.begin(), values.end(), positions.data<int32_t>());
auto actual = run_on_cpu(model, {{"data", make_f32_tensor({1, 2, 3, 64}, data)}, {"pos", positions}});
expect_near(actual, load_npy<float>(vision ? "vision_rope_expected" : "multimodal_imrope_expected"));
+ if (!vision) {
+ const auto converted_ops = model->get_ops();
+ EXPECT_TRUE(std::none_of(converted_ops.begin(), converted_ops.end(), [](const auto& node) {
+ return std::string(node->get_type_name()) == "RoPE";
+ }));
+ ov::pass::Manager manager;
+ manager.register_pass<ov::pass::RoPEFusion>();
+ manager.run_passes(model);
+ const auto ops = model->get_ops();
+ EXPECT_TRUE(std::any_of(ops.begin(), ops.end(), [](const auto& node) {
+ return std::string(node->get_type_name()) == "RoPE";
+ }));
+ actual = run_on_cpu(model, {{"data", make_f32_tensor({1, 2, 3, 64}, data)}, {"pos", positions}});
+ expect_near(actual, load_npy<float>("multimodal_imrope_expected"));
+ }
}
}
diff --git a/src/frontends/gguf/tests/test_shared_linear_inputs.cpp b/src/frontends/gguf/tests/test_shared_linear_inputs.cpp
new file mode 100644
index 00000000000..a25b0b54473
--- /dev/null
+++ b/src/frontends/gguf/tests/test_shared_linear_inputs.cpp
@@ -0,0 +1,336 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <cmath>
+
+#include "builder/blocks/common.hpp"
+#include "builder/blocks/ffn.hpp"
+#include "gtest/gtest.h"
+#include "node_context.hpp"
+#include "op_table.hpp"
+#include "op_test_utils.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/transpose.hpp"
+#include "utils.hpp"
+
+namespace {
+using namespace ov::frontend::gguf;
+
+ov::Output<ov::Node> projection(std::shared_ptr<TensorMap>& tensors,
+ const std::shared_ptr<ConstantCache>& cache,
+ const ov::PartialShape& shape,
+ size_t width,
+ const std::map<std::string, ov::Any>& attributes = {}) {
+ const std::string weight_name = "w" + std::to_string(width);
+ std::vector<float> values(width * 8);
+ for (size_t i = 0; i < values.size(); ++i)
+ values[i] = (static_cast<int>(i % 7) - 3) / 8.f;
+ (*tensors)[weight_name] = ov::op::v0::Constant::create(ov::element::f32, {width, 8}, values);
+ const auto decoder = std::make_shared<ov_gguf_test::SingleOpDecoder>(
+ "GGML_OP_MUL_MAT",
+ std::vector<ov_gguf_test::TensorDesc>{{weight_name, ov::element::f32, {1, 1, static_cast<int64_t>(width), 8}},
+ {"x", tensors->at("x").get_element_type(), shape}},
+ std::vector<ov_gguf_test::TensorDesc>{},
+ ov_gguf_test::TensorDesc{"y", ov::element::f32, ov::PartialShape::dynamic()},
+ attributes);
+ return op::translate_mulmat(NodeContext(decoder, tensors, cache))[0];
+}
+
+std::shared_ptr<ov::Node> linear_node(const ov::Output<ov::Node>& output) {
+ auto node = output.get_node_shared_ptr();
+ if (node->get_type_name() == std::string("Unsqueeze") || node->get_type_name() == std::string("Reshape"))
+ node = node->get_input_node_shared_ptr(0);
+ return node;
+}
+} // namespace
+
+TEST(GGUFSharedLinearInputs, PreservesBatchesDynamicShapesAndEmptyTokens) {
+ const ov::PartialShape shape{2, 1, -1, -1};
+ const auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shape);
+ auto tensors = std::make_shared<TensorMap>(TensorMap{{"x", x}});
+ const auto y = projection(tensors, std::make_shared<ConstantCache>(), shape, 3);
+ ASSERT_EQ(y.get_partial_shape(), (ov::PartialShape{2, 1, -1, 3}));
+ ASSERT_EQ(y.get_node()->get_type_name(), std::string("MatMul"));
+ const auto mm = linear_node(y);
+ ASSERT_EQ(mm->input_value(0), x->output(0));
+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{y}, ov::ParameterVector{x});
+ for (size_t tokens : {0, 1, 3}) {
+ ov::Tensor input(ov::element::f32, {2, 1, tokens, 8});
+ for (size_t i = 0; i < input.get_size(); ++i)
+ input.data<float>()[i] = (static_cast<int>(i % 11) - 5) / 4.f;
+ ov::Tensor output(ov::element::f32, {2, 1, tokens, 3});
+ ov::TensorVector outputs{output};
+ ASSERT_TRUE(model->evaluate(outputs, {input}));
+ ASSERT_EQ(outputs[0].get_shape(), (ov::Shape{2, 1, tokens, 3}));
+ for (size_t row = 0; row < 2 * tokens; ++row) {
+ for (size_t n = 0; n < 3; ++n) {
+ float expected = 0;
+ for (size_t k = 0; k < 8; ++k)
+ expected += input.data<float>()[row * 8 + k] * (static_cast<int>((n * 8 + k) % 7) - 3) / 8.f;
+ EXPECT_FLOAT_EQ(outputs[0].data<float>()[row * 3 + n], expected);
+ }
+ }
+ }
+}
+
+TEST(GGUFSharedLinearInputs, SharesRotationAndTrailingConversionAcrossProjections) {
+ const ov::PartialShape shape{2, 1, -1, 8};
+ for (const auto type : {ov::element::f32, ov::element::f16}) {
+ const auto x = std::make_shared<ov::op::v0::Parameter>(type, shape);
+ auto tensors = std::make_shared<TensorMap>(TensorMap{{"x", x}});
+ const auto cache = std::make_shared<ConstantCache>();
+ const std::map<std::string, ov::Any> attributes{{"hadamard_block", int64_t{8}}};
+ const auto q = projection(tensors, cache, shape, 3, attributes);
+ const auto k = projection(tensors, cache, shape, 5, attributes);
+ auto gate_attributes = attributes;
+ gate_attributes["activation_rank"] = 3;
+ const auto gate = projection(tensors, cache, shape, 7, gate_attributes);
+ const auto shared_input = linear_node(q)->input_value(0);
+ EXPECT_EQ(shared_input, linear_node(k)->input_value(0));
+ EXPECT_NE(shared_input, linear_node(gate)->input_value(0));
+ EXPECT_EQ(gate.get_partial_shape(), (ov::PartialShape{2, -1, 7}));
+ EXPECT_EQ(cache->hadamard_outputs.size(), 1);
+ EXPECT_EQ(cache->f32_activations.size(), type == ov::element::f16 ? 2 : 0);
+ EXPECT_EQ(cache->rank3_activations.size(), 1);
+ auto rotation = shared_input.get_node_shared_ptr();
+ if (type == ov::element::f16)
+ rotation = rotation->get_input_node_shared_ptr(0);
+ EXPECT_EQ(rotation->get_type_name(), std::string("Reshape"));
+ }
+}
+
+TEST(GGUFSharedLinearInputs, LeavesBroadcastWeightLayoutsUnchanged) {
+ for (const auto& shape : {ov::PartialShape{2, 2, -1, 8}, ov::PartialShape{2, -1, -1, 8}}) {
+ const auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shape);
+ auto tensors = std::make_shared<TensorMap>(TensorMap{{"x", x}});
+ const auto cache = std::make_shared<ConstantCache>();
+ const auto y = projection(tensors, cache, shape, 3, {{"hadamard_block", int64_t{8}}});
+ EXPECT_EQ(linear_node(y)->get_input_partial_shape(0), shape);
+ EXPECT_TRUE(cache->f32_activations.empty());
+ }
+ const ov::PartialShape shape{2, 1, -1, 8};
+ const auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shape);
+ auto tensors = std::make_shared<TensorMap>(TensorMap{{"x", x}});
+ const auto cache = std::make_shared<ConstantCache>();
+ (*tensors)["w"] = ov::op::v0::Constant::create(ov::element::f32, {2, 3, 8}, {1.f});
+ const auto decoder = std::make_shared<ov_gguf_test::SingleOpDecoder>(
+ "GGML_OP_MUL_MAT",
+ std::vector<ov_gguf_test::TensorDesc>{{"w", ov::element::f32, {1, 2, 3, 8}}, {"x", ov::element::f32, shape}},
+ std::vector<ov_gguf_test::TensorDesc>{},
+ ov_gguf_test::TensorDesc{"y", ov::element::f32, ov::PartialShape::dynamic()},
+ std::map<std::string, ov::Any>{{"hadamard_block", int64_t{8}}});
+ const auto y = op::translate_mulmat(NodeContext(decoder, tensors, cache))[0];
+ EXPECT_EQ(linear_node(y)->get_input_partial_shape(0), shape);
+ EXPECT_EQ(y.get_partial_shape(), (ov::PartialShape{2, 2, -1, 3}));
+ EXPECT_TRUE(cache->f32_activations.empty());
+}
+
+TEST(GGUFSharedLinearInputs, TernaryProjectionsExposeSupportedHadamardMatrices) {
+ for (const int64_t block : {256, 512, 1024, 4096}) {
+ SCOPED_TRACE(block);
+ const ov::PartialShape shape{2, 1, -1, block};
+ const auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shape);
+ const auto w = ov::op::v0::Constant::create(ov::element::u2, {16, static_cast<size_t>(block)}, {1});
+ auto tensors = std::make_shared<TensorMap>(
+ TensorMap{{"x", x}, {"w", std::make_shared<ov::op::v0::Convert>(w, ov::element::f32)}});
+ const auto cache = std::make_shared<ConstantCache>();
+ const auto decoder = std::make_shared<ov_gguf_test::SingleOpDecoder>(
+ "GGML_OP_MUL_MAT",
+ std::vector<ov_gguf_test::TensorDesc>{{"w", ov::element::f32, {1, 1, 16, block}},
+ {"x", ov::element::f32, shape}},
+ std::vector<ov_gguf_test::TensorDesc>{},
+ ov_gguf_test::TensorDesc{"y", ov::element::f32, ov::PartialShape::dynamic()},
+ std::map<std::string, ov::Any>{{"hadamard_block", block}});
+ const NodeContext context(decoder, tensors, cache);
+ const auto first = op::translate_mulmat(context)[0];
+ const auto second = op::translate_mulmat(context)[0];
+ EXPECT_EQ(first.get_partial_shape(), (ov::PartialShape{2, 1, -1, 16}));
+ const auto fc = linear_node(first);
+ EXPECT_EQ(fc->get_output_partial_shape(0), (ov::PartialShape{2, -1, 16}));
+ EXPECT_EQ(fc->input_value(0), linear_node(second)->input_value(0));
+ const auto rotation = fc->get_input_node_shared_ptr(0)->get_input_node_shared_ptr(0);
+ ASSERT_EQ(rotation->get_type_name(), std::string("MatMul"));
+ const auto matrix = ov::as_type_ptr<ov::op::v0::Constant>(rotation->get_input_node_shared_ptr(1));
+ ASSERT_NE(matrix, nullptr);
+ EXPECT_EQ(matrix->get_shape(), (ov::Shape{static_cast<size_t>(block), static_cast<size_t>(block)}));
+ EXPECT_EQ(matrix, context.get_hadamard_matrix(ov::element::f32, block));
+ EXPECT_EQ(cache->hadamard_matrices.size(), 1);
+ EXPECT_EQ(cache->hadamard_outputs.size(), 1);
+ }
+}
+
+TEST(GGUFSharedLinearInputs, TernaryProjectionRestoresSelectedTokenBatchLayout) {
+ const ov::PartialShape shape{1, 1, -1, 8};
+ const auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shape);
+ const auto w = ov::op::v0::Constant::create(ov::element::u2, {3, 8}, {1});
+ auto tensors = std::make_shared<TensorMap>(
+ TensorMap{{"x", x}, {"w", std::make_shared<ov::op::v0::Convert>(w, ov::element::f32)}});
+ const auto decoder = std::make_shared<ov_gguf_test::SingleOpDecoder>(
+ "GGML_OP_MUL_MAT",
+ std::vector<ov_gguf_test::TensorDesc>{{"w", ov::element::f32, {1, 1, 3, 8}}, {"x", ov::element::f32, shape}},
+ std::vector<ov_gguf_test::TensorDesc>{},
+ ov_gguf_test::TensorDesc{"y", ov::element::f32, ov::PartialShape::dynamic()},
+ std::map<std::string, ov::Any>{});
+ const auto y = op::translate_mulmat(NodeContext(decoder, tensors, std::make_shared<ConstantCache>()))[0];
+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{y}, ov::ParameterVector{x});
+ x->set_partial_shape({1, -1, 1, 8});
+ model->validate_nodes_and_infer_types();
+ EXPECT_EQ(model->output().get_partial_shape(), (ov::PartialShape{1, -1, 1, 3}));
+ ov::Tensor input(ov::element::f32, {1, 5, 1, 8});
+ for (size_t i = 0; i < input.get_size(); ++i)
+ input.data<float>()[i] = static_cast<float>(i);
+ ov::TensorVector outputs{ov::Tensor(ov::element::f32, {1, 5, 1, 3})};
+ ASSERT_TRUE(model->evaluate(outputs, {input}));
+ EXPECT_EQ(outputs[0].get_shape(), (ov::Shape{1, 5, 1, 3}));
+ for (size_t row = 0; row < 5; ++row)
+ for (size_t column = 0; column < 3; ++column)
+ EXPECT_FLOAT_EQ(outputs[0].data<float>()[row * 3 + column], 64.f * row + 28.f);
+}
+
+TEST(GGUFHadamardSharing, InverseRotationUsesSupportedMatrix) {
+ using namespace ov::frontend::gguf;
+ constexpr int64_t block = 256;
+ const auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{2, -1, block});
+ auto tensors = std::make_shared<TensorMap>(TensorMap{{"x", x}});
+ const auto decoder = std::make_shared<ov_gguf_test::SingleOpDecoder>(
+ "GGML_OP_GET_ROWS",
+ std::vector<ov_gguf_test::TensorDesc>{},
+ std::vector<ov_gguf_test::TensorDesc>{},
+ ov_gguf_test::TensorDesc{"y", ov::element::f32, ov::PartialShape::dynamic()},
+ std::map<std::string, ov::Any>{{"hadamard_block", block}, {"hadamard_inverse", true}});
+ const auto y = apply_hadamard(NodeContext(decoder, tensors, std::make_shared<ConstantCache>()), x);
+ ASSERT_EQ(y.get_node()->get_type_name(), std::string("Reshape"));
+ EXPECT_EQ(y.get_node()->get_input_node_shared_ptr(0)->get_type_name(), std::string("MatMul"));
+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{y}, ov::ParameterVector{x});
+ ov::Tensor input(ov::element::f32, {2, 1, block});
+ std::fill_n(input.data<float>(), input.get_size(), 1.f);
+ ov::TensorVector output{ov::Tensor(ov::element::f32, {2, 1, block})};
+ ASSERT_TRUE(model->evaluate(output, {input}));
+ for (size_t i = 0; i < input.get_size(); ++i)
+ EXPECT_FLOAT_EQ(output[0].data<float>()[i], i % block == 0 ? 16.f : 0.f);
+}
+
+TEST(GGUFHadamardSharing, DistinguishesSignsDirectionLayoutAndConversionScope) {
+ const ov::PartialShape shape{2, -1, 8};
+ const auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shape);
+ auto tensors = std::make_shared<TensorMap>(TensorMap{{"x", x}});
+ const auto cache = std::make_shared<ConstantCache>();
+ const auto rotate = [&](const ov::Tensor& signs,
+ bool inverse,
+ const std::vector<int64_t>& heads,
+ const std::shared_ptr<ConstantCache>& conversion_cache) {
+ const auto decoder = std::make_shared<ov_gguf_test::SingleOpDecoder>(
+ "GGML_OP_MUL_MAT",
+ std::vector<ov_gguf_test::TensorDesc>{{"x", ov::element::f32, shape}},
+ std::vector<ov_gguf_test::TensorDesc>{},
+ ov_gguf_test::TensorDesc{"y", ov::element::f32, shape},
+ std::map<std::string, ov::Any>{{"hadamard_block", int64_t{8}},
+ {"hadamard_signs", signs},
+ {"hadamard_inverse", inverse},
+ {"hadamard_gdn_heads", heads}});
+ return apply_hadamard(NodeContext(decoder, tensors, conversion_cache), x);
+ };
+ ov::Tensor signs(ov::element::f32, {8});
+ std::fill_n(signs.data<float>(), 8, 1.f);
+ const auto first = rotate(signs, false, {}, cache);
+ ov::Tensor same(ov::element::f32, {8});
+ std::copy_n(signs.data<float>(), 8, same.data<float>());
+ EXPECT_EQ(first, rotate(same, false, {}, cache));
+ same.data<float>()[3] = -1.f;
+ EXPECT_NE(first, rotate(same, false, {}, cache));
+ EXPECT_NE(first, rotate(signs, true, {}, cache));
+ EXPECT_NE(first, rotate(signs, false, {2, 2, 2}, cache));
+ EXPECT_NE(first, rotate(signs, false, {}, std::make_shared<ConstantCache>()));
+}
+
+TEST(GGUFSharedLinearInputs, JointInterleavedProjectionPreservesHeadsBatchesAndTokens) {
+ using namespace ov::frontend::gguf;
+ for (const auto& shape : {ov::PartialShape{2, -1, 8}, ov::PartialShape{2, 1, -1, 8}}) {
+ std::unordered_map<std::string, ov::Tensor> weights;
+ std::unordered_map<std::string, GgufTensorType> qtypes;
+ GraphEmitter emitter(weights, qtypes, "test");
+ const auto x = emitter.add_input("x", ov::element::f32, shape);
+ weights["joint.weight"] = ov::Tensor(ov::element::f32, {12, 8});
+ for (size_t i = 0; i < 96; ++i)
+ weights["joint.weight"].data<float>()[i] = (static_cast<int>(i % 13) - 6) / 8.f;
+ emitter.add_weight("joint.weight");
+ const auto joint = emitter.add_op("GGML_OP_MUL_MAT", "joint", {"joint.weight", "x"});
+ const auto parts = blocks::split_interleaved_projection(emitter, joint, {"q", "gate"}, 3, 2);
+ const auto model =
+ std::make_shared<ov::Model>(ov::OutputVector{emitter.value(parts[0]), emitter.value(parts[1])},
+ ov::ParameterVector{x});
+ for (const size_t tokens : {1, 3}) {
+ auto input_shape = shape.get_max_shape();
+ input_shape[input_shape.size() - 2] = tokens;
+ ov::Tensor input(ov::element::f32, input_shape);
+ for (size_t i = 0; i < input.get_size(); ++i)
+ input.data<float>()[i] = (static_cast<int>(i % 11) - 5) / 4.f;
+ auto output_shape = input_shape;
+ output_shape.back() = 6;
+ ov::TensorVector outputs{ov::Tensor(ov::element::f32, output_shape),
+ ov::Tensor(ov::element::f32, output_shape)};
+ ASSERT_TRUE(model->evaluate(outputs, {input}));
+ for (size_t part = 0; part < 2; ++part) {
+ ASSERT_EQ(outputs[part].get_shape(), output_shape);
+ for (size_t row = 0; row < 2 * tokens; ++row) {
+ for (size_t n = 0; n < 6; ++n) {
+ const size_t weight_row = (n / 2) * 4 + part * 2 + n % 2;
+ float expected = 0;
+ for (size_t k = 0; k < 8; ++k)
+ expected += input.data<float>()[row * 8 + k] *
+ weights["joint.weight"].data<float>()[weight_row * 8 + k];
+ EXPECT_FLOAT_EQ(outputs[part].data<float>()[row * 6 + n], expected);
+ }
+ }
+ }
+ }
+ }
+}
+
+TEST(GGUFSharedLinearInputs, GateUpProjectionKeepsGLUBranchesRank3) {
+ using namespace ov::frontend::gguf;
+ std::unordered_map<std::string, ov::Tensor> weights;
+ std::unordered_map<std::string, GgufTensorType> qtypes;
+ GraphEmitter emitter(weights, qtypes, "test");
+ const auto x = emitter.add_input("x", ov::element::f32, {2, 1, -1, 8});
+ for (const auto* name : {"ffn_gate.weight", "ffn_up.weight"}) {
+ weights[name] = ov::Tensor(ov::element::f32, {3, 8});
+ for (size_t i = 0; i < 24; ++i)
+ weights[name].data<float>()[i] = (static_cast<int>(i % 7) - 3) / 8.f;
+ }
+ const auto output = blocks::swiglu_gate_up(emitter,
+ "ffn_gate.weight",
+ "ffn_up.weight",
+ "x",
+ "ffn_gate",
+ "ffn_up",
+ "ffn_swiglu",
+ false);
+ EXPECT_EQ(emitter.value("ffn_gate").get_partial_shape(), (ov::PartialShape{2, -1, 3}));
+ EXPECT_EQ(emitter.value("ffn_up").get_partial_shape(), (ov::PartialShape{2, -1, 3}));
+ EXPECT_EQ(emitter.value("ffn_swiglu").get_partial_shape(), (ov::PartialShape{2, -1, 3}));
+ EXPECT_EQ(emitter.value(output).get_partial_shape(), (ov::PartialShape{2, 1, -1, 3}));
+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{emitter.value(output)}, ov::ParameterVector{x});
+ for (const size_t tokens : {1, 3}) {
+ ov::Tensor input(ov::element::f32, {2, 1, tokens, 8});
+ for (size_t i = 0; i < input.get_size(); ++i)
+ input.data<float>()[i] = (static_cast<int>(i % 11) - 5) / 4.f;
+ ov::TensorVector outputs{ov::Tensor(ov::element::f32, {2, 1, tokens, 3})};
+ ASSERT_TRUE(model->evaluate(outputs, {input}));
+ for (size_t row = 0; row < 2 * tokens; ++row) {
+ for (size_t n = 0; n < 3; ++n) {
+ float projection = 0;
+ for (size_t k = 0; k < 8; ++k)
+ projection +=
+ input.data<float>()[row * 8 + k] * weights["ffn_gate.weight"].data<float>()[n * 8 + k];
+ EXPECT_NEAR(outputs[0].data<float>()[row * 3 + n],
+ projection * projection / (1 + std::exp(-projection)),
+ 1e-6f);
+ }
+ }
+ }
+}
diff --git a/src/frontends/gguf/tests/test_weights.cpp b/src/frontends/gguf/tests/test_weights.cpp
index 691dc1c6c0e..1dbf116a04d 100644
--- a/src/frontends/gguf/tests/test_weights.cpp
+++ b/src/frontends/gguf/tests/test_weights.cpp
@@ -17,12 +17,20 @@
#include <vector>
#include "common_test_utils/file_utils.hpp"
+#include "node_context.hpp"
#include "op_test_utils.hpp"
#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
#include "openvino/op/gather.hpp"
#include "openvino/op/matmul.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/split.hpp"
+#include "openvino/op/subtract.hpp"
+#include "openvino/op/unsqueeze.hpp"
#include "quant/gguf.hpp"
#include "quant/weights.hpp"
+#include "utils.hpp"
using namespace ov_gguf_test;
@@ -75,14 +83,14 @@ TEST_P(GGUFWeight, MatchesGgmlToFloat) {
ASSERT_EQ(out.get_size(), ref.size());
const float* a = out.data<float>();
- 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;
}
+ 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]));
EXPECT_LE(max_diff, c.tol) << c.stem << ": frontend weight dequant diverges from ggml to_float";
}
@@ -214,6 +222,511 @@ TEST(GGUFWeight, Q8_1CpuMatmulAndGatherMatchRepresentedWeights) {
}
}
+TEST(GGUFWeight, TernaryRowsKeepCompressedDictionaryAndTiedProjection) {
+ for (const auto& format :
+ std::vector<std::pair<const char*, const char*>>{{"q2_0", "Q2_0"}, {"pq2_0", "PQ2_0"}, {"ptq1_0", "PTQ1_0"}}) {
+ SCOPED_TRACE(format.second);
+ const auto bytes = load_npy<uint8_t>(std::string(format.first) + "_qbytes");
+ const auto weight = make_weight_node(bytes_to_u8_tensor(bytes), format.second, {kRows, kCols});
+ auto indices = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{1, 1, 1, -1});
+ indices->set_friendly_name("indices");
+ indices->output(0).set_names({"indices"});
+ auto activation = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, kCols});
+ auto projection = std::make_shared<ov::op::v0::MatMul>(activation, weight, false, true);
+ auto decoder = SingleOpBuilder()
+ .op("GGML_OP_GET_ROWS")
+ .input("weight", ov::element::f32, {kRows, kCols})
+ .input("indices", ov::element::i64, {1, 1, 1, -1})
+ .output("rows", ov::element::f32, {1, 1, -1, kCols})
+ .decoder();
+ auto tensors = std::make_shared<TensorMap>();
+ (*tensors)["weight"] = weight;
+ (*tensors)["indices"] = indices;
+ NodeContext context(decoder, tensors);
+ auto rows = op::translate_get_rows(context)[0];
+ auto model = std::make_shared<ov::Model>(ov::OutputVector{rows}, ov::ParameterVector{indices});
+ size_t dictionaries = 0;
+ const void* dictionary_data = nullptr;
+ for (const auto& node : model->get_ops()) {
+ const auto constant = ov::as_type_ptr<ov::op::v0::Constant>(node);
+ if (!constant || constant->get_element_type() != ov::element::u8 || constant->get_shape().size() != 3)
+ continue;
+ ++dictionaries;
+ dictionary_data = constant->get_data_ptr();
+ EXPECT_EQ(constant->get_byte_size(), kRows * kCols / 4);
+ }
+ EXPECT_EQ(dictionaries, 1);
+ EXPECT_EQ(projection->get_input_node_shared_ptr(1), weight);
+ auto original = std::make_shared<ov::Model>(ov::OutputVector{weight}, ov::ParameterVector{});
+ size_t subtracts = 0;
+ for (const auto& op : original->get_ordered_ops()) {
+ const auto subtract = ov::as_type_ptr<ov::op::v1::Subtract>(op);
+ if (!subtract)
+ continue;
+ ++subtracts;
+ const auto convert = ov::as_type_ptr<ov::op::v0::Convert>(subtract->get_input_node_shared_ptr(1));
+ const auto zp = ov::as_type_ptr<ov::op::v0::Constant>(convert ? convert->get_input_node_shared_ptr(0)
+ : subtract->get_input_node_shared_ptr(1));
+ ASSERT_TRUE(zp);
+ EXPECT_EQ(zp->get_element_type(),
+ std::string(format.second) == "Q2_0" ? ov::element::u8 : ov::element::f16);
+ EXPECT_EQ(zp->get_shape(), ov::Shape{});
+ EXPECT_EQ(zp->cast_vector<float>(), std::vector<float>{1.f});
+ }
+ EXPECT_EQ(subtracts, 1);
+ size_t original_dictionaries = 0;
+ for (const auto& node : original->get_ops()) {
+ const auto constant = ov::as_type_ptr<ov::op::v0::Constant>(node);
+ if (constant && constant->get_element_type() == ov::element::u2) {
+ ++original_dictionaries;
+ EXPECT_EQ(dictionary_data, constant->get_data_ptr());
+ }
+ }
+ EXPECT_EQ(original_dictionaries, 1);
+ const auto reference = load_npy<float>(std::string(format.first) + "_deq");
+ for (const auto& selected : std::vector<std::vector<int64_t>>{{3, 0, 3}, {2}}) {
+ auto output = run_on_cpu(model, {{"indices", make_i64_tensor({1, 1, 1, selected.size()}, selected)}});
+ ASSERT_EQ(output.get_shape(), (ov::Shape{1, 1, selected.size(), kCols}));
+ for (size_t i = 0; i < selected.size(); ++i) {
+ for (size_t j = 0; j < kCols; ++j)
+ EXPECT_FLOAT_EQ(output.data<float>()[i * kCols + j], reference[selected[i] * kCols + j]);
+ }
+ }
+ }
+}
+
+TEST(GGUFWeight, GatherPreservesOtherWeightFormats) {
+ for (const auto& format : std::vector<std::pair<const char*, const char*>>{{"q1_0", "Q1_0"},
+ {"q2_k", "Q2_K"},
+ {"q4_0", "Q4_0"},
+ {"q8_0", "Q8_0"}}) {
+ SCOPED_TRACE(format.second);
+ const auto bytes = load_npy<uint8_t>(std::string(format.first) + "_qbytes");
+ const auto weight = make_weight_node(bytes_to_u8_tensor(bytes), format.second, {kRows, kCols});
+ auto indices = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});
+ const auto gather =
+ ov::as_type_ptr<ov::op::v8::Gather>(gather_weight_rows(weight, indices).get_node_shared_ptr());
+ ASSERT_TRUE(gather);
+ EXPECT_EQ(gather->get_input_node_shared_ptr(0), weight);
+ }
+}
+
+TEST(GGUFWeight, PreservesNonUniformU2ZeroPoints) {
+ using namespace ov::frontend::gguf;
+ WeightTensors tensors{ov::Tensor(ov::element::u2, {1, 256}),
+ ov::Tensor(ov::element::f16, {1, 2}),
+ ov::Tensor(ov::element::u8, {1, 2})};
+ auto* zp_data = tensors.zero_point.data<uint8_t>();
+ zp_data[0] = 1;
+ zp_data[1] = 2;
+ const auto node = make_weight_node(tensors, GGUF_TYPE_PTQ1_0);
+
+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{node}, ov::ParameterVector{});
+ size_t subtracts = 0;
+ for (const auto& op : model->get_ordered_ops()) {
+ const auto subtract = ov::as_type_ptr<ov::op::v1::Subtract>(op);
+ if (!subtract)
+ continue;
+ ++subtracts;
+ const auto convert = ov::as_type_ptr<ov::op::v0::Convert>(subtract->get_input_node_shared_ptr(1));
+ ASSERT_TRUE(convert);
+ const auto zp = ov::as_type_ptr<ov::op::v0::Constant>(convert->get_input_node_shared_ptr(0));
+ ASSERT_TRUE(zp);
+ EXPECT_EQ(zp->get_shape(), (ov::Shape{1, 2, 1}));
+ EXPECT_EQ(zp->cast_vector<uint8_t>(), (std::vector<uint8_t>{1, 2}));
+ }
+ EXPECT_EQ(subtracts, 1);
+}
+
+TEST(GGUFWeight, PreservesPQ2CodeThreeFallback) {
+ for (size_t lane = 0; lane < 4; ++lane) {
+ SCOPED_TRACE(lane);
+ auto bytes = load_npy<uint8_t>("pq2_0_qbytes");
+ bytes[2] = (bytes[2] & ~(3 << (lane * 2))) | (3 << (lane * 2));
+ const auto node = make_weight_node(bytes_to_u8_tensor(bytes), "PQ2_0", {kRows, kCols});
+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{node}, ov::ParameterVector{});
+ size_t subtracts = 0;
+ for (const auto& op : model->get_ordered_ops()) {
+ const auto subtract = ov::as_type_ptr<ov::op::v1::Subtract>(op);
+ if (!subtract)
+ continue;
+ ++subtracts;
+ EXPECT_EQ(subtract->get_input_shape(1), (ov::Shape{kRows, kCols / 128, 1}));
+ }
+ EXPECT_EQ(subtracts, 1);
+ const auto output = run_on_cpu(model, {});
+ uint16_t scale_bits;
+ std::memcpy(&scale_bits, bytes.data(), sizeof(scale_bits));
+ EXPECT_FLOAT_EQ(output.data<float>()[lane], 2.f * float(ov::float16::from_bits(scale_bits)));
+ }
+}
+
+TEST(GGUFWeight, MixedU2ProjectionsKeepGroupedZeroPoints) {
+ using namespace ov::frontend::gguf;
+ for (const bool mixed_inputs : {false, true}) {
+ for (const size_t count : {2, 3}) {
+ for (const bool grouped_first : {false, true}) {
+ for (const bool singleton : {false, true}) {
+ SCOPED_TRACE(::testing::Message()
+ << count << ":" << grouped_first << ":" << singleton << ":" << mixed_inputs);
+ const size_t k = singleton ? 128 : 256;
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32,
+ ov::PartialShape{-1, static_cast<int64_t>(k)});
+ input->output(0).get_tensor().set_names({"input"});
+ ov::OutputVector outputs;
+ std::vector<std::shared_ptr<ov::op::v1::Subtract>> subtracts;
+ for (size_t i = 0; i < count; ++i) {
+ const bool fallback = i == (grouped_first ? 0 : count - 1);
+ const size_t n = singleton && fallback ? 1 : 15;
+ WeightTensors tensors{ov::Tensor(ov::element::u2, {n, k}),
+ ov::Tensor(ov::element::f16, {n, k / 128}),
+ ov::Tensor(ov::element::u8, {n, k / 128})};
+ std::memset(tensors.weight.data(), fallback ? 0xff : 0x55, tensors.weight.get_byte_size());
+ std::fill_n(tensors.scales.data<ov::float16>(), tensors.scales.get_size(), ov::float16(0.125f));
+ std::memset(tensors.zero_point.data(), 1, tensors.zero_point.get_byte_size());
+ auto weight = make_weight_node(tensors, GGUF_TYPE_PQ2_0);
+ auto weight_model =
+ std::make_shared<ov::Model>(ov::OutputVector{weight}, ov::ParameterVector{});
+ for (const auto& node : weight_model->get_ops()) {
+ if (auto subtract = ov::as_type_ptr<ov::op::v1::Subtract>(node))
+ subtracts.push_back(subtract);
+ }
+ auto activation = std::make_shared<ov::op::v1::Reshape>(
+ input,
+ ov::op::v0::Constant::create(ov::element::i64,
+ {2},
+ std::vector<int64_t>{-1, static_cast<int64_t>(k)}),
+ false);
+ const ov::Output<ov::Node> projection_input =
+ mixed_inputs && fallback ? input->output(0) : activation->output(0);
+ outputs.push_back(std::make_shared<ov::op::v0::MatMul>(projection_input, weight, false, true));
+ }
+ auto model = std::make_shared<ov::Model>(outputs, ov::ParameterVector{input});
+ auto reference = model->clone();
+ normalize_u2_zero_points(model);
+ for (size_t i = 0; i < count; ++i) {
+ const bool fallback = i == (grouped_first ? 0 : count - 1);
+ const auto matmul = ov::as_type_ptr<ov::op::v0::MatMul>(outputs[i].get_node_shared_ptr());
+ EXPECT_EQ(ov::is_type<ov::op::v1::Reshape>(matmul->get_input_node_shared_ptr(0)),
+ !mixed_inputs || !fallback);
+ }
+ ASSERT_EQ(subtracts.size(), count);
+ for (const auto& subtract : subtracts) {
+ const auto convert =
+ ov::as_type_ptr<ov::op::v0::Convert>(subtract->get_input_node_shared_ptr(1));
+ ASSERT_TRUE(convert);
+ const auto zp = ov::as_type_ptr<ov::op::v0::Constant>(convert->get_input_node_shared_ptr(0));
+ ASSERT_TRUE(zp);
+ ASSERT_EQ(zp->get_shape().size(), 3);
+ EXPECT_EQ(zp->get_shape().back(), 1);
+ }
+ model->validate_nodes_and_infer_types();
+ ov::Tensor data(ov::element::f32, {1, k});
+ std::fill_n(data.data<float>(), k, 1.f);
+ ov::Core core;
+ const auto properties = ov::hint::inference_precision(ov::element::f32);
+ auto actual = core.compile_model(model, "CPU", properties).create_infer_request();
+ auto expected = core.compile_model(reference, "CPU", properties).create_infer_request();
+ actual.set_input_tensor(data);
+ expected.set_input_tensor(data);
+ actual.infer();
+ expected.infer();
+ for (size_t output = 0; output < count; ++output) {
+ const auto a = actual.get_output_tensor(output);
+ const auto b = expected.get_output_tensor(output);
+ ASSERT_EQ(a.get_size(), b.get_size());
+ for (size_t i = 0; i < a.get_size(); ++i)
+ EXPECT_FLOAT_EQ(a.data<const float>()[i], b.data<const float>()[i]);
+ }
+ }
+ }
+ }
+ }
+}
+
+TEST(GGUFWeight, HadamardProjectionGroupsPreserveDistinctActivations) {
+ using namespace ov::frontend::gguf;
+ for (const auto& [different_signs, different_output] :
+ std::vector<std::pair<bool, bool>>{{false, false}, {true, false}, {false, true}}) {
+ SCOPED_TRACE(::testing::Message() << different_signs << ":" << different_output);
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{-1, 256});
+ auto split =
+ std::make_shared<ov::op::v1::Split>(input, ov::op::v0::Constant::create(ov::element::i64, {}, {1}), 2);
+ ov::OutputVector outputs;
+ std::vector<std::shared_ptr<ov::op::v1::Subtract>> subtracts;
+ for (size_t i = 0; i < 2; ++i) {
+ const auto x = split->output(different_output ? i : 0);
+ ov::Tensor signs(ov::element::f32, {128});
+ std::fill_n(signs.data<float>(), 128, 1.f);
+ signs.data<float>()[0] = different_signs && i == 1 ? -1.f : 1.f;
+ const auto decoder = std::make_shared<SingleOpDecoder>(
+ "GGML_OP_MUL_MAT",
+ std::vector<TensorDesc>{{"x", ov::element::f32, {-1, 128}}},
+ std::vector<TensorDesc>{},
+ TensorDesc{"y", ov::element::f32, {-1, 128}},
+ std::map<std::string, ov::Any>{{"hadamard_block", int64_t{4}}, {"hadamard_signs", signs}});
+ auto tensor_map = std::make_shared<TensorMap>();
+ (*tensor_map)["x"] = x;
+ const auto activation = apply_hadamard(NodeContext(decoder, tensor_map), x);
+ WeightTensors tensors{ov::Tensor(ov::element::u2, {16, 128}),
+ ov::Tensor(ov::element::f16, {16, 1}),
+ ov::Tensor(ov::element::u8, {16, 1})};
+ std::memset(tensors.weight.data(), i == 0 ? 0xff : 0x99, tensors.weight.get_byte_size());
+ std::fill_n(tensors.scales.data<ov::float16>(), tensors.scales.get_size(), ov::float16(0.125f));
+ std::memset(tensors.zero_point.data(), 1, tensors.zero_point.get_byte_size());
+ const auto weight = make_weight_node(tensors, GGUF_TYPE_PQ2_0);
+ const auto weight_model = std::make_shared<ov::Model>(ov::OutputVector{weight}, ov::ParameterVector{});
+ for (const auto& node : weight_model->get_ordered_ops()) {
+ if (const auto subtract = ov::as_type_ptr<ov::op::v1::Subtract>(node))
+ subtracts.push_back(subtract);
+ }
+ outputs.push_back(std::make_shared<ov::op::v0::MatMul>(activation, weight, false, true));
+ }
+ auto model = std::make_shared<ov::Model>(outputs, ov::ParameterVector{input});
+ const auto reference = model->clone();
+ std::map<std::shared_ptr<ov::Node>, ov::OutputVector> inputs;
+ for (const auto& node : model->get_ordered_ops())
+ inputs[node] = node->input_values();
+ normalize_u2_zero_points(model);
+ ASSERT_EQ(subtracts.size(), 2);
+ EXPECT_FALSE(subtracts[0]->get_input_shape(1).empty());
+ EXPECT_EQ(subtracts[1]->get_input_shape(1).empty(), different_signs || different_output);
+ for (const auto& [node, original_inputs] : inputs) {
+ if (!ov::is_type<ov::op::v1::Subtract>(node)) {
+ EXPECT_EQ(node->input_values(), original_inputs);
+ }
+ }
+ ov::Tensor data(ov::element::f32, {2, 256});
+ for (size_t i = 0; i < data.get_size(); ++i)
+ data.data<float>()[i] = std::sin(static_cast<float>(i) * 0.1f);
+ ov::Core core;
+ const auto properties = ov::hint::inference_precision(ov::element::f32);
+ auto actual = core.compile_model(model, "CPU", properties).create_infer_request();
+ auto expected = core.compile_model(reference, "CPU", properties).create_infer_request();
+ actual.set_input_tensor(data);
+ expected.set_input_tensor(data);
+ actual.infer();
+ expected.infer();
+ for (size_t i = 0; i < 2; ++i) {
+ const auto a = actual.get_output_tensor(i);
+ const auto b = expected.get_output_tensor(i);
+ ASSERT_EQ(a.get_size(), b.get_size());
+ for (size_t j = 0; j < a.get_size(); ++j)
+ EXPECT_FLOAT_EQ(a.data<const float>()[j], b.data<const float>()[j]);
+ }
+ }
+}
+
+TEST(GGUFWeight, HadamardCodeThreeFallbackPreservesGroupedProjections) {
+ using namespace ov::frontend::gguf;
+ for (const auto type : {ov::element::f32, ov::element::f16}) {
+ SCOPED_TRACE(type);
+ for (const int64_t block : {256, 1024}) {
+ for (const int code3_branch : {-1, 0, 1, 2}) {
+ SCOPED_TRACE(::testing::Message() << block << ":" << code3_branch);
+ const ov::PartialShape shape{2, 1, -1, block};
+ const auto x = std::make_shared<ov::op::v0::Parameter>(type, shape);
+ x->set_friendly_name("x");
+ const auto cache = std::make_shared<ConstantCache>();
+ ov::OutputVector outputs;
+ std::vector<std::shared_ptr<ov::op::v1::Subtract>> subtracts;
+ for (int branch = 0; branch < (code3_branch == 2 ? 1 : 2); ++branch) {
+ WeightTensors tensors{ov::Tensor(ov::element::u2, {16, static_cast<size_t>(block)}),
+ ov::Tensor(ov::element::f16, {16, static_cast<size_t>(block / 128)}),
+ ov::Tensor(ov::element::f16, {16, static_cast<size_t>(block / 128)})};
+ std::memset(tensors.weight.data(), 0x99, tensors.weight.get_byte_size());
+ if (code3_branch == branch || code3_branch == 2)
+ static_cast<uint8_t*>(tensors.weight.data())[0] = 0x9b;
+ std::fill_n(tensors.scales.data<ov::float16>(), tensors.scales.get_size(), ov::float16(0.125f));
+ std::fill_n(tensors.zero_point.data<ov::float16>(),
+ tensors.zero_point.get_size(),
+ ov::float16(1.f));
+ const auto weight = make_weight_node(tensors, GGUF_TYPE_PQ2_0);
+ const auto weight_model =
+ std::make_shared<ov::Model>(ov::OutputVector{weight}, ov::ParameterVector{});
+ for (const auto& node : weight_model->get_ops()) {
+ if (const auto subtract = ov::as_type_ptr<ov::op::v1::Subtract>(node))
+ subtracts.push_back(subtract);
+ }
+ const auto decoder = std::make_shared<SingleOpDecoder>(
+ "GGML_OP_MUL_MAT",
+ std::vector<TensorDesc>{{"w", ov::element::f32, {1, 1, 16, block}}, {"x", type, shape}},
+ std::vector<TensorDesc>{},
+ TensorDesc{"y", ov::element::f32, ov::PartialShape::dynamic()},
+ std::map<std::string, ov::Any>{{"hadamard_block", block}, {"activation_rank", 3}});
+ auto tensors_map = std::make_shared<TensorMap>(TensorMap{{"x", x}, {"w", weight}});
+ outputs.push_back(op::translate_mulmat(NodeContext(decoder, tensors_map, cache))[0]);
+ }
+ const auto model = std::make_shared<ov::Model>(outputs, ov::ParameterVector{x});
+ const auto reference = model->clone();
+ normalize_u2_zero_points(model);
+ const auto nodes = model->get_ops();
+ EXPECT_EQ(std::count_if(nodes.begin(),
+ nodes.end(),
+ [](const auto& node) {
+ return node->get_rt_info().count("gguf_hadamard_block") != 0;
+ }),
+ code3_branch == -1 ? 1 : 0);
+ for (const auto& subtract : subtracts)
+ EXPECT_EQ(subtract->get_input_shape(1).empty(), code3_branch == -1);
+ const auto normalized = model->get_ops().size();
+ normalize_u2_zero_points(model);
+ EXPECT_EQ(model->get_ops().size(), normalized);
+ for (const size_t tokens : {1, 3}) {
+ ov::Tensor data(type, {2, 1, tokens, static_cast<size_t>(block)});
+ for (size_t i = 0; i < data.get_size(); ++i) {
+ if (type == ov::element::f16)
+ data.data<ov::float16>()[i] = ov::float16(100.f);
+ else
+ data.data<float>()[i] = std::sin(static_cast<float>(i) * 0.1f);
+ }
+ ov::TensorVector expected, actual;
+ for (size_t i = 0; i < outputs.size(); ++i) {
+ expected.emplace_back(ov::element::f32, ov::Shape{2, tokens, 16});
+ actual.emplace_back(ov::element::f32, ov::Shape{2, tokens, 16});
+ }
+ ASSERT_TRUE(reference->evaluate(expected, {data}));
+ ASSERT_TRUE(model->evaluate(actual, {data}));
+ for (size_t i = 0; i < outputs.size(); ++i) {
+ ASSERT_EQ(actual[i].get_shape(), expected[i].get_shape());
+ for (size_t j = 0; j < actual[i].get_size(); ++j)
+ EXPECT_NEAR(actual[i].data<float>()[j], expected[i].data<float>()[j], 1e-5f);
+ }
+ }
+ }
+ }
+ }
+}
+
+TEST(GGUFWeight, HadamardMixedWeightTypesKeepSeparateForms) {
+ using namespace ov::frontend::gguf;
+ const auto fixture = load_npy<uint8_t>("q4_0_qbytes");
+ std::vector<uint8_t> bytes;
+ for (size_t i = 0; i < 16; ++i)
+ bytes.insert(bytes.end(), fixture.begin(), fixture.end());
+ const auto q4 = make_weight_node(bytes_to_u8_tensor(bytes), "Q4_0", {16, 1024});
+ WeightTensors tensors{ov::Tensor(ov::element::u2, {16, 1024}),
+ ov::Tensor(ov::element::f16, {16, 8}),
+ ov::Tensor(ov::element::f16, {16, 8})};
+ std::memset(tensors.weight.data(), 0x99, tensors.weight.get_byte_size());
+ std::fill_n(tensors.scales.data<ov::float16>(), tensors.scales.get_size(), ov::float16(0.125f));
+ std::fill_n(tensors.zero_point.data<ov::float16>(), tensors.zero_point.get_size(), ov::float16(1.f));
+ const auto u2 = make_weight_node(tensors, GGUF_TYPE_PQ2_0);
+ for (const auto type : {ov::element::f32, ov::element::f16}) {
+ for (const bool u2_first : {false, true}) {
+ SCOPED_TRACE(::testing::Message() << type << ":" << u2_first);
+ const auto x = std::make_shared<ov::op::v0::Parameter>(type, ov::PartialShape{1, -1, 1024});
+ const auto cache = std::make_shared<ConstantCache>();
+ ov::OutputVector outputs;
+ ov::OutputVector references;
+ for (const bool ternary : {u2_first, !u2_first}) {
+ const auto weight = ternary ? u2 : q4;
+ const auto decoder = std::make_shared<SingleOpDecoder>(
+ "GGML_OP_MUL_MAT",
+ std::vector<TensorDesc>{{"w", ov::element::f32, {1, 1, 16, 1024}}, {"x", type, {1, 1, -1, 1024}}},
+ std::vector<TensorDesc>{},
+ TensorDesc{"y", ov::element::f32, ov::PartialShape::dynamic()},
+ std::map<std::string, ov::Any>{{"hadamard_block", int64_t{1024}}});
+ auto tensor_map = std::make_shared<TensorMap>(TensorMap{{"x", x}, {"w", weight}});
+ const NodeContext context(decoder, tensor_map, cache);
+ const auto output = op::translate_mulmat(context)[0];
+ const auto branch = std::make_shared<ov::Model>(ov::OutputVector{output}, ov::ParameterVector{x});
+ const auto nodes = branch->get_ops();
+ EXPECT_EQ(std::count_if(nodes.begin(),
+ nodes.end(),
+ [](const auto& node) {
+ return node->get_rt_info().count("gguf_hadamard_block") != 0;
+ }),
+ ternary ? 1 : 0);
+ EXPECT_EQ(op::translate_mulmat(context)[0].get_node()->input_value(0),
+ output.get_node()->input_value(0));
+ outputs.push_back(output);
+ const auto rotation = apply_hadamard(context, x, true);
+ references.push_back(
+ std::make_shared<ov::op::v0::MatMul>(context.get_f32_activation(rotation), weight, false, true));
+ }
+ EXPECT_EQ(cache->hadamard_outputs.size(), 2);
+ const auto model = std::make_shared<ov::Model>(outputs, ov::ParameterVector{x});
+ const auto reference = std::make_shared<ov::Model>(references, ov::ParameterVector{x});
+ normalize_u2_zero_points(model);
+ for (const size_t tokens : {1, 3}) {
+ ov::Tensor data(type, {1, tokens, 1024});
+ for (size_t i = 0; i < data.get_size(); ++i) {
+ if (type == ov::element::f16)
+ data.data<ov::float16>()[i] = ov::float16(100.f);
+ else
+ data.data<float>()[i] = std::sin(static_cast<float>(i) * 0.1f);
+ }
+ ov::TensorVector actual{ov::Tensor(ov::element::f32, {1, tokens, 16}),
+ ov::Tensor(ov::element::f32, {1, tokens, 16})};
+ ov::TensorVector expected{ov::Tensor(ov::element::f32, {1, tokens, 16}),
+ ov::Tensor(ov::element::f32, {1, tokens, 16})};
+ ASSERT_TRUE(model->evaluate(actual, {data}));
+ ASSERT_TRUE(reference->evaluate(expected, {data}));
+ for (size_t i = 0; i < actual.size(); ++i) {
+ for (size_t j = 0; j < actual[i].get_size(); ++j) {
+ const auto value = expected[i].data<float>()[j];
+ EXPECT_NEAR(actual[i].data<float>()[j], value, 1e-4f + 1e-5f * std::fabs(value));
+ }
+ }
+ }
+ }
+ }
+}
+
+TEST(GGUFWeight, MixedU2ProjectionsKeepFloatingZeroPointType) {
+ using namespace ov::frontend::gguf;
+ const auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{-1, 128});
+ ov::OutputVector outputs;
+ for (const bool fallback : {false, true}) {
+ WeightTensors tensors{ov::Tensor(ov::element::u2, {16, 128}),
+ ov::Tensor(ov::element::f16, {16, 1}),
+ ov::Tensor(ov::element::f16, {16, 1})};
+ std::memset(tensors.weight.data(), fallback ? 0xff : 0x55, tensors.weight.get_byte_size());
+ std::fill_n(tensors.scales.data<ov::float16>(), tensors.scales.get_size(), ov::float16(0.125f));
+ std::fill_n(tensors.zero_point.data<ov::float16>(), tensors.zero_point.get_size(), ov::float16(1.f));
+ outputs.push_back(
+ std::make_shared<ov::op::v0::MatMul>(input, make_weight_node(tensors, GGUF_TYPE_PTQ1_0), false, true));
+ }
+ const auto model = std::make_shared<ov::Model>(outputs, ov::ParameterVector{input});
+ normalize_u2_zero_points(model);
+ size_t subtracts = 0;
+ for (const auto& node : model->get_ops()) {
+ if (const auto subtract = ov::as_type_ptr<ov::op::v1::Subtract>(node)) {
+ ++subtracts;
+ EXPECT_EQ(subtract->get_input_shape(1), (ov::Shape{16, 1, 1}));
+ EXPECT_EQ(subtract->get_input_element_type(1), ov::element::f16);
+ }
+ }
+ EXPECT_EQ(subtracts, 2);
+}
+
+TEST(GGUFWeight, TernaryProjectionsKeepScalarZeroPoints) {
+ using namespace ov::frontend::gguf;
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{-1, 128});
+ ov::OutputVector outputs;
+ for (size_t i = 0; i < 3; ++i) {
+ WeightTensors tensors{ov::Tensor(ov::element::u2, {16, 128}),
+ ov::Tensor(ov::element::f16, {16, 1}),
+ ov::Tensor(ov::element::u8, {16, 1})};
+ std::memset(tensors.weight.data(), 0x55, tensors.weight.get_byte_size());
+ std::fill_n(tensors.scales.data<ov::float16>(), tensors.scales.get_size(), ov::float16(0.125f));
+ std::memset(tensors.zero_point.data(), 1, tensors.zero_point.get_byte_size());
+ outputs.push_back(
+ std::make_shared<ov::op::v0::MatMul>(input, make_weight_node(tensors, GGUF_TYPE_PTQ1_0), false, true));
+ }
+ auto model = std::make_shared<ov::Model>(outputs, ov::ParameterVector{input});
+ normalize_u2_zero_points(model);
+ size_t subtracts = 0;
+ for (const auto& node : model->get_ops()) {
+ if (const auto subtract = ov::as_type_ptr<ov::op::v1::Subtract>(node)) {
+ ++subtracts;
+ EXPECT_EQ(subtract->get_input_shape(1), ov::Shape{});
+ }
+ }
+ EXPECT_EQ(subtracts, 3);
+}
+
TEST(GGUFWeight, Q1_0KeepsBinaryCodesForAllWeightNames) {
const auto bytes = load_npy<uint8_t>("q1_0_qbytes");
const auto reference = load_npy<float>("q1_0_deq");
@@ -473,6 +986,8 @@ TEST(GGUFWeight, UsesIntegerZeroPointForRequantizedMatmulWeights) {
EXPECT_EQ(gguf_zero_point_type("token_embd.weight", GGUF_TYPE_Q4_K), ov::element::f16);
EXPECT_EQ(gguf_zero_point_type("output.weight", GGUF_TYPE_Q5_K), ov::element::f16);
EXPECT_EQ(gguf_zero_point_type("blk.0.attn_q.weight", GGUF_TYPE_Q2_0), ov::element::u8);
+ EXPECT_EQ(gguf_zero_point_type("blk.0.attn_q.weight", GGUF_TYPE_PQ2_0), ov::element::f16);
+ EXPECT_EQ(gguf_zero_point_type("blk.0.attn_q.weight", GGUF_TYPE_PTQ1_0), ov::element::f16);
}
class GGUFQ5KNative : public ::testing::Test {