OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[GGUF] Enable Bonsai and Bonsai-2 model families (#38817)
Maxim Vafin38ff87c03083
diff --git a/src/frontends/gguf/README.md b/src/frontends/gguf/README.mdindex 580cd2721e9..d98f5990352 100644--- a/src/frontends/gguf/README.md+++ b/src/frontends/gguf/README.md@@ -49,7 +49,7 @@ Projector files convert to encoder models; see [multimodal conversion](docs/mmpr* [Add or port an architecture](docs/architectures.md)* [Register extensions and build plugins](docs/extensions.md), with [runnable examples](examples/architecture_extension/README.md)* [Add an operation translator](docs/how_to_add_op.md)-* [Weight formats and precision](docs/quantization.md)+* [Weight formats, unpacking, memory costs and precision](docs/quantization.md)* [Debug accuracy differences](docs/debugging_accuracy.md)* [Build, test and regenerate references](docs/testing.md)diff --git a/src/frontends/gguf/docs/mmproj.md b/src/frontends/gguf/docs/mmproj.mdindex c770a92455a..8fb51d6cb4d 100644--- a/src/frontends/gguf/docs/mmproj.md+++ b/src/frontends/gguf/docs/mmproj.md@@ -30,6 +30,11 @@ 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.+InternViT-6B (width 3200, 45 layers) uses RMS norms like the reference, but has no fixture.Not implemented: `ldp`, `ldpv2`, `adapter`, `step3vl`, `gemma3nv`, `llama4`, `qwen3a`, `lfm2`,diff --git a/src/frontends/gguf/docs/quantization.md b/src/frontends/gguf/docs/quantization.mdindex e49e72f9135..7b7c9b9c1be 100644--- a/src/frontends/gguf/docs/quantization.md+++ b/src/frontends/gguf/docs/quantization.md@@ -1,31 +1,302 @@-# GGUF weights and execution precision+# GGUF weight formats, unpacking and execution precision-File quantization, frontend storage, inference arithmetic, and KV-cache precision are separate-choices. Support for a weight format does not establish model accuracy or device support.-The native format mapping lives in [`weights.cpp`](../src/quant/weights.cpp); parsing and tensor-extraction live in [`gguf.cpp`](../src/quant/gguf.cpp).+The GGUF frontend separates interleaved GGML blocks into OpenVINO weight, scale and optional+zero-point Constants. This guide covers their decoding, stored element types, storage costs+and conversion tradeoffs. File quantization, frontend storage, inference arithmetic and+KV-cache precision are separate choices; device compilation determines the execution+representation.++The implementation is in [`gguf.cpp`](../src/quant/gguf.cpp),+[`gguf_quants.cpp`](../src/quant/gguf_quants.cpp) and [`weights.cpp`](../src/quant/weights.cpp).++## Storage and graph conventions++The tables below describe the **native `.gguf` input path before device compilation**. The+[supplied-decoder path](#supplied-decoder-and-raw-byte-differences) has additional conversions.+Mixed checkpoint labels such as `Q4_K_M` select different formats for different tensors; they+do not define another block layout.++For a logical weight shape `[..., K]` and group size `G`, the decompression graph views codes+as `[..., K/G, G]` and scales/zero points as `[..., K/G, 1]`. It computes+`weight = (code - zero_point) * scale`, or `code * scale` for symmetric formats, then reshapes+back to `[..., K]`. Codes, scales and zero points are separate Constants. GGUF type identifiers+select the import algorithm; they do not become new OpenVINO element types.++Sub-byte Constants remain packed: `u1` holds eight binary codes per byte, with the first element+in the most significant bit. `u2` holds four codes per byte, and `i4`/`u4` hold two per byte,+with the first element in the least significant bits. The loader's `u32` tensors for+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.++The usual graph is `Convert -> [Subtract] -> Multiply -> Reshape -> Convert(F32)`. Decompression+uses the scale's element type, normally F16. Q6_K and formats with fractional F16 zero points+and code widths of at least four bits instead perform subtraction/multiplication in F32.+Q8_K uses F32 scales and thus F32 arithmetic. MXFP4 uses an F16 multiply. A final F32 output+does not undo rounding in earlier F16 operations, and does not imply that a full F32 weight+buffer is stored by the frontend.++Affine formats replace the source's additive offset with a fractional F16 zero point.+The scale products and zero-point ratios can round or overflow; a zero scale cannot retain+a nonzero offset. Fractional zero points can also prevent compressed FullyConnected fusion.+Integer-zero-point requantization avoids that fusion limitation where supported, but changes+the weight values and adds quantization error.## Native weight formats-| GGUF weight type | OpenVINO weight representation |-|---|---|-| `F32`, `F16`, `BF16` | Floating-point constants; converter-facing values are F32 |-| `Q1_0`, `Q3_K`, `Q4_0` | i4 codes with grouped scales |-| `Q5_0`, `Q5_1`, `Q6_K`, `Q8_0`, `Q8_K` | i8 codes with scales and format-specific zero points |-| `Q2_K`, `Q2_0` | u2 codes with grouped scales/zero points |-| `Q4_1`, `Q4_K` | u4 codes; ordinary matmul weights use integer-zero-point requantization by default |-| `Q5_K` | u8 requantization with integer zero points for ordinary matmul weights |-| `MXFP4` | f4e2m1 codes and f8e8m0 per-32 scales |--Widening codes to a supported storage type is different from requantizing values. Native Q6_K-uses explicit F32 decompression arithmetic. Embedding/output tensors retain fractional zero-points where applicable. Q4_K/Q4_1 and Q5_K requantization add error beyond that already present-in the file; the frontend prints an accuracy notice once per process for each approximation.-Mixed file labels such as `Q4_K_M` describe a checkpoint's tensor mix, not one tensor type.--The supplied-cgraph/raw-byte weight path can have different representation choices, including-channel-wise Q8_0_C requantization for embedding/output and selected formats. Record which-path produced the model when comparing weights; native storage is not a claim about backend storage.+`W`, `S` and `Z` below mean code, scale and zero-point payloads. Byte counts include all three+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.++| Format | Weights per GGUF block | GGUF bytes | Weight type (`W`) | Scale type (`S`) | Zero-point type (`Z`) | Native OpenVINO bytes (`W + S + Z`) | Change |+|---|---:|---:|---|---|---|---:|---:|+| F32 | 1 | 4 | `f32` | — | — | 4 | 0% |+| 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% |+| 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% |+| Q4_1, integer zero point | 32 | 20 | `u4` | `f16` | `u8` | `16 + 2 + 1` = 19 | -5.0% |+| Q4_1, fractional zero point | 32 | 20 | `u4` | `f16` | `f16` | `16 + 2 + 2` = 20 | 0% |+| Q4_K, integer zero point | 256 | 144 | `u4` | `f16` | `u8` | `128 + 16 + 8` = 152 | +5.6% |+| Q4_K, fractional zero point | 256 | 144 | `u4` | `f16` | `f16` | `128 + 16 + 16` = 160 | +11.1% |+| Q5_0 | 32 | 22 | `i8` | `f16` | — | `32 + 2` = 34 | +54.5% |+| Q5_1 | 32 | 24 | `i8` | `f16` | `f16` | `32 + 2 + 2` = 36 | +50.0% |+| Q5_K, integer zero point | 256 | 176 | `u8` | `f16` | `u8` | `256 + 16 + 8` = 280 | +59.1% |+| Q5_K, fractional zero point | 256 | 176 | `u8` | `f16` | `f16` | `256 + 16 + 16` = 288 | +63.6% |+| Q6_K | 256 | 210 | `i8` | `f16` | — | `256 + 32` = 288 | +37.1% |+| Q8_0 | 32 | 34 | `i8` | `f16` | — | `32 + 2` = 34 | 0% |+| Q8_K | 256 | 292 | `i8` | `f32` | — | `256 + 4` = 260 | -11.0% |+| MXFP4 | 32 | 17 | `f4e2m1` | `f8e8m0` | — | `16 + 1` = 17 | 0% |++Ordinary native Q4_1/Q4_K and Q5_K matrix weights use integer zero points by default.+`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.+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.++## Floating-point formats++F32, F16 and BF16 tensors are views of the memory-mapped file, without block unpacking or+quantization metadata. F16/BF16 Constants receive a Convert to F32 for operation translators.+There is no additional code quantization. Compilation may materialize a converted buffer,+so the original two-byte storage is not an upper bound on compiled weight memory. Auxiliary+integer tensors and F64 tensors likewise have no quantized block decomposition.++## Binary and ternary formats++### Q1_0++A block is an F16 scale followed by 16 bytes of binary codes for 128 weights. Import reverses+the bits in each byte from GGML's least-significant-bit-first order to OpenVINO's+most-significant-bit-first `u1` order. The scale is copied unchanged. Eight weights remain+packed per byte, without a zero-point tensor or requantization.++The graph converts bits to F16, computes `2 * bit - 1`, multiplies by the per-128 F16 scale,+reshapes to the logical weight dimensions and converts to F32. Forming the sign before+applying the scale avoids doubling the stored scale and overflowing large finite F16 scales.+The sign expression adds only two scalar Constants shared across groups. Both native and+raw-byte input paths preserve `u1`, including embedding/output tensors.++Device plugins need compressed binary matrix and lookup kernels to preserve this storage+through compilation. The current CPU compressed FullyConnected and Gather paths do not+support `u1`, so compilation expands these weights to floating point. This can substantially+increase execution and compilation memory despite the compact frontend representation.++### Q2_0 and PQ2_0++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`;+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+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.++### PTQ1_0++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:++```text+for (start, count, trits) in [(0, 16, 5), (16, 8, 5), (24, 2, 4)]:+ for n in 0 .. trits-1:+ for m in 0 .. count-1:+ q = (payload[start+m] * 3**n) modulo 256+ code = (q * 3) >> 8+ append code to packed u2 output+```++The modulo operation reflects the implementation's `uint8_t` intermediate; replacing this+with ordinary base-3 digit extraction would change the decoding. Import writes 32 bytes of+`u2` codes, copies the F16 scale and adds the same zero point of 1 as PQ2_0. There is no+decoding table or dense-trit decoder left in the IR; its graph is the usual grouped+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++A block holds an F16 scale and 16 bytes of four-bit codes. GGML's low nibbles describe the+first 16 weights and its high nibbles the next 16. Import reorders them into adjacent-element+packing, then XORs each byte with `0x88`. This converts unsigned codes 0..15 into signed+`i4` codes -8..7. The graph multiplies by the copied scale with group 32, without a zero point.++Storage size and code values are preserved after centering. Import still performs a reorder;+the F16 multiply and device arithmetic can round differently from a GGML kernel.++### Q5_0 and Q5_1++Both formats combine a four-byte high-bit mask with 16 bytes of low nibbles to reconstruct+32 five-bit codes: `q = low_nibble | (high_bit << 4)`.++Q5_0 stores one F16 scale and centers `q` by subtracting 16 at import, producing `i8` codes+-16..15 with group 32. Q5_1 stores an F16 scale `d` and an F16 additive offset `m`, keeps+`i8` codes 0..31, and stores the F16 zero point `-m/d`. Its graph computes `(q - zero_point) * d`+in F32; import uses zero point 0 when `d` is zero.++Both widen five-bit codes to one byte per weight without code requantization. Q5_1 has the+affine scale/zero-point limitations described in [graph conventions](#storage-and-graph-conventions).++### Q3_K++A 256-weight block contains 32 high-mask bytes, 64 low-code bytes, 12 packed sub-scale bytes+and an F16 scale `d`. Import reconstructs the signed three-bit code as+`low_two_bits - (high_mask_bit ? 0 : 4)`, reorders it into logical element order, and stores+it as `i4` (-4..3). Six-bit sub-scales are unpacked and centered by subtracting 32. Each+16-weight group receives an F16 scale `d * signed_sub_scale`.++There is no code requantization, but three-bit codes widen to four bits and compact scale+metadata becomes 16 F16 scales. Products stored as F16 can round or overflow.++### Q6_K++A block contains 128 low-nibble bytes, 64 high-two-bit bytes, 16 signed byte sub-scales and+an F16 scale `d`. Import joins the six-bit codes, subtracts 32, and writes `i8` (-32..31) in+logical order. Sixteen F16 scales hold `d * signed_sub_scale` for groups of 16. The graph+explicitly converts codes and scales to F32 before multiplying.++Code values are preserved, but widening to eight bits and expanding sub-scales increases storage.+F32 graph arithmetic avoids an F16 multiply, but the combined scales have already been rounded+to F16 at import.++### Q8_0 and Q8_K++Q8_0 directly copies 32 `i8` codes and one F16 scale per block. There is no code expansion,+requantization or extra metadata; its usual decompression multiply is F16.++Q8_K copies 256 `i8` codes and an F32 scale unchanged. Each GGUF block contains 256 code bytes,+four scale bytes and 32 bytes of precomputed sums (`16` values of type `i16`), totaling 292+bytes. OpenVINO omits the sums, leaving 260 bytes: a reduction of `32/292`, or 11.0%.++Each omitted sum is `bsums[j] = sum(codes[16*j : 16*j+16])`. These sums accelerate GGML's+quantized dot products but are not needed by the decompression graph. No weight information+or precision is lost by omitting them: reconstruction remains `weight[i] = scale * code[i]`+in F32, without requantization. The sums can be regenerated exactly from the retained codes+if a future kernel or GGUF exporter needs them. Preserving them would add unused storage to+the current representation. OpenVINO does not reproduce GGML's partial-sum kernel through+this representation. Q8_1 has no implemented native weight unpacking path.++## Affine K formats++### Q2_K++A block is `16 scale/min bytes | 64 code bytes | F16 d | F16 dmin`. Each scale/min byte+contains a four-bit sub-scale `s` and a four-bit sub-minimum `m`. Import reorders the two-bit+codes into packed `u2` element order. For each 16-weight group it stores F16 scale `d*s`+and F16 zero point `(dmin*m)/(d*s)`, or zero when the denominator is zero.++Codes stay two-bit without requantization, but the expanded metadata adds storage and has the+common affine limitations. Decompression arithmetic is F16; `u2` also limits device fusion.++### Q4_K and Q5_K++Both use 256-weight blocks with F16 `d`/`dmin` and 12 bytes packing eight six-bit sub-scales+and minima. Q4_K has 128 code bytes; Q5_K adds 32 high-bit bytes. Import extracts each+32-weight group's scale `sc = d*s` and subtractive offset `offset = dmin*m`, giving source+values `sc*q - offset`.++With a **fractional zero point**, Q4_K reorders and preserves the four-bit codes in `u4`;+Q5_K reconstructs five-bit codes 0..31 and stores them in `u8`. Both store F16 `sc` and+F16 `offset/sc` (zero for a zero scale), and their graph arithmetic is F32. Both have the+common affine limitations; Q5_K additionally widens its code payload.++With an **integer zero point**, both first reconstruct 32 source values in F32, then+requantize onto a new grid whose range includes zero. Q4_K uses 16 levels in packed `u4`:+min/max initialization, an integer zero point, and a least-squares scale refinement. Candidate+scales are evaluated after F16 rounding. The importer retains the original codes with a+rounded integer zero point unless a candidate reduces squared error without increasing+maximum absolute error. Q5_K uses 256 levels in `u8`, an F16 min/max scale and a rounded,+clipped integer zero point; values are rounded and clipped to 0..255.++Including zero in a one-sided group coarsens the available grid. Q5_K collapses a group to+zero if its new F16 scale is nonpositive or nonfinite.++### Q4_1++Q4_1 stores `F16 d | F16 m | 16 code bytes` for 32 weights, with values `d*q + m`.+The fractional path reorders its `u4` codes, copies `d` and stores F16 zero point `-m/d`,+then decompresses in F32 with the common affine limitations. The integer path uses the Q4_K+group requantizer described above with offset `-m`, reducing metadata by one byte per group.++## MXFP4++A block holds one E8M0 scale byte and 16 bytes of four-bit codes for 32 weights. Import+reorders the split low/high nibbles into element order and separates an `f4e2m1` weight+Constant from an `f8e8m0` scale Constant. OpenVINO's `f4e2m1` values are half the GGML lookup+values, while its E8M0 scale is twice the GGML scale; their product represents the same value.++The payload remains 17 bytes with no code requantization or host float expansion. The graph+converts both operands to F16, multiplies and converts the reshaped result to F32. F16 range+and arithmetic, and the device's support for these compressed element types, still matter.++## Supplied-decoder and raw-byte differences++The native loader supplies pre-extracted tensors to `make_weight_node`. A supplied decoder+can instead pass raw GGML bytes, a type name and a logical shape. The raw-byte overload+currently differs as follows:++| Case | Raw-byte representation | Drawback |+|---|---|---|+| Q4_1, Q5_1 | Full F32 Constant decoded with `d*q + m` before other format handling | 128 bytes per 32 weights: +540% for Q4_1, +433.3% for Q5_1 |+| Q1_0, including embedding/output | Packed `u1` plus per-128 F16 scales, as in native loading | Requires plugin binary decompression support to remain packed at execution |+| Quantized `token_embd.weight` / `output.weight`, except Q1_0 and the Q4_1/Q5_1 cases above | Channel-wise Q8_0_C: `i8` codes with one F16 scale per row | Additional lossy quantization; low-bit sources usually expand |+| Q5_K ordinary matrices | The same channel-wise Q8_0_C representation | Additional lossy quantization; different scale grouping from native Q5_K |+| Q4_K/Q5_K/Q6_K selected for Q8_0_C | Stream original F32-dequantized rows directly into channel-wise quantization | Per-worker F32 row scratch; avoids allocating a full temporary F32 matrix |+| Rank greater than two MXFP4 experts | Packed `u8` blocks retaining scale/code interleaving; expert selection and decompression happen on the graph | Different graph layout; device fusion and temporary storage depend on expert execution |++For Q8_0_C, each row uses `d = max(abs(values))/127`, stored as F16, and signed codes rounded+from `values/d`. A zero row has zero scale. A matrix of `R` rows and `K` columns stores+`R*K + 2*R` bytes. Other selected quantized sources are first extracted and then dequantized+one row at a time for this conversion. Plain F32/F16/BF16 return before channel-wise+requantization. Raw Q8_K has no implemented fill case, unlike the native Q8_K path.## Accuracy controls@@ -43,8 +314,7 @@ compiled = core.compile_model(model, "CPU", {Set `OV_GGUF_Q4_K_ZP_F16=1` **before starting the process** to preserve fractional Q4_K/Q4_1zero points instead of their default u4 requantization. It is cached on first use; changing theenvironment later in a notebook does not switch an already initialized process. The option-does not make every quantized format lossless. Fractional zero points can prevent compressed-FullyConnected fusion, slow matmul, or be unsupported by a device implementation.+does not make every quantized format lossless or guarantee device support for fractional zero points.llama.cpp's quantized kernels can quantize activations even when OpenVINO's dynamic activationquantization is disabled. Report comparisons against quantized CPU arithmetic separately from@@ -53,11 +323,20 @@ with worse full-logit error; use both metrics and the [acceptance criteria](test## Memory and packaging limits-Frontend compressed storage does not guarantee compressed execution. In particular, CPU compressed-expert matmul does not support u2 in this branch, so large Q2 MoE models can expand during-compilation. Include weight reorders and temporary buffers in memory estimates; a smaller context-does not remove those costs. Check [checkpoint-specific limits](supported_models.md#runtime-limitations).+For `N` weights of a uniform block format, multiply its OpenVINO bytes per block by+`N / weights_per_block`. Sum over tensor formats for a mixed checkpoint. This estimates+frontend payload storage, including per-group metadata.++Native quantized loading allocates independent buffers while reading the memory-mapped+source. Source pages and output buffers can coexist during import; the loader requests+eviction of processed source ranges, but this is not a guarantee about peak resident memory.+Splitting or reordering projections can also require copies. Constants built from the+extracted buffers share those buffers rather than copying each one again.-`Ternary-Bonsai-27B-Q2_0.gguf` uses g128 packing inconsistent with upstream Q2_0 g64. Use-`Ternary-Bonsai-27B-Q2_g64.gguf`; the frontend rejects the mismatched packaging. Adding a builder-or operation converter does not add a new quantization format.+During compilation a device may fuse decompression into its matrix kernel, reorder packed+weights, or expand them to floating point. Full F16 and F32 expansions require `2*N` and+`4*N` bytes respectively, potentially alongside packed storage. In particular, CPU compressed+expert matmul does not support `u2` in this implementation, so Q2 MoE weights can expand.+Weight reorders and temporary buffers add to these costs; reducing context length does not+remove them. KV caches, activation buffers and Hadamard transforms are separate from weight+payload estimates. See [checkpoint-specific limits](supported_models.md#runtime-limitations).diff --git a/src/frontends/gguf/docs/supported_models.md b/src/frontends/gguf/docs/supported_models.mdindex ee50cb0f962..03cdb113ec5 100644--- a/src/frontends/gguf/docs/supported_models.md+++ b/src/frontends/gguf/docs/supported_models.md@@ -114,3 +114,44 @@ GGML_OPENVINO_DEVICE=CPU GGML_OPENVINO_STATEFUL_EXECUTION=1 \```Checkpoints used `Q2_K`, `Q4_0`, `Q4_K_M`, `Q6_K` and `Q8_0`; other formats are covered by unit tests only.++## 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 |++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+indices cover context plus draft rows; callers provide a fully open attention mask for the+noncausal round. Outputs include `logits`, `dspark.hidden`, per-layer caches and, when present,+`dspark.corrected_logits` and raw `dspark.confidence_score`. `dspark_prev_tokens` supplies the+sampled predecessor for each auxiliary-head row. Sequential sampling and target-layer capture+belong to the caller. Log-SNR uses Prism's round-1 inference convention: the first draft+position is at `max_log_snr`, and the remaining masked positions are at `min_log_snr`.+Normalization `(log_snr - min_log_snr) / (max_log_snr - min_log_snr) * 1000` maps these+endpoints to 1000 and 0, independent of the bounds. Both bounds must still be present,+finite and strictly ordered, as required by the model's conditioning metadata.+Hidden-correction checkpoints and generic GenAI decoder adaptation are not supported.+Draft blocks up to 4096 tokens are supported.diff --git a/src/frontends/gguf/src/builder/api/graph_context.cpp b/src/frontends/gguf/src/builder/api/graph_context.cppindex 328cc390ba7..91d6fad2dda 100644--- a/src/frontends/gguf/src/builder/api/graph_context.cpp+++ b/src/frontends/gguf/src/builder/api/graph_context.cpp@@ -42,6 +42,7 @@ DecoderDimensions GgufGraphContext::configure_decoder(RopeMode rope, const Decodm_impl->check_open();OPENVINO_ASSERT(!m_impl->decoder, "[GGUF] decoder is already configured");auto normalized = decoder_config_from_meta(detail::MetadataAccess::get(metadata()).map);+ m_impl->emitter.configure_hadamard(normalized);auto config = std::make_unique<DecoderConfig>(normalized, m_impl->build_ctx.weights->weights, rope, options);auto& graph = *m_impl->emitter.graph();graph.has_rope = true;@@ -244,6 +245,7 @@ void GgufGraphContext::add_recurrent_state(const GgufValue& input, const GgufValstd::shared_ptr<GgufGraph> GgufGraphContext::finish() {m_impl->check_open();+ m_impl->emitter.validate_hadamard();const auto graph = m_impl->emitter.graph();OPENVINO_ASSERT(!graph->model_output_names.empty(), "[GGUF] graph has no outputs");std::set<std::string> available;diff --git a/src/frontends/gguf/src/builder/arch/decoder_builder.cpp b/src/frontends/gguf/src/builder/arch/decoder_builder.cppindex b88e68f37ed..31e8fad61c4 100644--- a/src/frontends/gguf/src/builder/arch/decoder_builder.cpp+++ b/src/frontends/gguf/src/builder/arch/decoder_builder.cpp@@ -48,6 +48,7 @@ DecoderBuilder::DecoderBuilder(const std::map<std::string, GGUFMetaData>& config: m_cfg(config, weights, rope, options),m_emit(weights, qtypes, m_cfg.arch, translators),m_kv(blocks::KvCachePlan::build(m_cfg)) {+ m_emit.configure_hadamard(config);auto& graph = *m_emit.graph();graph.has_rope = true;graph.rope_config = m_cfg.rope_config;@@ -386,6 +387,7 @@ std::shared_ptr<GgufGraph> DecoderBuilder::build() {}const std::string logits = build_head(cur);+ m_emit.validate_hadamard();// logits is the primary output; the cache_k/v_l* outputs (appended per layer above)// become Assign sinks via MakeStateful.diff --git a/src/frontends/gguf/src/builder/arch/dspark_builder.cpp b/src/frontends/gguf/src/builder/arch/dspark_builder.cppnew file mode 100644index 00000000000..af49bd74d84--- /dev/null+++ b/src/frontends/gguf/src/builder/arch/dspark_builder.cpp@@ -0,0 +1,163 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "builder/arch/dspark_builder.hpp"++#include <cmath>+#include <limits>++#include "builder/api/metadata_store.hpp"+#include "builder/blocks/attention.hpp"+#include "builder/blocks/common.hpp"+#include "builder/blocks/ffn.hpp"+#include "builder/decoder_config.hpp"++namespace ov::frontend::gguf {+namespace {+class DSparkBuilder : public ModelBuilder {+public:+ explicit DSparkBuilder(const BuildContext& context)+ : m_metadata(context.metadata),+ m_config(decoder_config_from_meta(detail::MetadataAccess::get(context.metadata).map),+ context.weights->weights,+ RopeMode::Neox),+ m_emitter(context.weights->weights, context.weights->qtypes, context.arch, context.weights->translators) {}++ std::shared_ptr<GgufGraph> build() override {+ using ov::element::f32;+ using ov::element::i32;+ const auto required_int = [&](const std::string& name) {+ const auto value = m_metadata.get_int("dspark.dspark." + name);+ OPENVINO_ASSERT(value && *value > 0, "[GGUF] invalid DSpark ", name);+ return *value;+ };+ const auto block = required_int("block_size");+ OPENVINO_ASSERT(block <= 4096, "[GGUF] DSpark block_size exceeds the supported maximum of 4096");+ const auto markov_rank = m_metadata.get_int("dspark.dspark.markov_rank").value_or(0);+ const bool confidence_head = m_metadata.get_bool("dspark.dspark.confidence_head").value_or(false);+ const bool confidence_with_markov =+ m_metadata.get_bool("dspark.dspark.confidence_head_with_markov").value_or(false);+ OPENVINO_ASSERT(!confidence_head || !confidence_with_markov || markov_rank > 0,+ "[GGUF] DSpark confidence_head_with_markov requires a positive markov_rank");+ const auto captures = m_metadata.get_int_array("dspark.dspark.target_layers");+ OPENVINO_ASSERT(!captures.empty(), "[GGUF] missing DSpark target_layers");+ OPENVINO_ASSERT(!m_metadata.get_bool("dspark.dspark.hidden_correction").value_or(false),+ "[GGUF] DSpark hidden correction is not supported");+ auto& e = m_emitter;+ auto& graph = *e.graph();+ graph.has_rope = true;+ graph.rope_config = m_config.rope_config;+ const auto kv = blocks::KvCachePlan::build(m_config);+ e.add_input("inp_tokens", i32, ps({1, 1, 1, block}));+ e.add_input("inp_pos", i32, ps({1, 1, 1, -1}));+ e.add_input("self_kq_mask", f32, ps({1, 1, -1, -1}));+ e.add_input("inp_kv_idx", i32, ps({1, 1, 1, -1}));+ e.add_input("token_len_per_seq", ov::element::i64, ps({1}));+ e.add_input("dspark_ctx_feat", f32, ps({1, 1, -1, static_cast<int64_t>(captures.size()) * m_config.n_embd}));+ e.add_weight("dspark.fc.weight");+ auto context = e.add_op("GGML_OP_MUL_MAT", "dspark.fc", {"dspark.fc.weight", "dspark_ctx_feat"});+ context = blocks::rms_norm(e, context, "dspark.hidden_norm.weight", "dspark.hidden_norm", m_config.rms_eps);+ e.add_weight("token_embd.weight");+ auto current = e.add_op("GGML_OP_GET_ROWS", "dspark.embedding", {"token_embd.weight", "inp_tokens"});+ if (m_metadata.get_bool("dspark.dspark.log_snr_conditioning").value_or(false)) {+ const auto low = m_metadata.get_float("dspark.dspark.min_log_snr");+ const auto high = m_metadata.get_float("dspark.dspark.max_log_snr");+ OPENVINO_ASSERT(low && high && std::isfinite(*low) && std::isfinite(*high) && *high > *low,+ "[GGUF] invalid DSpark log-SNR bounds");+ constexpr size_t feature_width = 128;+ const auto rows = static_cast<size_t>(block);+ OPENVINO_ASSERT(rows <= std::numeric_limits<size_t>::max() / feature_width / sizeof(float),+ "[GGUF] DSpark log-SNR feature byte count overflows size_t");+ ov::Tensor features(f32, {1, 1, rows, feature_width});+ for (size_t pos = 0; pos < rows; ++pos) {+ // Endpoint normalization maps max/min log-SNR to 1000/0 in Prism's inference schedule.+ const float normalized_time = pos == 0 ? 1000.f : 0.f;+ for (size_t i = 0; i < feature_width / 2; ++i) {+ const float angle = normalized_time * std::exp(-std::log(10000.f) * i / 64.f);+ features.data<float>()[pos * feature_width + i] = std::sin(angle);+ features.data<float>()[pos * feature_width + feature_width / 2 + i] = std::cos(angle);+ }+ }+ e.weights()["dspark.log_snr_features"] = features;+ e.add_named_weight("dspark.log_snr_features");+ auto snr = std::string("dspark.log_snr_features");+ for (int layer = 1; layer <= 2; ++layer) {+ const auto name = "dspark.log_snr_fc" + std::to_string(layer);+ e.add_weight(name + ".weight");+ snr = e.add_op("GGML_OP_MUL_MAT", name, {name + ".weight", snr});+ snr = blocks::add_bias(e, snr, name + ".bias", name + ".biased");+ if (layer == 1)+ snr = e.add_op("GGML_UNARY_OP_SILU", name + ".silu", {snr});+ }+ current = e.add_op("GGML_OP_ADD", "dspark.conditioned", {current, snr});+ }+ if (e.has_weight("dspark.mode_embedding.bias"))+ current = blocks::add_bias(e, current, "dspark.mode_embedding.bias", "dspark.mode");+ for (int layer = 0; layer < m_config.n_layer; ++layer) {+ const auto p = "blk." + std::to_string(layer) + ".";+ auto normalized = blocks::rms_norm(e, current, p + "attn_norm.weight", p + "norm", m_config.rms_eps);+ auto joined = e.add_op("GGML_OP_CONCAT", p + "context", {context, normalized}, 0, {{"concat_axis", 1}});+ auto attention = blocks::attention(e, m_config, kv, layer, joined);+ attention = e.add_op("GGML_OP_VIEW",+ p + "draft",+ {attention},+ 3,+ {{"view_slice", std::vector<int64_t>{2, -block, block}}});+ current = e.add_op("GGML_OP_ADD", p + "attn_residual", {current, attention});+ normalized = blocks::rms_norm(e, current, p + "ffn_norm.weight", p + "ffn_norm", m_config.rms_eps);+ const auto ffn = blocks::dense_ffn(e, m_config, p, normalized);+ current = e.add_op("GGML_OP_ADD", p + "ffn_residual", {current, ffn});+ }+ const auto hidden = current;+ current = blocks::rms_norm(e, current, "output_norm.weight", "result_norm", m_config.rms_eps);+ const auto output = e.has_weight("output.weight") ? "output.weight" : "token_embd.weight";+ e.add_weight(output);+ const auto logits = e.add_op("GGML_OP_MUL_MAT", "logits", {output, current});+ auto logits_value = e.value(logits);+ logits_value.set_names({"logits"});+ auto hidden_value = e.value(hidden);+ hidden_value.set_names({"dspark.hidden"});+ graph.model_output_names.insert(graph.model_output_names.begin(), {logits, hidden});+ std::string latent;+ if (markov_rank > 0) {+ e.add_input("dspark_prev_tokens", i32, ps({1, 1, 1, block}));+ e.add_weight("dspark.markov_head_a.weight");+ e.add_weight("dspark.markov_head_b.weight");+ latent = e.add_op("GGML_OP_GET_ROWS",+ "dspark.markov_latent",+ {"dspark.markov_head_a.weight", "dspark_prev_tokens"});+ const auto adjustment =+ e.add_op("GGML_OP_MUL_MAT", "dspark.markov_logits", {"dspark.markov_head_b.weight", latent});+ const auto corrected = e.add_op("GGML_OP_ADD", "dspark.corrected_logits", {logits, adjustment});+ auto corrected_value = e.value(corrected);+ corrected_value.set_names({"dspark.corrected_logits"});+ graph.model_output_names.push_back(corrected);+ }+ if (confidence_head) {+ auto features = hidden;+ if (confidence_with_markov)+ features =+ e.add_op("GGML_OP_CONCAT", "dspark.confidence_features", {hidden, latent}, 0, {{"concat_axis", 0}});+ e.add_weight("dspark.confidence_head.weight");+ auto confidence =+ e.add_op("GGML_OP_MUL_MAT", "dspark.confidence", {"dspark.confidence_head.weight", features});+ confidence = blocks::add_bias(e, confidence, "dspark.confidence_head.bias", "dspark.confidence_score");+ auto confidence_value = e.value(confidence);+ confidence_value.set_names({"dspark.confidence_score"});+ graph.model_output_names.push_back(confidence);+ }+ return e.graph();+ }++private:+ GgufMetadata m_metadata;+ DecoderConfig m_config;+ GraphEmitter m_emitter;+};+} // namespace++std::shared_ptr<ModelBuilder> make_dspark_builder(const BuildContext& context) {+ return std::make_shared<DSparkBuilder>(context);+}+} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/builder/arch/dspark_builder.hpp b/src/frontends/gguf/src/builder/arch/dspark_builder.hppnew file mode 100644index 00000000000..c8df9673cb2--- /dev/null+++ b/src/frontends/gguf/src/builder/arch/dspark_builder.hpp@@ -0,0 +1,10 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+#pragma once++#include "openvino/frontend/gguf/builder/model_builder.hpp"++namespace ov::frontend::gguf {+std::shared_ptr<ModelBuilder> make_dspark_builder(const BuildContext& context);+} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/builder/arch_registry.cpp b/src/frontends/gguf/src/builder/arch_registry.cppindex 6a1d70462f0..73f8f2c5d8c 100644--- a/src/frontends/gguf/src/builder/arch_registry.cpp+++ b/src/frontends/gguf/src/builder/arch_registry.cpp@@ -7,6 +7,7 @@#include <optional>#include <utility>+#include "builder/arch/dspark_builder.hpp"#include "builder/arch/mamba_builder.hpp"#include "builder/arch/mmproj_builder.hpp"#include "openvino/core/except.hpp"@@ -42,6 +43,7 @@ const ArchitectureEntry architectures[] = {},"clip.mmproj"},{"deepseek2-ocr", RopeMode::Neox},+ {"dspark", make_dspark_builder},{"ernie4_5-moe", RopeMode::Normal},{"exaone-moe", RopeMode::Neox},{"exaone4", RopeMode::Neox},diff --git a/src/frontends/gguf/src/builder/blocks/gated_delta_net.cpp b/src/frontends/gguf/src/builder/blocks/gated_delta_net.cppindex 9f86190568e..7130de7285d 100644--- a/src/frontends/gguf/src/builder/blocks/gated_delta_net.cpp+++ b/src/frontends/gguf/src/builder/blocks/gated_delta_net.cpp@@ -132,7 +132,7 @@ std::string gated_delta_net(GraphEmitter& e, const DecoderConfig& cfg, int il, cstd::string alpha_base = p + "ssm_alpha", beta_base = p + "ssm_beta";std::string conv_w = p + "ssm_conv1d.weight", a_w = p + "ssm_a", dt_w = p + "ssm_dt.bias";bool gqa_grouped = false;- if (H_v != H_k && H_v % H_k == 0) {+ if (!e.has_hadamard() && H_v != H_k && H_v % H_k == 0) {const int64_t rep = H_v / H_k;std::vector<int64_t> src(H_v);for (int64_t n = 0; n < H_v; ++n) {@@ -192,8 +192,9 @@ std::string gated_delta_net(GraphEmitter& e, const DecoderConfig& cfg, int il, ce.weight_parts(alpha_base),e.weight_qtype(beta_base),e.weight_qtype(alpha_base));- auto zba = ba ? concat_rows(e.weight_parts(gate_base), *ba, e.weight_qtype(gate_base), e.weight_qtype(beta_base))- : std::nullopt;+ auto zba = ba && !e.has_hadamard()+ ? concat_rows(e.weight_parts(gate_base), *ba, e.weight_qtype(gate_base), e.weight_qtype(beta_base))+ : std::nullopt;if (zba) {store_parts(e, p + "ssm_z_beta_alpha", *zba, e.weight_qtype(gate_base));e.add_weight(p + "ssm_z_beta_alpha.weight");diff --git a/src/frontends/gguf/src/builder/blocks/qkv_repack.cpp b/src/frontends/gguf/src/builder/blocks/qkv_repack.cppindex 6a1ee448d62..42bad3dd201 100644--- a/src/frontends/gguf/src/builder/blocks/qkv_repack.cpp+++ b/src/frontends/gguf/src/builder/blocks/qkv_repack.cpp@@ -17,6 +17,7 @@ void register_fused_qkv(GraphEmitter& e, const DecoderConfig& cfg, int il) {auto parts = split_fused_qkv_extracted(p + "attn_qkv", e.weights(), e.qtypes(), n_q, n_kv, n_kv);const std::array<std::string, 3> names = {p + "attn_q.weight", p + "attn_k.weight", p + "attn_v.weight"};for (size_t i = 0; i < 3; ++i) {+ e.inherit_hadamard(names[i], p + "attn_qkv.weight");e.emit_weight_op(names[i], parts[i].tensors, parts[i].qtype);}@@ -37,6 +38,7 @@ void register_qwen35_q_gate(GraphEmitter& e, const DecoderConfig& cfg, int 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);}}diff --git a/src/frontends/gguf/src/builder/graph_emitter.cpp b/src/frontends/gguf/src/builder/graph_emitter.cppindex 7d2878ac115..ab9d6a7a4a8 100644--- a/src/frontends/gguf/src/builder/graph_emitter.cpp+++ b/src/frontends/gguf/src/builder/graph_emitter.cpp@@ -4,6 +4,8 @@#include "graph_emitter.hpp"+#include <algorithm>+#include "gguf_builder_decoder.hpp"#include "op_table.hpp"#include "openvino/core/except.hpp"@@ -14,6 +16,15 @@ namespace ov::frontend::gguf {namespace {+template <typename T>+const T& required_metadata(const std::map<std::string, GGUFMetaData>& config, const std::string& key) {+ const auto entry = config.find(key);+ OPENVINO_ASSERT(entry != config.end(), "[GGUF] missing ", key);+ const auto* value = std::get_if<T>(&entry->second);+ OPENVINO_ASSERT(value, "[GGUF] invalid type for ", key);+ return *value;+}+WeightTensors find_weight_tensors(const std::unordered_map<std::string, ov::Tensor>& weights, const std::string& base) {WeightTensors tensors;if (auto it = weights.find(base + ".weight"); it != weights.end()) {@@ -79,6 +90,23 @@ std::string GraphEmitter::add_op(const std::string& op_type,int op_case,std::map<std::string, ov::Any> attrs,std::vector<std::string> extra_outputs) {+ if (!inputs.empty() && ((op_type == "GGML_OP_MUL_MAT" && m_hadamard_weights.count(inputs[0])) ||+ (op_type == "GGML_OP_GET_ROWS" && m_hadamard_inverse_weights.count(inputs[0])))) {+ m_hadamard_consumed.insert(inputs[0]);+ const auto width = value(inputs[0]).get_partial_shape().rbegin()->get_length();+ attrs["hadamard_block"] = m_hadamard_block;+ attrs["hadamard_inverse"] = op_type == "GGML_OP_GET_ROWS";+ if (!m_hadamard_signs.empty()) {+ OPENVINO_ASSERT(m_hadamard_signs.count(width), "[GGUF] missing Hadamard signs for width ", width);+ attrs["hadamard_signs"] = m_hadamard_signs.at(width);+ }+ if (op_type == "GGML_OP_MUL_MAT" && m_hadamard_v_heads && inputs[0].find(".ssm_out.") != std::string::npos) {+ OPENVINO_ASSERT(width % m_hadamard_v_heads == 0, "[GGUF] invalid Hadamard GDN width");+ attrs["hadamard_gdn_heads"] = std::vector<int64_t>{m_hadamard_v_heads / m_hadamard_k_heads,+ m_hadamard_k_heads,+ width / m_hadamard_v_heads};+ }+ }GgufOp op;op.op_type = op_type;op.name = name;@@ -96,6 +124,122 @@ std::string GraphEmitter::add_op(const std::string& op_type,return name;}+void GraphEmitter::inherit_hadamard(const std::string& name, const std::string& source) {+ if (m_hadamard_weights.count(source)) {+ m_hadamard_weights.insert(name);+ m_hadamard_consumed.insert(source);+ }+}++void GraphEmitter::validate_hadamard() const {+ for (const auto& names : {m_hadamard_weights, m_hadamard_inverse_weights})+ for (const auto& name : names)+ OPENVINO_ASSERT(m_hadamard_consumed.count(name), "[GGUF] unused Hadamard weight: ", name);+}++void GraphEmitter::configure_hadamard(const std::map<std::string, GGUFMetaData>& config) {+ const std::string prefix = "prism.hadamard.";+ if (!config.count(prefix + "version")) {+ OPENVINO_ASSERT(std::none_of(config.begin(),+ config.end(),+ [&](const auto& entry) {+ return entry.first.compare(0, prefix.size(), prefix) == 0;+ }),+ "[GGUF] missing prism.hadamard.version");+ return;+ }+ const auto scalar = [&](const std::string& key) {+ const auto& t = required_metadata<ov::Tensor>(config, key);+ OPENVINO_ASSERT(t.get_element_type() == ov::element::u32 && t.get_size() == 1, "[GGUF] invalid ", key);+ return *t.data<const uint32_t>();+ };+ const auto flag = [&](const std::string& key) {+ if (!config.count(key))+ return false;+ const auto& t = required_metadata<ov::Tensor>(config, key);+ OPENVINO_ASSERT(t.get_element_type() == ov::element::boolean && t.get_size() == 1, "[GGUF] invalid ", key);+ return *t.data<const char>() != 0;+ };+ const auto version = scalar(prefix + "version");+ const bool tied = flag(prefix + "tied_output");+ OPENVINO_ASSERT((version == 1 || version == 2) && (version == 2) == tied,+ "[GGUF] inconsistent Hadamard version/tied_output");+ m_hadamard_block = scalar(prefix + "block_size");+ OPENVINO_ASSERT(+ m_hadamard_block > 0 && m_hadamard_block <= 4096 && (m_hadamard_block & (m_hadamard_block - 1)) == 0,+ "[GGUF] invalid Hadamard block size");+ OPENVINO_ASSERT(+ required_metadata<std::string>(config, prefix + "transform") == "normalized-sylvester-walsh-hadamard" &&+ required_metadata<std::string>(config, prefix + "axis") == "input-last-dimension",+ "[GGUF] unsupported Hadamard transform/axis");+ const auto& names = required_metadata<std::vector<std::string>>(config, prefix + "weight_names");+ OPENVINO_ASSERT(!names.empty(), "[GGUF] empty Hadamard weight_names");+ for (const auto& name : names) {+ OPENVINO_ASSERT(has_weight(name) && m_hadamard_weights.insert(name).second,+ "[GGUF] missing or duplicate Hadamard weight: ",+ name);+ }+ if (config.count(prefix + "inverse_weight_names")) {+ for (const auto& name : required_metadata<std::vector<std::string>>(config, prefix + "inverse_weight_names")) {+ OPENVINO_ASSERT(name == "token_embd.weight" && has_weight(name) && !m_hadamard_weights.count(name) &&+ m_hadamard_inverse_weights.insert(name).second,+ "[GGUF] invalid Hadamard inverse weight: ",+ name);+ }+ }+ if (tied) {+ OPENVINO_ASSERT(!has_weight("output.weight") && m_hadamard_inverse_weights.count("token_embd.weight"),+ "[GGUF] tied Hadamard output requires a latent embedding and no output.weight");+ m_hadamard_weights.insert("token_embd.weight");+ } else {+ OPENVINO_ASSERT(m_hadamard_inverse_weights.empty() || has_weight("output.weight"),+ "[GGUF] latent tied embedding requires Hadamard version 2");+ }+ const auto& mode = required_metadata<std::string>(config, prefix + "sign_mode");+ OPENVINO_ASSERT(mode == "identity" || mode == "explicit", "[GGUF] unsupported Hadamard sign_mode");+ if (mode == "explicit") {+ const auto& widths = required_metadata<ov::Tensor>(config, prefix + "sign_widths");+ const auto& values = required_metadata<ov::Tensor>(config, prefix + "sign_values");+ OPENVINO_ASSERT(widths.get_element_type() == ov::element::i32 && widths.get_size() > 0,+ "[GGUF] invalid ",+ prefix + "sign_widths");+ OPENVINO_ASSERT(values.get_element_type() == ov::element::i32, "[GGUF] invalid ", prefix + "sign_values");+ size_t offset = 0;+ for (size_t i = 0; i < widths.get_size(); ++i) {+ const int64_t width = widths.data<const int32_t>()[i];+ OPENVINO_ASSERT(width > 0 && width % m_hadamard_block == 0 &&+ static_cast<size_t>(width) <= values.get_size() - offset &&+ !m_hadamard_signs.count(width),+ "[GGUF] invalid Hadamard sign width");+ ov::Tensor signs(ov::element::f32, {static_cast<size_t>(width)});+ for (int64_t j = 0; j < width; ++j) {+ const auto sign = values.data<const int32_t>()[offset++];+ OPENVINO_ASSERT(sign == -1 || sign == 1, "[GGUF] Hadamard signs must be +/-1");+ signs.data<float>()[j] = static_cast<float>(sign);+ }+ m_hadamard_signs.emplace(width, signs);+ }+ OPENVINO_ASSERT(offset == values.get_size(), "[GGUF] Hadamard sign_values length mismatch");+ }+ for (const auto& names : {m_hadamard_weights, m_hadamard_inverse_weights})+ for (const auto& name : names) {+ const auto& shape = weight_tensor(name).get_shape();+ OPENVINO_ASSERT(shape.size() == 2, "[GGUF] Hadamard requires matrix weights: ", name);+ const auto width = shape.back();+ OPENVINO_ASSERT(width > 0 && width % m_hadamard_block == 0 &&+ (m_hadamard_signs.empty() || m_hadamard_signs.count(width)),+ "[GGUF] invalid Hadamard width for ",+ name);+ }+ if (flag(prefix + "gdn_v_grouped")) {+ m_hadamard_v_heads = required_metadata<int>(config, "ssm_time_step_rank");+ m_hadamard_k_heads = required_metadata<int>(config, "ssm_group_count");+ OPENVINO_ASSERT(+ m_hadamard_k_heads > 0 && m_hadamard_v_heads > 0 && m_hadamard_v_heads % m_hadamard_k_heads == 0,+ "[GGUF] invalid Hadamard GDN heads");+ }+}+std::shared_ptr<ov::op::v0::Parameter> GraphEmitter::add_input(const std::string& name,ov::element::Type type,const ov::PartialShape& shape) {diff --git a/src/frontends/gguf/src/builder/graph_emitter.hpp b/src/frontends/gguf/src/builder/graph_emitter.hppindex 75680710f03..93dfc823326 100644--- a/src/frontends/gguf/src/builder/graph_emitter.hpp+++ b/src/frontends/gguf/src/builder/graph_emitter.hpp@@ -113,6 +113,13 @@ public:return m_emitted_weights.count(name) > 0;}+ void configure_hadamard(const std::map<std::string, GGUFMetaData>& config);+ void validate_hadamard() const;+ bool has_hadamard() const {+ return m_hadamard_block != 0;+ }+ void inherit_hadamard(const std::string& name, const std::string& source);+private:std::unordered_map<std::string, ov::Tensor>& m_weights;std::unordered_map<std::string, GgufTensorType>& m_qtypes;@@ -124,6 +131,13 @@ private:// 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.std::set<std::string> m_emitted_weights;+ int64_t m_hadamard_block = 0;+ int64_t m_hadamard_v_heads = 0;+ int64_t m_hadamard_k_heads = 0;+ std::set<std::string> m_hadamard_weights;+ std::set<std::string> m_hadamard_inverse_weights;+ std::set<std::string> m_hadamard_consumed;+ std::map<int64_t, ov::Tensor> m_hadamard_signs;};// Shapes are kept in the OpenVINO/GGML logical order [ne3, ne2, ne1, ne0] (reverse of GGUFdiff --git a/src/frontends/gguf/src/op/get_rows.cpp b/src/frontends/gguf/src/op/get_rows.cppindex 6c9a2a03627..081d80a8493 100644--- a/src/frontends/gguf/src/op/get_rows.cpp+++ b/src/frontends/gguf/src/op/get_rows.cpp@@ -117,6 +117,7 @@ OutputVector translate_get_rows(const NodeContext& context) {// The two Squeezes above dropped the leading axes; restore ggml's rank-4 form.res = std::make_shared<ov::op::v0::Unsqueeze>(res, ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));+ res = apply_hadamard(context, res);return rename_outputs_with_suffix({convert_rows(res)}, context.get_name());}diff --git a/src/frontends/gguf/src/op/mulmat.cpp b/src/frontends/gguf/src/op/mulmat.cppindex c123e14747d..8e68cc6e101 100644--- a/src/frontends/gguf/src/op/mulmat.cpp+++ b/src/frontends/gguf/src/op/mulmat.cpp@@ -33,6 +33,7 @@ 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);bool transpose_b = true;if (op_case == 2) {diff --git a/src/frontends/gguf/src/pass/adapt_to_genai.cpp b/src/frontends/gguf/src/pass/adapt_to_genai.cppindex 8dde1593df4..601ddb97966 100644--- a/src/frontends/gguf/src/pass/adapt_to_genai.cpp+++ b/src/frontends/gguf/src/pass/adapt_to_genai.cpp@@ -232,6 +232,9 @@ ov::Output<ov::Node> pad_media_placeholders(const ov::Model& model, const ov::Oubool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {using namespace ov::op;+ if (find_parameter(model, "dspark_ctx_feat"))+ return false;+for (const auto& output : model->outputs()) {if (output.get_names().count("embeddings"))return false;diff --git a/src/frontends/gguf/src/quant/gguf.cpp b/src/frontends/gguf/src/quant/gguf.cppindex 971497aa560..e2fcaae6035 100644--- a/src/frontends/gguf/src/quant/gguf.cpp+++ b/src/frontends/gguf/src/quant/gguf.cpp@@ -9,6 +9,7 @@#include "gguf.hpp"+#include <algorithm>#include <array>#include <cmath>#include <cstdint>@@ -66,6 +67,10 @@ TypeTraits type_traits(uint32_t type) {return {256, 84};case GGUF_TYPE_Q2_0:return {64, 18}; // f16 scale + 64x 2-bit codes (16 bytes)+ case GGUF_TYPE_PQ2_0:+ return {128, 34};+ case GGUF_TYPE_PTQ1_0:+ return {128, 28};case GGUF_TYPE_Q3_K:return {256, 110};case GGUF_TYPE_Q4_K:@@ -112,7 +117,7 @@ std::optional<QuantLayout> quant_layout(uint32_t type) {case GGUF_TYPE_Q4_0:return QuantLayout{ov::element::i4, 1, ov::element::f16, 32, symmetric};case GGUF_TYPE_Q1_0:- return QuantLayout{ov::element::i4, 1, ov::element::f16, 128, symmetric};+ return QuantLayout{ov::element::u1, 1, ov::element::f16, 128, symmetric};case GGUF_TYPE_Q3_K:return QuantLayout{ov::element::i4, 1, ov::element::f16, 16, symmetric};case GGUF_TYPE_Q5_0:@@ -127,6 +132,9 @@ std::optional<QuantLayout> quant_layout(uint32_t type) {return QuantLayout{ov::element::u2, 1, ov::element::f16, 16, asymmetric};case GGUF_TYPE_Q2_0:return QuantLayout{ov::element::u2, 1, ov::element::f16, 64, asymmetric};+ case GGUF_TYPE_PQ2_0:+ case GGUF_TYPE_PTQ1_0:+ return QuantLayout{ov::element::u2, 1, ov::element::f16, 128, asymmetric};case GGUF_TYPE_Q4_1:case GGUF_TYPE_Q4_K:return QuantLayout{ov::element::u32, 8, ov::element::f16, 32, asymmetric};@@ -495,6 +503,56 @@ GGUFLoad get_gguf_data(const std::string& file) {// Tensor data starts at the next `alignment`-aligned offset after the info section.uint64_t data_off = cur.offset() + ov::util::align_padding_size(alignment, cur.offset());+ // Older Prism files used the upstream Q2_0 id for group-128 payloads.+ std::vector<uint64_t> offsets;+ for (const auto& ti : infos)+ offsets.push_back(ti.offset);+ std::sort(offsets.begin(), offsets.end());+ OPENVINO_ASSERT(data_off <= fsize && (offsets.empty() || offsets.back() <= fsize - data_off),+ "[load_gguf] tensor offset runs past EOF");+ std::vector<TensorInfo*> ambiguous_q2;+ bool legacy_g128 = false;+ for (auto& ti : infos) {+ if (ti.type != GGUF_TYPE_Q2_0 || ti.dim[0] == 0)+ continue;+ const auto next = std::upper_bound(offsets.begin(), offsets.end(), ti.offset);+ OPENVINO_ASSERT(data_off <= fsize && ti.offset <= fsize - data_off,+ "[load_gguf] tensor '",+ ti.name,+ "' offset runs past EOF");+ const auto span = (next == offsets.end() ? fsize - data_off : *next) - ti.offset;+ const auto size_for = [&](uint32_t type) {+ const auto traits = type_traits(type);+ uint64_t blocks = ti.dim[0] / traits.items_per_block;+ for (uint32_t d = 1; d < ti.ndim; ++d) {+ OPENVINO_ASSERT(ti.dim[d] == 0 || blocks <= std::numeric_limits<uint64_t>::max() / ti.dim[d],+ "[load_gguf] tensor '",+ ti.name,+ "' byte count overflows");+ blocks *= ti.dim[d];+ }+ OPENVINO_ASSERT(blocks <= std::numeric_limits<uint64_t>::max() / traits.bytes_per_block,+ "[load_gguf] tensor '",+ ti.name,+ "' byte count overflows");+ const auto bytes = blocks * traits.bytes_per_block;+ return bytes <= span && (bytes == span || ov::util::align_padding_size(alignment, bytes) == span - bytes);+ };+ const bool g64 = ti.dim[0] % 64 == 0 && size_for(GGUF_TYPE_Q2_0);+ const bool g128 = ti.dim[0] % 128 == 0 && size_for(GGUF_TYPE_PQ2_0);+ OPENVINO_ASSERT(g64 || g128, "[load_gguf] tensor '", ti.name, "' has invalid Q2_0 packing");+ if (g64 && g128) {+ ambiguous_q2.push_back(&ti);+ } else if (g128) {+ ti.type = GGUF_TYPE_PQ2_0;+ legacy_g128 = true;+ }+ }+ if (legacy_g128) {+ for (auto* ti : ambiguous_q2)+ ti->type = GGUF_TYPE_PQ2_0;+ }+// Validate file-controlled shapes before allocating repacked tensors.auto quant_sizes = [](const TensorInfo& ti, const QuantLayout& ql) -> std::array<size_t, 3> {const ov::Shape shape = [&ti]() {@@ -601,7 +659,7 @@ GGUFLoad get_gguf_data(const std::string& file) {if (ti.type == GGUF_TYPE_MXFP4) {gguf_fill_mxfp4(tensor, weights, scales);- } else if (ti.type == GGUF_TYPE_Q2_0) {+ } else if (ti.type == GGUF_TYPE_Q2_0 || ti.type == GGUF_TYPE_PQ2_0 || ti.type == GGUF_TYPE_PTQ1_0) {gguf_fill_q2_0(tensor, weights, scales, zp);} else if (layout->asymmetric) {gguf_fill_asym(tensor, weights, scales, zp);@@ -869,6 +927,10 @@ std::map<std::string, GGUFMetaData> decoder_config_from_meta(// 0.0 means no soft-cap.config["final_logit_softcapping"] = metadata_to_float_or(metadata, arch + ".final_logit_softcapping", 0.0f);+ for (const auto& [key, value] : metadata) {+ if (key.compare(0, 15, "prism.hadamard.") == 0)+ config[key] = value;+ }return config;}diff --git a/src/frontends/gguf/src/quant/gguf.hpp b/src/frontends/gguf/src/quant/gguf.hppindex 5786e1247ca..b502a989378 100644--- a/src/frontends/gguf/src/quant/gguf.hpp+++ b/src/frontends/gguf/src/quant/gguf.hpp@@ -43,6 +43,8 @@ enum GgufTensorType {GGUF_TYPE_MXFP4 = 39, // 4-bit microscaling (gpt-oss): 1-byte E8M0 scale + 32x E2M1GGUF_TYPE_Q1_0 = 41, // binary: f16 scale + 128x 1-bit codes, value = bit ? +scale : -scaleGGUF_TYPE_Q2_0 = 42, // ternary: f16 scale + 64x 2-bit codes, value = (code - 1) * scale+ GGUF_TYPE_PQ2_0 = 142,+ GGUF_TYPE_PTQ1_0 = 143,GGUF_TYPE_COUNT,};@@ -92,8 +94,8 @@ using GGUFLoad = std::tuple<std::unordered_map<std::string, GGUFMetaData>,std::shared_ptr<ov::MappedMemory>>;// Fill pre-allocated weights and f16 scales from a symmetric GGUF tensor-// (Q8_0/Q5_0/Q6_K: i8 weights; Q4_0/Q3_K: i4 weights packed as u8).-// No zero-point: the center value is subtracted during unpacking so weights are centered at 0.+// (Q8_0/Q5_0/Q6_K: i8 weights; Q4_0/Q3_K: i4 weights; Q1_0: u1 weights).+// Integer weights are centered during unpacking; Q1_0 keeps binary codes and applies 2 * bit - 1 in the graph.void gguf_fill_sym(const GgufTensor& tensor, ov::Tensor& weights, ov::Tensor& scales);// Fill pre-allocated weights, f16 scales, and integer zero-points from an asymmetric GGUFdiff --git a/src/frontends/gguf/src/quant/gguf_quants.cpp b/src/frontends/gguf/src/quant/gguf_quants.cppindex 3649ecc2300..e8f2e864105 100644--- a/src/frontends/gguf/src/quant/gguf_quants.cpp+++ b/src/frontends/gguf/src/quant/gguf_quants.cpp@@ -805,13 +805,10 @@ static void fill_q4_0(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Ten});}-// Q1_0 block: 18 bytes = f16 scale d + 128 packed 1-bit codes (bit ? +d : -d).-// We re-expand each bit to an i4 nibble (0 -> 0xF, 1 -> 0x1), packed two-per-byte-// low-nibble-first - same layout OpenVINO already uses for Q4_0.-// So Q1_0 reuses the existing SYMMETRIC_I4 path unchanged.+// GGML binary codes are LSB-first; OpenVINO u1 codes are MSB-first.static void fill_q1_0(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr) {const uint64_t bytes_per_block = 18;- const uint64_t out_bytes_per_block = 64; // 128 elements as i4, 2 per byte+ const uint64_t out_bytes_per_block = 16;auto data = static_cast<const uint8_t*>(tensor.weights_data);auto weights = static_cast<uint8_t*>(weights_arr.data());auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();@@ -823,12 +820,11 @@ static void fill_q1_0(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tenscales[i] = ov::float16::from_bits(scale_bits);const uint8_t* qs = block + 2;uint8_t* out = weights + i * out_bytes_per_block;- for (int j = 0; j < 128; j += 2) {- const int bit0 = (qs[j / 8] >> (j % 8)) & 1;- const int bit1 = (qs[(j + 1) / 8] >> ((j + 1) % 8)) & 1;- const uint8_t nib0 = bit0 ? 0x1 : 0xF;- const uint8_t nib1 = bit1 ? 0x1 : 0xF;- out[j / 2] = static_cast<uint8_t>(nib0 | (nib1 << 4));+ for (size_t j = 0; j < out_bytes_per_block; ++j) {+ uint8_t bits = qs[j];+ bits = ((bits & 0x55) << 1) | ((bits & 0xaa) >> 1);+ bits = ((bits & 0x33) << 2) | ((bits & 0xcc) >> 2);+ out[j] = (bits << 4) | (bits >> 4);}});}@@ -856,8 +852,9 @@ void fill_q8_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& sc// (dequantize_row_q2_0: `(qs[j/4] >> ((j%4)*2)) & 3`), which is exactly the order OpenVINO's u2// Constant reads, so the 16 code bytes are copied verbatim. The zero-point is the constant 1.void gguf_fill_q2_0(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr, ov::Tensor& zp_arr) {- const uint64_t bytes_per_block = 18;- const uint64_t bytes_per_block_codes = 16;+ const bool dense_trits = tensor.type == GGUF_TYPE_PTQ1_0;+ const uint64_t bytes_per_block_codes = tensor.type == GGUF_TYPE_Q2_0 ? 16 : 32;+ const uint64_t bytes_per_block = dense_trits ? 28 : bytes_per_block_codes + 2;auto data = static_cast<const uint8_t*>(tensor.weights_data);auto weights = static_cast<uint8_t*>(weights_arr.data());auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();@@ -866,9 +863,29 @@ void gguf_fill_q2_0(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensoov::parallel_for(scales_arr.get_size(), [&](size_t i) {const uint8_t* block = data + i * bytes_per_block;uint16_t scale_bits;- std::memcpy(&scale_bits, block, sizeof(scale_bits));+ std::memcpy(&scale_bits, block + (dense_trits ? 26 : 0), sizeof(scale_bits));scales[i] = ov::float16::from_bits(scale_bits);- std::memcpy(weights + i * bytes_per_block_codes, block + 2, bytes_per_block_codes);+ auto* codes = weights + i * bytes_per_block_codes;+ if (dense_trits) {+ std::memset(codes, 0, bytes_per_block_codes);+ constexpr uint8_t powers[] = {1, 3, 9, 27, 81};+ size_t index = 0;+ const auto unpack = [&](size_t start, size_t count, size_t trits) {+ for (size_t n = 0; n < trits; ++n) {+ for (size_t m = 0; m < count; ++m) {+ const uint8_t q = block[start + m] * powers[n];+ const uint8_t code = (static_cast<uint16_t>(q) * 3) >> 8;+ codes[index / 4] |= code << (2 * (index % 4));+ ++index;+ }+ }+ };+ unpack(0, 16, 5);+ unpack(16, 8, 5);+ unpack(24, 2, 4);+ } else {+ std::memcpy(codes, block + 2, bytes_per_block_codes);+ }zp.store(i, 1.0f);});}diff --git a/src/frontends/gguf/src/quant/weights.cpp b/src/frontends/gguf/src/quant/weights.cppindex c8adfe65712..95d0968a889 100644--- a/src/frontends/gguf/src/quant/weights.cpp+++ b/src/frontends/gguf/src/quant/weights.cpp@@ -66,7 +66,7 @@ WeightFormat get_weight_format(GgufTensorType qtype) {case GGUF_TYPE_MXFP4:return {FillKind::MXFP4, 32, ov::element::f4e2m1};case GGUF_TYPE_Q1_0:- return {FillKind::SYMMETRIC, 128, ov::element::i4};+ return {FillKind::SYMMETRIC, 128, ov::element::u1};case GGUF_TYPE_Q4_0:return {FillKind::SYMMETRIC, 32, ov::element::i4};case GGUF_TYPE_Q3_K:@@ -82,6 +82,9 @@ WeightFormat get_weight_format(GgufTensorType qtype) {return {FillKind::ASYMMETRIC, 16, ov::element::u2};case GGUF_TYPE_Q2_0:return {FillKind::Q2_0, 64, ov::element::u2};+ case GGUF_TYPE_PQ2_0:+ case GGUF_TYPE_PTQ1_0:+ return {FillKind::Q2_0, 128, ov::element::u2};case GGUF_TYPE_Q4_1:case GGUF_TYPE_Q4_K:return {FillKind::ASYMMETRIC, 32, ov::element::u32};@@ -191,6 +194,16 @@ std::shared_ptr<ov::Node> make_compressed(const WeightTensors& tensors, ov::elemauto final_shape_node =std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{orig_shape.size()}, orig_shape);+ if (et == ov::element::u1) {+ const auto precision = tensors.scales.get_element_type();+ auto bits = std::make_shared<ov::op::v0::Convert>(weights_node, precision);+ auto doubled = std::make_shared<ov::op::v1::Multiply>(bits, ov::op::v0::Constant::create(precision, {}, {2}));+ auto signs = std::make_shared<ov::op::v1::Subtract>(doubled, ov::op::v0::Constant::create(precision, {}, {1}));+ auto scaled = std::make_shared<ov::op::v1::Multiply>(signs, scales_node);+ auto reshaped = std::make_shared<ov::op::v1::Reshape>(scaled, final_shape_node, false);+ return std::make_shared<ov::op::v0::Convert>(reshaped, ov::element::f32);+ }+if (explicit_f32) {ov::Output<ov::Node> values = std::make_shared<ov::op::v0::Convert>(weights_node, ov::element::f32);if (zp_node) {@@ -341,7 +354,7 @@ bool is_embedding_or_output(const std::string& name) {// Decide whether a weight is requantized to Q8_0_C, mirroring llama.cpp's// ggml_openvino_get_requant_type for the CPU/GPU (non-NPU) path.bool needs_q8_0_c_requant(const std::string& name, GgufTensorType qtype) {- return is_embedding_or_output(name) || qtype == GGUF_TYPE_Q5_K;+ return qtype != GGUF_TYPE_Q1_0 && (is_embedding_or_output(name) || qtype == GGUF_TYPE_Q5_K);}// Keep an exact-decode escape hatch for strict validation against ggml's original Q4_K / Q4_1 values.@@ -409,7 +422,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) {+ if (qtype == GGUF_TYPE_Q2_0 || qtype == GGUF_TYPE_PQ2_0 || qtype == GGUF_TYPE_PTQ1_0) {return ov::element::u8;}const bool requantized = qtype == GGUF_TYPE_Q5_K ||@@ -467,7 +480,9 @@ GgufTensorType gguf_type_from_name(const std::string& quant_type) {{"Q8_K", GGUF_TYPE_Q8_K},{"MXFP4", GGUF_TYPE_MXFP4},{"Q1_0", GGUF_TYPE_Q1_0},- {"Q2_0", GGUF_TYPE_Q2_0}};+ {"Q2_0", GGUF_TYPE_Q2_0},+ {"PQ2_0", GGUF_TYPE_PQ2_0},+ {"PTQ1_0", GGUF_TYPE_PTQ1_0}};// Accept ggml's lowercase type names ("q4_0", "q6_K", "f16", ...) as well as the// canonical uppercase form.auto it = names.find(ov::util::to_upper(quant_type));diff --git a/src/frontends/gguf/src/utils.cpp b/src/frontends/gguf/src/utils.cppindex 36f52459603..dbf57810d56 100644--- a/src/frontends/gguf/src/utils.cpp+++ b/src/frontends/gguf/src/utils.cpp@@ -14,8 +14,10 @@#include "openvino/core/model.hpp"#include "openvino/op/add.hpp"#include "openvino/op/clamp.hpp"+#include "openvino/op/concat.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/convert.hpp"+#include "openvino/op/convert_like.hpp"#include "openvino/op/cos.hpp"#include "openvino/op/divide.hpp"#include "openvino/op/gather.hpp"@@ -27,6 +29,7 @@#include "openvino/op/shape_of.hpp"#include "openvino/op/sin.hpp"#include "openvino/op/slice.hpp"+#include "openvino/op/split.hpp"#include "openvino/op/sqrt.hpp"#include "openvino/op/squeeze.hpp"#include "openvino/op/subtract.hpp"@@ -35,6 +38,55 @@namespace ov::frontend::gguf {+ov::Output<ov::Node> apply_hadamard(const NodeContext& context, ov::Output<ov::Node> input) {+ const auto block = context.get_attribute<int64_t>("hadamard_block", 0);+ if (block == 0)+ return input;+ using namespace ov::op;+ const auto shape = input.get_partial_shape();+ FRONT_END_OP_CONVERSION_CHECK(shape.rank().is_static() && shape.size() > 0 && shape[shape.size() - 1].is_static(),+ "Hadamard requires a static feature width");+ const auto width = shape[shape.size() - 1].get_length();+ 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);+ };+ 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", {});+ if (!heads.empty()) {+ FRONT_END_OP_CONVERSION_CHECK(heads.size() == 3 && heads[0] * heads[1] * heads[2] == width,+ "Invalid Hadamard GDN feature order");+ input = std::make_shared<v1::Reshape>(input, pattern({-1, heads[0], heads[1], heads[2]}), false);+ 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)+ 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);+ }+ 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);+ return input;+}+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.hppindex 7d49b037ed8..25337cf7c39 100644--- a/src/frontends/gguf/src/utils.hpp+++ b/src/frontends/gguf/src/utils.hpp@@ -62,6 +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);+/// \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.txtindex 404adc07a60..ada968c59cb 100644--- a/src/frontends/gguf/tests/CMakeLists.txt+++ b/src/frontends/gguf/tests/CMakeLists.txt@@ -45,6 +45,7 @@ set(FRONTEND_SRCS"${FE_SRC_DIR}/builder/api/metadata.cpp""${FE_SRC_DIR}/builder/api/tensor_table.cpp""${FE_SRC_DIR}/builder/arch/decoder_builder.cpp"+ "${FE_SRC_DIR}/builder/arch/dspark_builder.cpp""${FE_SRC_DIR}/builder/arch/mamba_builder.cpp""${FE_SRC_DIR}/builder/arch/mmproj_builder.cpp""${FE_SRC_DIR}/op/multimodal.cpp"diff --git a/src/frontends/gguf/tests/dspark_oracle.cpp b/src/frontends/gguf/tests/dspark_oracle.cppnew file mode 100644index 00000000000..5fffe8cc2bd--- /dev/null+++ b/src/frontends/gguf/tests/dspark_oracle.cpp@@ -0,0 +1,72 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <cmath>+#include <cstdint>+#include <fstream>+#include <vector>++#include "ggml-backend.h"+#include "llama-ext.h"+#include "llama.h"++int main(int argc, char** argv) {+ if (argc != 3)+ return 2;+ llama_backend_init();+ ggml_backend_dev_t devices[] = {ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU), nullptr};+ if (!devices[0])+ return 3;+ auto mp = llama_model_default_params();+ mp.devices = devices;+ mp.n_gpu_layers = 0;+ auto* model = llama_model_load_from_file(argv[1], mp);+ if (!model)+ return 4;+ llama_dspark_meta meta;+ if (!llama_model_dspark_get_meta(model, &meta))+ return 5;+ auto cp = llama_context_default_params();+ cp.n_ctx = cp.n_batch = cp.n_ubatch = 128;+ cp.n_threads = cp.n_threads_batch = 4;+ cp.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_DISABLED;+ auto* ctx = llama_init_from_model(model, cp);+ if (!ctx)+ return 6;+ llama_set_causal_attn(ctx, false);+ std::ofstream out(argv[2], std::ios::binary);+ const int32_t dimensions[] = {static_cast<int32_t>(meta.n_embd_cap),+ meta.block_size,+ static_cast<int32_t>(meta.n_vocab)};+ out.write(reinterpret_cast<const char*>(dimensions), sizeof(dimensions));+ for (int32_t rows : {2, 3}) {+ llama_memory_clear(llama_get_memory(ctx), true);+ std::vector<float> features(rows * meta.n_embd_cap);+ std::vector<int32_t> positions(rows);+ for (size_t i = 0; i < features.size(); ++i)+ features[i] = std::sin(static_cast<float>(i)) * .1f;+ for (int32_t i = 0; i < rows; ++i)+ positions[i] = i;+ llama_set_dspark_ctx(ctx, features.data(), rows, meta.n_embd_cap, positions.data());+ auto batch = llama_batch_init(rows + meta.block_size, 0, 1);+ batch.n_tokens = rows + meta.block_size;+ for (int32_t i = 0; i < batch.n_tokens; ++i) {+ batch.token[i] = i < rows ? 0 : i - rows + 1;+ batch.pos[i] = i;+ batch.n_seq_id[i] = 1;+ batch.seq_id[i][0] = 0;+ batch.logits[i] = i >= rows;+ }+ const auto rc = llama_decode(ctx, batch);+ llama_batch_free(batch);+ if (rc)+ return 7;+ out.write(reinterpret_cast<const char*>(&rows), sizeof(rows));+ out.write(reinterpret_cast<const char*>(llama_get_logits(ctx)), meta.block_size * meta.n_vocab * sizeof(float));+ }+ llama_free(ctx);+ llama_model_free(model);+ llama_backend_free();+ return out ? 0 : 8;+}diff --git a/src/frontends/gguf/tests/gen_arch_accuracy.py b/src/frontends/gguf/tests/gen_arch_accuracy.pyindex f36ce56349d..7de00be3444 100644--- a/src/frontends/gguf/tests/gen_arch_accuracy.py+++ b/src/frontends/gguf/tests/gen_arch_accuracy.py@@ -24,6 +24,7 @@ CASES = {# Real checkpoints quantize attn_gate apart from ssm_beta/ssm_alpha: F16 here selects the# frontend's beta+alpha-only merge, and an F16 beta in layer 2 selects separate projections."qwen35-mixed": {"architecture": "qwen35", "f16": ("attn_gate", "blk.2.ssm_beta")},+ "bonsai2-hadamard": {"architecture": "qwen35", "hadamard": True},"nemotron_h": {},"mamba2": {}, "mamba2-tied": {"architecture": "mamba2", "tied": True},"llama": {},@@ -130,7 +131,7 @@ def write_mamba2_model(path, opts, arch="mamba2"):finish(w)-def write_qwen35_model(path, arch, fused_experts=False, f16=()):+def write_qwen35_model(path, arch, fused_experts=False, f16=(), hadamard=False):w = gguf.GGUFWriter(path, arch)d, head, heads, kv, ff, vocab = 32, 16, 4, 2, 48, 32state, groups, vheads, kernel = 8, 2, 4, 4@@ -153,6 +154,22 @@ def write_qwen35_model(path, arch, fused_experts=False, f16=()):"state_size": state, "conv_kernel": kernel}.items():w.add_uint32(arch + ".ssm." + key, value)w.add_uint32(arch + ".full_attention_interval", 4)+ if hadamard:+ names = ["output.weight"]+ for layer in range(4):+ p = f"blk.{layer}."+ kinds = ("attn_qkv", "attn_gate", "ssm_out") if layer < 3 else ("attn_q", "attn_k", "attn_v", "attn_output")+ names.extend(p + kind + ".weight" for kind in (*kinds, "ffn_gate", "ffn_up", "ffn_down"))+ w.add_uint32("prism.hadamard.version", 1)+ w.add_uint32("prism.hadamard.block_size", 8)+ w.add_string("prism.hadamard.transform", "normalized-sylvester-walsh-hadamard")+ w.add_string("prism.hadamard.axis", "input-last-dimension")+ w.add_string("prism.hadamard.sign_mode", "explicit")+ w.add_array("prism.hadamard.weight_names", names)+ w.add_array("prism.hadamard.inverse_weight_names", ["token_embd.weight"])+ w.add_key_value("prism.hadamard.sign_widths", [32, 48, 64], gguf.GGUFValueType.ARRAY, gguf.GGUFValueType.INT32)+ w.add_key_value("prism.hadamard.sign_values", [(-1 if i % 3 else 1) for i in range(144)], gguf.GGUFValueType.ARRAY, gguf.GGUFValueType.INT32)+ w.add_bool("prism.hadamard.gdn_v_grouped", True)moe = arch == "qwen35moe"if moe:w.add_expert_count(4)@@ -277,7 +294,7 @@ def write_model(path, arch, opts):if arch == "gemma4":return write_gemma4_model(path, opts)if arch in ("qwen35", "qwen35moe"):- return write_qwen35_model(path, arch, opts.get("fused_experts", False), opts.get("f16", ()))+ return write_qwen35_model(path, arch, opts.get("fused_experts", False), opts.get("f16", ()), opts.get("hadamard", False))if arch in ("mamba2", "nemotron_h"):return write_mamba2_model(path, opts, arch)w = gguf.GGUFWriter(path, arch)diff --git a/src/frontends/gguf/tests/gen_dspark_accuracy.py b/src/frontends/gguf/tests/gen_dspark_accuracy.pynew file mode 100644index 00000000000..e80e83dde08--- /dev/null+++ b/src/frontends/gguf/tests/gen_dspark_accuracy.py@@ -0,0 +1,97 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++"""Generate DSpark full-logit fixtures using a CPU-only Prism llama.cpp oracle."""+import argparse+from pathlib import Path+import subprocess+import tempfile++import gguf+import numpy as np++from mmproj_fixtures import finish, save_npz+++def write_model(path):+ rng = np.random.default_rng(1234)+ w = gguf.GGUFWriter(path, "dspark")+ w.add_block_count(2)+ w.add_context_length(128)+ w.add_embedding_length(64)+ w.add_feed_forward_length(96)+ w.add_head_count(2)+ w.add_head_count_kv(1)+ w.add_layer_norm_rms_eps(1e-6)+ w.add_rope_freq_base(10000.0)+ w.add_tokenizer_model("none")+ w.add_vocab_size(256)+ w.add_uint32("dspark.dspark.block_size", 4)+ w.add_uint32("dspark.dspark.mask_token_id", 255)+ w.add_array("dspark.dspark.target_layers", [1, 16])+ w.add_bool("dspark.dspark.log_snr_conditioning", True)+ w.add_float32("dspark.dspark.min_log_snr", -9.0)+ w.add_float32("dspark.dspark.max_log_snr", 9.0)++ def tensor(name, shape, norm=False):+ w.add_tensor(name, np.ones(shape, np.float32) if norm else rng.normal(0, 0.02, shape).astype(np.float32))++ tensor("token_embd.weight", (256, 64))+ tensor("output_norm.weight", (64,), True)+ tensor("dspark.fc.weight", (64, 128))+ tensor("dspark.hidden_norm.weight", (64,), True)+ for layer, width in ((1, 128), (2, 64)):+ tensor(f"dspark.log_snr_fc{layer}.weight", (64, width))+ tensor(f"dspark.log_snr_fc{layer}.bias", (64,))+ for layer in range(2):+ p = f"blk.{layer}."+ tensor(p + "attn_norm.weight", (64,), True)+ for kind, width in (("q", 64), ("k", 32), ("v", 32)):+ tensor(p + f"attn_{kind}.weight", (width, 64))+ tensor(p + "attn_output.weight", (64, 64))+ for kind in ("q", "k"):+ tensor(p + f"attn_{kind}_norm.weight", (32,), True)+ tensor(p + "ffn_norm.weight", (64,), True)+ tensor(p + "ffn_gate.weight", (96, 64))+ tensor(p + "ffn_down.weight", (64, 96))+ tensor(p + "ffn_up.weight", (96, 64))+ w.add_uint32("dspark.dspark.markov_rank", 8)+ w.add_bool("dspark.dspark.confidence_head", True)+ w.add_bool("dspark.dspark.confidence_head_with_markov", True)+ for name, shape in (+ ("dspark.markov_head_a.weight", (256, 8)),+ ("dspark.markov_head_b.weight", (256, 8)),+ ("dspark.confidence_head.weight", (1, 72)),+ ("dspark.confidence_head.bias", (1,)),+ ):+ tensor(name, shape)+ finish(w)+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--oracle", required=True)+ parser.add_argument("--output", type=Path, default=Path(__file__).parent / "test_data/arch_accuracy/dspark.npz")+ args = parser.parse_args()+ with tempfile.TemporaryDirectory() as directory:+ model, reference = Path(directory) / "model.gguf", Path(directory) / "reference.bin"+ write_model(model)+ subprocess.run([args.oracle, str(model), str(reference)], check=True)+ with reference.open("rb") as f:+ width, block, vocab = np.frombuffer(f.read(12), np.int32)+ arrays = {"model": np.frombuffer(model.read_bytes(), np.uint8), "width": np.array([width])}+ reader = gguf.GGUFReader(model)+ for t in reader.tensors:+ if t.name.startswith(("dspark.markov", "dspark.confidence")):+ arrays[t.name] = t.data.copy()+ for rows in (2, 3):+ assert np.frombuffer(f.read(4), np.int32)[0] == rows+ arrays[f"logits_{rows}"] = np.frombuffer(f.read(int(block * vocab * 4)), np.float32).reshape(+ block, vocab+ )+ assert not f.read(1)+ save_npz(args.output, arrays)+++if __name__ == "__main__":+ main()diff --git a/src/frontends/gguf/tests/gen_prism_quant_accuracy.py b/src/frontends/gguf/tests/gen_prism_quant_accuracy.pynew file mode 100644index 00000000000..28b17c17b6c--- /dev/null+++ b/src/frontends/gguf/tests/gen_prism_quant_accuracy.py@@ -0,0 +1,35 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++"""Generate private Prism quantization fixtures using its exported ggml CPU functions."""+import argparse+import ctypes+from pathlib import Path++import numpy as np+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--library", required=True, help="Prism libggml-base shared library")+ parser.add_argument("--output", type=Path, default=Path(__file__).parent / "test_data")+ args = parser.parse_args()+ library = ctypes.CDLL(args.library)+ rng = np.random.default_rng(20261013)+ for name, block_bytes in (("pq2_0", 34), ("ptq1_0", 28)):+ values = rng.normal(0, 0.4, (4, 256)).astype(np.float32)+ packed = np.empty((4 * 256 // 128 * block_bytes,), np.uint8)+ reference = np.empty_like(values)+ quantize = getattr(library, "quantize_row_" + name + "_ref")+ dequantize = getattr(library, "dequantize_row_" + name)+ for function in (quantize, dequantize):+ function.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64]+ function.restype = None+ quantize(values.ctypes.data, packed.ctypes.data, values.size)+ dequantize(packed.ctypes.data, reference.ctypes.data, reference.size)+ np.save(args.output / (name + "_qbytes.npy"), packed)+ np.save(args.output / (name + "_deq.npy"), reference.reshape(-1))+++if __name__ == "__main__":+ main()diff --git a/src/frontends/gguf/tests/test_arch_accuracy.cpp b/src/frontends/gguf/tests/test_arch_accuracy.cppindex 7365dab5bcd..208b0831df8 100644--- a/src/frontends/gguf/tests/test_arch_accuracy.cpp+++ b/src/frontends/gguf/tests/test_arch_accuracy.cpp@@ -8,13 +8,21 @@#include <cstring>#include <filesystem>#include <fstream>+#include <limits>#include <set>+#include <tuple>+#include "builder/api/metadata_store.hpp"+#include "builder/arch/dspark_builder.hpp"+#include "builder/gguf_builder_decoder.hpp"+#include "builder/gguf_graph.hpp"+#include "builder/graph_emitter.hpp"#include "cnpy.h"#include "common_test_utils/common_utils.hpp"#include "common_test_utils/test_assertions.hpp"#include "gtest/gtest.h"#include "op_test_utils.hpp"+#include "openvino/core/type/float16.hpp"#include "openvino/frontend/extension/decoder_transformation.hpp"#include "openvino/frontend/gguf/adapt_mmproj_to_genai.hpp"#include "openvino/frontend/gguf/adapt_to_genai.hpp"@@ -32,10 +40,449 @@#include "openvino/pass/manager.hpp"#include "openvino/pass/sdpa_to_paged_attention.hpp"#include "quant/gguf.hpp"+#include "utils.hpp"namespace {class GGUFArchitectureAccuracy : public ::testing::TestWithParam<const char*> {};+TEST(GGUFDSparkAccuracy, ConfidenceAndMarkovHeadsAreIndependent) {+ using namespace ov::frontend::gguf;+ const 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"));+ for (const auto& [rank, confidence, with_markov] :+ {std::tuple{0, false, false}, {0, true, false}, {8, false, false}, {8, true, false}, {8, true, true}}) {+ SCOPED_TRACE(::testing::Message() << rank << ", " << confidence << ", " << with_markov);+ auto loaded = get_gguf_data(temporary.path);+ auto& metadata = std::get<0>(loaded);+ auto& weights = std::get<1>(loaded);+ auto& qtypes = std::get<2>(loaded);+ ov::Tensor rank_value(ov::element::u32, {});+ *rank_value.data<uint32_t>() = static_cast<uint32_t>(rank);+ metadata["dspark.dspark.markov_rank"] = rank_value;+ for (const auto& [key, enabled] :+ {std::pair{"confidence_head", confidence}, {"confidence_head_with_markov", with_markov}}) {+ ov::Tensor flag(ov::element::boolean, {});+ *flag.data<char>() = enabled;+ metadata[std::string("dspark.dspark.") + key] = flag;+ }+ if (rank == 0) {+ weights.erase("dspark.markov_head_a.weight");+ weights.erase("dspark.markov_head_b.weight");+ }+ ov::Tensor projection(ov::element::f32, {1, with_markov ? size_t{72} : size_t{64}});+ std::copy_n(weights.at("dspark.confidence_head.weight").data<const float>(),+ projection.get_size(),+ projection.data<float>());+ weights["dspark.confidence_head.weight"] = projection;+ detail::MetadataStore store{metadata};+ detail::WeightStore tensors{weights, qtypes};+ const BuildContext context{GgufMetadata(store), "dspark", &tensors};+ const auto graph = make_dspark_builder(context)->build();+ EXPECT_EQ(graph->model_inputs.count("dspark_prev_tokens"), rank > 0 ? 1u : 0u);+ FrontEnd frontend;+ std::shared_ptr<GgufDecoder> decoder = std::make_shared<GgufBuilderDecoder>(graph);+ const auto model = frontend.convert(frontend.load(decoder));+ std::set<std::string> outputs;+ for (const auto& output : model->outputs())+ outputs.insert(output.get_names().begin(), output.get_names().end());+ EXPECT_EQ(outputs.count("dspark.confidence_score"), confidence ? 1u : 0u);+ EXPECT_EQ(outputs.count("dspark.corrected_logits"), rank > 0 ? 1u : 0u);+ if (!confidence)+ continue;+ ov::Core core;+ auto compiled = core.compile_model(model,+ "CPU",+ ov::hint::inference_precision(ov::element::f32),+ ov::hint::dynamic_quantization_group_size(0),+ ov::inference_num_threads(4));+ auto request = compiled.create_infer_request();+ for (const auto& input : compiled.inputs()) {+ const auto name = input.get_any_name();+ auto shape = input.get_partial_shape();+ for (size_t i = 0; i < shape.size(); ++i)+ if (shape[i].is_dynamic())+ shape[i] = name == "dspark_ctx_feat" ? 2 : 6;+ ov::Tensor value(input.get_element_type(), shape.to_shape());+ std::memset(value.data(), 0, value.get_byte_size());+ if (input.get_element_type() == ov::element::i32)+ for (size_t i = 0; i < value.get_size(); ++i)+ value.data<int32_t>()[i] = static_cast<int32_t>(i);+ request.set_tensor(name, value);+ }+ request.infer();+ const auto hidden = request.get_tensor("dspark.hidden");+ const auto score = request.get_tensor("dspark.confidence_score");+ ASSERT_EQ(score.get_size(), 4u);+ for (size_t token = 0; token < 4; ++token) {+ double expected = weights.at("dspark.confidence_head.bias").data<const float>()[0];+ for (size_t feature = 0; feature < 64; ++feature)+ expected += hidden.data<const float>()[token * 64 + feature] * projection.data<const float>()[feature];+ if (with_markov)+ for (size_t feature = 0; feature < 8; ++feature)+ expected += weights.at("dspark.markov_head_a.weight").data<const float>()[token * 8 + feature] *+ projection.data<const float>()[64 + feature];+ EXPECT_NEAR(score.data<const float>()[token], expected, 1e-6);+ }+ }+}++TEST(GGUFDSparkAccuracy, ConfidenceWithMarkovRequiresPositiveRank) {+ using namespace ov::frontend::gguf;+ const 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"));+ auto loaded = get_gguf_data(temporary.path);+ auto& metadata = std::get<0>(loaded);+ ov::Tensor rank(ov::element::u32, {});+ *rank.data<uint32_t>() = 0;+ metadata["dspark.dspark.markov_rank"] = rank;+ detail::MetadataStore store{metadata};+ detail::WeightStore tensors{std::get<1>(loaded), std::get<2>(loaded)};+ const BuildContext context{GgufMetadata(store), "dspark", &tensors};+ OV_EXPECT_THROW(make_dspark_builder(context)->build(),+ ov::Exception,+ testing::HasSubstr("confidence_head_with_markov"));+}++TEST(GGUFHadamardMetadata, MissingAndMistypedFieldsNameTheInvalidKey) {+ 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"));+ auto loaded = get_gguf_data(temporary.path);+ const auto config = decoder_config_from_meta(std::get<0>(loaded));+ GraphEmitter valid(std::get<1>(loaded), std::get<2>(loaded), "qwen35");+ EXPECT_NO_THROW(valid.configure_hadamard(config));+ for (const std::string key : {"prism.hadamard.version",+ "prism.hadamard.block_size",+ "prism.hadamard.transform",+ "prism.hadamard.axis",+ "prism.hadamard.weight_names",+ "prism.hadamard.inverse_weight_names",+ "prism.hadamard.sign_mode",+ "prism.hadamard.sign_widths",+ "prism.hadamard.sign_values",+ "prism.hadamard.gdn_v_grouped",+ "ssm_time_step_rank",+ "ssm_group_count"}) {+ SCOPED_TRACE(key);+ for (const bool missing : {false, true}) {+ if (missing && (key == "prism.hadamard.inverse_weight_names" || key == "prism.hadamard.gdn_v_grouped"))+ continue;+ auto invalid = config;+ if (missing)+ invalid.erase(key);+ else+ invalid[key] = std::monostate{};+ GraphEmitter emitter(std::get<1>(loaded), std::get<2>(loaded), "qwen35");+ OV_EXPECT_THROW(emitter.configure_hadamard(invalid), ov::Exception, testing::HasSubstr(key));+ }+ if (std::holds_alternative<ov::Tensor>(config.at(key))) {+ auto invalid = config;+ invalid[key] = ov::Tensor(ov::element::f32, {1});+ GraphEmitter emitter(std::get<1>(loaded), std::get<2>(loaded), "qwen35");+ OV_EXPECT_THROW(emitter.configure_hadamard(invalid), ov::Exception, testing::HasSubstr(key));+ }+ }+}++TEST(GGUFDSparkAccuracy, RejectsOversizedDraftBlocksBeforeBuildingTheGraph) {+ const 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"));+ auto loaded = ov::frontend::gguf::get_gguf_data(temporary.path);+ auto& metadata = std::get<0>(loaded);+ auto& weights = std::get<1>(loaded);+ auto& qtypes = std::get<2>(loaded);+ ov::frontend::gguf::detail::MetadataStore store{metadata};+ ov::frontend::gguf::detail::WeightStore tensors{weights, qtypes};+ const ov::frontend::gguf::BuildContext context{ov::frontend::gguf::GgufMetadata(store), "dspark", &tensors};+ for (int64_t block : {int64_t{0}, int64_t{4097}, int64_t{UINT32_MAX}, std::numeric_limits<int64_t>::max()}) {+ SCOPED_TRACE(block);+ ov::Tensor value(ov::element::i64, {});+ *value.data<int64_t>() = block;+ metadata["dspark.dspark.block_size"] = value;+ auto builder = ov::frontend::gguf::make_dspark_builder(context);+ try {+ builder->build();+ FAIL() << "Invalid DSpark block size was accepted";+ } catch (const ov::Exception& error) {+ EXPECT_NE(std::string(error.what()).find("block_size"), std::string::npos);+ }+ }+ ov::Tensor value(ov::element::i64, {});+ *value.data<int64_t>() = 4096;+ metadata["dspark.dspark.block_size"] = value;+ const auto graph = ov::frontend::gguf::make_dspark_builder(context)->build();+ EXPECT_EQ(graph->model_inputs.at("inp_tokens")->get_output_partial_shape(0), (ov::PartialShape{1, 1, 1, 4096}));+ EXPECT_EQ(weights.at("dspark.log_snr_features").get_byte_size(), 4096 * 128 * sizeof(float));+}++TEST(GGUFDSparkAccuracy, LogSnrUsesNormalizedEndpointsAndRequiresValidBounds) {+ using namespace ov::frontend::gguf;+ const 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"));+ const std::string low_key = "dspark.dspark.min_log_snr";+ const std::string high_key = "dspark.dspark.max_log_snr";+ for (const auto& [low, high] : {std::pair{-9.f, 9.f}, {-9.f, 6.f}, {1.f, 5.f}}) {+ auto loaded = get_gguf_data(temporary.path);+ auto& metadata = std::get<0>(loaded);+ for (const auto& [key, value] : {std::pair{low_key, low}, {high_key, high}}) {+ ov::Tensor bound(ov::element::f32, {});+ *bound.data<float>() = value;+ metadata[key] = bound;+ }+ detail::MetadataStore store{metadata};+ detail::WeightStore tensors{std::get<1>(loaded), std::get<2>(loaded)};+ const BuildContext context{GgufMetadata(store), "dspark", &tensors};+ EXPECT_NO_THROW(make_dspark_builder(context)->build());+ const auto& features = tensors.weights.at("dspark.log_snr_features");+ for (size_t pos = 0; pos < 4; ++pos) {+ const float log_snr = pos == 0 ? high : low;+ const float time = (log_snr - low) / (high - low) * 1000.f;+ for (size_t i = 0; i < 64; ++i) {+ const float angle = time * std::exp(-std::log(10000.f) * i / 64.f);+ EXPECT_FLOAT_EQ(features.data<const float>()[pos * 128 + i], std::sin(angle));+ EXPECT_FLOAT_EQ(features.data<const float>()[pos * 128 + 64 + i], std::cos(angle));+ }+ }+ }+ for (const auto& [key, value, missing] : {std::tuple{low_key, 0.f, true},+ {high_key, 0.f, true},+ {low_key, std::numeric_limits<float>::quiet_NaN(), false},+ {high_key, std::numeric_limits<float>::infinity(), false},+ {low_key, 9.f, false},+ {low_key, 10.f, false}}) {+ SCOPED_TRACE(key);+ auto loaded = get_gguf_data(temporary.path);+ auto& metadata = std::get<0>(loaded);+ if (missing) {+ metadata.erase(key);+ } else {+ ov::Tensor bound(ov::element::f32, {});+ *bound.data<float>() = value;+ metadata[key] = bound;+ }+ detail::MetadataStore store{metadata};+ detail::WeightStore tensors{std::get<1>(loaded), std::get<2>(loaded)};+ const BuildContext context{GgufMetadata(store), "dspark", &tensors};+ OV_EXPECT_THROW(make_dspark_builder(context)->build(), ov::Exception, testing::HasSubstr("log-SNR bounds"));+ }+}++TEST(GGUFHadamardTypes, ExplicitF32SignsFollowF16Activations) {+ using ov::element::f16;+ const ov::PartialShape shape{-1, 8};+ ov::Tensor signs(ov::element::f32, {8});+ for (size_t i = 0; i < 8; ++i)+ signs.data<float>()[i] = i % 3 == 0 ? -1.f : 1.f;+ for (const bool inverse : {false, true}) {+ SCOPED_TRACE(inverse);+ const auto decoder = std::make_shared<ov_gguf_test::SingleOpDecoder>(+ "GGML_OP_MUL_MAT",+ std::vector<ov_gguf_test::TensorDesc>{{"x", f16, shape}},+ std::vector<ov_gguf_test::TensorDesc>{},+ ov_gguf_test::TensorDesc{"y", f16, shape},+ std::map<std::string, ov::Any>{{"hadamard_block", int64_t{4}},+ {"hadamard_signs", signs},+ {"hadamard_inverse", inverse}});+ const auto x = std::make_shared<ov::op::v0::Parameter>(f16, shape);+ auto tensor_map = std::make_shared<ov::frontend::gguf::TensorMap>();+ (*tensor_map)["x"] = x;+ const ov::frontend::gguf::NodeContext context(decoder, tensor_map);+ const auto y = ov::frontend::gguf::apply_hadamard(context, x);+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{y}, ov::ParameterVector{x});+ ASSERT_EQ(y.get_element_type(), f16);+ ov::Core core;+ auto compiled = core.compile_model(model,+ "CPU",+ ov::hint::inference_precision(ov::element::f32),+ ov::inference_num_threads(4));+ ASSERT_EQ(compiled.input().get_element_type(), f16);+ ASSERT_EQ(compiled.output().get_element_type(), f16);+ auto request = compiled.create_infer_request();+ for (size_t rows : {1, 3}) {+ ov::Tensor input(f16, {rows, 8});+ for (size_t i = 0; i < input.get_size(); ++i)+ input.data<ov::float16>()[i] = ov::float16(static_cast<float>(i % 7) - 3.f);+ request.set_input_tensor(input);+ request.infer();+ const auto output = request.get_output_tensor();+ ASSERT_EQ(output.get_shape(), input.get_shape());+ for (size_t offset = 0; offset < input.get_size(); offset += 4) {+ for (size_t column = 0; column < 4; ++column) {+ float expected = 0.f;+ for (size_t row = 0; row < 4; ++row) {+ const size_t bits = row & column;+ const float sylvester = bits == 1 || bits == 2 ? -1.f : 1.f;+ expected += static_cast<float>(input.data<ov::float16>()[offset + row]) * sylvester *+ (inverse ? 1.f : signs.data<float>()[(offset + row) % 8]);+ }+ expected *= .5f * (inverse ? signs.data<float>()[(offset + column) % 8] : 1.f);+ EXPECT_FLOAT_EQ(static_cast<float>(output.data<ov::float16>()[offset + column]), expected);+ }+ }+ }+ }+}++class GGUFHadamardAccuracy : public ::testing::TestWithParam<std::tuple<int64_t, bool>> {};++TEST_P(GGUFHadamardAccuracy, ButterflyPreservesSylvesterOrderSignsAndDynamicShapes) {+ const auto block = std::get<0>(GetParam());+ const auto inverse = std::get<1>(GetParam());+ const auto width = static_cast<size_t>(2 * block);+ const ov::PartialShape shape{2, -1, 2 * block};+ ov::Tensor signs(ov::element::f32, {width});+ for (size_t i = 0; i < width; ++i)+ signs.data<float>()[i] = i % 3 == 0 ? -1.f : 1.f;+ const std::vector<int64_t> heads = block == 8 && !inverse ? std::vector<int64_t>{2, 2, 4} : std::vector<int64_t>{};+ 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", block},+ {"hadamard_signs", signs},+ {"hadamard_inverse", inverse},+ {"hadamard_gdn_heads", heads}});+ const auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shape);+ auto tensor_map = std::make_shared<ov::frontend::gguf::TensorMap>();+ (*tensor_map)["x"] = x;+ const ov::frontend::gguf::NodeContext context(decoder, tensor_map);+ 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;+ for (const auto& op : model->get_ordered_ops()) {+ EXPECT_NE(op->get_type_name(), std::string("MatMul"));+ 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);+ ov::Core core;+ auto compiled =+ core.compile_model(model, "CPU", ov::hint::inference_precision(ov::element::f32), ov::inference_num_threads(4));+ auto request = compiled.create_infer_request();+ const auto sylvester_sign = [](size_t row, size_t column) {+ size_t bits = row & column;+ bool odd = false;+ while (bits) {+ odd = !odd;+ bits &= bits - 1;+ }+ return odd ? -1. : 1.;+ };+ for (size_t rows : {1, 3, 1}) {+ SCOPED_TRACE(rows);+ ov::Tensor input(ov::element::f32, {2, rows, width});+ for (size_t i = 0; i < input.get_size(); ++i)+ input.data<float>()[i] = block < 4096 ? std::sin(static_cast<float>(i) * .37f) : 0.f;+ if (block == 4096)+ for (size_t group = 0; group < input.get_size() / block; ++group)+ input.data<float>()[group * block + (group * 17 + 3) % block] = static_cast<float>(group + 1);+ std::vector<float> ordered(input.data<float>(), input.data<float>() + input.get_size());+ if (!heads.empty())+ for (size_t row = 0; row < 2 * rows; ++row)+ for (size_t a = 0; a < 2; ++a)+ for (size_t b = 0; b < 2; ++b)+ for (size_t d = 0; d < 4; ++d)+ ordered[row * width + (b * 2 + a) * 4 + d] =+ input.data<float>()[row * width + (a * 2 + b) * 4 + d];+ std::vector<float> expected(input.get_size());+ for (size_t group = 0; group < input.get_size() / block; ++group) {+ for (size_t column = 0; column < static_cast<size_t>(block); ++column) {+ double sum = 0.;+ const auto accumulate = [&](size_t row) {+ const auto index = group * block + row;+ const auto sign = inverse ? 1.f : signs.data<float>()[index % width];+ sum += ordered[index] * sign * sylvester_sign(row, column);+ };+ if (block == 4096)+ accumulate((group * 17 + 3) % block);+ else+ for (size_t row = 0; row < static_cast<size_t>(block); ++row)+ accumulate(row);+ expected[group * block + column] =+ static_cast<float>(sum / std::sqrt(static_cast<double>(block))) *+ (inverse ? signs.data<float>()[(group * block + column) % width] : 1.f);+ }+ }+ request.set_input_tensor(input);+ request.infer();+ EXPECT_EQ(request.get_output_tensor().get_shape(), input.get_shape());+ ov_gguf_test::expect_near(request.get_output_tensor(), expected, 2e-5f);+ }+}++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::Bool()));++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"));+ ov::frontend::gguf::FrontEnd frontend;+ auto model = frontend.convert(frontend.load(temporary.path));+ EXPECT_FALSE(ov::frontend::gguf::pass::AdaptToGenAI().run_on_model(model));+ ov::Core core;+ auto compiled = core.compile_model(model,+ "CPU",+ ov::hint::inference_precision(ov::element::f32),+ ov::hint::dynamic_quantization_group_size(0),+ ov::inference_num_threads(4));+ auto request = compiled.create_infer_request();+ for (size_t rows : {2, 3, 2}) {+ SCOPED_TRACE(rows);+ const auto count = rows + 4;+ for (const auto& input : compiled.inputs()) {+ const auto name = input.get_any_name();+ auto shape = input.get_partial_shape();+ for (size_t i = 0; i < shape.size(); ++i)+ if (shape[i].is_dynamic())+ shape[i] = name == "dspark_ctx_feat" ? rows : count;+ ov::Tensor value(input.get_element_type(), shape.to_shape());+ std::memset(value.data(), 0, value.get_byte_size());+ if (name == "dspark_ctx_feat") {+ for (size_t i = 0; i < value.get_size(); ++i)+ value.data<float>()[i] = std::sin(static_cast<float>(i)) * .1f;+ } else if (name == "inp_tokens" || name == "dspark_prev_tokens" || name == "inp_pos" ||+ name == "inp_kv_idx") {+ for (size_t i = 0; i < value.get_size(); ++i)+ value.data<int32_t>()[i] =+ static_cast<int32_t>(i) + (name == "inp_tokens" || name == "dspark_prev_tokens" ? 1 : 0);+ }+ request.set_tensor(name, value);+ }+ request.infer();+ const auto actual = request.get_tensor("logits");+ const auto& expected = ov_gguf_test::npz_array(arrays, "logits_" + std::to_string(rows));+ ASSERT_EQ(actual.get_size(), expected.num_vals);+ ov_gguf_test::expect_nmse_below(+ ov_gguf_test::nmse(actual.data<const float>(), expected.data<float>(), actual.get_size()),+ 1e-5);+ const auto hidden = request.get_tensor("dspark.hidden");+ const auto corrected = request.get_tensor("dspark.corrected_logits");+ const auto confidence = request.get_tensor("dspark.confidence_score");+ const auto* a = ov_gguf_test::npz_array(arrays, "dspark.markov_head_a.weight").data<float>();+ const auto* b = ov_gguf_test::npz_array(arrays, "dspark.markov_head_b.weight").data<float>();+ const auto* c = ov_gguf_test::npz_array(arrays, "dspark.confidence_head.weight").data<float>();+ const auto bias = ov_gguf_test::npz_array(arrays, "dspark.confidence_head.bias").data<float>()[0];+ for (size_t token = 0; token < 4; ++token) {+ double score = bias;+ for (size_t feature = 0; feature < 64; ++feature)+ score += hidden.data<const float>()[token * 64 + feature] * c[feature];+ for (size_t rank = 0; rank < 8; ++rank)+ score += a[(token + 1) * 8 + rank] * c[64 + rank];+ EXPECT_NEAR(confidence.data<const float>()[token], score, 1e-6);+ for (size_t vocab = 0; vocab < 256; ++vocab) {+ double logit = actual.data<const float>()[token * 256 + vocab];+ for (size_t rank = 0; rank < 8; ++rank)+ logit += a[(token + 1) * 8 + rank] * b[vocab * 8 + rank];+ EXPECT_NEAR(corrected.data<const float>()[token * 256 + vocab], logit, 1e-6);+ }+ }+ }+}+// Check batching and beam reordering against independent stateful requests. The// same synthetic checkpoints are qualified against llama.cpp below.void check_batched_decode(const std::shared_ptr<ov::Model>& model) {@@ -86,7 +533,8 @@ void check_batched_decode(const std::shared_ptr<ov::Model>& model) {}TEST(GGUFMultimodalBackboneAdaptation, QwenAndGemmaSupportBatchesAndPagedAttention) {- for (const auto* family : {"qwen35", "qwen35moe", "qwen35moe-fused", "gemma4-mqa", "gemma4-moe", "gemma4-ple"}) {+ for (const auto* family :+ {"qwen35", "bonsai2-hadamard", "qwen35moe", "qwen35moe-fused", "gemma4-mqa", "gemma4-moe", "gemma4-ple"}) {SCOPED_TRACE(family);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"));@@ -572,6 +1020,7 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {INSTANTIATE_TEST_SUITE_P(Architectures,GGUFArchitectureAccuracy,::testing::Values("qwen35",+ "bonsai2-hadamard","qwen35-mixed","qwen35moe","qwen35moe-fused",diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/README.md b/src/frontends/gguf/tests/test_data/arch_accuracy/README.mdindex e52bb4cf0b2..6932bded50a 100644--- a/src/frontends/gguf/tests/test_data/arch_accuracy/README.md+++ b/src/frontends/gguf/tests/test_data/arch_accuracy/README.md@@ -12,10 +12,11 @@ expert projections, and F16 Gated-DeltaNet gate/beta projections that disable thprojection merges as mixed quantization does in real checkpoints), Gemma4 mixed-head MQA/MoE variants and an E2B/E4B-style Gemma4 withper-layer embeddings and shared KV layers that omit unused K/V weights (`gemma4-ple`). Reference revisions are:-| Fixtures | Upstream llama.cpp CPU oracle |+| Fixtures | llama.cpp CPU oracle ||---|---|-| Decoder/embedding fixtures other than the Mamba cases below | `03fa73cb27f5c251b9528489b18d303b1366aca4` (2026-09-08; includes Muse Glimmer) |+| Decoder/embedding fixtures other than the Mamba and Prism cases below | Upstream `03fa73cb27f5c251b9528489b18d303b1366aca4` (2026-09-08; includes Muse Glimmer) || `mamba2`, `mamba2-tied`, `nemotron_h` | `476c01efe88aad7880a8132d5d3a415f2ca75139`, recorded when these fixtures were added |+| `bonsai2-hadamard`, `dspark` | [PrismML-Eng/llama.cpp](https://github.com/PrismML-Eng/llama.cpp/tree/e8fd209c975c80aa7fb36a8423571ff3b1b7e955), `e8fd209c975c80aa7fb36a8423571ff3b1b7e955` |The cases use distinct nonzero weights and nonuniform norm scales, four query heads,grouped-query attention (single KV head for Gemma), and token batches `[1,2,3]`, `[4]`,@@ -60,6 +61,35 @@ against its recorded revision and use `--architectures mamba2 mamba2-tied nemotrOmitting `--architectures` attempts every case with the supplied oracle; use it only for adeliberate full reference refresh and review the numerical changes and provenance together.+For the Prism fixtures, use the exact fork revision above. From `src/frontends/gguf/tests`,+set `LLAMA_SRC` and `LLAMA_BUILD` to separate source and build directories, then run:++```sh+git clone https://github.com/PrismML-Eng/llama.cpp "$LLAMA_SRC"+git -C "$LLAMA_SRC" checkout e8fd209c975c80aa7fb36a8423571ff3b1b7e955+cmake -S "$LLAMA_SRC" -B "$LLAMA_BUILD" -G Ninja \+ -DCMAKE_BUILD_TYPE=Release -DGGML_OPENVINO=OFF -DGGML_CUDA=OFF -DGGML_NATIVE=OFF \+ -DLLAMA_BUILD_TESTS=OFF -DLLAMA_BUILD_EXAMPLES=OFF -DLLAMA_BUILD_SERVER=OFF \+ -DLLAMA_BUILD_APP=OFF -DLLAMA_BUILD_TOOLS=OFF+cmake --build "$LLAMA_BUILD" --target llama --parallel+c++ -std=c++17 -O2 architecture_oracle.cpp \+ -I "$LLAMA_SRC/include" -I "$LLAMA_SRC/ggml/include" \+ -L "$LLAMA_BUILD/bin" -Wl,-rpath,"$LLAMA_BUILD/bin" \+ -lllama -lggml -lggml-base -o architecture_oracle_prism+c++ -std=c++17 -O2 dspark_oracle.cpp \+ -I "$LLAMA_SRC/include" -I "$LLAMA_SRC/ggml/include" -I "$LLAMA_SRC/src" \+ -L "$LLAMA_BUILD/bin" -Wl,-rpath,"$LLAMA_BUILD/bin" \+ -lllama -lggml -lggml-base -o dspark_oracle+PYTHONPATH="$LLAMA_SRC/gguf-py" python3 gen_arch_accuracy.py \+ --oracle ./architecture_oracle_prism --architectures bonsai2-hadamard+PYTHONPATH="$LLAMA_SRC/gguf-py" python3 gen_dspark_accuracy.py --oracle ./dspark_oracle+```++`bonsai2-hadamard.npz` uses the architecture oracle with explicit Hadamard signs and+Gated-DeltaNet feature ordering. `dspark.npz` uses the DSpark API oracle for noncausal+draft blocks with log-SNR conditioning; it also stores Markov and confidence projection+weights for the head checks. The upstream oracle revision does not supply these Prism contracts.+For an additional real-checkpoint check, create `<arch>.gguf` in a separate directory,then run `architecture_oracle <arch>.gguf <arch>.bin "The capital of France is"`.Set `OV_GGUF_ACCURACY_DATA` to that directory and filter the test to that architecture.diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/bonsai2-hadamard.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/bonsai2-hadamard.npznew file mode 100644index 00000000000..2bf644fd0f6Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/bonsai2-hadamard.npz differdiff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/dspark.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/dspark.npznew file mode 100644index 00000000000..5cfec158f10Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/dspark.npz differdiff --git a/src/frontends/gguf/tests/test_data/pq2_0_deq.npy b/src/frontends/gguf/tests/test_data/pq2_0_deq.npynew file mode 100644index 00000000000..86682a5e2ebBinary files /dev/null and b/src/frontends/gguf/tests/test_data/pq2_0_deq.npy differdiff --git a/src/frontends/gguf/tests/test_data/pq2_0_qbytes.npy b/src/frontends/gguf/tests/test_data/pq2_0_qbytes.npynew file mode 100644index 00000000000..4f4318815f2Binary files /dev/null and b/src/frontends/gguf/tests/test_data/pq2_0_qbytes.npy differdiff --git a/src/frontends/gguf/tests/test_data/ptq1_0_deq.npy b/src/frontends/gguf/tests/test_data/ptq1_0_deq.npynew file mode 100644index 00000000000..2245282603eBinary files /dev/null and b/src/frontends/gguf/tests/test_data/ptq1_0_deq.npy differdiff --git a/src/frontends/gguf/tests/test_data/ptq1_0_qbytes.npy b/src/frontends/gguf/tests/test_data/ptq1_0_qbytes.npynew file mode 100644index 00000000000..33571f50a96Binary files /dev/null and b/src/frontends/gguf/tests/test_data/ptq1_0_qbytes.npy differdiff --git a/src/frontends/gguf/tests/test_parser.cpp b/src/frontends/gguf/tests/test_parser.cppindex 94f8941ffd1..917d8bf5e20 100644--- a/src/frontends/gguf/tests/test_parser.cpp+++ b/src/frontends/gguf/tests/test_parser.cpp@@ -4,8 +4,10 @@#include <array>#include <fstream>+#include <tuple>#include <utility>+#include "builder/graph_emitter.hpp"#include "common_test_utils/common_utils.hpp"#include "gguf_writer.hpp"#include "op_test_utils.hpp"@@ -68,6 +70,32 @@ protected:std::string m_path;};+TEST_F(GGUFParser, Q1_0PreservesBinaryStorageAndScaleValues) {+ const auto bytes = load_npy<uint8_t>("q1_0_qbytes");+ const auto reference = load_npy<float>("q1_0_deq");+ ASSERT_NO_FATAL_FAILURE(write_tensor("token_embd.weight", GGUF_TYPE_Q1_0, 256, 4, bytes));+ const auto loaded = get_gguf_data(m_path);+ const auto& arrays = std::get<1>(loaded);+ const auto& weights = arrays.at("token_embd.weight");+ const auto& scales = arrays.at("token_embd.scales");+ ASSERT_EQ(weights.get_element_type(), ov::element::u1);+ EXPECT_EQ(weights.get_shape(), (ov::Shape{4, 256}));+ EXPECT_EQ(weights.get_byte_size(), 128);+ EXPECT_EQ(scales.get_byte_size(), 16);+ EXPECT_EQ(arrays.count("token_embd.zp"), 0);+ for (size_t group = 0; group < scales.get_size(); ++group) {+ uint16_t bits;+ std::memcpy(&bits, bytes.data() + group * 18, sizeof(bits));+ EXPECT_EQ(scales.data<ov::float16>()[group].to_bits(), bits);+ }+ const auto node = make_weight_node({weights, scales, {}}, GGUF_TYPE_Q1_0);+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{node}, ov::ParameterVector{});+ const auto output = run_on_cpu(model, {});+ ASSERT_EQ(output.get_size(), reference.size());+ for (size_t i = 0; i < reference.size(); ++i)+ EXPECT_FLOAT_EQ(output.data<const float>()[i], reference[i]);+}+TEST_F(GGUFParser, Q2_0KeepsIntegerZeroPointsForAllWeightNames) {const auto bytes = load_npy<uint8_t>("q2_0_qbytes");const auto reference = load_npy<float>("q2_0_deq");@@ -94,6 +122,61 @@ TEST_F(GGUFParser, Q2_0KeepsIntegerZeroPointsForAllWeightNames) {}}+TEST_F(GGUFParser, PrismTernaryFormatsMatchGgmlIncludingLegacyGroup128) {+ for (const auto& [stem, file_type, expected_type] : {std::tuple{"pq2_0", GGUF_TYPE_PQ2_0, GGUF_TYPE_PQ2_0},+ std::tuple{"ptq1_0", GGUF_TYPE_PTQ1_0, GGUF_TYPE_PTQ1_0},+ std::tuple{"pq2_0", GGUF_TYPE_Q2_0, GGUF_TYPE_PQ2_0}}) {+ SCOPED_TRACE(stem);+ const auto bytes = load_npy<uint8_t>(std::string(stem) + "_qbytes");+ const auto reference = load_npy<float>(std::string(stem) + "_deq");+ ASSERT_NO_FATAL_FAILURE(write_tensor("token_embd.weight", file_type, 256, 4, bytes));+ const auto loaded = get_gguf_data(m_path);+ const auto& arrays = std::get<1>(loaded);+ EXPECT_EQ(std::get<2>(loaded).at("token_embd.qtype"), expected_type);+ EXPECT_EQ(arrays.at("token_embd.scales").get_shape(), (ov::Shape{4, 2}));+ const auto node = make_weight_node(+ {arrays.at("token_embd.weight"), arrays.at("token_embd.scales"), arrays.at("token_embd.zp")},+ expected_type,+ "token_embd");+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{node}, ov::ParameterVector{});+ const auto output = run_on_cpu(model, {});+ ASSERT_EQ(output.get_size(), reference.size());+ for (size_t i = 0; i < reference.size(); ++i)+ EXPECT_FLOAT_EQ(output.data<const float>()[i], reference[i]);+ }+}++TEST(GGUFHadamardMetadata, RejectsInvalidBlocksWidthsAndUnusedWeights) {+ std::unordered_map<std::string, ov::Tensor> weights{{"output.weight", ov::Tensor(ov::element::f32, {4, 16})},+ {"token_embd.weight", ov::Tensor(ov::element::f32, {4, 12})}};+ std::unordered_map<std::string, GgufTensorType> qtypes;+ const auto scalar = [](uint32_t value) {+ ov::Tensor tensor(ov::element::u32, {});+ *tensor.data<uint32_t>() = value;+ return tensor;+ };+ const std::string p = "prism.hadamard.";+ std::map<std::string, GGUFMetaData> config{{p + "version", scalar(1)},+ {p + "block_size", scalar(8)},+ {p + "transform", std::string("normalized-sylvester-walsh-hadamard")},+ {p + "axis", std::string("input-last-dimension")},+ {p + "sign_mode", std::string("identity")},+ {p + "weight_names", std::vector<std::string>{"output.weight"}}};+ for (uint32_t block : {0, 3, 8192}) {+ auto invalid = config;+ invalid[p + "block_size"] = scalar(block);+ ov::frontend::gguf::GraphEmitter emitter(weights, qtypes, "qwen35");+ EXPECT_ANY_THROW(emitter.configure_hadamard(invalid));+ }+ auto inverse = config;+ inverse[p + "inverse_weight_names"] = std::vector<std::string>{"token_embd.weight"};+ ov::frontend::gguf::GraphEmitter bad_inverse(weights, qtypes, "qwen35");+ EXPECT_ANY_THROW(bad_inverse.configure_hadamard(inverse));+ ov::frontend::gguf::GraphEmitter unused(weights, qtypes, "qwen35");+ ASSERT_NO_THROW(unused.configure_hadamard(config));+ EXPECT_ANY_THROW(unused.validate_hadamard());+}+// Q4_K uses an integer zero-point by default and the faithful f16 one under OV_GGUF_Q4_K_ZP_F16,// for language and projector models alike.TEST_F(GGUFParser, Q4KZeroPointModeAppliesToLanguageAndProjectorModels) {diff --git a/src/frontends/gguf/tests/test_weights.cpp b/src/frontends/gguf/tests/test_weights.cppindex 6833c9627d7..382065b762c 100644--- a/src/frontends/gguf/tests/test_weights.cpp+++ b/src/frontends/gguf/tests/test_weights.cpp@@ -16,6 +16,7 @@#include <vector>#include "op_test_utils.hpp"+#include "openvino/op/constant.hpp"#include "quant/weights.hpp"using namespace ov_gguf_test;@@ -88,11 +89,54 @@ INSTANTIATE_TEST_SUITE_P(AllQuantTypes,WeightCase{"q5_k", "Q5_K", kTolRequant},WeightCase{"q6_k", "Q6_K", kTolRequant},WeightCase{"q2_0", "Q2_0", kTolFaithful},- WeightCase{"q1_0", "Q1_0", kTolFaithful}),+ WeightCase{"q1_0", "Q1_0", kTolFaithful},+ WeightCase{"pq2_0", "PQ2_0", 0.f},+ WeightCase{"ptq1_0", "PTQ1_0", 0.f}),[](const ::testing::TestParamInfo<WeightCase>& i) {return std::string(i.param.stem);});+TEST(GGUFWeight, Q1_0KeepsBinaryCodesForAllWeightNames) {+ const auto bytes = load_npy<uint8_t>("q1_0_qbytes");+ const auto reference = load_npy<float>("q1_0_deq");+ for (const std::string name : {"blk.0.attn_q.weight", "token_embd.weight", "output.weight"}) {+ SCOPED_TRACE(name);+ const auto node = make_weight_node(bytes_to_u8_tensor(bytes), "Q1_0", {kRows, kCols}, name);+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{node}, ov::ParameterVector{});+ size_t binary_bytes = 0;+ for (const auto& op : model->get_ordered_ops()) {+ if (const auto constant = ov::as_type_ptr<ov::op::v0::Constant>(op)) {+ EXPECT_NE(constant->get_element_type(), ov::element::i4);+ EXPECT_NE(constant->get_element_type(), ov::element::i8);+ if (constant->get_element_type() == ov::element::u1)+ binary_bytes += constant->get_byte_size();+ }+ }+ EXPECT_EQ(binary_bytes, kRows * kCols / 8);+ const auto output = run_on_cpu(model, {});+ ASSERT_EQ(output.get_size(), reference.size());+ for (size_t i = 0; i < reference.size(); ++i)+ EXPECT_FLOAT_EQ(output.data<const float>()[i], reference[i]);+ }+}++TEST(GGUFWeight, Q1_0PreservesFiniteScaleRange) {+ const std::vector<ov::float16> scales{65504.f, -65504.f, 0.f, ov::float16::from_bits(1)};+ std::vector<uint8_t> bytes(scales.size() * 18);+ for (size_t group = 0; group < scales.size(); ++group) {+ const auto bits = scales[group].to_bits();+ std::memcpy(bytes.data() + group * 18, &bits, sizeof(bits));+ std::fill_n(bytes.data() + group * 18 + 2, 16, 0x55);+ }+ const auto node = make_weight_node(bytes_to_u8_tensor(bytes), "Q1_0", {1, scales.size() * 128});+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{node}, ov::ParameterVector{});+ const auto output = run_on_cpu(model, {});+ for (size_t i = 0; i < output.get_size(); ++i) {+ const float scale = static_cast<float>(scales[i / 128]);+ EXPECT_FLOAT_EQ(output.data<const float>()[i], i % 2 == 0 ? scale : -scale);+ }+}+// token_embd / output are requantized to channel-wise Q8_0_C, and that path reads the zero-point// as f16 -- Q2_0 used to hard-code u8 here, which threw for every ternary model.TEST(GGUFWeightRequant, Q2_0AsTokenEmbdAndOutput) {@@ -287,6 +331,7 @@ TEST(GGUFFusedQkvWeight, PreservesScalesForMxfp4AndQ8K) {};check(ov::frontend::gguf::GGUF_TYPE_MXFP4, ov::element::f4e2m1, ov::element::f8e8m0, 8);+ check(ov::frontend::gguf::GGUF_TYPE_Q1_0, ov::element::u1, ov::element::f16, 2);check(ov::frontend::gguf::GGUF_TYPE_Q8_K, ov::element::i8, ov::element::f32, 1);}diff --git a/tests/model_hub_tests/gguf/bonsai_models.json b/tests/model_hub_tests/gguf/bonsai_models.jsonnew file mode 100644index 00000000000..f88b69d2696--- /dev/null+++ b/tests/model_hub_tests/gguf/bonsai_models.json@@ -0,0 +1,232 @@+{+ "models": [+ {+ "repo_id": "prism-ml/Ternary-Bonsai-2-27B-gguf",+ "revision": "b072e1d3b35a0a630cece372c2127528e0994386",+ "filename": "Ternary-Bonsai-2-27B-F16.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-2-27B-gguf",+ "revision": "b072e1d3b35a0a630cece372c2127528e0994386",+ "filename": "Ternary-Bonsai-2-27B-PQ2_0.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-2-27B-gguf",+ "revision": "b072e1d3b35a0a630cece372c2127528e0994386",+ "filename": "Ternary-Bonsai-2-27B-PTQ1_0.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-2-27B-gguf",+ "revision": "b072e1d3b35a0a630cece372c2127528e0994386",+ "filename": "Ternary-Bonsai-2-27B-mmproj-BF16.gguf",+ "kind": "mmproj"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-2-27B-gguf",+ "revision": "b072e1d3b35a0a630cece372c2127528e0994386",+ "filename": "Ternary-Bonsai-2-27B-mmproj-Q8_0.gguf",+ "kind": "mmproj"+ },+ {+ "repo_id": "prism-ml/Bonsai-27B-gguf",+ "revision": "f10afb355f104535e3e3e98cf7ab7795c72bd292",+ "filename": "Bonsai-27B-F16.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Bonsai-27B-gguf",+ "revision": "f10afb355f104535e3e3e98cf7ab7795c72bd292",+ "filename": "Bonsai-27B-Q1_0.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Bonsai-27B-gguf",+ "revision": "f10afb355f104535e3e3e98cf7ab7795c72bd292",+ "filename": "Bonsai-27B-dspark-Q4_1.gguf",+ "kind": "dspark"+ },+ {+ "repo_id": "prism-ml/Bonsai-27B-gguf",+ "revision": "f10afb355f104535e3e3e98cf7ab7795c72bd292",+ "filename": "Bonsai-27B-dspark-bf16.gguf",+ "kind": "dspark"+ },+ {+ "repo_id": "prism-ml/Bonsai-27B-gguf",+ "revision": "f10afb355f104535e3e3e98cf7ab7795c72bd292",+ "filename": "Bonsai-27B-mmproj-BF16.gguf",+ "kind": "mmproj"+ },+ {+ "repo_id": "prism-ml/Bonsai-27B-gguf",+ "revision": "f10afb355f104535e3e3e98cf7ab7795c72bd292",+ "filename": "Bonsai-27B-mmproj-Q8_0.gguf",+ "kind": "mmproj"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-27B-gguf",+ "revision": "86e89f34c93201c3dfd5e5880fedb0022fc7e34d",+ "filename": "Ternary-Bonsai-27B-F16.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-27B-gguf",+ "revision": "86e89f34c93201c3dfd5e5880fedb0022fc7e34d",+ "filename": "Ternary-Bonsai-27B-PQ2_0.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-27B-gguf",+ "revision": "86e89f34c93201c3dfd5e5880fedb0022fc7e34d",+ "filename": "Ternary-Bonsai-27B-Q2_0.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-27B-gguf",+ "revision": "86e89f34c93201c3dfd5e5880fedb0022fc7e34d",+ "filename": "Ternary-Bonsai-27B-Q2_g64.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-27B-gguf",+ "revision": "86e89f34c93201c3dfd5e5880fedb0022fc7e34d",+ "filename": "Ternary-Bonsai-27B-dspark-Q4_1.gguf",+ "kind": "dspark"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-27B-gguf",+ "revision": "86e89f34c93201c3dfd5e5880fedb0022fc7e34d",+ "filename": "Ternary-Bonsai-27B-dspark-bf16.gguf",+ "kind": "dspark"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-27B-gguf",+ "revision": "86e89f34c93201c3dfd5e5880fedb0022fc7e34d",+ "filename": "Ternary-Bonsai-27B-mmproj-BF16.gguf",+ "kind": "mmproj"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-27B-gguf",+ "revision": "86e89f34c93201c3dfd5e5880fedb0022fc7e34d",+ "filename": "Ternary-Bonsai-27B-mmproj-Q8_0.gguf",+ "kind": "mmproj"+ },+ {+ "repo_id": "prism-ml/Bonsai-8B-gguf",+ "revision": "48516770dd04643643e9f9019a2a349cf26c5dbd",+ "filename": "Bonsai-8B-Q1_0.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Bonsai-8B-gguf",+ "revision": "48516770dd04643643e9f9019a2a349cf26c5dbd",+ "filename": "Bonsai-8B.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-8B-gguf",+ "revision": "c2aefbeb4b24469cd11579c3384b990404c17a30",+ "filename": "Ternary-Bonsai-8B-F16.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-8B-gguf",+ "revision": "c2aefbeb4b24469cd11579c3384b990404c17a30",+ "filename": "Ternary-Bonsai-8B-PQ2_0.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-8B-gguf",+ "revision": "c2aefbeb4b24469cd11579c3384b990404c17a30",+ "filename": "Ternary-Bonsai-8B-Q2_0.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-8B-gguf",+ "revision": "c2aefbeb4b24469cd11579c3384b990404c17a30",+ "filename": "Ternary-Bonsai-8B-Q2_0_g64.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Bonsai-1.7B-gguf",+ "revision": "210a9e99f79cb184909d49595906526eb2b3dd9a",+ "filename": "Bonsai-1.7B-Q1_0.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Bonsai-1.7B-gguf",+ "revision": "210a9e99f79cb184909d49595906526eb2b3dd9a",+ "filename": "Bonsai-1.7B.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-1.7B-gguf",+ "revision": "983b5dec2ff16aab79990711ba0f828a499a7e6a",+ "filename": "Ternary-Bonsai-1.7B-F16.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-1.7B-gguf",+ "revision": "983b5dec2ff16aab79990711ba0f828a499a7e6a",+ "filename": "Ternary-Bonsai-1.7B-PQ2_0.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-1.7B-gguf",+ "revision": "983b5dec2ff16aab79990711ba0f828a499a7e6a",+ "filename": "Ternary-Bonsai-1.7B-Q2_0.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-1.7B-gguf",+ "revision": "983b5dec2ff16aab79990711ba0f828a499a7e6a",+ "filename": "Ternary-Bonsai-1.7B-Q2_0_g64.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-4B-gguf",+ "revision": "a3eb42bafe873f9686bc97486c43b72ef7d75ec8",+ "filename": "Ternary-Bonsai-4B-F16.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-4B-gguf",+ "revision": "a3eb42bafe873f9686bc97486c43b72ef7d75ec8",+ "filename": "Ternary-Bonsai-4B-PQ2_0.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-4B-gguf",+ "revision": "a3eb42bafe873f9686bc97486c43b72ef7d75ec8",+ "filename": "Ternary-Bonsai-4B-Q2_0.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-4B-gguf",+ "revision": "a3eb42bafe873f9686bc97486c43b72ef7d75ec8",+ "filename": "Ternary-Bonsai-4B-Q2_0_g64.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Bonsai-4B-gguf",+ "revision": "78f2c2bacd0904ffaba24b4873ed975e5818354a",+ "filename": "Bonsai-4B-Q1_0.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Bonsai-4B-gguf",+ "revision": "78f2c2bacd0904ffaba24b4873ed975e5818354a",+ "filename": "Bonsai-4B.gguf",+ "kind": "decoder"+ },+ {+ "repo_id": "prism-ml/Ternary-Bonsai-2-27B-gguf-dev",+ "revision": "2a263ef827a2e215f3ddd14c9871a5bd1800fcbc",+ "filename": "Ternary-Bonsai-2-27B-Q2_0-prism-fork-required.gguf",+ "kind": "decoder"+ }+ ]+}diff --git a/tests/model_hub_tests/gguf/gguf_mmproj_nightly b/tests/model_hub_tests/gguf/gguf_mmproj_nightlyindex 96240a43e99..7af30978a28 100644--- a/tests/model_hub_tests/gguf/gguf_mmproj_nightly+++ b/tests/model_hub_tests/gguf/gguf_mmproj_nightly@@ -7,3 +7,9 @@ gemma4v+gemma4a,unsloth/gemma-4-E2B-it-GGUF,mmproj-F16.ggufultravox,ggml-org/ultravox-v0_5-llama-3_2-1b-GGUF,mmproj-ultravox-v0_5-llama-3_2-1b-f16.ggufqwen2.5vl_merger+qwen2a,ggml-org/Qwen2.5-Omni-3B-GGUF,mmproj-Qwen2.5-Omni-3B-Q8_0.ggufdeepseekocr,ggml-org/deepseek-ocr-GGUF,mmproj-DeepSeek-OCR-Q8_0.gguf,skip,the test has no input contract for SAM tiles and views yet+qwen3vl_merger,prism-ml/Bonsai-27B-gguf,Bonsai-27B-mmproj-BF16.gguf+qwen3vl_merger,prism-ml/Bonsai-27B-gguf,Bonsai-27B-mmproj-Q8_0.gguf+qwen3vl_merger,prism-ml/Ternary-Bonsai-27B-gguf,Ternary-Bonsai-27B-mmproj-BF16.gguf+qwen3vl_merger,prism-ml/Ternary-Bonsai-27B-gguf,Ternary-Bonsai-27B-mmproj-Q8_0.gguf+qwen3vl_merger,prism-ml/Ternary-Bonsai-2-27B-gguf,Ternary-Bonsai-2-27B-mmproj-BF16.gguf+qwen3vl_merger,prism-ml/Ternary-Bonsai-2-27B-gguf,Ternary-Bonsai-2-27B-mmproj-Q8_0.ggufdiff --git a/tests/model_hub_tests/gguf/gguf_models_nightly b/tests/model_hub_tests/gguf/gguf_models_nightlyindex 29ac5038822..159a0692227 100644--- a/tests/model_hub_tests/gguf/gguf_models_nightly+++ b/tests/model_hub_tests/gguf/gguf_models_nightly@@ -34,3 +34,7 @@ minimax-m2,mradermacher/MiniMax-M2.1-REAP-50-i1-GGUF,MiniMax-M2.1-REAP-50.i1-Q2_jais2,mradermacher/JAIS2-IT-0.3-GGUF,JAIS2-IT-0.3.Q4_K_M.ggufnemotron_h,bartowski/nvidia_Nemotron-H-8B-Reasoning-128K-GGUF,nvidia_Nemotron-H-8B-Reasoning-128K-Q4_K_M.ggufmamba2-2.7b,Nicholas55555/mamba2-2.7b-Q8_0-GGUF,mamba2-2.7b-q8_0.gguf+qwen35-bonsai-pq2_0,prism-ml/Ternary-Bonsai-27B-gguf,Ternary-Bonsai-27B-PQ2_0.gguf+qwen35-bonsai2-pq2_0,prism-ml/Ternary-Bonsai-2-27B-gguf,Ternary-Bonsai-2-27B-PQ2_0.gguf+qwen35-bonsai2-ptq1_0,prism-ml/Ternary-Bonsai-2-27B-gguf,Ternary-Bonsai-2-27B-PTQ1_0.gguf+qwen35-bonsai2-q2_0,prism-ml/Ternary-Bonsai-2-27B-gguf-dev,Ternary-Bonsai-2-27B-Q2_0-prism-fork-required.ggufdiff --git a/tests/model_hub_tests/gguf/test_bonsai.py b/tests/model_hub_tests/gguf/test_bonsai.pynew file mode 100644index 00000000000..540e5e94902--- /dev/null+++ b/tests/model_hub_tests/gguf/test_bonsai.py@@ -0,0 +1,65 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++"""Opt-in complete Bonsai checkpoint catalog, including all published GGUF tensor mixes."""+import json+import os+from pathlib import Path++import numpy as np+import openvino as ov+import pytest++from huggingface_hub import hf_hub_download+from utils import assert_valid_logits, convert_gguf_model, _run_two_steps++CATALOG = json.loads(Path(__file__).with_name("bonsai_models.json").read_text())+MODELS = [m for m in CATALOG["models"] if m["kind"] != "mmproj"]++[email protected]("checkpoint", MODELS, ids=[m["filename"] for m in MODELS])+def test_bonsai_checkpoint(checkpoint, ie_device):+ if os.environ.get("GGUF_BONSAI_ALL") != "1":+ pytest.skip("Set GGUF_BONSAI_ALL=1 on a runner sized for 27B F16 checkpoints")+ path = hf_hub_download(checkpoint["repo_id"], checkpoint["filename"], revision=checkpoint["revision"])+ model = convert_gguf_model(path)+ compiled = ov.Core().compile_model(+ model,+ ie_device,+ {+ "INFERENCE_PRECISION_HINT": "f32",+ "DYNAMIC_QUANTIZATION_GROUP_SIZE": 0,+ },+ )+ if checkpoint["kind"] == "decoder":+ info = model.get_rt_info()+ pairs = info["gguf_recurrent_states"].value if "gguf_recurrent_states" in info else []+ states = dict(zip(pairs[1::2], pairs[::2]))+ imrope = bool(info["gguf_is_imrope"].value) if "gguf_is_imrope" in info else False+ assert_valid_logits(_run_two_steps(compiled, imrope, states))+ return+ request = compiled.create_infer_request()+ block = compiled.input("inp_tokens").partial_shape[-1].get_length()+ width = compiled.input("dspark_ctx_feat").partial_shape[-1].get_length()+ heads = next(p.partial_shape[2].get_length() for p in compiled.inputs if p.get_any_name().startswith("cache_k_"))+ for rows in (2, 3):+ count = rows + block+ feed = {}+ for port in compiled.inputs:+ name = port.get_any_name()+ if name in ("inp_tokens", "dspark_prev_tokens"):+ value = np.arange(1, block + 1, dtype=np.int32).reshape(1, 1, 1, block)+ elif name == "inp_pos":+ value = np.arange(count, dtype=np.int32).reshape(1, 1, 1, count)+ elif name == "inp_kv_idx":+ value = np.arange(count * heads, dtype=np.int32).reshape(1, 1, 1, count * heads)+ elif name == "dspark_ctx_feat":+ value = (0.1 * np.sin(np.arange(rows * width, dtype=np.float32))).reshape(1, 1, rows, width)+ else:+ shape = [d.get_length() if d.is_static else count for d in port.partial_shape]+ value = np.zeros(shape, dtype=port.element_type.to_dtype())+ feed[name] = value+ outputs = request.infer(feed)+ assert_valid_logits(outputs[compiled.output("logits")])+ for value in outputs.values():+ assert np.isfinite(value).all()