Skip to content

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

[GGUF] Enable Cohere2, Gemma3n, Qwen3VL/Qwen3VL-MoE, Qwen3-ASR/TTS, EAGLE3 and DFlash (#39000)

Maxim Vafinf1d5dd64bfb9
diff --git a/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/decoder_options.hpp b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/decoder_options.hpp
index 92939db3f30..6bd06633ac1 100644
--- a/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/decoder_options.hpp
+++ b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/decoder_options.hpp
@@ -57,6 +57,7 @@ struct GGUF_FRONTEND_API DecoderScales {
bool token_embeddings_only = false;
float attention = 0.0f;
float attention_temperature = 0.0f;
+ float attention_value = 0.0f;
float attention_soft_cap = 0.0f;
float logits_soft_cap = 0.0f;
};
@@ -121,6 +122,13 @@ struct GGUF_FRONTEND_API DecoderLayerOverrides {
std::optional<bool> experts;
};
+struct GGUF_FRONTEND_API DecoderDraft {
+ bool norm_before_fc = false;
+ bool norm_before_residual = false;
+ std::vector<int32_t> target_layers;
+ int mask_token_id = 0;
+};
+
struct GGUF_FRONTEND_API DecoderParameters {
std::string architecture;
DecoderShape dimensions;
@@ -129,6 +137,9 @@ struct GGUF_FRONTEND_API DecoderParameters {
DecoderAttention attention;
DecoderExperts experts;
DecoderHybrid hybrid;
+ DecoderDraft draft;
+ bool parallel_ffn = false;
+ int deepstack_layers = 0;
FfnActivation activation = FfnActivation::SwiGlu;
bool embedding_model = false;
int pooling_type = 0;
diff --git a/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/tensor_table.hpp b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/tensor_table.hpp
index 8087701686e..c6bfc70cd56 100644
--- a/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/tensor_table.hpp
+++ b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/tensor_table.hpp
@@ -4,6 +4,9 @@
#pragma once
+#include <cstdint>
+#include <optional>
+#include <set>
#include <string>
#include "openvino/frontend/gguf/builder/value.hpp"
@@ -27,6 +30,10 @@ public:
// Check presence without emitting a graph node.
bool has(const std::string& gguf_name) const;
+ // Original on-disk GGUF type IDs, before conversion or weight repacking.
+ std::optional<uint32_t> source_type(const std::string& gguf_name) const;
+ std::set<uint32_t> source_types() const;
+
// Weight of layer `il` by suffix: layer(3, "attn_norm.weight") -> "blk.3.attn_norm.weight".
GgufValue layer(int il, const std::string& suffix) const;
diff --git a/src/frontends/gguf/docs/debugging_accuracy.md b/src/frontends/gguf/docs/debugging_accuracy.md
index a8215368bb8..c8ba0ff3aa0 100644
--- a/src/frontends/gguf/docs/debugging_accuracy.md
+++ b/src/frontends/gguf/docs/debugging_accuracy.md
@@ -26,7 +26,10 @@ may compute their expectations inline; see [operation tests](how_to_add_op.md#te
Record both revisions, checkpoint and quantization, input tensors or token history, device,
inference precision, activation quantization, and cache precision. Use reference-token replay
after a greedy choice differs; comparing later logits on different histories hides the cause.
-Coherent text is a functional check, not numerical acceptance.
+Coherent text alone is a smoke check. Use [WWB model validation](../../../../.claude/skills/ov-gguf/references/wwb.md)
+to compare quantized generated-text quality against the same original-weight floating
+reference for llama.cpp and GenAI. A quantized token/logit mismatch can remain a numerical
+diagnostic while the measured model is supported; WWB does not replace graph/API checks.
The same checkpoint does not imply the same arithmetic. Compare against both native quantized
CPU execution and, when needed, F32 arithmetic on the checkpoint's represented weights. Expanding
@@ -41,6 +44,20 @@ Agreement of the expansions with a discrepancy only in quantized execution impli
arithmetic; retain the original failed gate. A requantized fixture or a separately downloaded
F16 checkpoint cannot establish parity for the original model.
+For attention, record flash versus nonflash execution and intermediate rounding separately
+from KV storage precision. The pinned llama.cpp nonflash F16-cache path rounds queries
+before QK and softmax probabilities before PV, with F32 outputs. Compare an attention
+subgraph on identical Q/K/V and masks before attributing full-model drift to cache updates.
+Sparse gates followed by normalization can amplify a small attention discrepancy.
+
+Check that diagnostic casts survive compilation. Under CPU F32 inference, an ordinary
+F32-to-F16-to-F32 pair can be removed by precision conversion. Inspect the executed graph
+and observe a known half-rounded tensor; use `ov::disable_conversion` from
+`transformations/rt_info/disable_precision_conversion.hpp` on the narrowing Convert when
+the experiment requires it. A passing manual QK/softmax/PV decomposition does not establish
+a production fix: retain the original gate and verify stateful execution and
+SDPA-to-PagedAttention conversion before changing the frontend's attention path.
+
## Localize the failing boundary
1. **Inputs:** align tokenization, prompts, chat templates, masks, positions, and preprocessing.
diff --git a/src/frontends/gguf/docs/extensions.md b/src/frontends/gguf/docs/extensions.md
index a6d2ca80afb..96c6686b8d9 100644
--- a/src/frontends/gguf/docs/extensions.md
+++ b/src/frontends/gguf/docs/extensions.md
@@ -104,6 +104,13 @@ in a separate projector registry. It builds one vision or audio branch; the `cli
selects branches as described in [mmproj.md](mmproj.md#files-with-vision-and-audio-encoders), names
outputs `vision.embeddings` / `audio.embeddings` and finishes the model.
+Decoder builders declare GenAI adaptation through `parameters.model_contract`. The optional
+`supports_genai_adaptation` takes precedence over `genai.enabled`; `genai` also specifies
+multimodal positions, causal or context-prefix attention, preserved inputs and auxiliary output
+mappings. Logits are first by default; `genai.logits_first` can preserve legacy ordering.
+Extensions may override these choices without changing `AdaptToGenAI`. Models saved without
+the contract use the builder-owned legacy resolver.
+
A `ProjectorDefinition` has `id`, `architecture`, `modality` (`vision` or `audio`),
`projector_type`, `build` and optional `match`, `genai_layout` and `genai_adapter`. `build` appends to the shared `GgufGraphContext` and
returns `ProjectorResult`: the output and optional string configuration under the modality prefix.
@@ -163,6 +170,13 @@ adds built-in component groups only where the projector declared none; declared
batching, outputs and state prefixes are preserved. `build_builtin_projector()` also builds
`lfm3vl` (vision) and `lfm3a` (audio).
+A projector can declare equally sized feature blocks through string entries in
+`ProjectorResult.config`: `<modality>.embedding_output_count` gives the positive output count,
+and `<modality>.embedding_output.<index>` gives each nonempty, unique output name. These entries
+survive IR serialization and control generic output splitting. Built-in builders declare the
+standard feature names; the builder-owned resolver also handles legacy auxiliary-count metadata,
+or a single feature output if no count is present.
+
A custom `genai_adapter` runs for both `EMBEDDINGS` and `VISION_ENCODERS` after generic extraction
of the selected modality. It receives an independent model clone and returns `ModelAdapterResult`:
the primary graph in `model` and optional named graphs in `models`. It can replace the entire
diff --git a/src/frontends/gguf/docs/mmproj.md b/src/frontends/gguf/docs/mmproj.md
index 7ef20fd27db..6c4b547afd8 100644
--- a/src/frontends/gguf/docs/mmproj.md
+++ b/src/frontends/gguf/docs/mmproj.md
@@ -11,13 +11,38 @@ the regular decoder path.
audio branch. Built-in entries come from `projector_catalog` in
[`mmproj_builder.cpp`](../src/builder/arch/mmproj_builder.cpp) and from the LFM3 builder.
-| Modality | Projectors |
-|---|---|
-| Vision | `gemma3`, `idefics3`, `janus_pro`, `mlp`, `internvl`, `resampler`, `minicpmv4_6`, `minicpmv4_7`, `qwen2vl_merger`, `qwen2.5vl_merger`, `qwen3vl_merger`, `pixtral`, `phi4`, `lfm2`, `lfm3vl`, `gemma4v`, `gemma4uv`, `muse-glimmer`, `deepseekocr`, `deepseekocr2` |
-| Audio | `gemma4a`, `gemma4ua`, `lfm2a`, `lfm3a`, `qwen2a`, `ultravox`, `voxtral`, `musicflamingo`, `meralion`, `glma` |
-| Speech generation | `lfm3a_gen`; the LFM2.5 vocoder is a separate `lfm2.audio_vocoder` architecture |
-
-Not implemented: `ldp`, `ldpv2`, `adapter`, `step3vl`, `gemma3nv`, `llama4`, `qwen3a`,
+| Modality | Projector | Graph features |
+|---|---|---|
+| Vision | `gemma3`, `idefics3`, `janus_pro` | SigLIP; fused QKV and legacy FFN names |
+| Vision | `mlp` | CLIP feature layers; normalized variant detected from tensors |
+| Vision | `internvl` | InternViT, class token, pixel-shuffle merge |
+| Vision | `resampler` | MiniCPM-V resampler, `clip.minicpmv_version` 2-6 and 100045 |
+| Vision | `gemma3nv` | MobileNet stem, UIR, attention and multiscale feature branches; vision-only support |
+| Vision | `minicpmv4_6` | window attention, two-stage merging |
+| Vision | `minicpmv4_7` | window-attention and direct 2x2 merging; packed-patch GenAI layout |
+| Vision | `qwen2vl_merger`, `qwen2.5vl_merger`, `qwen3vl_merger` | temporal pairs, M-RoPE, windows (2.5), DeepStack (3) |
+| Vision | `pixtral` | 2D RoPE, patch merger, row separators |
+| Vision | `phi4` | dynamic resolution, resized positions |
+| Vision | `lfm2` | SigLIP, resized positions, pixel unshuffle, optional projector LayerNorm |
+| Vision | `lfm3vl` | temporal packed patches and streaming vision |
+| Vision | `gemma4v`, `gemma4uv` | two-axis positions, per-tensor clipping, pooling; unified patch normalization |
+| Vision | `muse-glimmer` | sparse/global windows, two-axis RoPE, pixel shuffle |
+| Vision | `deepseekocr`, `deepseekocr2` | SAM local/global attention, tiles, queries, view separators |
+| Audio | `gemma4a` | causal convolution, 12-position relative attention with softcap |
+| Audio | `gemma4ua` | raw 640-sample waveform frames |
+| Audio | `qwen3a` | Qwen3-ASR audio encoder |
+| Audio | `qwen3tts_spkenc` | speaker features |
+| Audio | `lfm2a`, `lfm3a` | LFM audio encoders |
+| Generated audio | `qwen3tts_gen` | code predictor and streaming codec |
+| Generated audio | `lfm3a_gen` | depthformer, feedback and codec components |
+| Audio | `qwen2a`, `ultravox`, `voxtral`, `musicflamingo`, `meralion`, `glma` | Whisper-derived encoders |
+
+The built-in `qwen3vl_merger` projector supports BF16 and Q8_0 weights.
+
+InternViT-6B (width 3200, 45 layers) uses RMS norms like the reference, but has no fixture.
+The LFM2.5 vocoder is a separate `lfm2.audio_vocoder` architecture.
+
+Not implemented: `ldp`, `ldpv2`, `adapter`, `step3vl`, `llama4`,
`kimivl`, `paddleocr`, `lightonocr`, `cogvlm`, `dots_ocr`, `glm4v`, `youtuvl`, `yasa2`,
`kimik25`, `nemotron_v2_vl`, `exaone4_5`, `hunyuanvl`, `granite_speech`, `mimovl`,
`granite4_vision`. An unsupported projector fails conversion of the whole file.
@@ -39,11 +64,27 @@ See [testing](testing.md) for commands and acceptance criteria.
## Files with vision and audio encoders
-One file may carry at most one vision and one audio encoder (for example Gemma4 and Qwen2.5-Omni).
-`clip.has_vision_encoder` / `clip.has_audio_encoder` select the encoders, and each takes its
-projector from `clip.projector_type` or the per-modality `clip.<modality>.projector_type`. The
-encoders become disconnected branches of one model: vision reads `v.*` tensors and `vision.*`
-inputs and produces `vision.embeddings`; audio uses `a.*`, `audio.*` and `audio.embeddings`.
+A projector file holds at most one vision and one audio encoder; Gemma4 E2B/E4B/12B files carry
+both. Conversion builds the file's supported encoders into one model:
+
+1. `clip.has_vision_encoder` and `clip.has_audio_encoder` select the encoders. A file with
+ neither fails conversion unless the file declares supported speech-generation components.
+2. Each encoder takes its projector from the global `clip.projector_type`, or else from
+ `clip.vision.projector_type` / `clip.audio.projector_type`. A combined file therefore uses the
+ per-modality keys; only the legacy `qwen2.5o` resolves to a different projector per modality
+ (Qwen2.5 VL vision, Qwen2 audio). An unsupported projector fails conversion of the whole file,
+ except for the combined Gemma3n `gemma3nv` vision / `gemma3na` audio pair. As in the reference,
+ this pair builds only vision when no registered extension handles its audio branch.
+3. The encoders become disconnected branches of the same graph. Vision reads `v.*` tensors and
+ `vision.*` inputs and produces `vision.embeddings`; audio reads `a.*` tensors and `audio.*`
+ inputs and produces `audio.embeddings`.
+4. `gguf_mmproj` rt_info records each encoder's `<modality>.projector` and `<modality>.merge`.
+ The omitted Gemma3n audio branch retains `audio.projector=gemma3na` and
+ `audio.supported=false`; both fields survive serialization, and GenAI adaptation skips the
+ unsupported audio branch while returning the vision encoder.
+
+Running the combined model requires the inputs of both branches. `AdaptMmprojToGenAI` (below)
+turns it into one encoder; apply it to a clone per modality to obtain both.
Declared speech-generation components are built into the same model.
## Graph boundary
@@ -147,6 +188,11 @@ per-layer inputs. These passes expose graph contracts; they do not construct tok
preprocessing or a complete GenAI pipeline. GenAI uses an F16 KV cache for GGUF multimodal models
to match llama.cpp, unless cache precision is set explicitly.
+`gemma3nv` exposes `pixel_values`; `qwen3a` and `qwen3tts_spkenc` expose `features` in the
+native audio layout. These adapted graphs require consumer support: GenAI's GGUF VLM integration
+does not yet accept these projector pairings, and its existing Qwen3 audio encoder uses a different
+input interface.
+
## Speech generation components
Builders declare speech components in `ModelContract::component_groups["audio_generation"]`,
@@ -155,14 +201,23 @@ audio groups describe their encoders the same way, so adaptation also works afte
unadapted IR. The adapter keeps only the selected component's state and prunes other branches.
For LFM3, `lfm3a_gen` provides `depthformer`, `feedback` and `codec` models; sampling and
waveform reconstruction belong to the caller.
+Qwen3TTS `qwen3tts_gen` provides `predictor` and `codec` models. The codec keeps its
+`gen_audio.state_in.*` and `gen_audio.state_out.*` tensors as explicit streaming inputs and outputs.
### LFM2 audio components
LFM2.5 Audio uses the `lfm2a` encoder for audio input and the standalone `lfm2.audio_vocoder`
GGUF (depthformer, feedback and codec) for speech output; the publisher's architecture string is
-normalized on load. The vocoder is checked against pinned publisher PyTorch fixtures. GenAI
-supplies waveform preprocessing and speech reconstruction in the `gguf-frontend-mmproj`
-integration. Older Mimi-based LFM2 speech output is not supported.
+normalized on load. The encoder takes `audio.features` `[1,1,mel_bins,frames]` and
+`audio.pos_emb` `[1,1,2*ceil(frames/8)-1,encoder_width]`; its adapter exposes
+`audio_features` `[1,tokens,hidden]`. The vocoder exposes `audio.depth_logits`, `audio.feedback`,
+`audio.codec_features` and `audio.istft_window`.
+
+The Q4_0 encoder matches represented-F32 references with NMSE `3.81e-10` and `2.35e-9`.
+The vocoder is checked against pinned publisher PyTorch fixtures; Q4_0 depthformer and
+detokenizer represented-F32 comparisons have NMSE `2.62e-12` and `1.32e-9`. GenAI supplies
+waveform preprocessing and speech reconstruction in the `gguf-frontend-mmproj` integration.
+Older Mimi-based LFM2 speech output is not supported.
## Known limitations
@@ -189,7 +244,6 @@ do not indicate an mmproj integration regression.
## Projector extensions
-Use [ProjectorExtension](extensions.md#extend-mmproj-with-a-projector-component) to add or
-replace one vision/audio branch under the `clip` coordinator; the
-[examples](../examples/architecture_extension/README.md) build and run one. A different
-whole-model format needs an `ArchitectureExtension`.
+Use [ProjectorExtension](extensions.md#extend-mmproj-with-a-projector-component) to add or replace one
+vision/audio branch under the `clip` coordinator; the [examples](../examples/architecture_extension/README.md)
+build and run one. A different whole-model format needs an `ArchitectureExtension`.
diff --git a/src/frontends/gguf/docs/quantization.md b/src/frontends/gguf/docs/quantization.md
index 6cef246c113..31444c535db 100644
--- a/src/frontends/gguf/docs/quantization.md
+++ b/src/frontends/gguf/docs/quantization.md
@@ -9,6 +9,24 @@ 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).
+## Preparing an F32 reference
+
+Use F32 to isolate graph correctness from quantized arithmetic differences for
+[supported families](supported_models.md#native-gguf-path).
+Quantized formats remain supported when their F32/F16 reference path works; known
+accuracy differences are documented separately. Convert from the original Hugging Face checkpoint with llama.cpp's
+`convert_hf_to_gguf.py --outtype f32`. This creates a separate checkpoint format.
+For an existing GGUF, exact F32 materialization must preserve metadata, tensor names
+and shapes; decode every tensor using its GGML type, write F32 payloads, and set
+`general.file_type=0`. Verify the output tensor inventory and finite values before
+using it. A filename ending in `f32` or a file-type metadata edit does not convert weights.
+
+Materializing a quantized GGUF preserves its represented values; it cannot recover
+information lost during the original quantization. Record both file hashes and test
+the new file against its own llama.cpp reference. Original quantized-checkpoint
+failures remain separate. F32 increases disk and compilation memory, especially
+for models with many experts.
+
## Storage and graph conventions
The loader retains one raw descriptor per original tensor, including its logical shape,
@@ -97,7 +115,7 @@ The type columns describe extracted tensors; their decompression or Convert outp
| MXFP4 | 32 | 17 | `f4e2m1` | `f8e8m0` | — | `16 + 1` = 17 | 0% |
Ordinary native Q4_1/Q4_K matrix weights use integer zero points by default.
-Ordinary native Q5_K matrix weights use symmetric i8 with one F16 scale per 32 weights
+Ordinary native Q5_K matrix weights use symmetric i8 by default, with one F16 scale per 32 weights
and no zero point. Source values are decoded and requantized using the group maximum
absolute value; this adds rounding error and changes the grid from the former asymmetric u8
representation. Conversion uses a 256-value scratch buffer per source block. The converted
@@ -105,7 +123,7 @@ weight/scale payload is 2.86% smaller than the former u8/integer-zero-point payl
Group size remains 32 for all devices.
`token_embd.weight` and `output.weight` use fractional zero points for these affine formats;
Q5_1 and Q2_K also use fractional zero points. See [accuracy controls](#accuracy-controls)
-to select fractional zero points for all Q4_1/Q4_K tensors.
+to select fractional zero points for all Q4_1/Q4_K/Q5_K tensors.
Q2_0 uses a `u8` zero point of 1. PQ2_0/PTQ1_0 use F16 zero points of 1,
including embeddings.
The frontend prints an accuracy notice once per process for each requantization approximation.
@@ -357,8 +375,8 @@ compiled = core.compile_model(model, "CPU", {
})
```
-Set `OV_GGUF_Q4_K_ZP_F16=1` **before starting the process** to preserve fractional Q4_K/Q4_1
-zero points instead of their default u4 requantization. It is cached on first use; changing the
+Set `OV_GGUF_Q4_K_ZP_F16=1` **before starting the process** to preserve fractional Q4_K/Q4_1/Q5_K
+zero points instead of their default u4/u8 or symmetric i8 requantization. It is cached on first use; changing the
environment later in a notebook does not switch an already initialized process. The option
does not make every quantized format lossless or guarantee device support for fractional zero points.
@@ -384,6 +402,14 @@ During compilation a device may fuse decompression into its matrix kernel, reord
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.
+Plain F16/BF16 expert constants use `GatherMatmul`, avoiding a per-token copy of
+the selected expert weights. CPU compilation may expand the entire expert tensor
+to F32, doubling its payload relative to the original half-precision storage.
+On GPUs without systolic support, these layers cannot compile. On supported GPUs,
+an explicit F32 inference precision hint may also fail; lower-precision execution
+can round differently from F32.
+See [internal-op serialization limits](runtime.md#internal-operations-and-serialization).
+
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/runtime.md b/src/frontends/gguf/docs/runtime.md
index 2faea1b5580..7c7e1826e45 100644
--- a/src/frontends/gguf/docs/runtime.md
+++ b/src/frontends/gguf/docs/runtime.md
@@ -95,17 +95,22 @@ interface. Select the mode with `GenAIAdaptOptions::input`:
| Mode | Inputs | Output |
|---|---|---|
-| `IDS_TO_LOGITS` (default) | `input_ids [B,T]`, `attention_mask [B,KV]`, `position_ids [B,T]`, `beam_idx [B]` | `logits [B,T,vocab]` |
-| `EMBEDS_TO_LOGITS` | `inputs_embeds [B,T,D]` instead of `input_ids`; see [multimodal language models](mmproj.md#using-the-encoders-and-a-language-model) | `logits [B,T,vocab]` |
+| `IDS_TO_LOGITS` (default) | `input_ids [B,T]`, `attention_mask [B,KV]`, `position_ids [B,T]`, `beam_idx [B]` | `logits [B,N,vocab]` |
+| `EMBEDS_TO_LOGITS` | `inputs_embeds [B,T,D]` instead of `input_ids`; see [multimodal language models](mmproj.md#using-the-encoders-and-a-language-model) | `logits [B,N,vocab]` |
`EMBEDS_TO_LOGITS` also returns the token lookup as `text_embeddings` and, for architectures with
per-layer token embeddings, `text_embeddings_per_layer`.
+- The number of output rows `N` depends on the model and attention backend. Standard SDPA decoders
+ generally select the last token per sequence; PagedAttention can expose a row for each token.
- The leading dimensions are derived from the live inputs, so one graph serves both SDPA and
`ov::pass::SDPAToPagedAttention`.
- The LM head is connected directly to the logits Result with a rank-3 input, so GenAI's
slice-before-matmul optimization projects only the sampled rows during prefill.
+ A scalar output scale is moved to the activation input when the head has no other consumers;
+ softcap output chains remain recognizable without expanding compressed weights.
- Sliding-window masks use the `gguf_swa_window_size` rt_info value when the file records a window length.
+ Noncausal sliding-window attention is not supported by GenAI adaptation.
- Gated-DeltaNet states (`qwen35`, `qwen35moe`) and LFM2 short-convolution states
(`lfm2`, `lfm2moe`) get a dynamic batch, follow `beam_idx` and mask
left padding. Mamba 2 and `nemotron_h` states stay at one sequence: greedy, batch-1 decoding only.
diff --git a/src/frontends/gguf/docs/supported_models.md b/src/frontends/gguf/docs/supported_models.md
index 7396dffc80d..117426c22ec 100644
--- a/src/frontends/gguf/docs/supported_models.md
+++ b/src/frontends/gguf/docs/supported_models.md
@@ -20,23 +20,27 @@ Tested models list real checkpoints and their quantization. `—` means no check
| Architecture | Tested model | Notes |
|---|---|---|
-| `afmoe` | Trinity-Nano-Preview BF16 | Dense lead, routed/shared experts, sigmoid gating, pre/post norms, three sliding layers then one global NoPE layer; F32 oracle fixture |
+| `afmoe` | Trinity-Nano-Preview BF16 | Dense lead, routed/shared experts, sigmoid gating, pre/post norms, three sliding layers then one global NoPE layer |
| `bailingmoe2` | Ling-mini-2.0 Q2_K | Sigmoid routing, biased/grouped selection, shared experts |
+| `cohere2` | c4ai-command-r7b-12-2024 Q4_0 | Parallel LayerNorm attention/FFN; RoPE on local layers |
| `deepseek2-ocr` | DeepSeek-OCR-2 Q4_K_M | Language backbone: dense lead layers, shared/routed experts |
+| `dflash` | Qwen3.6-35B-A3B Q4_K_M / DFlash BF16 | Context-only cache commits, noncausal noise block, optional post-norms/scales and shared V |
+| `eagle3` | Qwen3-8B Q8_0 / EAGLE3 F16 | Target feature fusion, optional pre-FC/residual norms and vocabulary mapping |
| `ernie4_5-moe` | ERNIE-4.5-21B-A3B-PT Q4_K_M | Interleaved MoE, biased selection, normalized weights, shared experts |
| `exaone-moe` | K-EXAONE-236B-A23B Q2_K | Dense lead, shared/routed experts, RoPE on SWA layers only |
| `exaone4` | EXAONE-4.0-1.2B Q4_K_M | Post-norm-only attention and FFN |
| `gemma` | gemma-2b Q4_K_M | GeGLU, multi-query attention |
| `gemma2` | gemma-2-2b-it Q4_K_M | Post-norms, SWA, attention and final soft-caps |
| `gemma3` | gemma-3-1b-it Q4_0 | Post-norms, final soft-cap, separate global/local RoPE scaling |
+| `gemma3n` | Gemma3n E2B Q4_0 | AltUp, Laurel, sparse FFN, per-layer embeddings and shared KV |
| `gemma4` | gemma-4-E2B-it Q4_0 | SWA, per-layer embeddings, shared KV, dense plus routed experts |
| `glm4moe` | GLM-4.5-Air REAP50 Q2_K | Biased sigmoid selection, shared experts, optional QK-norm |
-| `gpt-oss` | gpt-oss-20b Q4_0 | MoE, attention sinks, SWA, OAI gated activation; **no numerical fixture**; CPU expands MXFP4 experts to F32 at compile time (about 120 GiB for 20B) |
+| `gpt-oss` | gpt-oss-20b Q4_0 | MoE, attention sinks, SWA, OAI gated activation; CPU expands MXFP4 experts to F32 at compile time (about 120 GiB for 20B) |
| `hunyuan-dense` | Hunyuan-0.5B-Instruct Q8_0 | Learned QK-norm after RoPE |
| `hunyuan-moe` | Hunyuan-A13B-Instruct Q2_K | QK-norm after RoPE, routed and shared experts |
| `jais2` | Jais-2-8B-Chat Q4_K_M | Biased LayerNorm, ungated ReLU² FFN |
| `lfm2` | LFM2-350M / LFM2.5-1.2B-Instruct Q4_0 | LFM2 / LFM2.5 dense hybrid short convolution and GQA, QK-norm, tied head |
-| `lfm2.audio_vocoder` | LFM2.5-Audio-1.5B Q4_0 ([component parity](mmproj.md#lfm2-audio-components)) | Standalone speech component; accepts the existing publisher architecture string |
+| `lfm2.audio_vocoder` | LFM2.5-Audio-1.5B Q4_0 ([audio components](mmproj.md#lfm2-audio-components)) | Standalone speech component; accepts the existing publisher architecture string |
| `lfm2moe` | LFM2.5-8B-A1B Q4_0 | LFM2 / LFM2.5 MoE hybrid, dense lead, biased normalized expert routing |
| `lfm3` | LFM3-1.7B / LFM3-VL-2B / LFM3-Audio-2B / LFM3-Omni-2B Q4_0 | Dense hybrid convolution/GQA, per-head output gates, paired optional post norms, tied output, mixed full/sliding RoPE |
| `llama` | Devstral Small 2507 24B Q4_K_M | llama-2 / llama-3, YaRN |
@@ -45,7 +49,7 @@ Tested models list real checkpoints and their quantization. `—` means no check
| `mamba2` | Mamba2-2.7B Q8_0 | Mamba 2 mixer, tied or separate output; one-sequence greedy decoding |
| `mellum` | Mellum2-12B-A2.5B-Instruct Q4_K_M | MoE with normalized expert weights |
| `minicpm` | MiniCPM-2B-sft Q4_0 | Embedding/residual scales, inverse logit scale |
-| `minimax-m2` | MiniMax-M2.1-REAP-50 Q2_K | Full-width QK-norm, partial RoPE, normalized experts |
+| `minimax-m2` | MiniMax-M2.1-REAP-50 Q2_K | Full-width QK-norm, partial RoPE, normalized experts; see [memory limits](quantization.md#memory-and-packaging-limits) |
| `mistral3` | Devstral Small 2 24B; Ministral-3-3B-Instruct-2512 Q4_K_M | Dense, NORMAL RoPE, attention temperature |
| `muse-glimmer` | Muse-Glimmer-30B Q4_0 | RoPE on SWA layers, attention output gate, pre/post norms |
| `nemotron_h` | Nemotron-H-8B-Reasoning-128K Q4_K_M | Hybrid Mamba 2 / attention / ReLU² FFN; one-sequence greedy decoding |
@@ -54,22 +58,14 @@ Tested models list real checkpoints and their quantization. `—` means no check
| `plamo3` | plamo-3-nict-2b-base Q4_K_M | Fused QKV and gate/up, bare post-norms, SWA |
| `qwen2` | Qwen2.5-0.5B-Instruct Q4_0 | qwen2 / qwen2.5 |
| `qwen3` | Qwen3-0.6B Q4_0 | QK-norm before RoPE |
+| `qwen3tts` | Qwen3TTS represented F32 | Speech decoder; projector and codec are separate components |
| `qwen35` | Qwen3.5-4B Q4_0; Ternary-Bonsai-2-27B PQ2_0 | Hybrid GatedDeltaNet + attention, interleaved M-RoPE, folded Hadamard weights; batching and beam search with SDPA and PA |
| `qwen35moe` | Qwen3.6-35B-A3B Q4_K_M / Q4_0 | Hybrid GatedDeltaNet, separate or fused routed experts, shared expert |
| `qwen3moe` | Qwen3-0.9B-A0.6B Q4_K_M | NEOX RoPE, per-head QK-norm, normalized experts |
+| `qwen3vl` | Qwen3-VL-2B Q4_0 | Interleaved multimodal RoPE and DeepStack inputs |
+| `qwen3vlmoe` | Qwen3-Omni-30B-A3B Q4_K_M | Multimodal RoPE and routed experts |
| `smollm3` | SmolLM3-3B Q4_K_M | NORMAL RoPE, skipped on every fourth layer |
-### Numerical regression coverage
-
-[`GGUFArchitectureAccuracy`](../tests/test_arch_accuracy.cpp) runs 40 small nonzero F32 decoder
-fixtures (every decoder above except `gpt-oss`, plus Devstral YaRN/temperature, Gemma4 MQA/MoE/PLE,
-Qwen3.5 mixed and fused variants) and `GGUFEmbeddingAccuracy` five embedding fixtures. Each compares
-complete logits with llama.cpp CPU through prefill, decode and a two-token cache append. Fixtures
-cover sliding-window boundaries, SmolLM3's NoPE layer, ERNIE without `expert_shared_count` and
-Bailing grouped routing; see the [fixture README](../tests/test_data/arch_accuracy/README.md).
-`GGUFMultimodalBackboneAdaptation` checks padded batches, beam reordering and PagedAttention for
-`qwen35`, `qwen35moe` and `gemma4`. Zero-weight fingerprints add structural coverage.
-
### Runtime limitations
- **Recurrent states:** Gated-DeltaNet states support batching and beams through `AdaptToGenAI`;
@@ -98,13 +94,7 @@ Manually validated with the backend's stateful execution:
These runs record no llama.cpp revision. [llama.cpp compatibility CI](../../../../.github/workflows/job_gguf_llamacpp_validation.yml)
pins the backend revision and runs its operator tests plus state scenarios on generated
-`llama`, `qwen2` and `qwen3` models only. A run passes when the output is coherent and consistent
-with the ggml CPU backend:
-
-```sh
-GGML_OPENVINO_DEVICE=CPU GGML_OPENVINO_STATEFUL_EXECUTION=1 \
- llama-completion -m <model>.gguf -p "The capital of France is" -n 12 -no-cnv --no-warmup
-```
+`llama`, `qwen2` and `qwen3` models only.
Checkpoints used `Q2_K`, `Q4_0`, `Q4_K_M`, `Q6_K` and `Q8_0`; other formats are covered by unit tests only.
@@ -119,22 +109,6 @@ LFM2.5 8B-A1B and LFM2 24B-A2B use the same MoE builder; the 24B checkpoint has
replayed. LFM2-VL and LFM2.5-VL language backbones use `lfm2`; their separate SigLIP vision
projector is covered in [mmproj.md](mmproj.md).
-Six nonzero F32 llama.cpp fixtures cover mixed layer order, tied heads, a sliding-window
-boundary, fused QKV, dense-leading MoE, and all-routed sigmoid MoE. They compare full logits
-through prefill, cached one/multiple-token decode, and state reset with NMSE below `1e-5`.
-Batching, left padding, beam reordering, injected embeddings and structural conversion to
-PagedAttention/PagedCausalConv1D are covered separately. This does not establish a GenAI
-multimodal application or audio generation pipeline.
-
-Real CPU reference-token replay uses llama.cpp `03fa73cb27f5c251b9528489b18d303b1366aca4`,
-F32 inference, F16 KV, and disabled activation quantization. The prompt is
-`The capital of France is`. Quantized-CPU logit NMSE ranges are `2.32e-4..6.20e-3` for
-LFM2-350M, `3.99e-4..1.45e-3` for LFM2.5-1.2B-Instruct, and `2.98e-4..8.17e-2` for
-LFM2.5-8B-A1B. These pass the real-checkpoint greedy-choice gate above, not the F32
-fixture NMSE gate. Checkpoint revisions are `8fdc9d526b7ed346b19257551b05816c7912ecc2`,
-`8ed288026e23958ad9dfa92d53ed773a8eee7125`, and
-`49c14831707011e64d70b2ebd8462ba08d608434`, respectively, from LiquidAI's GGUF repositories.
-
The standalone `lfm2.audio_vocoder` architecture loads LFM2.5 Audio depthformer and
codec components; the existing publisher architecture string is also accepted.
It consumes hidden states and codec codes rather than text tokens; see
diff --git a/src/frontends/gguf/docs/testing.md b/src/frontends/gguf/docs/testing.md
index 185eb713fc4..72c89c647f3 100644
--- a/src/frontends/gguf/docs/testing.md
+++ b/src/frontends/gguf/docs/testing.md
@@ -9,6 +9,7 @@ This Linux single-configuration example puts binaries and libraries in an explic
```sh
cmake -S . -B build-gguf -DCMAKE_BUILD_TYPE=Release \
-DENABLE_OV_GGUF_FRONTEND=ON -DENABLE_TESTS=ON -DBUILD_SHARED_LIBS=ON \
+ -DCMAKE_COMPILE_WARNING_AS_ERROR=ON \
-DCMAKE_RUNTIME_OUTPUT_DIRECTORY="$PWD/build-gguf/bin" \
-DCMAKE_LIBRARY_OUTPUT_DIRECTORY="$PWD/build-gguf/bin"
cmake --build build-gguf --target ov_gguf_frontend_tests ov_gguf_architecture_library_tests --parallel
@@ -36,6 +37,11 @@ Use `--gtest_list_tests` for exact parameterized names; filter while iterating,
runs in environment teardown, so inspect the process exit status even if no individual test failed.
Shared changes require the affected architecture/projector numerical and structural regressions.
+The Cohere2 and Gemma3n PagedAttention parity tests require FP16 KV caches and skip on ARM64,
+whose CPU PagedAttention executor does not support that cache precision. Their architecture
+conversion and stateful SDPA tests still run there. FP32-cache ARM64 PA equivalence is not
+established by these tests.
+
`GGUFShards` covers discovery from either shard, unordered explicit lists, renamed files in
different directories, metadata-only first shards, mapping lifetime, invalid or incomplete
shard sets, repeated scalar/array metadata, and conversion equivalence with a single-file model,
@@ -122,9 +128,15 @@ Keep registration, structural conversion, numerical agreement, and application f
as separate evidence. A new architecture needs a nonzero oracle fixture and a real-checkpoint
comparison; exercise relevant positions, sizes, cache appends/resets, and adaptation paths.
-| Check | Acceptance and limit |
+For each model architecture, a working F32/F16 reference path establishes
+architecture support. Implemented quantized formats remain enabled even when their
+checkpoint comparison falls below the numerical or greedy agreement thresholds.
+Record those failed comparisons as accuracy limitations; do not relabel them as
+parity passes. Unsupported tensor encodings and graph/runtime errors remain failures.
+
+| Check | Numerical parity threshold and limit |
|---|---|
-| Native decoder F32 fixture | Full-logit normalized MSE below `1e-5`; F32 inference, F16 KV, activation quantization disabled |
+| Native decoder F32 fixture | Full-logit normalized MSE below `1e-5`; Gemma3n uses `2e-5` (`3e-4` on ARM64) with every-step greedy equality; F32 inference, F16 KV, activation quantization disabled |
| Native real decoder replay | Same first prediction and at least 90% matching greedy choices over prefill plus 12 reference-token steps; record full-logit errors |
| mmproj fixture | Raw and adapted embeddings, normalized MSE below `1e-5`; dynamic cases reuse one compiled model |
| mmproj real checkpoint | CPU NMSE below `1e-5` unless an explicit model-list override documents the reason; other devices are not calibrated to the CPU limit |
diff --git a/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hpp
index 5d6f5f11560..7e7788b9093 100644
--- a/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hpp
+++ b/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hpp
@@ -31,11 +31,32 @@ struct ModelComponentGroup {
std::map<std::string, ModelComponentContract> models;
};
+// Define this outside ModelContract so Clang can instantiate std::optional.
+struct ModelGenAIContract {
+ enum class PositionLayout { THREE_AXIS, SEQUENCE_THREE_AXIS };
+ struct AuxiliaryOutput {
+ std::string source_tensor;
+ std::string name;
+ std::optional<int64_t> squeeze_axis;
+ };
+
+ bool enabled = true;
+ PositionLayout position_layout = PositionLayout::SEQUENCE_THREE_AXIS;
+ bool causal_attention = true;
+ std::string attention_context_input;
+ std::vector<AuxiliaryOutput> auxiliary_outputs;
+ std::vector<std::string> preserved_inputs;
+ bool logits_first = true;
+};
+
struct ModelContract {
enum class ImageAttentionMode { CAUSAL, GLOBAL_AND_SLIDING, SLIDING_ONLY };
+ using GenAIContract = ModelGenAIContract;
+
std::optional<bool> batchable_recurrent;
ImageAttentionMode image_attention = ImageAttentionMode::CAUSAL;
+ std::optional<GenAIContract> genai;
std::vector<std::string> sequence_outputs;
std::map<std::string, ModelComponentGroup> component_groups;
std::optional<bool> supports_genai_adaptation;
diff --git a/src/frontends/gguf/src/builder/api/tensor_table.cpp b/src/frontends/gguf/src/builder/api/tensor_table.cpp
index edc9a081c5d..e7804415ff1 100644
--- a/src/frontends/gguf/src/builder/api/tensor_table.cpp
+++ b/src/frontends/gguf/src/builder/api/tensor_table.cpp
@@ -9,7 +9,6 @@
#include "openvino/frontend/gguf/builder/graph_context.hpp"
#include "openvino/frontend/gguf/builder/model_builder.hpp"
#include "openvino/frontend/gguf/builder/value.hpp"
-#include "openvino/util/common_util.hpp"
namespace ov::frontend::gguf {
@@ -31,6 +30,21 @@ bool GgufTensors::has(const std::string& gguf_name) const {
return (*m_ctx->m_impl).emitter.has_weight(gguf_name);
}
+std::optional<uint32_t> GgufTensors::source_type(const std::string& gguf_name) const {
+ const auto& weights = m_ctx->m_impl->build_ctx.weights->weights;
+ const auto found = weights.find(gguf_name);
+ if (found == weights.end())
+ return std::nullopt;
+ return static_cast<uint32_t>(found->second.qtype);
+}
+
+std::set<uint32_t> GgufTensors::source_types() const {
+ std::set<uint32_t> types;
+ for (const auto& entry : m_ctx->m_impl->build_ctx.weights->weights)
+ types.insert(static_cast<uint32_t>(entry.second.qtype));
+ return types;
+}
+
GgufValue GgufTensors::operator()(const std::string& gguf_name) const {
auto& impl = (*m_ctx->m_impl);
auto& e = impl.emitter;
@@ -38,13 +52,8 @@ GgufValue GgufTensors::operator()(const std::string& gguf_name) const {
return GgufValue();
}
impl.check_open();
- if (!e.weight_emitted(gguf_name)) {
- if (ov::util::ends_with(gguf_name, ".weight")) {
- e.add_weight(gguf_name);
- } else {
- e.add_weight(gguf_name);
- }
- }
+ if (!e.weight_emitted(gguf_name))
+ e.add_weight(gguf_name);
return GgufValue(gguf_name, e.value(gguf_name));
}
diff --git a/src/frontends/gguf/src/builder/arch/decoder_builder.cpp b/src/frontends/gguf/src/builder/arch/decoder_builder.cpp
index e3897f73516..642080dfa9a 100644
--- a/src/frontends/gguf/src/builder/arch/decoder_builder.cpp
+++ b/src/frontends/gguf/src/builder/arch/decoder_builder.cpp
@@ -16,18 +16,34 @@
#include "builder/arch/decoder_builder.hpp"
#include <cmath>
+#include <limits>
#include "builder/api/metadata_store.hpp"
#include "builder/blocks/common.hpp"
#include "builder/blocks/ffn.hpp"
#include "builder/blocks/gated_delta_net.hpp"
+#include "openvino/op/add.hpp"
+#include "openvino/op/broadcast.hpp"
+#include "openvino/op/concat.hpp"
#include "openvino/op/constant.hpp"
+#include "openvino/op/divide.hpp"
#include "openvino/op/gather.hpp"
+#include "openvino/op/gelu.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/multiply.hpp"
#include "openvino/op/parameter.hpp"
#include "openvino/op/reduce_mean.hpp"
+#include "openvino/op/reduce_sum.hpp"
+#include "openvino/op/relu.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/scatter_update.hpp"
#include "openvino/op/shape_of.hpp"
+#include "openvino/op/slice.hpp"
+#include "openvino/op/sqrt.hpp"
#include "openvino/op/squeeze.hpp"
#include "openvino/op/subtract.hpp"
+#include "openvino/op/tanh.hpp"
+#include "openvino/op/transpose.hpp"
namespace ov::frontend::gguf {
@@ -45,6 +61,26 @@ DecoderBuilder::DecoderBuilder(const BuildContext& context, const DecoderParamet
m_emit(context.weights->weights, context.arch, context.weights->translators),
m_kv(blocks::KvCachePlan::build(m_cfg)) {
m_cfg.configure_graph(m_emit, context.metadata);
+ auto& graph = *m_emit.graph();
+ if (m_cfg.arch == "eagle3" || m_cfg.arch == "dflash") {
+ const auto& captures = m_cfg.draft_target_layers;
+ OPENVINO_ASSERT(!captures.empty(), "[GGUF] draft target_layers must not be empty");
+ if (m_cfg.arch == "eagle3") {
+ OPENVINO_ASSERT(captures.size() == 3, "[GGUF] Eagle3 requires three target layers");
+ graph.model_rt_info["eagle3_mode"] = true;
+ graph.model_rt_info["hidden_layers_list"] = captures;
+ } else {
+ graph.model_rt_info["dflash_mode"] = true;
+ ov::AnyMap info;
+ std::string layers;
+ for (const auto layer : captures)
+ layers += (layers.empty() ? "" : ",") + std::to_string(layer - 1);
+ info["target_layer_ids"] = layers;
+ info["mask_token_id"] = std::to_string(m_cfg.draft_mask_token_id);
+ info["candidate_position_offset"] = "0";
+ graph.model_rt_info["dflash"] = info;
+ }
+ }
}
void DecoderBuilder::build_inputs() {
@@ -79,8 +115,17 @@ void DecoderBuilder::build_inputs() {
}
std::string DecoderBuilder::build_embeddings() {
- // GET_ROWS(token_embd.weight, inp_tokens) -> "embd"
- m_emit.add_weight("token_embd.weight");
+ if ((m_cfg.arch == "eagle3" || m_cfg.arch == "dflash") && !m_emit.has_weight("token_embd.weight")) {
+ auto weight = std::make_shared<ov::op::v0::Parameter>(f32, ov::PartialShape{-1, m_cfg.n_embd});
+ weight->set_friendly_name("gguf.target_token_embedding");
+ weight->output(0).set_names({"gguf.target_token_embedding"});
+ m_emit.add_extra_input_node("token_embd.weight", weight);
+ if (auto& genai = m_emit.graph()->model_contract.genai)
+ genai->preserved_inputs.push_back("gguf.target_token_embedding");
+ } else {
+ // GET_ROWS(token_embd.weight, inp_tokens) -> "embd"
+ m_emit.add_weight("token_embd.weight");
+ }
std::string cur = m_emit.add_op("GGML_OP_GET_ROWS", "embd", {"token_embd.weight", "inp_tokens"});
// The tagged node ends the lookup that AdaptToGenAI moves into the embedding model.
const auto mark_token_embedding = [&](const std::string& name) {
@@ -285,8 +330,13 @@ std::string DecoderBuilder::build_layer(int il, const std::string& layer_in) {
auto ffn_inp = m_emit.add_op("GGML_OP_ADD", p + "ffn_inp", {ao, sa});
// Pre-FFN/MoE norm. Key varies by arch (ffn_norm_key is resolved in DecoderConfig).
- auto ffn_norm =
- m_cfg.post_norm_only ? ffn_inp : norm(m_emit, ffn_inp, p + m_cfg.ffn_norm_key, p + "ffn_norm", m_cfg.rms_eps);
+ auto ffn_norm = m_cfg.parallel_ffn ? attn_norm
+ : m_cfg.post_norm_only
+ ? ffn_inp
+ : norm(m_emit, ffn_inp, p + m_cfg.ffn_norm_key, p + "ffn_norm", m_cfg.rms_eps);
+ if (m_cfg.parallel_ffn && selects_output_rows(il)) {
+ ffn_norm = m_emit.add_op("GGML_OP_GET_ROWS", p + "ffn_norm_g", {ffn_norm, "inp_out_ids"});
+ }
// Hybrid MoE: lead layers (il < n_dense_lead) are always dense regardless of is_moe.
const bool is_moe_layer = m_cfg.layer_is_moe(il);
@@ -322,6 +372,14 @@ std::string DecoderBuilder::build_head(const std::string& in) {
// final norm + lm_head
const auto norm = m_cfg.layer_norm ? blocks::layer_norm : blocks::rms_norm;
std::string cur = norm(m_emit, in, "output_norm.weight", "result_norm", m_cfg.rms_eps);
+ if (m_cfg.arch == "qwen3tts") {
+ const auto hidden = "qwen3tts.hidden_states";
+ m_emit.add_op("GGML_OP_SCALE", hidden, {cur}, 0, {{"scale", 1.f}, {"bias", 0.f}});
+ ov::Output<ov::Node>(m_emit.value(hidden)).set_names({hidden});
+ m_emit.graph()->model_output_names.push_back(hidden);
+ if (auto& genai = m_emit.graph()->model_contract.genai)
+ genai->auxiliary_outputs.push_back({hidden, "last_hidden_state", 1});
+ }
if (m_cfg.embedding_model) {
using namespace ov::op;
auto embeddings = m_emit.value(cur);
@@ -345,24 +403,62 @@ std::string DecoderBuilder::build_head(const std::string& in) {
return "embeddings";
}
- const std::string lm_head_w = m_emit.has_weight("output.weight") ? "output.weight" : "token_embd.weight";
- m_emit.add_weight(lm_head_w);
+ const bool draft = m_cfg.arch == "eagle3" || m_cfg.arch == "dflash";
+ const std::string lm_head_w = m_emit.has_weight("output.weight") || draft ? "output.weight" : "token_embd.weight";
+ if (draft && !m_emit.has_weight(lm_head_w)) {
+ auto weight = std::make_shared<ov::op::v0::Parameter>(f32, ov::PartialShape{-1, m_cfg.n_embd});
+ weight->set_friendly_name("gguf.target_lm_head");
+ weight->output(0).set_names({"gguf.target_lm_head"});
+ m_emit.add_extra_input_node(lm_head_w, weight);
+ if (auto& genai = m_emit.graph()->model_contract.genai)
+ genai->preserved_inputs.push_back("gguf.target_lm_head");
+ } else {
+ m_emit.add_weight(lm_head_w);
+ }
auto logits = m_emit.add_op("GGML_OP_MUL_MAT", "result_output", {lm_head_w, cur});
// MiniCPM scales the logits (1/(n_embd/dim_model_base)).
- if (m_cfg.logit_scale != 1.0f) {
+ const bool transform_logits = m_cfg.arch != "dflash";
+ if (transform_logits && m_cfg.logit_scale != 1.0f) {
logits = blocks::scale(m_emit, logits, m_cfg.logit_scale, "result_output_scaled");
}
// Gemma2/Gemma3 final logit soft-cap: tanh(logits / cap) * cap.
- if (m_cfg.final_logit_soft_cap != 0.0f) {
+ if (transform_logits && m_cfg.final_logit_soft_cap != 0.0f) {
logits = blocks::scale(m_emit, logits, 1.0f / m_cfg.final_logit_soft_cap, "logits_softcap_scaled");
logits = m_emit.add_op("GGML_UNARY_OP_TANH", "logits_softcap_tanh", {logits});
logits = blocks::scale(m_emit, logits, m_cfg.final_logit_soft_cap, "result_output_softcapped");
}
+ if (m_cfg.arch == "dflash" && m_emit.has_weight("d2t")) {
+ using namespace ov::op;
+ const auto& mapping = m_emit.weight_source("d2t").data;
+ OPENVINO_ASSERT(mapping.get_element_type() == i64 && mapping.get_shape().size() == 1,
+ "[GGUF] DFlash d2t must be a rank-one i64 tensor");
+ auto shape = std::make_shared<v3::ShapeOf>(m_emit.value(logits));
+ auto leading = std::make_shared<v8::Slice>(shape,
+ v0::Constant::create(i64, {1}, {0}),
+ v0::Constant::create(i64, {1}, {3}),
+ v0::Constant::create(i64, {1}, {1}));
+ auto vocab = std::make_shared<v8::Gather>(std::make_shared<v3::ShapeOf>(m_emit.value("token_embd.weight")),
+ v0::Constant::create(i64, {1}, {0}),
+ v0::Constant::create(i64, {}, {0}));
+ auto target =
+ std::make_shared<v3::Broadcast>(v0::Constant::create(f32, {}, {-std::numeric_limits<float>::infinity()}),
+ std::make_shared<v0::Concat>(ov::OutputVector{leading, vocab}, 0));
+ auto scattered = std::make_shared<v3::ScatterUpdate>(target,
+ std::make_shared<v0::Constant>(mapping),
+ m_emit.value(logits),
+ v0::Constant::create(i64, {}, {3}));
+ m_emit.add_extra_input_node("result_output_mapped", scattered);
+ logits = "result_output_mapped";
+ }
return logits;
}
std::shared_ptr<GgufGraph> DecoderBuilder::build() {
build_inputs();
+ if (m_cfg.deepstack_layers > 0) {
+ OPENVINO_ASSERT(m_cfg.deepstack_layers < m_cfg.n_layer, "[GGUF] DeepStack layers exceed the decoder stack");
+ m_emit.add_input("deepstack_embeds", f32, ps({D, m_cfg.deepstack_layers, D, m_cfg.n_embd}));
+ }
std::string cur = build_embeddings();
@@ -379,9 +475,24 @@ std::shared_ptr<GgufGraph> DecoderBuilder::build() {
build_per_layer_embeddings(cur);
}
- for (int il = 0; il < m_cfg.n_layer; ++il) {
- cur = build_layer(il, cur);
- }
+ if (m_cfg.arch == "gemma3n") {
+ cur = build_gemma3n(cur);
+ } else if (m_cfg.arch == "eagle3") {
+ cur = build_eagle3(cur);
+ } else if (m_cfg.arch == "dflash") {
+ cur = build_dflash(cur);
+ } else
+ for (int il = 0; il < m_cfg.n_layer; ++il) {
+ cur = build_layer(il, cur);
+ if (il < m_cfg.deepstack_layers) {
+ auto visual = m_emit.add_op("GGML_OP_VIEW",
+ "blk." + std::to_string(il) + ".deepstack_slice",
+ {"deepstack_embeds"},
+ 3,
+ {{"view_slice", std::vector<int64_t>{1, il, 1}}});
+ cur = m_emit.add_op("GGML_OP_ADD", "blk." + std::to_string(il) + ".deepstack_out", {cur, visual});
+ }
+ }
const std::string logits = build_head(cur);
m_emit.validate_hadamard();
@@ -390,7 +501,235 @@ std::shared_ptr<GgufGraph> DecoderBuilder::build() {
// become Assign sinks via MakeStateful.
auto graph = m_emit.graph();
graph->model_output_names.insert(graph->model_output_names.begin(), logits);
+ if (m_cfg.arch == "eagle3" && m_emit.has_weight("d2t")) {
+ const auto& mapping = m_emit.weight_source("d2t").data;
+ OPENVINO_ASSERT(mapping.get_element_type() == i64, "[GGUF] Eagle3 d2t must be i64");
+ auto constant = std::make_shared<ov::op::v0::Constant>(mapping);
+ constant->set_friendly_name("d2t");
+ m_emit.add_extra_input_node("d2t", constant);
+ constant->output(0).set_names({"d2t"});
+ graph->model_output_names.push_back("d2t");
+ if (auto& genai = graph->model_contract.genai)
+ genai->auxiliary_outputs.push_back({"d2t", "d2t", std::nullopt});
+ }
return graph;
}
+std::string DecoderBuilder::build_dflash(const std::string& embeddings) {
+ m_emit.add_weight("fc.weight");
+ const auto width = m_emit.value("fc.weight").get_partial_shape().rbegin()->get_length();
+ m_emit.add_input("hidden_states", f32, {1, 1, -1, width});
+ auto context = m_emit.add_op("GGML_OP_MUL_MAT", "dflash.fc", {"fc.weight", "hidden_states"});
+ if (m_emit.has_weight("fc.scale")) {
+ m_emit.add_weight("fc.scale");
+ context = m_emit.add_op("GGML_OP_MUL", "dflash.fc_scaled", {context, "fc.scale"});
+ }
+ context = blocks::rms_norm(m_emit, context, "enc.output_norm.weight", "dflash.encoder_norm", m_cfg.rms_eps);
+ std::string current = embeddings;
+ const auto dynamic_slice = [&](const std::string& value, const std::string& name, bool keep_noise) {
+ using namespace ov::op;
+ auto context_shape = std::make_shared<v3::ShapeOf>(m_emit.value(context));
+ auto noise_shape = std::make_shared<v3::ShapeOf>(m_emit.value(embeddings));
+ auto axis = v0::Constant::create(i64, {1}, {2});
+ auto scalar_axis = v0::Constant::create(i64, {}, {0});
+ auto n_context = std::make_shared<v8::Gather>(context_shape, axis, scalar_axis);
+ auto n_noise = std::make_shared<v8::Gather>(noise_shape, axis, scalar_axis);
+ ov::Output<ov::Node> begin = keep_noise ? n_context->output(0) : v0::Constant::create(i64, {1}, {0});
+ ov::Output<ov::Node> end =
+ keep_noise ? std::make_shared<v1::Add>(n_context, n_noise)->output(0) : n_context->output(0);
+ auto sliced =
+ std::make_shared<v8::Slice>(m_emit.value(value), begin, end, v0::Constant::create(i64, {1}, {1}), axis);
+ m_emit.add_extra_input_node(name, sliced);
+ return name;
+ };
+ for (int layer = 0; layer < m_cfg.n_layer; ++layer) {
+ const auto p = "blk." + std::to_string(layer) + ".";
+ auto normalized = blocks::rms_norm(m_emit, current, p + "attn_norm.weight", p + "noise_norm", m_cfg.rms_eps);
+ auto joined = m_emit.add_op("GGML_OP_CONCAT", p + "context", {context, normalized}, 0, {{"concat_axis", 1}});
+ auto attended = blocks::attention(m_emit, m_cfg, m_kv, layer, joined);
+ attended = dynamic_slice(attended, p + "noise_attention", true);
+ if (m_cfg.attention_value_scale != 0.f)
+ attended = blocks::scale(m_emit, attended, m_cfg.attention_value_scale, p + "attention_scaled");
+ if (m_cfg.has_attn_post_norm)
+ attended = blocks::rms_norm(m_emit,
+ attended,
+ p + m_cfg.attn_post_norm_key,
+ p + "post_attention_norm",
+ m_cfg.rms_eps);
+ current = m_emit.add_op("GGML_OP_ADD", p + "attn_residual", {current, attended});
+ normalized = blocks::rms_norm(m_emit, current, p + "ffn_norm.weight", p + "ffn_norm", m_cfg.rms_eps);
+ auto ffn = m_cfg.is_geglu ? blocks::geglu_ffn(m_emit, m_cfg, p, normalized)
+ : blocks::dense_ffn(m_emit, m_cfg, p, normalized);
+ if (m_cfg.has_ffn_post_norm)
+ ffn = blocks::rms_norm(m_emit, ffn, p + m_cfg.ffn_post_norm_key, p + "post_ffw_norm", m_cfg.rms_eps);
+ current = m_emit.add_op("GGML_OP_ADD", p + "ffn_residual", {current, ffn});
+ if (m_emit.has_weight(p + "layer_output_scale.weight")) {
+ m_emit.add_weight(p + "layer_output_scale.weight");
+ current = m_emit.add_op("GGML_OP_MUL", p + "scaled_out", {current, p + "layer_output_scale.weight"});
+ }
+ for (const auto side : {"k", "v"}) {
+ const auto cache = "cache_" + std::string(side) + "_l" + std::to_string(layer);
+ m_emit.value(cache).get_node_shared_ptr()->get_rt_info()["gguf.draft_context"] =
+ m_emit.value(context).get_node_shared_ptr()->get_friendly_name();
+ }
+ }
+ return current;
+}
+
+std::string DecoderBuilder::build_eagle3(const std::string& embeddings) {
+ using namespace ov::op;
+ OPENVINO_ASSERT(m_cfg.n_layer == 1, "[GGUF] Eagle3 requires one decoder layer");
+ m_emit.add_weight("fc.weight");
+ const auto feature_width = m_emit.value("fc.weight").get_partial_shape().rbegin()->get_length();
+ m_emit.add_input("hidden_states", f32, {1, 1, -1, feature_width});
+ std::string hidden = "hidden_states";
+ if (m_cfg.draft_norm_before_fc)
+ hidden = blocks::rms_norm(m_emit, hidden, "enc.output_norm.weight", "eagle3.encoder_norm", m_cfg.rms_eps);
+ hidden = m_emit.add_op("GGML_OP_MUL_MAT", "eagle3.fc", {"fc.weight", hidden});
+ const std::string p = "blk.0.";
+ auto normalized_embedding =
+ blocks::rms_norm(m_emit, embeddings, p + "attn_norm.weight", p + "embedding_norm", m_cfg.rms_eps);
+ auto normalized_hidden =
+ blocks::rms_norm(m_emit, hidden, p + "attn_norm_2.weight", p + "hidden_norm", m_cfg.rms_eps);
+ auto joined = m_emit.add_op("GGML_OP_CONCAT",
+ p + "joined",
+ {normalized_embedding, normalized_hidden},
+ 0,
+ {{"concat_axis", 0}});
+ auto attention = blocks::attention(m_emit, m_cfg, m_kv, 0, joined);
+ auto residual = m_cfg.draft_norm_before_residual ? normalized_hidden : hidden;
+ auto current = m_emit.add_op("GGML_OP_ADD", p + "attention_residual", {attention, residual});
+ auto normalized = blocks::rms_norm(m_emit, current, p + "ffn_norm.weight", p + "ffn_norm", m_cfg.rms_eps);
+ auto ffn = blocks::dense_ffn(m_emit, m_cfg, p, normalized);
+ current = m_emit.add_op("GGML_OP_ADD", "eagle3.prenorm", {current, ffn});
+ ov::Output<ov::Node>(m_emit.value(current)).set_names({current});
+ m_emit.graph()->model_output_names.push_back(current);
+ if (auto& genai = m_emit.graph()->model_contract.genai)
+ genai->auxiliary_outputs.push_back({current, "last_hidden_state", 1});
+ return current;
+}
+
+std::string DecoderBuilder::build_gemma3n(const std::string& embeddings) {
+ using namespace ov::op;
+ using Value = ov::Output<ov::Node>;
+ auto& e = m_emit;
+ const auto scalar = [](float value) {
+ return v0::Constant::create(f32, {}, {value});
+ };
+ const auto axis = [](int64_t value) {
+ return v0::Constant::create(i64, {1}, {value});
+ };
+ const auto reshape = [](const Value& x, const std::vector<int64_t>& shape) -> Value {
+ return std::make_shared<v1::Reshape>(x, v0::Constant::create(i64, {shape.size()}, shape), true);
+ };
+ const auto transpose = [](const Value& x, const std::vector<int64_t>& order) -> Value {
+ return std::make_shared<v1::Transpose>(x, v0::Constant::create(i64, {order.size()}, order));
+ };
+ const auto publish = [&](const Value& x, const std::string& name) {
+ x.get_node_shared_ptr()->set_friendly_name(name);
+ e.add_extra_input_node(name, x.get_node_shared_ptr());
+ return name;
+ };
+ const auto weight = [&](const std::string& name) -> Value {
+ e.add_weight(name);
+ return e.value(name);
+ };
+ const auto linear = [&](const Value& x, const std::string& name) -> Value {
+ return std::make_shared<v0::MatMul>(x, weight(name + ".weight"), false, true);
+ };
+ const auto norm = [&](const Value& x, const std::string& name) -> Value {
+ return e.value(blocks::rms_norm(e, publish(x, name + ".input"), name + ".weight", name, m_cfg.rms_eps));
+ };
+ const auto magnitude = [&](const Value& x) -> Value {
+ return std::make_shared<v0::Sqrt>(
+ std::make_shared<v1::ReduceSum>(std::make_shared<v1::Multiply>(x, x), axis(3), true));
+ };
+ const auto rescale = [&](const Value& x, const Value& target) -> Value {
+ return std::make_shared<v1::Divide>(std::make_shared<v1::Multiply>(x, target), magnitude(x));
+ };
+ const auto select = [&](const Value& x, int64_t index) -> Value {
+ return std::make_shared<v8::Gather>(x, axis(index), v0::Constant::create(i64, {}, {1}));
+ };
+ const auto router = [&](const Value& x, const std::string& p) -> Value {
+ auto normalized = norm(x, p + "altup_router_norm");
+ return std::make_shared<v0::Tanh>(
+ linear(std::make_shared<v1::Multiply>(normalized, scalar(1.f / m_cfg.n_embd)), p + "altup_router"));
+ };
+ constexpr int64_t streams = 4;
+ auto input = e.value(embeddings);
+ auto added = linear(input, "altup_proj");
+ added = rescale(added, magnitude(input));
+ Value current = std::make_shared<v0::Concat>(ov::OutputVector{input, added}, 1);
+ publish(current, "inp_stacked");
+ for (int il = 0; il < m_cfg.n_layer; ++il) {
+ const auto p = "blk." + std::to_string(il) + ".";
+ auto coefficients =
+ reshape(linear(router(select(current, 0), p), p + "altup_predict_coef"), {0, -1, streams, streams});
+ auto token_major = transpose(current, {0, 2, 1, 3});
+ auto prediction = std::make_shared<v0::MatMul>(coefficients, token_major);
+ Value predictions = std::make_shared<v1::Add>(current, transpose(prediction, {0, 2, 1, 3}));
+ publish(predictions, p + "predictions");
+ auto active = select(predictions, 0);
+ auto normalized = norm(active, p + "attn_norm");
+ auto laurel = norm(linear(linear(normalized, p + "laurel_l"), p + "laurel_r"), p + "laurel_post_norm");
+ laurel = std::make_shared<v1::Add>(laurel, normalized);
+ auto attention = blocks::attention(e, m_cfg, m_kv, il, publish(normalized, p + "normalized"));
+ auto attended = norm(e.value(attention), p + "post_attention_norm");
+ attended = std::make_shared<v1::Add>(attended, active);
+ Value combined =
+ std::make_shared<v1::Multiply>(std::make_shared<v1::Add>(attended, laurel), scalar(1.f / std::sqrt(2.f)));
+ publish(combined, p + "attn_laurel");
+ auto ffn_input = norm(combined, p + "ffn_norm");
+ auto gate = linear(ffn_input, p + "ffn_gate");
+ if (il < 10) {
+ auto mean = std::make_shared<v1::ReduceMean>(gate, axis(3), true);
+ auto delta = std::make_shared<v1::Subtract>(gate, mean);
+ auto variance =
+ std::make_shared<v1::ReduceSum>(std::make_shared<v1::Multiply>(delta, delta), axis(3), true);
+ const auto width = e.weight_rows(p + "ffn_gate.weight");
+ auto deviation =
+ std::make_shared<v0::Sqrt>(std::make_shared<v1::Multiply>(variance, scalar(1.f / (width - 1))));
+ gate = std::make_shared<v0::Relu>(std::make_shared<v1::Subtract>(
+ gate,
+ std::make_shared<v1::Add>(mean,
+ std::make_shared<v1::Multiply>(deviation, scalar(1.6448533535003662f)))));
+ }
+ publish(gate, p + "sparse_gate");
+ auto activated_gate = std::make_shared<v7::Gelu>(gate, GeluApproximationMode::TANH);
+ auto ffn =
+ linear(std::make_shared<v1::Multiply>(activated_gate, linear(ffn_input, p + "ffn_up")), p + "ffn_down");
+ auto output = std::make_shared<v1::Add>(norm(ffn, p + "post_ffw_norm"), combined);
+ publish(output, p + "attn_ffw_laurel_gated");
+ auto innovation = std::make_shared<v1::Subtract>(output, active);
+ auto correction = linear(router(output, p), p + "altup_correct_coef");
+ correction = std::make_shared<v1::Add>(correction, scalar(1.f));
+ correction = transpose(correction, {0, 3, 2, 1});
+ Value corrected =
+ std::make_shared<v1::Add>(predictions, std::make_shared<v1::Multiply>(innovation, correction));
+ publish(corrected, p + "corrected");
+ auto corrected_active =
+ std::make_shared<v1::Multiply>(select(corrected, 0), weight(p + "altup_correct_scale.weight"));
+ auto injection = linear(corrected_active, p + "inp_gate");
+ publish(injection, p + "input_projection");
+ injection = std::make_shared<v7::Gelu>(injection, GeluApproximationMode::TANH);
+ auto per_layer = select(e.value("per_layer_embd"), il);
+ injection = norm(linear(std::make_shared<v1::Multiply>(injection, per_layer), p + "proj"), p + "post_norm");
+ auto rest = std::make_shared<v8::Gather>(corrected,
+ v0::Constant::create(i64, {3}, {1, 2, 3}),
+ v0::Constant::create(i64, {}, {1}));
+ current = std::make_shared<v0::Concat>(
+ ov::OutputVector{select(corrected, 0), std::make_shared<v1::Add>(rest, injection)},
+ 1);
+ publish(current, p + "l_out");
+ }
+ auto active = select(current, 0);
+ auto rest = std::make_shared<v8::Gather>(current,
+ v0::Constant::create(i64, {3}, {1, 2, 3}),
+ v0::Constant::create(i64, {}, {1}));
+ auto projected = rescale(linear(rest, "altup_unembd_proj"), magnitude(active));
+ auto summed = std::make_shared<v1::ReduceSum>(projected, axis(1), true);
+ return publish(std::make_shared<v1::Multiply>(std::make_shared<v1::Add>(active, summed), scalar(.25f)),
+ "gemma3n.output");
+}
+
} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/arch/decoder_builder.hpp b/src/frontends/gguf/src/builder/arch/decoder_builder.hpp
index 642380a023a..dab944c8782 100644
--- a/src/frontends/gguf/src/builder/arch/decoder_builder.hpp
+++ b/src/frontends/gguf/src/builder/arch/decoder_builder.hpp
@@ -43,6 +43,9 @@ private:
// Final norm, lm_head, and the optional logit scale / soft-cap.
std::string build_head(const std::string& cur);
+ std::string build_gemma3n(const std::string& embeddings);
+ std::string build_eagle3(const std::string& embeddings);
+ std::string build_dflash(const std::string& embeddings);
bool selects_output_rows(int il) const {
return il == m_cfg.n_layer - 1 && !m_cfg.embedding_model;
}
diff --git a/src/frontends/gguf/src/builder/arch/decoder_family.cpp b/src/frontends/gguf/src/builder/arch/decoder_family.cpp
index b5fc0c38004..9d3e0c9c9c6 100644
--- a/src/frontends/gguf/src/builder/arch/decoder_family.cpp
+++ b/src/frontends/gguf/src/builder/arch/decoder_family.cpp
@@ -25,11 +25,22 @@ DecoderParameters decoder_family_defaults(const std::string& arch, int layers, i
p.architecture = arch;
p.attention.rope_mode = arch_uses_neox_rope(arch) ? RopeMode::Neox : RopeMode::Normal;
p.embedding_model = arch == "llama-embed";
- if (arch == "jais2") {
+ p.causal_attention = arch != "dflash";
+ p.model_contract.genai.emplace();
+ auto& genai = *p.model_contract.genai;
+ if (arch == "dspark" || p.embedding_model)
+ p.model_contract.supports_genai_adaptation = false;
+ genai.causal_attention = p.causal_attention;
+ if (is_one_of(arch, {"qwen3vl", "qwen3vlmoe", "qwen3tts"}))
+ genai.position_layout = ModelContract::GenAIContract::PositionLayout::THREE_AXIS;
+ if (arch == "dflash")
+ genai.attention_context_input = "hidden_states";
+ if (is_one_of(arch, {"jais2", "cohere2"}))
p.normalization.kind = NormalizationKind::Layer;
+ p.parallel_ffn = arch == "cohere2";
+ if (arch == "jais2")
p.activation = FfnActivation::ReluSquared;
- }
- if (is_one_of(arch, {"gemma", "gemma2", "gemma3", "gemma4"})) {
+ if (is_one_of(arch, {"gemma", "gemma2", "gemma3", "gemma3n", "gemma4"})) {
p.activation = FfnActivation::GeGlu;
p.scales.embedding = std::sqrt(static_cast<float>(embedding));
}
@@ -43,21 +54,25 @@ DecoderParameters decoder_family_defaults(const std::string& arch, int layers, i
}
p.normalization.qk_after_rope = is_one_of(arch, {"hunyuan-dense", "hunyuan-moe", "maincoder"});
p.normalization.post_only = arch == "exaone4";
- p.normalization.value_norm = arch == "gemma4";
+ p.normalization.value_norm = arch == "gemma4" || arch == "gemma3n";
if (arch == "gemma4") {
p.normalization.qk_full_width = false;
+ }
+ if (arch == "gemma4" || arch == "gemma3n") {
p.scales.attention = 1.0f;
} else if (arch == "gemma2" && layers == 46 && heads > 0) {
p.scales.attention = 1.0f / std::sqrt(static_cast<float>(embedding / heads));
}
- p.scales.token_embeddings_only = is_one_of(arch, {"gemma3", "gemma4"});
- p.attention.sliding_window = p.scales.token_embeddings_only;
+ p.scales.token_embeddings_only = is_one_of(arch, {"gemma3", "gemma3n", "gemma4"});
+ p.attention.sliding_window = is_one_of(arch, {"gemma3", "gemma4"});
p.attention.window_size = (arch == "gemma2" || (arch == "exaone4" && layers == 64)) ? 4096 : 0;
- p.attention.sliding_period = arch == "gemma3" ? 6
- : arch == "plamo3" ? 8
- : (arch == "afmoe" || arch == "exaone4" || arch == "exaone-moe") ? 4
- : 2;
- if (is_one_of(arch, {"gemma3", "plamo3"}))
+ p.attention.sliding_period = arch == "gemma3n" ? 5
+ : arch == "gemma3" ? 6
+ : arch == "plamo3" ? 8
+ : (arch == "afmoe" || arch == "cohere2" || arch == "exaone4" || arch == "exaone-moe")
+ ? 4
+ : 2;
+ if (is_one_of(arch, {"gemma3", "gemma3n", "plamo3"}))
p.attention.sliding_rope.freq_base = 10000.0f;
// Zero inherits the global scale; local Gemma RoPE retains its training scale.
if (is_one_of(arch, {"gemma3", "gemma4"}))
@@ -67,16 +82,24 @@ DecoderParameters decoder_family_defaults(const std::string& arch, int layers, i
p.normalization.post_epsilon = 1e-8f;
}
p.attention.rope_on_sliding_only =
- arch == "muse-glimmer" || arch == "exaone-moe" || (arch == "exaone4" && layers == 64);
+ arch == "muse-glimmer" || arch == "cohere2" || arch == "exaone-moe" || (arch == "exaone4" && layers == 64);
if (is_one_of(arch, {"afmoe", "smollm3"}))
p.attention.rope_skip_period = 4;
- p.experts.normalize_weights =
- is_one_of(arch, {"hunyuan-moe", "minimax-m2", "qwen3moe", "qwen35moe", "ernie4_5-moe", "mellum", "gemma4"});
+ p.experts.normalize_weights = is_one_of(arch,
+ {"hunyuan-moe",
+ "minimax-m2",
+ "qwen3moe",
+ "qwen3next",
+ "qwen3vlmoe",
+ "qwen35moe",
+ "ernie4_5-moe",
+ "mellum",
+ "gemma4"});
if (is_one_of(arch, {"afmoe", "glm4moe"}))
p.experts.routing = ExpertRouting::Sigmoid;
- if (is_one_of(arch, {"qwen35", "qwen35moe"})) {
+ if (is_one_of(arch, {"qwen35", "qwen35moe", "qwen3next"})) {
p.hybrid.kind = RecurrentKind::GatedDeltaNet;
- p.attention.rope_mode = RopeMode::Interleaved;
+ p.attention.rope_mode = arch == "qwen3next" ? RopeMode::Neox : RopeMode::Interleaved;
p.attention.interleaved_q_gate = true;
p.attention.fused_qkv = false;
p.attention.output_gate = true;
@@ -88,6 +111,13 @@ DecoderParameters decoder_family_defaults(const std::string& arch, int layers, i
p.attention.sliding_on_attention_layers = true;
p.model_contract.batchable_recurrent = true;
}
+ if (is_one_of(arch, {"qwen3vl", "qwen3vlmoe", "qwen3tts"}))
+ p.attention.rope_mode = RopeMode::Interleaved;
+ if (arch == "gemma3n") {
+ p.dimensions.per_layer_embedding = 256;
+ p.dimensions.shared_kv_layers = std::max(0, layers - 20);
+ p.scales.logits_soft_cap = 30.0f;
+ }
if (arch == "gemma3")
p.model_contract.image_attention = ModelContract::ImageAttentionMode::GLOBAL_AND_SLIDING;
if (arch == "gemma4" && embedding != 1536 && embedding != 2560)
@@ -131,6 +161,13 @@ DecoderParameters resolve_decoder_parameters(const GgufMetadata& metadata,
p.scales.logits = 1.0f / p.scales.logits;
if (p.architecture == "lfm2moe")
p.experts.weights_scale = 0.0f;
+ if (p.architecture == "dflash" && metadata.has(p.architecture + ".hidden_activation")) {
+ const auto activation = metadata.get_str(p.architecture + ".hidden_activation");
+ OPENVINO_ASSERT(
+ activation && (*activation == "silu" || *activation == "gelu" || *activation == "gelu_pytorch_tanh"),
+ "[GGUF] unsupported DFlash hidden activation");
+ p.activation = *activation == "silu" ? FfnActivation::SwiGlu : FfnActivation::GeGlu;
+ }
apply_decoder_options(p, options);
return p;
}
diff --git a/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp b/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp
index e9bfffdf990..5d7573b1733 100644
--- a/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp
+++ b/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp
@@ -10,6 +10,7 @@
#include <limits>
#include <map>
#include <optional>
+#include <set>
#include <sstream>
#include <vector>
@@ -21,6 +22,7 @@
#include "lfm3_projector_builder.hpp"
#include "openvino/frontend/gguf/builder/graph_context.hpp"
#include "projector_adapter.hpp"
+#include "qwen3tts_projector.hpp"
namespace ov::frontend::gguf {
namespace {
@@ -32,6 +34,9 @@ enum class EncoderTopology {
SIGLIP,
CLIP,
WHISPER,
+ QWEN3_AUDIO,
+ QWEN3_SPEAKER,
+ MOBILENET,
QWEN,
INTERNVL,
RESAMPLER,
@@ -84,6 +89,8 @@ constexpr ProjectorTopology projector_catalog[] = {
{"audio", "gemma4ua", EncoderTopology::UNIFIED_AUDIO, 0, ProjectorLayout::Unsupported, AudioLayout::UnifiedGemma4},
{"vision", "minicpmv4_6", EncoderTopology::MINICPM46},
{"vision", "minicpmv4_7", EncoderTopology::MINICPM46, 0, ProjectorLayout::PackedPatches},
+ {"audio", "qwen3a", EncoderTopology::QWEN3_AUDIO},
+ {"audio", "qwen3tts_spkenc", EncoderTopology::QWEN3_SPEAKER},
{"vision", "gemma3", EncoderTopology::SIGLIP, SWAPPED_FFN, ProjectorLayout::Image},
{"vision", "idefics3", EncoderTopology::SIGLIP, SWAPPED_FFN},
{"vision", "janus_pro", EncoderTopology::SIGLIP},
@@ -93,6 +100,7 @@ constexpr ProjectorTopology projector_catalog[] = {
{"vision", "qwen2vl_merger", EncoderTopology::QWEN, SWAPPED_FFN},
{"vision", "qwen2.5vl_merger", EncoderTopology::QWEN, RMS_NORM | SWAPPED_FFN},
{"vision", "qwen3vl_merger", EncoderTopology::QWEN, 0, ProjectorLayout::SplitMerger},
+ {"vision", "gemma3nv", EncoderTopology::MOBILENET, 0, ProjectorLayout::Image},
{"audio", "qwen2a", EncoderTopology::WHISPER, POOL_2},
{"audio", "ultravox", EncoderTopology::WHISPER},
{"audio", "voxtral", EncoderTopology::WHISPER, POOL_2},
@@ -139,6 +147,21 @@ EncoderConfig config(const GgufMetadata& meta, const std::string& modality, cons
"'");
c.topology = entry->topology;
c.traits = entry->traits;
+ if (c.topology == EncoderTopology::QWEN3_SPEAKER) {
+ c.width = positive(meta, key + "projection_dim");
+ c.heads = c.kv_heads = 1;
+ c.layers = 3;
+ c.eps = 1e-12f;
+ return c;
+ }
+ if (c.topology == EncoderTopology::MOBILENET) {
+ c.width = positive(meta, key + "embedding_length");
+ c.image_size = positive(meta, key + "image_size");
+ c.heads = c.kv_heads = 1;
+ c.layers = 0;
+ c.eps = 1e-6f;
+ return c;
+ }
if (c.topology == EncoderTopology::UNIFIED_AUDIO) {
c.width = 640;
c.heads = 1;
@@ -269,6 +292,12 @@ public:
result.config["vision.minicpmv_version"] = std::to_string(c.version);
result.config["vision.query_count"] = std::to_string(c.queries);
}
+ const auto output_count = modality == "vision" ? auxiliary.size() + 1 : 1;
+ result.config[modality + ".embedding_output_count"] = std::to_string(output_count);
+ result.config[modality + ".embedding_output.0"] = modality == "vision" ? "image_features" : "audio_features";
+ for (size_t i = 1; i < output_count; ++i)
+ result.config[modality + ".embedding_output." + std::to_string(i)] =
+ "deepstack_features." + std::to_string(i - 1);
if (modality == "vision") {
result.config["vision.auxiliary_count"] = std::to_string(auxiliary.size());
result.config["vision.patch_size"] = std::to_string(c.patch);
@@ -545,7 +574,116 @@ private:
GgufValue gather_rows(const GgufValue& x, const std::string& index_name) {
return g.node("GGML_OP_GET_ROWS", {x, index_input(index_name)});
}
+ GgufValue mobilenet(const EncoderConfig& c) {
+ const auto has = [&](const std::string& name) {
+ return g.tensors().has(name + ".weight");
+ };
+ const auto conv = [&](const GgufValue& x, const std::string& name, int64_t stride, bool depthwise = false) {
+ const auto weight = g.tensors().require(name + ".weight");
+ const auto padding = stride == 1 ? weight.ne(0) / 2 : 0;
+ auto y = g.node("GGML_OP_CONV_2D",
+ {weight, x},
+ 0,
+ {{"conv_params", std::vector<int64_t>{stride, stride, padding, padding, 1, 1}},
+ {"same_padding", stride > 1},
+ {"depthwise", depthwise}});
+ return y;
+ };
+ const auto spatial_norm = [&](const GgufValue& x, const std::string& name) {
+ if (!has(name))
+ return x;
+ auto y = g.build_norm(transpose(x, {0, 3, 2, 1}), g.tensors()(name + ".weight"), 1e-6f);
+ return transpose(y, {0, 3, 2, 1});
+ };
+ const auto activate = [&](const GgufValue& x) {
+ return g.node("GGML_UNARY_OP_GELU", {x});
+ };
+ auto x = g.add_input("vision.pixel_values", ov::element::f32, {1, 3, c.image_size, c.image_size});
+ x = conv(x, "v.conv_stem.conv", 2);
+ if (auto bias = g.tensors()("v.conv_stem.conv.bias"))
+ x = add(x, reshape(bias, {1, -1, 1, 1}));
+ x = activate(spatial_norm(x, "v.conv_stem.bn"));
+ std::vector<GgufValue> stages;
+ for (int stage = 0; stage < 4; ++stage) {
+ bool found = false;
+ for (int block = 0;; ++block) {
+ const auto p = "v.blk." + std::to_string(stage) + "." + std::to_string(block) + ".";
+ if (!has(p + "conv_exp") && !has(p + "dw_start.conv") && !has(p + "pw_exp.conv") &&
+ !has(p + "attn.query.proj"))
+ break;
+ found = true;
+ const auto residual = x;
+ const int64_t stride = block == 0 ? 2 : 1;
+ if (has(p + "conv_exp")) {
+ x = activate(spatial_norm(conv(x, p + "conv_exp", stride), p + "bn1"));
+ x = spatial_norm(conv(x, p + "conv_pwl", 1), p + "bn2");
+ } else if (has(p + "attn.query.proj")) {
+ auto normalized = spatial_norm(x, p + "norm");
+ auto q = conv(normalized, p + "attn.query.proj", 1);
+ const auto kv = [&](const std::string& side) {
+ auto value = normalized;
+ if (has(p + "attn." + side + ".down_conv"))
+ value = spatial_norm(conv(value, p + "attn." + side + ".down_conv", 2, true),
+ p + "attn." + side + ".norm");
+ return conv(value, p + "attn." + side + ".proj", 1);
+ };
+ auto k = kv("key"), v = kv("value");
+ const auto width = k.ne(2), heads = q.ne(2) / width;
+ q = transpose(reshape(q, {1, heads, width, -1}), {0, 3, 1, 2});
+ k = transpose(reshape(k, {1, 1, width, -1}), {0, 3, 1, 2});
+ v = transpose(reshape(v, {1, 1, width, -1}), {0, 3, 1, 2});
+ auto attended = attention(q, k, v, 1.f / std::sqrt(float(width)));
+ attended = transpose(attended, {0, 2, 3, 1});
+ attended = reshape(attended, {1, heads * width, residual.ne(1), residual.ne(0)});
+ x = conv(attended, p + "attn.output.proj", 1);
+ } else {
+ if (has(p + "dw_start.conv"))
+ x = spatial_norm(conv(x, p + "dw_start.conv", 1, true), p + "dw_start.bn");
+ if (has(p + "pw_exp.conv"))
+ x = activate(spatial_norm(conv(x, p + "pw_exp.conv", 1), p + "pw_exp.bn"));
+ if (has(p + "dw_mid.conv"))
+ x = activate(spatial_norm(conv(x, p + "dw_mid.conv", stride, true), p + "dw_mid.bn"));
+ if (has(p + "pw_proj.conv"))
+ x = spatial_norm(conv(x, p + "pw_proj.conv", 1), p + "pw_proj.bn");
+ }
+ if (!has(p + "conv_exp"))
+ if (auto gamma = g.tensors()(p + "layer_scale.gamma"))
+ x = mul(x, reshape(gamma, {1, -1, 1, 1}));
+ if (x.shape() == residual.shape())
+ x = add(x, residual);
+ }
+ if (found)
+ stages.push_back(x);
+ }
+ OPENVINO_ASSERT(!stages.empty(), "[GGUF] Gemma3n vision requires MobileNet blocks");
+ std::vector<GgufValue> features =
+ stages.size() == 4 ? std::vector<GgufValue>{stages[2], stages[3]} : std::vector<GgufValue>{stages.back()};
+ x = features.front();
+ for (size_t i = 1; i < features.size(); ++i) {
+ auto resized = g.node("GGML_OP_UPSCALE",
+ {features[i], features.front()},
+ 0,
+ {{"resize_like", true}, {"interpolation_mode", 0}});
+ x = concat(x, resized, 2);
+ }
+ if (has("v.msfa.ffn.pw_exp.conv"))
+ x = activate(spatial_norm(conv(x, "v.msfa.ffn.pw_exp.conv", 1), "v.msfa.ffn.pw_exp.bn"));
+ if (has("v.msfa.ffn.pw_proj.conv"))
+ x = spatial_norm(conv(x, "v.msfa.ffn.pw_proj.conv", 1), "v.msfa.ffn.pw_proj.bn");
+ if (x.ne(0) > 16) {
+ OPENVINO_ASSERT(x.ne(0) % 16 == 0, "[GGUF] Gemma3n output grid must be divisible by 16");
+ x = pool(x, x.ne(0) / 16, x.ne(0) / 16);
+ }
+ x = spatial_norm(x, "v.msfa.norm");
+ OPENVINO_ASSERT(x.ne(2) == c.width, "[GGUF] Gemma3n vision channel width mismatch");
+ x = transpose(reshape(x, {1, 1, c.width, -1}));
+ x = g.build_norm(scale(x, std::sqrt(float(c.width))), g.tensors()("mm.soft_emb_norm.weight"), 1e-6f);
+ x = linear(x, "mm.input_projection", false);
+ return g.build_norm(x, {}, 1e-6f);
+ }
GgufValue vision(const EncoderConfig& c) {
+ if (c.topology == EncoderTopology::MOBILENET)
+ return mobilenet(c);
if (c.topology == EncoderTopology::OCR || c.topology == EncoderTopology::OCR2)
return ocr_vision(c);
if (c.topology == EncoderTopology::PIXTRAL || c.topology == EncoderTopology::GEMMA4 ||
@@ -1141,7 +1279,99 @@ private:
x = g.build_norm(x, g.tensors()("mm.a.soft_emb_norm.weight"), c.eps);
return linear(x, "mm.a.input_projection", false);
}
+ GgufValue speaker_convolution(const GgufValue& input, const std::string& base, int dilation = 1) {
+ auto weight = g.tensors().require(base + ".weight");
+ const auto kernel = weight.ne(0), channels = weight.ne(1), output = weight.ne(2);
+ auto x = reshape(input, {1, channels, 1, -1});
+ const auto padding = (kernel - 1) * dilation / 2;
+ if (padding)
+ x = g.node("GGML_OP_PAD", {x}, 0, {{"reflect_last_axis", padding}});
+ weight = reshape(weight, {output, channels, 1, kernel});
+ x = g.node("GGML_OP_CONV_2D", {weight, x}, 0, {{"conv_params", std::vector<int64_t>{1, 1, 0, 0, dilation, 1}}});
+ return add(x, reshape(g.tensors().require(base + ".bias"), {1, output, 1, 1}));
+ }
+ GgufValue speaker_encoder(const EncoderConfig& c) {
+ const auto mel = positive(g.metadata(), "clip.audio.num_mel_bins");
+ auto x = g.add_input("audio.features", ov::element::f32, {1, mel, 1, -1});
+ const auto relu = [&](const GgufValue& value) {
+ return g.node("GGML_UNARY_OP_RELU", {value});
+ };
+ const auto mean = [&](const GgufValue& value) {
+ auto sum = g.node("GGML_OP_SUM_ROWS", {value});
+ return g.node(
+ "GGML_OP_DIV",
+ {sum, g.node("GGML_OP_SUM_ROWS", {g.node("GGML_OP_FILL", {value}, 0, {{"fill_value", 1.f}})})});
+ };
+ const auto deviation = [&](const GgufValue& variance) {
+ return g.node("GGML_OP_SQRT", {scale(variance, 1.f, c.eps)});
+ };
+ x = relu(speaker_convolution(x, "a.conv1d.0"));
+ std::vector<GgufValue> blocks;
+ for (int layer = 1; layer <= 3; ++layer) {
+ const auto p = "a.blk." + std::to_string(layer) + ".";
+ auto residual = x;
+ x = relu(speaker_convolution(x, p + "conv_pw1"));
+ const auto channels = x.shape()[1].get_length();
+ OPENVINO_ASSERT(channels % 8 == 0, "[GGUF] speaker Res2Net channels must be divisible by eight");
+ const auto branch_width = channels / 8;
+ auto first = slice(x, 1, 0, branch_width);
+ auto branches = first;
+ GgufValue previous;
+ for (int branch = 1; branch < 8; ++branch) {
+ auto part = slice(x, 1, branch * branch_width, branch_width);
+ if (previous)
+ part = add(part, previous);
+ previous = relu(speaker_convolution(part, p + "res2." + std::to_string(branch - 1), layer + 1));
+ branches = concat(branches, previous, 2);
+ }
+ x = relu(speaker_convolution(branches, p + "conv_pw2"));
+ auto gate = relu(speaker_convolution(mean(x), p + "se_conv1"));
+ gate = g.node("GGML_UNARY_OP_SIGMOID", {speaker_convolution(gate, p + "se_conv2")});
+ x = add(mul(x, gate), residual);
+ blocks.push_back(x);
+ }
+ x = relu(speaker_convolution(concat(concat(blocks[0], blocks[1], 2), blocks[2], 2), "a.conv_out"));
+ auto average = mean(x);
+ auto centered = g.node("GGML_OP_SUB", {x, average});
+ auto stddev = deviation(mean(g.node("GGML_OP_SQR", {centered})));
+ auto mean_repeated = g.node("GGML_OP_REPEAT", {average, x});
+ auto std_repeated = g.node("GGML_OP_REPEAT", {stddev, x});
+ auto context = concat(concat(x, mean_repeated, 2), std_repeated, 2);
+ auto attention = g.node("GGML_UNARY_OP_TANH", {relu(speaker_convolution(context, "a.asp_tdnn"))});
+ attention = g.node("GGML_OP_SOFT_MAX", {speaker_convolution(attention, "a.asp_attn")});
+ auto weighted_mean = g.node("GGML_OP_SUM_ROWS", {mul(attention, x)});
+ auto delta = g.node("GGML_OP_SUB", {x, weighted_mean});
+ auto variance = g.node("GGML_OP_SUM_ROWS", {mul(attention, g.node("GGML_OP_SQR", {delta}))});
+ return reshape(speaker_convolution(concat(weighted_mean, deviation(variance), 2), "mm.a.fc"),
+ {1, 1, 1, c.width});
+ }
GgufValue audio(const EncoderConfig& c) {
+ if (c.topology == EncoderTopology::QWEN3_SPEAKER)
+ return speaker_encoder(c);
+ if (c.topology == EncoderTopology::QWEN3_AUDIO) {
+ const auto mel = positive(g.metadata(), "clip.audio.num_mel_bins");
+ auto features = g.add_input("audio.features", ov::element::f32, {1, mel, 1, -1});
+ auto chunks = reshape(features, {1, mel, -1, 100});
+ auto x = transpose(chunks, {2, 0, 1, 3});
+ for (int i = 1; i <= 3; ++i) {
+ const auto base = "a.conv2d." + std::to_string(i);
+ auto weight = g.tensors().require(base + ".weight");
+ x = convolution(x, weight, 2, 1);
+ if (auto bias = g.tensors()(base + ".bias"))
+ x = add(x, reshape(bias, {1, weight.ne(3), 1, 1}));
+ x = g.node("GGML_UNARY_OP_GELU_ERF", {x});
+ }
+ const auto conv_width = g.tensors().require("a.conv_out.weight").ne(0);
+ x = reshape(transpose(x, {0, 3, 1, 2}), {1, 1, -1, conv_width});
+ x = linear(x, "a.conv_out");
+ auto table = g.tensors().require("a.position_embd.weight");
+ auto positions = slice(reshape(table, {1, 1, table.ne(1), c.width}), 2, 0, 13);
+ auto target = reshape(x, {1, -1, 13, c.width});
+ auto tiled = g.node("GGML_OP_REPEAT", {positions, target});
+ x = add(x, reshape(tiled, {1, 1, -1, c.width}));
+ x = vit(x, c, {});
+ return ffn(x, "mm.a.mlp.1", "mm.a.mlp.2", "GGML_UNARY_OP_GELU_ERF");
+ }
if (c.topology == EncoderTopology::LFM2_AUDIO)
return lfm2_audio(c);
if (c.topology == EncoderTopology::GEMMA4_AUDIO)
@@ -1212,6 +1442,13 @@ std::vector<std::string> build_mmproj_encoders(GgufGraphContext& g,
continue;
const auto type = resolve_projector_type(ctx.metadata, modality);
const auto definition = registry.find(ctx.metadata, modality, type);
+ if (!definition && std::string(modality) == "audio" && type == "gemma3na" &&
+ ctx.metadata.get_bool("clip.has_vision_encoder").value_or(false) &&
+ resolve_projector_type(ctx.metadata, "vision") == "gemma3nv") {
+ config["audio.projector"] = type;
+ config["audio.supported"] = "false";
+ continue;
+ }
OPENVINO_ASSERT(definition, "[GGUF] unsupported ", modality, " mmproj projector '", type, "'");
encoders.push_back(definition);
}
@@ -1295,10 +1532,23 @@ public:
std::map<std::string, std::string> config;
const auto modalities = build_mmproj_encoders(g, ctx, adapters, config);
const auto generation_type = resolve_projector_type(ctx.metadata, "gen.audio");
+ const auto explicit_generation_type = ctx.metadata.get_str("clip.gen.audio.projector_type").value_or("");
const bool lfm3 = resolve_projector_type(ctx.metadata, "vision") == "lfm3vl" ||
resolve_projector_type(ctx.metadata, "audio") == "lfm3a" || generation_type == "lfm3a_gen";
- const bool generation = lfm3 && ctx.metadata.get_bool("clip.has_gen_audio_encoder").value_or(false);
- OPENVINO_ASSERT(!modalities.empty() || generation, "[GGUF] mmproj has no encoder");
+ const bool has_generation = ctx.metadata.get_bool("clip.has_gen_audio_encoder").value_or(false);
+ const bool qwen3tts_generation = has_generation && explicit_generation_type == "qwen3tts_gen";
+ const bool lfm3_generation = has_generation && lfm3;
+ if (has_generation && !qwen3tts_generation && !lfm3_generation && modalities.empty())
+ OPENVINO_THROW("[GGUF] unsupported generated audio projector '", explicit_generation_type, "'");
+ OPENVINO_ASSERT(!modalities.empty() || qwen3tts_generation || lfm3_generation, "[GGUF] mmproj has no encoder");
+ if (qwen3tts_generation) {
+ auto contract = g.model_contract();
+ contract.component_groups.try_emplace("audio_generation", Qwen3TTSProjector(g).build());
+ g.configure_model_contract(contract);
+ config["gen_audio.projector"] = explicit_generation_type;
+ config["gen_audio.window_size"] = "72";
+ config["gen_audio.sample_rate"] = "24000";
+ }
if (lfm3) {
auto contract = g.model_contract();
if (!contract.batchable_recurrent)
@@ -1309,7 +1559,7 @@ public:
ModelComponentGroup{
"encoder",
{{"encoder", {{modality + ".embeddings"}, modality == "audio" ? "audio.state." : ""}}}});
- if (generation) {
+ if (lfm3_generation) {
OPENVINO_ASSERT(generation_type == "lfm3a_gen", "[GGUF] unsupported LFM3 audio generation projector");
build_lfm3_audio_generation(g);
contract.component_groups.try_emplace(
diff --git a/src/frontends/gguf/src/builder/arch/projector_adapter.cpp b/src/frontends/gguf/src/builder/arch/projector_adapter.cpp
index 501a0b00742..a2e7188a8d6 100644
--- a/src/frontends/gguf/src/builder/arch/projector_adapter.cpp
+++ b/src/frontends/gguf/src/builder/arch/projector_adapter.cpp
@@ -570,6 +570,37 @@ std::string projector_layout_name(ProjectorLayout layout) {
OPENVINO_THROW("[GGUF] invalid GenAI projector layout contract");
}
+std::vector<std::string> projector_embedding_outputs(const std::shared_ptr<ov::Model>& model,
+ const std::string& modality) {
+ const auto key = modality + ".embedding_output_count";
+ std::vector<std::string> outputs;
+ if (model->has_rt_info({"gguf_mmproj", key})) {
+ const auto count = mmproj_int_metadata(model, key);
+ OPENVINO_ASSERT(count > 0, "[GGUF] projector embedding output count must be positive");
+ std::unordered_set<std::string> names;
+ for (int64_t i = 0; i < count; ++i) {
+ const auto name_key = modality + ".embedding_output." + std::to_string(i);
+ OPENVINO_ASSERT(model->has_rt_info({"gguf_mmproj", name_key}),
+ "[GGUF] missing projector embedding output '",
+ name_key,
+ "'");
+ auto name = model->get_rt_info<std::string>({"gguf_mmproj", name_key});
+ OPENVINO_ASSERT(!name.empty() && names.insert(name).second,
+ "[GGUF] projector embedding output names must be nonempty and unique");
+ outputs.push_back(std::move(name));
+ }
+ } else {
+ const auto auxiliary = modality == "vision" && model->has_rt_info({"gguf_mmproj", "vision.auxiliary_count"})
+ ? mmproj_int_metadata(model, "vision.auxiliary_count", 0)
+ : 0;
+ OPENVINO_ASSERT(auxiliary >= 0, "[GGUF] projector auxiliary count must be nonnegative");
+ outputs.push_back(modality == "vision" ? "image_features" : "audio_features");
+ for (int64_t i = 0; i < auxiliary; ++i)
+ outputs.push_back("deepstack_features." + std::to_string(i));
+ }
+ return outputs;
+}
+
std::string audio_layout_name(AudioLayout layout) {
for (const auto& [candidate, name] : audio_layout_names) {
if (candidate == layout)
diff --git a/src/frontends/gguf/src/builder/arch/projector_adapter.hpp b/src/frontends/gguf/src/builder/arch/projector_adapter.hpp
index ad034a0c5c1..ade4959bc26 100644
--- a/src/frontends/gguf/src/builder/arch/projector_adapter.hpp
+++ b/src/frontends/gguf/src/builder/arch/projector_adapter.hpp
@@ -7,6 +7,7 @@
#include <map>
#include <memory>
#include <string>
+#include <vector>
#include "openvino/core/model.hpp"
#include "openvino/frontend/gguf/extension/projector.hpp"
@@ -19,6 +20,8 @@ std::string projector_layout_name(ProjectorLayout layout);
std::string audio_layout_name(AudioLayout layout);
// Vision GenAI layout of a built-in projector type; Unsupported for other types.
ProjectorLayout builtin_projector_layout(const std::string& projector_type);
+std::vector<std::string> projector_embedding_outputs(const std::shared_ptr<ov::Model>& model,
+ const std::string& modality);
// Throws when the model declares no adaptable GenAI vision layout.
ProjectorLayout read_projector_layout(const std::shared_ptr<ov::Model>& model);
ProjectorModels adapt_projector_layout(const std::shared_ptr<ov::Model>& model);
diff --git a/src/frontends/gguf/src/builder/arch/qwen3tts_projector.hpp b/src/frontends/gguf/src/builder/arch/qwen3tts_projector.hpp
new file mode 100644
index 00000000000..9453a353362
--- /dev/null
+++ b/src/frontends/gguf/src/builder/arch/qwen3tts_projector.hpp
@@ -0,0 +1,368 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <algorithm>
+#include <cmath>
+#include <limits>
+#include <string>
+#include <vector>
+
+#include "openvino/frontend/gguf/builder/graph_context.hpp"
+#include "quant/gguf.hpp"
+
+namespace ov::frontend::gguf {
+
+class Qwen3TTSProjector {
+public:
+ explicit Qwen3TTSProjector(GgufGraphContext& graph) : g(graph) {}
+
+ ModelComponentGroup build() {
+ code_predictor();
+ waveform();
+ return {"predictor", {{"predictor", {predictor_outputs, ""}}, {"codec", {codec_outputs, ""}}}};
+ }
+
+private:
+ GgufGraphContext& g;
+ size_t constant_id = 0;
+ std::vector<std::string> predictor_outputs;
+ std::vector<std::string> codec_outputs;
+
+ GgufValue constant(const std::vector<float>& values, const ov::Shape& shape) {
+ ov::Tensor tensor(ov::element::f32, shape);
+ std::copy(values.begin(), values.end(), tensor.data<float>());
+ return g.add_constant("tts.constant." + std::to_string(constant_id++), tensor);
+ }
+ GgufValue scalar(float value) {
+ return constant({value}, {1, 1, 1, 1});
+ }
+ GgufValue reshape(const GgufValue& x, std::vector<int64_t> shape) {
+ return g.node("GGML_OP_RESHAPE", {x}, 0, {{"reshape_target", std::move(shape)}});
+ }
+ GgufValue transpose(const GgufValue& x, std::vector<int64_t> order) {
+ return g.node("GGML_OP_TRANSPOSE", {x}, 0, {{"perm", std::move(order)}});
+ }
+ GgufValue slice(const GgufValue& x, int64_t axis, int64_t begin, int64_t count) {
+ return g.node("GGML_OP_VIEW", {x}, 3, {{"view_slice", std::vector<int64_t>{axis, begin, count}}});
+ }
+ GgufValue cast(const GgufValue& x, ov::element::Type type) {
+ return g.node("GGML_OP_CPY", {x}, 0, {{"dst_type", type}});
+ }
+ GgufValue add(const GgufValue& a, const GgufValue& b) {
+ return g.node("GGML_OP_ADD", {a, b});
+ }
+ GgufValue mul(const GgufValue& a, const GgufValue& b) {
+ return g.node("GGML_OP_MUL", {a, b});
+ }
+ GgufValue scale(const GgufValue& x, float factor, float bias = 0) {
+ return g.node("GGML_OP_SCALE", {x}, 0, {{"scale", factor}, {"bias", bias}});
+ }
+ GgufValue concat(const GgufValue& a, const GgufValue& b, int64_t axis) {
+ return g.node("GGML_OP_CONCAT", {a, b}, 0, {{"concat_axis", int(a.shape().rank().get_length() - 1 - axis)}});
+ }
+ GgufValue linear(const GgufValue& x, const std::string& base) {
+ auto y = g.node("GGML_OP_MUL_MAT", {g.tensors().require(base + ".weight"), x});
+ if (auto bias = g.tensors()(base + ".bias"))
+ y = add(y, bias);
+ return y;
+ }
+ GgufValue norm(const GgufValue& x, const std::string& base, float eps) {
+ return g.build_norm(x, g.tensors().require(base + ".weight"), eps);
+ }
+ GgufValue ffn(const GgufValue& x, const std::string& base) {
+ return linear(mul(g.node("GGML_UNARY_OP_SILU", {linear(x, base + "ffn_gate")}), linear(x, base + "ffn_up")),
+ base + "ffn_down");
+ }
+ GgufValue rope(const GgufValue& x, const GgufValue& pos, float theta, int64_t width) {
+ RopeConfig r;
+ r.n_dims = int(width);
+ r.freq_base = theta;
+ r.freq_scale = r.attn_factor = 1.f;
+ r.per_op = true;
+ return g.node("GGML_OP_ROPE", {x, pos}, 1 << 16, {{"rope_config", r}});
+ }
+ GgufValue rows(const GgufValue& table, const GgufValue& ids) {
+ return g.node("GGML_OP_GET_ROWS", {table, reshape(ids, {1, 1, 1, -1})});
+ }
+ GgufValue table(const GgufValue& stacked, int64_t group) {
+ return reshape(slice(stacked, stacked.shape().rank().get_length() - 3, group, 1),
+ {1, 1, stacked.ne(1), stacked.ne(0)});
+ }
+ GgufValue sample(const GgufValue& logits, const GgufValue& random) {
+ const auto vocab = logits.ne(0);
+ const auto top_k = g.metadata().get_int("general.sampling.top_k").value_or(50);
+ const auto top_p = g.metadata().get_float("general.sampling.top_p").value_or(1.0);
+ OPENVINO_ASSERT(top_p > 0 && top_p <= 1 && top_k >= 0, "[GGUF] invalid Qwen3TTS sampling defaults");
+ const auto count = top_k > 0 ? std::min(top_k, vocab) : vocab;
+ const bool filter_k = top_k > 0 && top_k < vocab;
+ std::vector<float> vocabulary(static_cast<size_t>(vocab));
+ for (int64_t i = 0; i < vocab; ++i)
+ vocabulary[size_t(i)] = float(i);
+ auto indices = filter_k || top_p < 1 ? g.node("GGML_OP_TOP_K", {logits}, 0, {{"k", count}})
+ : cast(constant(vocabulary, {1, 1, 1, size_t(vocab)}), ov::element::i32);
+ // Match the pinned ggml CPU candidate order used by on-device sampling.
+ if (top_p == 1 && count > 1 && filter_k) {
+ auto ordered = indices;
+ auto first = slice(indices, 3, 0, 1);
+ auto second = slice(indices, 3, 1, 1);
+ indices = concat(second, first, 3);
+ if (count > 2)
+ indices = concat(indices, slice(ordered, 3, 2, count - 2), 3);
+ }
+ auto sorted = reshape(rows(reshape(logits, {1, 1, vocab, 1}), indices), {1, 1, 1, count});
+ auto probabilities = g.node("GGML_OP_SOFT_MAX", {sorted});
+ auto cumulative = g.node("GGML_OP_CUMSUM", {probabilities});
+ if (top_p < 1) {
+ auto before = scale(cumulative, -1, float(top_p));
+ auto keep = g.node("GGML_UNARY_OP_STEP", {before});
+ auto crossing = g.node("GGML_OP_SUM_ROWS", {keep});
+ crossing = g.node("GGML_OP_CLAMP", {crossing}, 0, {{"clamp_min", 0.f}, {"clamp_max", float(count - 1)}});
+ std::vector<float> offsets(static_cast<size_t>(count));
+ for (int64_t i = 0; i < count; ++i)
+ offsets[size_t(i)] = float(i);
+ keep = g.node(
+ "GGML_UNARY_OP_STEP",
+ {add(g.node("GGML_OP_SUB", {crossing, constant(offsets, {1, 1, 1, size_t(count)})}), scalar(.5f))});
+ sorted = add(sorted, g.node("GGML_OP_LOG", {keep}));
+ cumulative = g.node("GGML_OP_CUMSUM", {g.node("GGML_OP_SOFT_MAX", {sorted})});
+ }
+ cumulative = g.node("GGML_OP_DIV", {cumulative, slice(cumulative, 3, count - 1, 1)});
+ auto crosses = g.node("GGML_UNARY_OP_STEP", {g.node("GGML_OP_SUB", {cumulative, random})});
+ auto index = cast(scale(g.node("GGML_OP_SUM_ROWS", {crosses}), -1, float(count)), ov::element::i32);
+ return reshape(rows(reshape(indices, {1, 1, count, 1}), index), {1, 1, 1, 1});
+ }
+
+ void code_predictor() {
+ const std::string root = "a.gen.code.";
+ const auto heads = g.metadata().get_int("clip.gen.audio.attention.head_count").value_or(0);
+ const auto kv_heads = g.metadata().get_int("clip.gen.audio.attention.head_count_kv").value_or(heads);
+ const auto layers = g.metadata().get_int("clip.gen.audio.block_count").value_or(0);
+ const auto eps = float(g.metadata().get_float("clip.gen.audio.attention.layer_norm_epsilon").value_or(1e-6));
+ OPENVINO_ASSERT(heads > 0 && kv_heads > 0 && heads % kv_heads == 0 && layers > 0 && eps > 0,
+ "[GGUF] invalid Qwen3TTS code predictor dimensions");
+ auto embeddings = g.tensors().require(root + "embd.weight");
+ auto output_embeddings = g.tensors().require(root + "out_embd.weight");
+ auto head = g.tensors().require(root + "head.weight");
+ const auto groups = head.ne(2);
+ OPENVINO_ASSERT(groups > 0 && groups == embeddings.ne(2), "[GGUF] Qwen3TTS codebook count mismatch");
+ const auto hidden_width = output_embeddings.ne(0);
+ auto raw = g.add_input("gen_audio.hidden_states", ov::element::f32, {1, 1, 1, hidden_width});
+ auto code0 = g.add_input("gen_audio.code0", ov::element::i32, {1, 1, 1, 1});
+ auto feedback = reshape(rows(output_embeddings, code0), {1, 1, 1, hidden_width});
+ std::vector<GgufValue> keys(static_cast<size_t>(layers)), values(static_cast<size_t>(layers));
+ auto current_codes = code0;
+ auto previous = code0;
+ const auto project = [&](const GgufValue& value) {
+ return g.tensors().has(root + "proj_in.weight") ? linear(value, root + "proj_in") : value;
+ };
+ for (int64_t pos = 0; pos <= groups; ++pos) {
+ auto x = pos == 0 ? raw : pos == 1 ? feedback : rows(table(embeddings, pos - 2), previous);
+ x = project(reshape(x, {1, 1, 1, hidden_width}));
+ auto positions = cast(scalar(float(pos)), ov::element::i32);
+ for (int64_t il = 0; il < layers; ++il) {
+ const auto base = root + "blk." + std::to_string(il) + ".";
+ auto h = norm(x, base + "ln1", eps);
+ auto q = linear(h, base + "attn_q"), k = linear(h, base + "attn_k"), v = linear(h, base + "attn_v");
+ const auto width = q.ne(0) / heads;
+ OPENVINO_ASSERT(width > 0 && width % 2 == 0 && k.ne(0) == kv_heads * width && v.ne(0) == k.ne(0),
+ "[GGUF] Qwen3TTS code predictor attention geometry mismatch");
+ q = norm(reshape(q, {1, 1, heads, width}), base + "attn_q_norm", eps);
+ k = norm(reshape(k, {1, 1, kv_heads, width}), base + "attn_k_norm", eps);
+ q = rope(q, positions, 1000000.f, width);
+ k = rope(k, positions, 1000000.f, width);
+ v = reshape(v, {1, 1, kv_heads, width});
+ keys[size_t(il)] = pos ? concat(keys[size_t(il)], k, 1) : k;
+ values[size_t(il)] = pos ? concat(values[size_t(il)], v, 1) : v;
+ auto attn = g.node("GGML_OP_FLASH_ATTN_EXT",
+ {q, keys[size_t(il)], values[size_t(il)]},
+ 100,
+ {{"scale", 1.f / std::sqrt(float(width))}, {"f32_attention", true}});
+ x = add(x, linear(reshape(attn, {1, 1, 1, heads * width}), base + "attn_out"));
+ x = add(x, ffn(norm(x, base + "ln2", eps), base));
+ }
+ if (pos) {
+ auto logits = g.node("GGML_OP_MUL_MAT", {table(head, pos - 1), norm(x, root + "output_norm", eps)});
+ const auto name = "gen_audio.logits." + std::to_string(pos - 1);
+ g.set_output(logits, name);
+ predictor_outputs.push_back(name);
+ auto random =
+ g.add_input("gen_audio.random." + std::to_string(pos - 1), ov::element::f32, {1, 1, 1, 1});
+ previous = sample(logits, random);
+ current_codes = concat(current_codes, previous, 2);
+ feedback = add(feedback, reshape(rows(table(embeddings, pos - 1), previous), {1, 1, 1, hidden_width}));
+ }
+ }
+ g.set_output(current_codes, "gen_audio.codes");
+ g.set_output(feedback, "gen_audio.embeddings");
+ predictor_outputs.insert(predictor_outputs.end(), {"gen_audio.codes", "gen_audio.embeddings"});
+ }
+
+ GgufValue state(const std::string& name, int64_t channels, int64_t length) {
+ return g.add_input("gen_audio.state_in." + name, ov::element::f32, {1, channels, 1, length});
+ }
+ void update(const std::string& name, const GgufValue& value) {
+ const auto output = "gen_audio.state_out." + name;
+ g.set_output(value, output);
+ codec_outputs.push_back(output);
+ }
+ GgufValue causal_conv(GgufValue x,
+ const std::string& base,
+ int64_t dilation,
+ const std::string& name,
+ bool depthwise = false) {
+ auto weight = g.tensors().require(base + ".weight");
+ const auto kernel = weight.ne(0), input_channels = x.ne(2), output_channels = weight.ne(2);
+ const auto pad = (kernel - 1) * dilation;
+ const auto length = x.ne(0);
+ if (pad) {
+ x = concat(state(name, input_channels, pad), x, 3);
+ update(name, slice(x, 3, length, pad));
+ }
+ const auto source_type = g.tensors().source_type(base + ".weight");
+ const bool f16_im2col =
+ !depthwise && source_type && (*source_type == GGUF_TYPE_F32 || *source_type == GGUF_TYPE_F16);
+ auto w = reshape(weight, {output_channels, weight.ne(1), 1, kernel});
+ auto y = g.node("GGML_OP_CONV_2D",
+ {w, x},
+ 0,
+ {{"conv_params", std::vector<int64_t>{1, 1, 0, 0, dilation, 1}},
+ {"depthwise", depthwise},
+ {"im2col_precision_f16", f16_im2col}});
+ if (auto bias = g.tensors()(base + ".bias"))
+ y = add(y, reshape(bias, {1, output_channels, 1, 1}));
+ return y;
+ }
+ GgufValue causal_transpose(const GgufValue& x, const std::string& base, int64_t stride, const std::string& name) {
+ auto weight = g.tensors().require(base + ".weight");
+ const auto channels = weight.ne(1), trim = weight.ne(0) - stride, emit = x.ne(0) * stride;
+ auto y = g.node("GGML_OP_CONV_TRANSPOSE_1D",
+ {reshape(weight, {weight.ne(2), channels, weight.ne(0)}), reshape(x, {1, x.ne(2), x.ne(0)})},
+ 0,
+ {{"stride", stride}});
+ y = reshape(y, {1, channels, 1, emit + trim});
+ if (trim) {
+ OPENVINO_ASSERT(emit >= trim, "[GGUF] Qwen3TTS waveform chunk too short");
+ auto head = add(slice(y, 3, 0, trim), state(name, channels, trim));
+ update(name, slice(y, 3, emit, trim));
+ y = emit == trim ? head : concat(head, slice(y, 3, trim, emit - trim), 3);
+ }
+ if (auto bias = g.tensors()(base + ".bias"))
+ y = add(y, reshape(bias, {1, channels, 1, 1}));
+ return y;
+ }
+ GgufValue snake(const GgufValue& x, const std::string& base) {
+ auto alpha = reshape(g.tensors().require(base + ".alpha"), {1, x.ne(2), 1, 1});
+ auto beta = reshape(g.tensors().require(base + ".beta"), {1, x.ne(2), 1, 1});
+ return add(x, mul(g.node("GGML_OP_SQR", {g.node("GGML_OP_SIN", {mul(x, alpha)})}), beta));
+ }
+ GgufValue channels_last(const GgufValue& x) {
+ return transpose(x, {0, 2, 3, 1});
+ }
+ GgufValue channels_first(const GgufValue& x) {
+ return transpose(x, {0, 3, 1, 2});
+ }
+
+ void waveform() {
+ const std::string root = "a.gen.wav.";
+ constexpr int64_t frames = 72, heads = 16, prefix = frames - 1;
+ auto acoustic = g.tensors().require(root + "quant.rest.codebook.weight");
+ const auto groups = acoustic.ne(2);
+ auto codes = g.add_input("gen_audio.audio_codes", ov::element::i32, {1, 1, groups + 1, frames});
+ auto semantic = rows(g.tensors().require(root + "quant.first.codebook.weight"), slice(codes, 2, 0, 1));
+ auto hidden = linear(semantic, root + "quant.first.out_proj");
+ GgufValue sum;
+ for (int64_t group = 0; group < groups; ++group) {
+ auto embd = rows(table(acoustic, group), slice(codes, 2, group + 1, 1));
+ sum = sum ? add(sum, embd) : embd;
+ }
+ hidden = add(hidden, linear(sum, root + "quant.rest.out_proj"));
+ auto x = causal_conv(channels_first(hidden), root + "pre_conv", 1, "pre_conv");
+ auto cur = linear(channels_last(x), root + "tfm.in_proj");
+ auto position_state = state("tfm_pos", 1, 1);
+ std::vector<float> offsets(static_cast<size_t>(frames)), key_offsets(static_cast<size_t>(prefix + frames));
+ for (int64_t i = 0; i < frames; ++i)
+ offsets[size_t(i)] = float(i);
+ for (int64_t i = 0; i < prefix + frames; ++i)
+ key_offsets[size_t(i)] = float(i);
+ auto positions = cast(add(position_state, constant(offsets, {1, 1, 1, size_t(frames)})), ov::element::i32);
+ update("tfm_pos", scale(position_state, 1, float(frames)));
+ std::vector<float> band(size_t(frames * (prefix + frames)));
+ for (int64_t i = 0; i < frames; ++i)
+ for (int64_t j = 0; j < prefix + frames; ++j)
+ band[size_t(i * (prefix + frames) + j)] = j <= prefix + i && j > i - 1 ? 1.f : 0.f;
+ auto warm = g.node("GGML_UNARY_OP_STEP",
+ {scale(add(constant(key_offsets, {1, 1, 1, size_t(prefix + frames)}), position_state),
+ 1,
+ .5f - float(prefix))});
+ auto mask = g.node("GGML_OP_LOG", {mul(warm, constant(band, {1, 1, size_t(frames), size_t(prefix + frames)}))});
+ for (int64_t il = 0; il < 8; ++il) {
+ const auto base = root + "tfm.blk." + std::to_string(il) + ".";
+ auto h = norm(cur, base + "ln1", 1e-5f);
+ auto q = linear(h, base + "attn_q"), k = linear(h, base + "attn_k"), v = linear(h, base + "attn_v");
+ const auto width = q.ne(0) / heads;
+ OPENVINO_ASSERT(width > 0 && width % 2 == 0 && k.ne(0) == q.ne(0) && v.ne(0) == q.ne(0),
+ "[GGUF] invalid Qwen3TTS waveform transformer head geometry");
+ q = rope(reshape(q, {1, frames, heads, width}), positions, 10000.f, width);
+ k = rope(reshape(k, {1, frames, heads, width}), positions, 10000.f, width);
+ v = reshape(v, {1, frames, heads, width});
+ const auto cache = [&](const GgufValue& value, const std::string& name) {
+ auto old = reshape(state(name, prefix, heads * width), {1, prefix, heads, width});
+ auto full = concat(old, value, 1);
+ update(name, reshape(slice(full, 1, frames, prefix), {1, prefix, 1, heads * width}));
+ return full;
+ };
+ auto full_k = cache(k, "tfm_k_" + std::to_string(il));
+ auto full_v = cache(v, "tfm_v_" + std::to_string(il));
+ auto attn = g.node("GGML_OP_FLASH_ATTN_EXT",
+ {q, full_k, full_v, mask},
+ 100,
+ {{"scale", 1.f / std::sqrt(float(width))}, {"f32_attention", true}});
+ auto out = linear(reshape(attn, {1, 1, frames, heads * width}), base + "attn_out");
+ if (auto scale_weight = g.tensors()(base + "ls1.weight"))
+ out = mul(out, scale_weight);
+ cur = add(cur, out);
+ out = ffn(norm(cur, base + "ln2", 1e-5f), base);
+ if (auto scale_weight = g.tensors()(base + "ls2.weight"))
+ out = mul(out, scale_weight);
+ cur = add(cur, out);
+ }
+ x = channels_first(linear(norm(cur, root + "tfm.output_norm", 1e-5f), root + "tfm.out_proj"));
+ for (int64_t il = 0; il < 2; ++il) {
+ const auto base = root + "up.blk." + std::to_string(il) + ".";
+ x = causal_transpose(x, base + "conv", 2, "");
+ auto h = channels_last(causal_conv(x, base + "dwconv", 1, "up" + std::to_string(il) + "_dwconv", true));
+ h = g.build_norm_ln(h,
+ g.tensors().require(base + "norm.weight"),
+ g.tensors().require(base + "norm.bias"),
+ 1e-6f);
+ h = linear(g.node("GGML_UNARY_OP_GELU", {linear(h, base + "pw1")}), base + "pw2");
+ x = add(x, channels_first(mul(h, g.tensors().require(base + "gamma"))));
+ }
+ x = causal_conv(x, root + "dac.entry", 1, "dac_entry");
+ const int64_t dilations[] = {1, 3, 9};
+ for (int64_t il = 0; il < 4; ++il) {
+ const auto base = root + "dac.blk." + std::to_string(il) + ".";
+ const auto name = "dac" + std::to_string(il);
+ const auto stride = g.tensors().require(base + "conv.weight").ne(0) / 2;
+ x = causal_transpose(snake(x, base + "snake"), base + "conv", stride, name + "_tail");
+ for (int64_t ir = 0; ir < 3; ++ir) {
+ const auto block = base + "res." + std::to_string(ir) + ".";
+ auto h = causal_conv(snake(x, block + "act1"),
+ block + "conv1",
+ dilations[ir],
+ name + "_res" + std::to_string(ir));
+ h = causal_conv(snake(h, block + "act2"), block + "conv2", 1, "");
+ x = add(x, h);
+ }
+ }
+ x = causal_conv(snake(x, root + "dac.post_snake"), root + "dac.post_conv", 1, "dac_post_conv");
+ x = g.node("GGML_OP_CLAMP", {x}, 0, {{"clamp_min", -1.f}, {"clamp_max", 1.f}});
+ g.set_output(reshape(x, {-1}), "gen_audio.waveform");
+ codec_outputs.push_back("gen_audio.waveform");
+ }
+};
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/arch_registry.cpp b/src/frontends/gguf/src/builder/arch_registry.cpp
index 706ab0a4b73..d1983503fbe 100644
--- a/src/frontends/gguf/src/builder/arch_registry.cpp
+++ b/src/frontends/gguf/src/builder/arch_registry.cpp
@@ -4,9 +4,11 @@
#include "arch_registry.hpp"
+#include <algorithm>
#include <optional>
#include <utility>
+#include "builder/api/metadata_store.hpp"
#include "builder/arch/dspark_builder.hpp"
#include "builder/arch/lfm_builder.hpp"
#include "builder/arch/mamba_builder.hpp"
@@ -17,7 +19,10 @@ namespace ov::frontend::gguf {
namespace {
struct ArchitectureEntry {
- ArchitectureEntry(const char* name, RopeMode rope) : name(name), rope(rope) {}
+ ArchitectureEntry(const char* name, RopeMode rope, ArchitectureDefinition::MatchFn match = {})
+ : name(name),
+ rope(rope),
+ match(std::move(match)) {}
ArchitectureEntry(const char* name,
ArchitectureDefinition::BuilderFactory factory,
@@ -45,8 +50,12 @@ const ArchitectureEntry architectures[] = {
meta.get_bool("clip.has_gen_audio_encoder").value_or(false);
},
"clip.mmproj"},
+ {"cohere2", RopeMode::Normal},
+ {"gemma3n", RopeMode::Neox},
{"deepseek2-ocr", RopeMode::Neox},
{"dspark", make_dspark_builder},
+ {"dflash", RopeMode::Neox},
+ {"eagle3", RopeMode::Normal},
{"ernie4_5-moe", RopeMode::Normal},
{"exaone-moe", RopeMode::Neox},
{"exaone4", RopeMode::Neox},
@@ -82,26 +91,39 @@ const ArchitectureEntry architectures[] = {
{"plamo3", RopeMode::Neox},
{"qwen2", RopeMode::Neox},
{"qwen3", RopeMode::Neox},
+ {"qwen3tts", RopeMode::Interleaved},
{"qwen35", RopeMode::Interleaved},
{"qwen35moe", RopeMode::Interleaved},
+ {"qwen3vl", RopeMode::Interleaved},
+ {"qwen3vlmoe", RopeMode::Interleaved},
{"qwen3moe", RopeMode::Neox},
{"smollm3", RopeMode::Normal},
};
} // namespace
+bool is_qwen3_asr(const GgufMetadata& metadata) {
+ const auto tags = metadata.get_str_array("general.tags");
+ return metadata.architecture() == "qwen3vl" &&
+ std::find(tags.begin(), tags.end(), "automatic-speech-recognition") != tags.end();
+}
+
std::vector<ArchitectureDefinition> builtin_architectures() {
std::vector<ArchitectureDefinition> definitions;
for (const auto& entry : architectures) {
if (entry.factory) {
definitions.push_back({entry.id ? entry.id : entry.name, entry.name, entry.factory, entry.match});
} else {
- definitions.push_back(make_decoder_architecture(entry.name, entry.rope.value()));
+ auto definition = make_decoder_architecture(entry.name, entry.rope.value());
+ definition.match = entry.match;
+ definitions.push_back(std::move(definition));
}
}
return definitions;
}
bool arch_uses_neox_rope(const std::string& arch) {
+ if (arch == "qwen3next")
+ return true;
for (const auto& entry : architectures) {
if (arch == entry.name)
return entry.rope == RopeMode::Neox;
diff --git a/src/frontends/gguf/src/builder/arch_registry.hpp b/src/frontends/gguf/src/builder/arch_registry.hpp
index bda2d1403cf..fce3d097809 100644
--- a/src/frontends/gguf/src/builder/arch_registry.hpp
+++ b/src/frontends/gguf/src/builder/arch_registry.hpp
@@ -17,6 +17,7 @@ constexpr int ROPE_OP_CASE_NORMAL = 0x00000000;
constexpr int ROPE_OP_CASE_NEOX = 0x00010000;
constexpr int ROPE_OP_CASE_IMROPE = 0x00020000;
bool arch_uses_neox_rope(const std::string& arch);
+bool is_qwen3_asr(const GgufMetadata& metadata);
// Single catalog for built-in decoder and custom-family definitions.
std::vector<ArchitectureDefinition> builtin_architectures();
diff --git a/src/frontends/gguf/src/builder/blocks/attention.cpp b/src/frontends/gguf/src/builder/blocks/attention.cpp
index 714abd37c62..39ee391b914 100644
--- a/src/frontends/gguf/src/builder/blocks/attention.cpp
+++ b/src/frontends/gguf/src/builder/blocks/attention.cpp
@@ -59,6 +59,7 @@ std::string attention(GraphEmitter& e,
const bool has_own_kv = (cfg.shared_kv_layers == 0) || (il < kv.n_own_kv);
// Qwen35 packs Q and the output gate into one interleaved attn_q_gate projection.
const bool joint_q_gate = cfg.interleaved_q_gate;
+ bool shared_v = false;
// Q/K/V projection weights. Fused-QKV archs (phi-3, minicpm) carry a single attn_qkv weight;
// split it into separate q/k/v weights so the rest of the layer is architecture-agnostic.
@@ -76,8 +77,10 @@ std::string attention(GraphEmitter& e,
// head_count_kv==1 and no separate attn_v.weight; V reuses K's extracted tensors.
if (e.has_weight(p + "attn_v.weight"))
e.add_weight(p + "attn_v.weight");
- else
+ else {
e.add_weight_from(p + "attn_v.weight", p + "attn_k");
+ shared_v = true;
+ }
}
}
std::string q, gate;
@@ -127,7 +130,7 @@ std::string attention(GraphEmitter& e,
if (cfg.has_qk_norm && !cfg.qk_norm_full && !cfg.qk_norm_after_rope)
qk_norm();
// gemma4: V gets a plain RMSNorm (no multiplicative weight, just normalize).
- if (cfg.has_v_norm && has_own_kv)
+ if ((cfg.has_v_norm || (cfg.arch == "dflash" && shared_v)) && has_own_kv)
v = e.add_op("GGML_OP_RMS_NORM", p + "Vcur_normed", {v}, 0, {{"eps", cfg.rms_eps}});
// RoPE. rope_freqs.weight (per-dim frequency factor) is an optional 3rd input.
diff --git a/src/frontends/gguf/src/builder/blocks/common.cpp b/src/frontends/gguf/src/builder/blocks/common.cpp
index 29ff485d23e..de61dccd4ff 100644
--- a/src/frontends/gguf/src/builder/blocks/common.cpp
+++ b/src/frontends/gguf/src/builder/blocks/common.cpp
@@ -29,7 +29,7 @@ std::string layer_norm(GraphEmitter& e,
e.add_weight(weight);
auto norm = e.add_op("GGML_OP_NORM", out_prefix + ".norm", {in}, 0, {{"eps", eps}});
auto scaled = e.add_op("GGML_OP_MUL", out_prefix + ".scaled", {norm, weight});
- return add_bias(e, scaled, bias_weight_name(weight), out_prefix);
+ return e.has_weight(bias_weight_name(weight)) ? add_bias(e, scaled, bias_weight_name(weight), out_prefix) : scaled;
}
std::string bias_weight_name(const std::string& weight_name) {
diff --git a/src/frontends/gguf/src/builder/blocks/gated_delta_net.cpp b/src/frontends/gguf/src/builder/blocks/gated_delta_net.cpp
index e75d9d81f28..e38d1e3cd0c 100644
--- a/src/frontends/gguf/src/builder/blocks/gated_delta_net.cpp
+++ b/src/frontends/gguf/src/builder/blocks/gated_delta_net.cpp
@@ -70,9 +70,57 @@ std::string gated_delta_net(GraphEmitter& e, const DecoderConfig& cfg, int il, c
std::string qkv_base = p + "attn_qkv", gate_base = p + "attn_gate", out_base = p + "ssm_out";
std::string alpha_base = p + "ssm_alpha", beta_base = p + "ssm_beta";
std::string conv_base = p + "ssm_conv1d", a_base = p + "ssm_a", dt_base = p + "ssm_dt";
- bool gqa_grouped = false;
+ const bool qwen3next = cfg.arch == "qwen3next";
+ if (qwen3next)
+ OPENVINO_ASSERT(H_v >= H_k && H_v % H_k == 0, "[GGUF] Gated-DeltaNet requires an integral V/K head ratio");
+ if (qwen3next && !e.has_weight(qkv_base + ".weight")) {
+ const auto fused = p + "ssm_in.weight";
+ const int64_t group_value = value_dim / H_k;
+ const int64_t group_width = 2 * S + 2 * group_value;
+ OPENVINO_ASSERT(e.weight_rows(fused) == H_k * group_width, "[GGUF] invalid legacy Qwen3-Next QKVZ rows");
+ std::vector<int64_t> qkv_order, gate_order;
+ const std::array<std::pair<int64_t, int64_t>, 4> ranges{std::make_pair(0, S),
+ {S, S},
+ {2 * S, group_value},
+ {2 * S + group_value, group_value}};
+ for (size_t i = 0; i < ranges.size(); ++i) {
+ const auto& range = ranges[i];
+ auto& order = i == ranges.size() - 1 ? gate_order : qkv_order;
+ for (int64_t h = 0; h < H_k; ++h)
+ for (int64_t row = 0; row < range.second; ++row)
+ order.push_back(h * group_width + range.first + row);
+ }
+ e.derive_weight(qkv_base + ".weight",
+ "GGML_OP_VIEW",
+ {fused},
+ 105,
+ {{"gather_axis", int64_t{0}}, {"gather_indices", qkv_order}});
+ e.derive_weight(gate_base + ".weight",
+ "GGML_OP_VIEW",
+ {fused},
+ 105,
+ {{"gather_axis", int64_t{0}}, {"gather_indices", gate_order}});
+ }
+ if (qwen3next && !e.has_weight(beta_base + ".weight")) {
+ const auto fused = p + "ssm_ba.weight";
+ OPENVINO_ASSERT(e.has_weight(fused) && e.weight_rows(fused) == 2 * H_v,
+ "[GGUF] invalid Qwen3-Next beta/alpha projection");
+ const auto per_group = H_v / H_k;
+ for (int64_t part = 0; part < 2; ++part) {
+ std::vector<int64_t> order;
+ for (int64_t h = 0; h < H_k; ++h)
+ for (int64_t row = 0; row < per_group; ++row)
+ order.push_back(h * 2 * per_group + part * per_group + row);
+ e.derive_weight((part == 0 ? beta_base : alpha_base) + ".weight",
+ "GGML_OP_VIEW",
+ {fused},
+ 105,
+ {{"gather_axis", int64_t{0}}, {"gather_indices", order}});
+ }
+ }
+ bool gqa_grouped = qwen3next;
const bool grouped_hadamard = e.has_grouped_hadamard_gdn();
- if ((!e.has_hadamard() || grouped_hadamard) && H_v != H_k && H_v % H_k == 0) {
+ if (!gqa_grouped && (!e.has_hadamard() || grouped_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) {
diff --git a/src/frontends/gguf/src/builder/decoder_config.cpp b/src/frontends/gguf/src/builder/decoder_config.cpp
index f165d05e6ae..c0435a39ca5 100644
--- a/src/frontends/gguf/src/builder/decoder_config.cpp
+++ b/src/frontends/gguf/src/builder/decoder_config.cpp
@@ -36,7 +36,25 @@ DecoderConfig::DecoderConfig(const DecoderParameters& p, const GgufWeightTable&
return weights.count(name) > 0;
};
arch = p.architecture;
+ if (arch == "dflash") {
+ for (const auto& [name, tensor] : weights) {
+ const bool auxiliary = name.rfind("markov_", 0) == 0 || name.rfind("conf_proj.", 0) == 0 ||
+ name.rfind("selector_", 0) == 0 || name.rfind("lilicorr.", 0) == 0 ||
+ name.find(".attn_conv_") != std::string::npos ||
+ name.find(".ffn_conv_") != std::string::npos;
+ OPENVINO_ASSERT(!auxiliary,
+ "[GGUF] unsupported DFlash auxiliary tensor '",
+ name,
+ "'; only the base DFlash architecture is supported");
+ }
+ }
model_contract = p.model_contract;
+ parallel_ffn = p.parallel_ffn;
+ deepstack_layers = p.deepstack_layers;
+ draft_norm_before_fc = p.draft.norm_before_fc;
+ draft_norm_before_residual = p.draft.norm_before_residual;
+ draft_target_layers = p.draft.target_layers;
+ draft_mask_token_id = p.draft.mask_token_id;
n_layer = p.dimensions.layers;
n_embd = p.dimensions.embedding;
const int query_heads = p.dimensions.query_heads;
@@ -53,6 +71,10 @@ DecoderConfig::DecoderConfig(const DecoderParameters& p, const GgufWeightTable&
n_layer_nextn);
const int stored_layers = n_layer;
n_layer -= n_layer_nextn;
+ OPENVINO_ASSERT(deepstack_layers >= 0 && deepstack_layers < n_layer,
+ "[GGUF] DeepStack layers must fit the decoder stack");
+ OPENVINO_ASSERT(n_embd_per_layer >= 0 && shared_kv_layers >= 0 && shared_kv_layers < n_layer,
+ "[GGUF] invalid per-layer embedding or shared KV dimensions");
const auto valid_layer_count = [&](size_t count) {
return count == 0 || count == static_cast<size_t>(n_layer) || count == static_cast<size_t>(stored_layers);
};
@@ -98,6 +120,7 @@ DecoderConfig::DecoderConfig(const DecoderParameters& p, const GgufWeightTable&
expert_weights_scale = p.experts.weights_scale;
expert_weights_norm = p.experts.normalize_weights;
embedding_scale = p.scales.embedding;
+ attention_value_scale = p.scales.attention_value;
residual_scale = p.scales.residual;
logit_scale = p.scales.logits;
embedding_scale_tokens_only = p.scales.token_embeddings_only;
@@ -106,6 +129,7 @@ DecoderConfig::DecoderConfig(const DecoderParameters& p, const GgufWeightTable&
attn_soft_cap = p.scales.attention_soft_cap;
final_logit_soft_cap = p.scales.logits_soft_cap;
for (const auto value : {embedding_scale,
+ attention_value_scale,
residual_scale,
logit_scale,
attention_scale,
@@ -149,7 +173,7 @@ DecoderConfig::DecoderConfig(const DecoderParameters& p, const GgufWeightTable&
has_sinks = p.attention.sinks.value_or(has("blk.0.attn_sinks.weight"));
has_swa = has_swa || has_sinks;
const bool periodic_swa = has_swa;
- const int probe = (std::max(0, dense_lead) / moe_layer_step + 1) * moe_layer_step - 1;
+ const int64_t probe = (int64_t(std::max(0, dense_lead)) / moe_layer_step + 1) * moe_layer_step - 1;
const auto expert_prefix = "blk." + std::to_string(probe) + ".";
const bool is_moe = p.experts.enabled.value_or(has(expert_prefix + "ffn_gate_exps.weight") ||
has(expert_prefix + "ffn_gate_up_exps.weight"));
diff --git a/src/frontends/gguf/src/builder/decoder_config.hpp b/src/frontends/gguf/src/builder/decoder_config.hpp
index 1eb114bbbc3..304a75d9dbb 100644
--- a/src/frontends/gguf/src/builder/decoder_config.hpp
+++ b/src/frontends/gguf/src/builder/decoder_config.hpp
@@ -18,7 +18,7 @@ namespace ov::frontend::gguf {
class GraphEmitter;
// Internal configuration resolved from metadata, tensor shapes and architecture semantics.
-// Extensions override ambiguous semantics through DecoderOptions before dependent plans are built.
+// Typed parameters resolve semantics before dependent plans are built.
struct DecoderConfig {
DecoderConfig(const DecoderParameters& parameters, const GgufWeightTable& weights);
@@ -41,6 +41,8 @@ struct DecoderConfig {
int pooling_type = 0;
bool causal_attention = true;
bool layer_norm = false;
+ bool parallel_ffn = false;
+ int deepstack_layers = 0;
bool relu_squared_ffn = false;
// ---- auto-detected per-architecture structure ----
@@ -89,8 +91,13 @@ struct DecoderConfig {
int expert_groups = 1;
int expert_groups_used = 1;
float embedding_scale = 1.0f;
+ float attention_value_scale = 0.0f;
// Like llama.cpp's Gemma3/Gemma4, scale token lookups only; injected embeddings stay raw.
bool embedding_scale_tokens_only = false;
+ bool draft_norm_before_fc = false;
+ bool draft_norm_before_residual = false;
+ std::vector<int32_t> draft_target_layers;
+ int draft_mask_token_id = 0;
float residual_scale = 1.0f;
float logit_scale = 1.0f;
float attention_temperature_scale = 0.0f;
diff --git a/src/frontends/gguf/src/builder/decoder_metadata.cpp b/src/frontends/gguf/src/builder/decoder_metadata.cpp
index 388ea203d6f..980a85644c2 100644
--- a/src/frontends/gguf/src/builder/decoder_metadata.cpp
+++ b/src/frontends/gguf/src/builder/decoder_metadata.cpp
@@ -71,6 +71,18 @@ DecoderParameters read_decoder_parameters(const GgufMetadata& m, DecoderParamete
const auto key = [&](const std::string& suffix) {
return p.architecture + "." + suffix;
};
+ if (p.architecture == "dflash") {
+ for (const auto& [name, value] : detail::MetadataAccess::get(m).map)
+ OPENVINO_ASSERT(name.rfind("lilicorr.", 0) != 0 && name.rfind("dflash.markov", 0) != 0,
+ "[GGUF] unsupported DFlash auxiliary metadata '",
+ name,
+ "'; only the base DFlash architecture is supported");
+ for (const auto* suffix : {"conv_kernel_size", "conv_group_size", "selector_rank", "selector_top_k"})
+ OPENVINO_ASSERT(integer(m, key(suffix), 0) == 0,
+ "[GGUF] unsupported DFlash auxiliary metadata '",
+ key(suffix),
+ "'; only the base DFlash architecture is supported");
+ }
auto& d = p.dimensions;
d.layers = integer(m, key("block_count"), d.layers, d.layers == 0);
d.embedding = integer(m, key("embedding_length"), d.embedding, d.embedding == 0);
@@ -182,6 +194,13 @@ DecoderParameters read_decoder_parameters(const GgufMetadata& m, DecoderParamete
a.sliding_window = a.sliding_window || a.window_size > 0 || !a.sliding_layers.empty();
d.per_layer_embedding = integer(m, key("embedding_length_per_layer_input"), d.per_layer_embedding);
d.shared_kv_layers = integer(m, key("attention.shared_kv_layers"), d.shared_kv_layers);
+ p.deepstack_layers = integer(m, key("n_deepstack_layers"), p.deepstack_layers);
+ p.draft.norm_before_fc = flag(m, key("norm_before_fc"), p.draft.norm_before_fc);
+ p.draft.norm_before_residual = flag(m, key("norm_before_residual"), p.draft.norm_before_residual);
+ if (m.has(key("target_layers")))
+ p.draft.target_layers = integers(m, key("target_layers"));
+ if (p.architecture == "eagle3" || p.architecture == "dflash")
+ p.draft.mask_token_id = integer(m, "tokenizer.ggml.mask_token_id", p.draft.mask_token_id);
auto& e = p.experts;
e.count = integer(m, key("expert_count"), e.count);
e.used = integer(m, key("expert_used_count"), e.used);
@@ -205,6 +224,7 @@ DecoderParameters read_decoder_parameters(const GgufMetadata& m, DecoderParamete
scales.logits = real(m, key("logit_scale"), scales.logits);
scales.attention = real(m, key("attention.scale"), scales.attention);
scales.attention_temperature = real(m, key("attention.temperature_scale"), scales.attention_temperature);
+ scales.attention_value = real(m, key("attention.value_scale"), scales.attention_value);
scales.attention_soft_cap = real(m, key("attn_logit_softcapping"), scales.attention_soft_cap);
scales.logits_soft_cap = real(m, key("final_logit_softcapping"), scales.logits_soft_cap);
auto& hybrid = p.hybrid;
diff --git a/src/frontends/gguf/src/builder/gguf_builder.cpp b/src/frontends/gguf/src/builder/gguf_builder.cpp
index eaa9817f3d3..ad40dcd1a8b 100644
--- a/src/frontends/gguf/src/builder/gguf_builder.cpp
+++ b/src/frontends/gguf/src/builder/gguf_builder.cpp
@@ -62,6 +62,9 @@ GraphBuilder make_gguf_builder(GGUFLoad loaded, const ArchRegistry& registry) {
// Family detection is only a diagnostic fallback; it must not reject a registered family.
const auto definition = registry.find(meta_view);
if (!definition) {
+ OPENVINO_ASSERT(!is_qwen3_asr(meta_view),
+ "[GGUF] native GGUF builder does not support the Qwen3 ASR subtype tagged "
+ "'automatic-speech-recognition'. Register an ArchitectureExtension.");
const auto kind = detect_model_kind(metadata);
OPENVINO_ASSERT(kind == ModelKind::DECODER,
"[GGUF] no builder for ",
diff --git a/src/frontends/gguf/src/builder/gguf_builder_decoder.cpp b/src/frontends/gguf/src/builder/gguf_builder_decoder.cpp
index 202a04e59eb..e7ff5460a35 100644
--- a/src/frontends/gguf/src/builder/gguf_builder_decoder.cpp
+++ b/src/frontends/gguf/src/builder/gguf_builder_decoder.cpp
@@ -25,6 +25,8 @@ const GgufOp& GgufBuilderDecoder::node() const {
// carry source shapes; converters infer them from their OpenVINO inputs.
ov::Any GgufBuilderDecoder::get_attribute(const std::string& name) const {
+ if (name == "model_rt_info" && m_node_idx < 0)
+ return m_graph->model_rt_info;
if (name == "architecture" && m_node_idx < 0)
return m_graph->architecture;
// RoPE config is queried at model scope (prepare_graph_inputs, to build the shared
diff --git a/src/frontends/gguf/src/builder/gguf_graph.hpp b/src/frontends/gguf/src/builder/gguf_graph.hpp
index ddffe0cbbe2..9503f4ae33b 100644
--- a/src/frontends/gguf/src/builder/gguf_graph.hpp
+++ b/src/frontends/gguf/src/builder/gguf_graph.hpp
@@ -41,6 +41,7 @@ struct GgufOp {
// a parsed GGUF file; consumed by GgufBuilderDecoder.
struct GgufGraph {
std::string architecture;
+ ov::AnyMap model_rt_info;
ModelContract model_contract;
ModelAdapters model_adapters;
std::vector<GgufOp> nodes;
diff --git a/src/frontends/gguf/src/builder/graph_emitter.hpp b/src/frontends/gguf/src/builder/graph_emitter.hpp
index 7016cd7403c..fdc3d0316e8 100644
--- a/src/frontends/gguf/src/builder/graph_emitter.hpp
+++ b/src/frontends/gguf/src/builder/graph_emitter.hpp
@@ -45,6 +45,9 @@ public:
const ov::Shape& weight_shape(const std::string& name) const;
int64_t weight_rows(const std::string& name) const;
GgufTensorType weight_qtype(const std::string& base) const;
+ const GgufWeight& weight_source(const std::string& name) const {
+ return m_weights.at(name);
+ }
// Whether selecting `columns` of a parser weight keeps its quantization groups whole.
bool column_groups_aligned(const std::string& name, const std::vector<int64_t>& columns) const;
void add_generated_weight(const std::string& name, const ov::Tensor& tensor);
diff --git a/src/frontends/gguf/src/builder/legacy_model_contract.hpp b/src/frontends/gguf/src/builder/legacy_model_contract.hpp
index 9af71ba5bbd..b7611b9f9ff 100644
--- a/src/frontends/gguf/src/builder/legacy_model_contract.hpp
+++ b/src/frontends/gguf/src/builder/legacy_model_contract.hpp
@@ -27,6 +27,7 @@
#include "openvino/op/multiply.hpp"
#include "openvino/op/parameter.hpp"
#include "openvino/op/reshape.hpp"
+#include "openvino/op/result.hpp"
#include "openvino/op/shape_of.hpp"
#include "openvino/op/split.hpp"
#include "openvino/op/squeeze.hpp"
@@ -219,9 +220,48 @@ inline bool resolve_legacy_genai_adaptation(const std::shared_ptr<ov::Model>& mo
return true;
}
+inline ModelContract::GenAIContract resolve_legacy_genai_contract(const std::shared_ptr<ov::Model>& model) {
+ ModelContract::GenAIContract contract;
+ contract.enabled = resolve_legacy_genai_adaptation(model);
+ const auto architecture = model->has_rt_info({"gguf_architecture"})
+ ? model->get_rt_info<std::string>({"gguf_architecture"})
+ : std::string{};
+ for (const auto& parameter : model->get_parameters()) {
+ if (parameter->get_friendly_name() == "gguf.target_token_embedding" ||
+ parameter->get_friendly_name() == "gguf.target_lm_head")
+ contract.preserved_inputs.push_back(parameter->output(0).get_any_name());
+ }
+ for (const auto& output : model->outputs())
+ if (output.get_names().count("embeddings"))
+ contract.enabled = false;
+ if (architecture == "qwen3vl" || architecture == "qwen3vlmoe" || architecture == "qwen3tts")
+ contract.position_layout = ModelContract::GenAIContract::PositionLayout::THREE_AXIS;
+ if (architecture == "dflash") {
+ contract.causal_attention = false;
+ contract.attention_context_input = "hidden_states";
+ }
+ const auto& results = model->get_results();
+ for (size_t i = 1; i < results.size(); ++i) {
+ auto source = results[i]->input_value(0);
+ const auto& name = source.get_node()->get_friendly_name();
+ if (architecture != "eagle3" &&
+ (architecture != "qwen3tts" || name.find("qwen3tts.hidden_states") == std::string::npos))
+ continue;
+ const bool mapping = architecture == "eagle3" && name.find("d2t") != std::string::npos;
+ const auto selector = "gguf.legacy_auxiliary_output." + std::to_string(i);
+ auto names = source.get_names();
+ names.insert(selector);
+ source.set_names(names);
+ contract.auxiliary_outputs.push_back(
+ {selector, mapping ? "d2t" : "last_hidden_state", mapping ? std::nullopt : std::optional<int64_t>{1}});
+ }
+ return contract;
+}
+
inline ModelContract resolve_legacy_model_contract(const std::shared_ptr<ov::Model>& model,
std::optional<int64_t> embedding_width) {
ModelContract contract;
+ contract.genai = resolve_legacy_genai_contract(model);
contract.supports_genai_adaptation = resolve_legacy_genai_adaptation(model);
if (!model->has_rt_info({"gguf_architecture"}))
return contract;
diff --git a/src/frontends/gguf/src/builder/model_kind.cpp b/src/frontends/gguf/src/builder/model_kind.cpp
index c7a75f2bf59..a2d65df8f8f 100644
--- a/src/frontends/gguf/src/builder/model_kind.cpp
+++ b/src/frontends/gguf/src/builder/model_kind.cpp
@@ -43,7 +43,7 @@ ModelKind detect_model_kind(const std::unordered_map<std::string, GGUFMetaData>&
if (meta_flag(metadata, "clip.has_vision_encoder")) {
return ModelKind::VISION;
}
- if (meta_flag(metadata, "clip.has_audio_encoder")) {
+ if (meta_flag(metadata, "clip.has_audio_encoder") || meta_flag(metadata, "clip.has_gen_audio_encoder")) {
return ModelKind::AUDIO;
}
return ModelKind::DECODER;
diff --git a/src/frontends/gguf/src/genai_adaptation.cpp b/src/frontends/gguf/src/genai_adaptation.cpp
index a68b29c0de6..9573830117e 100644
--- a/src/frontends/gguf/src/genai_adaptation.cpp
+++ b/src/frontends/gguf/src/genai_adaptation.cpp
@@ -77,7 +77,9 @@ ModelMap adapt_mmproj(const std::shared_ptr<ov::Model>& model) {
add("vision_embeddings", vision);
}
}
- if (model->has_rt_info({"gguf_mmproj", "audio.projector"})) {
+ if (model->has_rt_info({"gguf_mmproj", "audio.projector"}) &&
+ (!model->has_rt_info({"gguf_mmproj", "audio.supported"}) ||
+ model->get_rt_info<std::string>({"gguf_mmproj", "audio.supported"}) != "false")) {
auto audio = model->clone();
const bool has_adapter = has_genai_adapter(audio, "audio");
AdaptMmprojToGenAI adapter(AdaptMmprojToGenAI::Modality::AUDIO);
diff --git a/src/frontends/gguf/src/model_contract.hpp b/src/frontends/gguf/src/model_contract.hpp
index 9cc78f05126..d0883b496a8 100644
--- a/src/frontends/gguf/src/model_contract.hpp
+++ b/src/frontends/gguf/src/model_contract.hpp
@@ -14,7 +14,41 @@
namespace ov::frontend::gguf {
+inline int64_t model_contract_integer(const std::string& value, int64_t maximum) {
+ OPENVINO_ASSERT(!value.empty() && value.find_first_not_of("0123456789") == std::string::npos,
+ "[GGUF] invalid model contract integer");
+ int64_t number = 0;
+ for (const auto character : value) {
+ const auto digit = character - '0';
+ OPENVINO_ASSERT(number <= maximum / 10 && (number != maximum / 10 || digit <= maximum % 10),
+ "[GGUF] model contract integer out of range");
+ number = number * 10 + digit;
+ }
+ return number;
+}
+
+inline void validate_genai_contract(const ModelContract::GenAIContract& contract) {
+ OPENVINO_ASSERT(contract.position_layout == ModelContract::GenAIContract::PositionLayout::THREE_AXIS ||
+ contract.position_layout == ModelContract::GenAIContract::PositionLayout::SEQUENCE_THREE_AXIS,
+ "[GGUF] invalid GenAI position layout");
+ OPENVINO_ASSERT(contract.auxiliary_outputs.size() <= 1024 && contract.preserved_inputs.size() <= 1024,
+ "[GGUF] too many GenAI contract ports");
+ std::unordered_set<std::string> sources, names, inputs;
+ for (const auto& output : contract.auxiliary_outputs) {
+ OPENVINO_ASSERT(!output.source_tensor.empty() && !output.name.empty() && output.name != "logits" &&
+ sources.insert(output.source_tensor).second && names.insert(output.name).second,
+ "[GGUF] invalid or duplicate GenAI auxiliary output");
+ OPENVINO_ASSERT(!output.squeeze_axis || (*output.squeeze_axis >= 0 && *output.squeeze_axis <= 3),
+ "[GGUF] invalid GenAI output squeeze axis");
+ }
+ for (const auto& input : contract.preserved_inputs)
+ OPENVINO_ASSERT(!input.empty() && inputs.insert(input).second,
+ "[GGUF] invalid or duplicate preserved GenAI input");
+}
+
inline void validate_model_contract(const ModelContract& contract) {
+ if (contract.genai)
+ validate_genai_contract(*contract.genai);
const auto validate_outputs = [](const std::vector<std::string>& outputs) {
std::unordered_set<std::string> names;
for (const auto& name : outputs)
@@ -61,14 +95,44 @@ inline void write_model_contract(const std::shared_ptr<ov::Model>& model, const
ov::AnyMap{{"outputs", component.outputs}, {"state_prefix", component.state_prefix}});
component_groups.emplace(name, ov::AnyMap{{"primary", group.primary}, {"models", models}});
}
- const bool supports_genai = contract.supports_genai_adaptation ? *contract.supports_genai_adaptation
- : resolve_legacy_genai_adaptation(model);
+ const bool supports_genai =
+ contract.supports_genai_adaptation
+ ? *contract.supports_genai_adaptation
+ : (contract.genai ? contract.genai->enabled : resolve_legacy_genai_adaptation(model));
model->get_rt_info()["gguf_model_contract"] =
ov::AnyMap{{"batchable_recurrent", recurrent},
{"image_attention", image_attention},
{"sequence_outputs", contract.sequence_outputs},
{"component_groups", component_groups},
{"supports_genai_adaptation", std::string(supports_genai ? "true" : "false")}};
+ if (contract.genai) {
+ const auto& genai = *contract.genai;
+ ov::AnyMap outputs, inputs;
+ for (size_t i = 0; i < genai.auxiliary_outputs.size(); ++i) {
+ const auto& output = genai.auxiliary_outputs[i];
+ outputs["port_" + std::to_string(i)] =
+ ov::AnyMap{{"source_tensor", output.source_tensor},
+ {"name", output.name},
+ {"squeeze_axis", output.squeeze_axis ? std::to_string(*output.squeeze_axis) : "none"}};
+ }
+ for (size_t i = 0; i < genai.preserved_inputs.size(); ++i)
+ inputs["port_" + std::to_string(i)] = genai.preserved_inputs[i];
+ model->set_rt_info(
+ ov::AnyMap{{"version", std::string{"1"}},
+ {"enabled", std::string{supports_genai ? "true" : "false"}},
+ {"position_layout",
+ std::string{genai.position_layout == ModelContract::GenAIContract::PositionLayout::THREE_AXIS
+ ? "three_axis"
+ : "sequence_three_axis"}},
+ {"causal_attention", std::string{genai.causal_attention ? "true" : "false"}},
+ {"attention_context_input", genai.attention_context_input},
+ {"logits_first", std::string{genai.logits_first ? "true" : "false"}},
+ {"output_count", std::to_string(genai.auxiliary_outputs.size())},
+ {"input_count", std::to_string(genai.preserved_inputs.size())},
+ {"outputs", outputs},
+ {"inputs", inputs}},
+ {"gguf_model_contract", "genai"});
+ }
}
inline ModelContract read_model_contract(const std::shared_ptr<ov::Model>& model,
@@ -79,13 +143,56 @@ inline ModelContract read_model_contract(const std::shared_ptr<ov::Model>& model
return contract;
}
ModelContract contract;
+ const bool has_genai = model->has_rt_info({"gguf_model_contract", "genai"});
+ if (has_genai) {
+ const auto value = [&](const std::string& name) {
+ return model->get_rt_info<std::string>({"gguf_model_contract", "genai", name});
+ };
+ const auto boolean = [&](const std::string& name) {
+ const auto text = value(name);
+ OPENVINO_ASSERT(text == "true" || text == "false", "[GGUF] invalid GenAI contract boolean ", name);
+ return text == "true";
+ };
+ OPENVINO_ASSERT(value("version") == "1", "[GGUF] unsupported GenAI model contract version");
+ ModelContract::GenAIContract genai;
+ genai.enabled = boolean("enabled");
+ genai.causal_attention = boolean("causal_attention");
+ genai.logits_first = boolean("logits_first");
+ genai.attention_context_input = value("attention_context_input");
+ const auto layout = value("position_layout");
+ OPENVINO_ASSERT(layout == "three_axis" || layout == "sequence_three_axis",
+ "[GGUF] invalid GenAI position layout");
+ if (layout == "three_axis")
+ genai.position_layout = ModelContract::GenAIContract::PositionLayout::THREE_AXIS;
+ const auto output_count = model_contract_integer(value("output_count"), 1024);
+ for (int64_t i = 0; i < output_count; ++i) {
+ const auto field = [&](const std::string& name) {
+ return model->get_rt_info<std::string>(
+ {"gguf_model_contract", "genai", "outputs", "port_" + std::to_string(i), name});
+ };
+ const auto axis = field("squeeze_axis");
+ genai.auxiliary_outputs.push_back(
+ {field("source_tensor"),
+ field("name"),
+ axis == "none" ? std::nullopt : std::optional<int64_t>{model_contract_integer(axis, 3)}});
+ }
+ const auto input_count = model_contract_integer(value("input_count"), 1024);
+ for (int64_t i = 0; i < input_count; ++i)
+ genai.preserved_inputs.push_back(model->get_rt_info<std::string>(
+ {"gguf_model_contract", "genai", "inputs", "port_" + std::to_string(i)}));
+ contract.genai = std::move(genai);
+ } else {
+ contract.genai = resolve_legacy_genai_contract(model);
+ }
if (model->has_rt_info({"gguf_model_contract", "supports_genai_adaptation"})) {
const auto value = model->get_rt_info<std::string>({"gguf_model_contract", "supports_genai_adaptation"});
OPENVINO_ASSERT(value == "true" || value == "false", "[GGUF] invalid GenAI adaptation contract");
contract.supports_genai_adaptation = value == "true";
} else {
- contract.supports_genai_adaptation = resolve_legacy_genai_adaptation(model);
+ contract.supports_genai_adaptation =
+ has_genai ? contract.genai->enabled : resolve_legacy_genai_adaptation(model);
}
+ contract.genai->enabled = *contract.supports_genai_adaptation;
if (model->has_rt_info({"gguf_model_contract", "batchable_recurrent"})) {
const auto value = model->get_rt_info<std::string>({"gguf_model_contract", "batchable_recurrent"});
OPENVINO_ASSERT(value == "true" || value == "false" || value == "auto",
diff --git a/src/frontends/gguf/src/op/flash_attn_ext.cpp b/src/frontends/gguf/src/op/flash_attn_ext.cpp
index 8728570f35b..50095e3c313 100644
--- a/src/frontends/gguf/src/op/flash_attn_ext.cpp
+++ b/src/frontends/gguf/src/op/flash_attn_ext.cpp
@@ -134,7 +134,9 @@ OutputVector translate_flash_attn_ext(const NodeContext& context) {
// Encoders keep f32 attention; decoders use f16 SDPA.
const auto sdpa_type = context.get_attribute<bool>("f32_attention", false) ? ov::element::f32 : ov::element::f16;
- auto q = std::make_shared<ov::op::v0::Convert>(q_f32, sdpa_type);
+ ov::Output<ov::Node> q = q_f32;
+ if (q_f32.get_element_type() != sdpa_type)
+ q = std::make_shared<ov::op::v0::Convert>(q_f32, sdpa_type);
auto scale_node = std::make_shared<ov::op::v0::Constant>(sdpa_type, ov::Shape{}, std::vector<float>{scale});
ov::Output<ov::Node> mask_sliced, res;
diff --git a/src/frontends/gguf/src/op/mul_mat_id.cpp b/src/frontends/gguf/src/op/mul_mat_id.cpp
index 742285391bc..2f7583abaf5 100644
--- a/src/frontends/gguf/src/op/mul_mat_id.cpp
+++ b/src/frontends/gguf/src/op/mul_mat_id.cpp
@@ -17,10 +17,12 @@
#include "openvino/op/concat.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/convert.hpp"
+#include "openvino/op/equal.hpp"
#include "openvino/op/gather.hpp"
#include "openvino/op/greater_eq.hpp"
#include "openvino/op/matmul.hpp"
#include "openvino/op/multiply.hpp"
+#include "openvino/op/reduce_prod.hpp"
#include "openvino/op/reshape.hpp"
#include "openvino/op/select.hpp"
#include "openvino/op/shape_of.hpp"
@@ -235,10 +237,44 @@ ov::Output<ov::Node> translate_mul_mat_id_gathermatmul(ov::Output<ov::Node> expe
// down : b is [.., T, K, cols] (already per-slot) -> A = [K, T, cols]
const auto& bps = b.get_partial_shape();
const int64_t cols = bps[bps.size() - 1].get_length();
- const bool has_k =
+ // A plain [1, T, cols] input can also have T == K. Count all leading axes,
+ // since a decoder can place the dynamic token dimension before a unit axis.
+ ov::Dimension id_tokens(1);
+ for (int i = 0; i < ids_rank - 1; ++i) {
+ id_tokens *= ids.get_partial_shape()[i];
+ }
+ ov::Dimension activation_tokens(1);
+ std::vector<int> activation_batch_dims;
+ for (size_t i = 0; i + 2 < bps.size(); ++i) {
+ activation_tokens *= bps[i];
+ activation_batch_dims.push_back(static_cast<int>(i));
+ }
+ const bool token_axis_matches = activation_tokens.compatible(id_tokens);
+ const bool has_k_axis =
K > 1 && bps.size() >= 2 && bps[bps.size() - 2].is_static() && bps[bps.size() - 2].get_length() == K;
+ const bool has_k = has_k_axis && token_axis_matches;
ov::Output<ov::Node> a;
- if (has_k) {
+ if (has_k_axis && (activation_tokens.is_dynamic() != id_tokens.is_dynamic())) {
+ // Resolve mixed static/dynamic layouts at runtime without changing the usual dynamic down path.
+ auto ids_shape = std::make_shared<ov::op::v3::ShapeOf>(ids_2d, ov::element::i64);
+ auto tokens = gather_dims(ids_shape, {0});
+ auto b_shape = std::make_shared<ov::op::v3::ShapeOf>(b, ov::element::i64);
+ ov::Output<ov::Node> b_tokens = const_i64({1});
+ if (!activation_batch_dims.empty()) {
+ b_tokens = std::make_shared<ov::op::v1::ReduceProd>(gather_dims(b_shape, activation_batch_dims),
+ const_i64({0}),
+ true);
+ }
+ auto matches = std::make_shared<ov::op::v1::Equal>(tokens, b_tokens);
+ auto slots = std::make_shared<ov::op::v1::Select>(matches, const_i64({K}), const_i64({1}));
+ auto tkc_shape = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{tokens, slots, const_i64({cols})}, 0);
+ auto b_tkc = std::make_shared<ov::op::v1::Reshape>(b, tkc_shape, false);
+ auto target = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{tokens, const_i64({K, cols})}, 0);
+ auto per_expert = std::make_shared<ov::op::v3::Broadcast>(b_tkc, target);
+ a = std::make_shared<ov::op::v1::Transpose>(
+ per_expert,
+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, std::vector<int64_t>{1, 0, 2}));
+ } else if (has_k) {
auto b_tkc = std::make_shared<ov::op::v1::Reshape>(
b,
ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, std::vector<int64_t>{-1, K, cols}),
@@ -331,8 +367,7 @@ ov::Output<ov::Node> translate_mul_mat_id_generic(ov::Output<ov::Node> expert_we
// GGML_OP_MUL_MAT_ID: per-token MoE expert matmul. ids select which expert row of the weight
// tensor each token uses; activations are gathered/broadcast accordingly and matmul'd. Dispatch:
// - packed MXFP4 experts -> on-graph dequant + per-expert matmul;
-// - constant-backed experts (the real .gguf models) -> internal GatherMatmul (compressed,
-// memory-bounded, one fused batched matmul);
+// - constant-backed experts -> internal GatherMatmul;
// - non-constant experts (single-op tests / dynamic) -> portable Gather + MatMul fallback.
OutputVector translate_mul_mat_id(const NodeContext& context) {
num_inputs_check(context, 3, 3);
diff --git a/src/frontends/gguf/src/op/mulmat.cpp b/src/frontends/gguf/src/op/mulmat.cpp
index b87322f9b5c..714130b8139 100644
--- a/src/frontends/gguf/src/op/mulmat.cpp
+++ b/src/frontends/gguf/src/op/mulmat.cpp
@@ -81,7 +81,7 @@ OutputVector translate_mulmat(const NodeContext& context) {
auto B_shape = context.get_input_shape(0);
auto A_shape = context.get_input_shape(1);
- if (A_shape[1].is_dynamic() || B_shape[1].is_dynamic()) {
+ if (B_shape.rank() == 2 || A_shape[1].is_dynamic() || B_shape[1].is_dynamic()) {
// Variable encoder grids use equal or singleton batch axes. MatMul validates
// their broadcast compatibility at runtime; do not freeze a grid dimension.
res = std::make_shared<ov::op::v0::MatMul>(A, B, false, transpose_b);
diff --git a/src/frontends/gguf/src/op/multimodal.cpp b/src/frontends/gguf/src/op/multimodal.cpp
index 1beb81f113e..d07b6d29dd9 100644
--- a/src/frontends/gguf/src/op/multimodal.cpp
+++ b/src/frontends/gguf/src/op/multimodal.cpp
@@ -7,6 +7,7 @@
#include "openvino/op/add.hpp"
#include "openvino/op/concat.hpp"
#include "openvino/op/convert.hpp"
+#include "openvino/op/convert_like.hpp"
#include "openvino/op/convolution.hpp"
#include "openvino/op/divide.hpp"
#include "openvino/op/floor_mod.hpp"
@@ -30,6 +31,7 @@
#include "openvino/op/subtract.hpp"
#include "openvino/op/transpose.hpp"
#include "openvino/op/unsqueeze.hpp"
+#include "transformations/rt_info/disable_precision_conversion.hpp"
#include "utils.hpp"
namespace ov::frontend::gguf::op {
@@ -94,6 +96,37 @@ ov::Output<ov::Node> antialiased_bilinear(const ov::Output<ov::Node>& input,
}
} // namespace
+OutputVector translate_unary_step(const NodeContext& context) {
+ num_inputs_check(context, 1, 1);
+ const auto input = context.get_input(0);
+ auto zero = ov::op::v0::Constant::create(input.get_element_type(), {}, {0});
+ auto result = std::make_shared<ov::op::v0::Convert>(std::make_shared<ov::op::v1::Greater>(input, zero),
+ input.get_element_type());
+ return rename_outputs_with_suffix({result}, context.get_name());
+}
+
+OutputVector translate_conv_transpose_1d(const NodeContext& context) {
+ num_inputs_check(context, 2, 2);
+ const auto stride = context.get_attribute<int64_t>("stride");
+ FRONT_END_OP_CONVERSION_CHECK(stride > 0, "CONV_TRANSPOSE_1D requires a positive stride");
+ auto w = context.get_input(0), x = context.get_input(1);
+ FRONT_END_OP_CONVERSION_CHECK(w.get_partial_shape().rank() == 3 && x.get_partial_shape().rank() == 3,
+ "CONV_TRANSPOSE_1D expects [IC,OC,K] weights and [B,IC,T] input");
+ if (w.get_element_type() != x.get_element_type())
+ w = std::make_shared<ov::op::v1::ConvertLike>(w, x);
+ // The ARM CPU 1D decomposition loses kernel reversal; see openvinotoolkit/openvino#39000.
+ const auto axis = i64_const({2});
+ auto convolution =
+ std::make_shared<ov::op::v1::ConvolutionBackpropData>(std::make_shared<ov::op::v0::Unsqueeze>(x, axis),
+ std::make_shared<ov::op::v0::Unsqueeze>(w, axis),
+ ov::Strides{1, size_t(stride)},
+ ov::CoordinateDiff{0, 0},
+ ov::CoordinateDiff{0, 0},
+ ov::Strides{1, 1});
+ auto result = std::make_shared<ov::op::v0::Squeeze>(convolution, axis);
+ return rename_outputs_with_suffix({result}, context.get_name());
+}
+
OutputVector translate_upscale(const NodeContext& context) {
num_inputs_check(context, 2, 2);
const int flags = context.get_attribute<int>("interpolation_mode", 1);
@@ -138,24 +171,34 @@ OutputVector translate_conv_2d(const NodeContext& context) {
w = std::make_shared<ov::op::v0::Convert>(w, ov::element::f32);
if (x.get_element_type() != ov::element::f32)
x = std::make_shared<ov::op::v0::Convert>(x, ov::element::f32);
+ const auto strides = ov::Strides{size_t(p[1]), size_t(p[0])};
+ const auto pads = ov::CoordinateDiff{std::ptrdiff_t(p[3]), std::ptrdiff_t(p[2])};
+ const auto dilation = ov::Strides{size_t(p[5]), size_t(p[4])};
+ const auto auto_pad =
+ context.get_attribute<bool>("same_padding", false) ? ov::op::PadType::SAME_UPPER : ov::op::PadType::EXPLICIT;
if (context.get_attribute<bool>("depthwise", false)) {
- w = std::make_shared<ov::op::v0::Unsqueeze>(w, i64_const({1}));
- return rename_outputs_with_suffix({std::make_shared<ov::op::v1::GroupConvolution>(
- x,
- w,
- ov::Strides{size_t(p[1]), size_t(p[0])},
- ov::CoordinateDiff{std::ptrdiff_t(p[3]), std::ptrdiff_t(p[2])},
- ov::CoordinateDiff{std::ptrdiff_t(p[3]), std::ptrdiff_t(p[2])},
- ov::Strides{size_t(p[5]), size_t(p[4])})},
- context.get_name());
+ const auto shape = w.get_partial_shape();
+ FRONT_END_OP_CONVERSION_CHECK(shape.rank() == 4 && shape[1] == 1,
+ "Depthwise CONV_2D expects [channels, 1, height, width] weights");
+ w = std::make_shared<ov::op::v0::Unsqueeze>(w, i64_const({2}));
+ return rename_outputs_with_suffix(
+ {std::make_shared<ov::op::v1::GroupConvolution>(x, w, strides, pads, pads, dilation, auto_pad)},
+ context.get_name());
+ }
+ const auto weight_type = context.get_input(0).get_element_type();
+ if (context.get_attribute<bool>("im2col_precision_f16", false) &&
+ (weight_type == ov::element::f32 || weight_type == ov::element::f16)) {
+ const auto round_operand = [](const ov::Output<ov::Node>& operand) {
+ auto narrow = std::make_shared<ov::op::v0::Convert>(operand, ov::element::f16);
+ // ggml's F16 im2col rounds both operands before the F32 dot product.
+ ov::disable_conversion(narrow, ov::element::f16, ov::element::f32);
+ return std::make_shared<ov::op::v0::Convert>(narrow, ov::element::f32);
+ };
+ x = round_operand(x);
+ w = round_operand(w);
}
return rename_outputs_with_suffix(
- {std::make_shared<ov::op::v1::Convolution>(x,
- w,
- ov::Strides{size_t(p[1]), size_t(p[0])},
- ov::CoordinateDiff{std::ptrdiff_t(p[3]), std::ptrdiff_t(p[2])},
- ov::CoordinateDiff{std::ptrdiff_t(p[3]), std::ptrdiff_t(p[2])},
- ov::Strides{size_t(p[5]), size_t(p[4])})},
+ {std::make_shared<ov::op::v1::Convolution>(x, w, strides, pads, pads, dilation, auto_pad)},
context.get_name());
}
diff --git a/src/frontends/gguf/src/op/pad.cpp b/src/frontends/gguf/src/op/pad.cpp
index 8698586582d..4d937f3366f 100644
--- a/src/frontends/gguf/src/op/pad.cpp
+++ b/src/frontends/gguf/src/op/pad.cpp
@@ -61,6 +61,16 @@ OutputVector translate_pad(const NodeContext& context) {
num_inputs_check(context, 1, 1);
auto input = context.get_input(0);
+ const auto reflect = context.get_attribute<int64_t>("reflect_last_axis", 0);
+ if (reflect) {
+ FRONT_END_OP_CONVERSION_CHECK(reflect > 0 && input.get_partial_shape().rank().is_static(),
+ "Reflect padding requires a positive extent and static rank");
+ std::vector<int64_t> extents(input.get_partial_shape().size(), 0);
+ extents.back() = reflect;
+ auto pads = ov::op::v0::Constant::create(ov::element::i64, {extents.size()}, extents);
+ auto result = std::make_shared<ov::op::v1::Pad>(input, pads, pads, ov::op::PadMode::REFLECT);
+ return rename_outputs_with_suffix({result}, context.get_name());
+ }
const auto multiple = context.get_attribute<int64_t>("pad_tokens_to_multiple", 0);
if (multiple) {
FRONT_END_OP_CONVERSION_CHECK(multiple > 0 && input.get_partial_shape().rank() == 4,
diff --git a/src/frontends/gguf/src/op_table.cpp b/src/frontends/gguf/src/op_table.cpp
index 90e54a4caa4..a40b232de24 100644
--- a/src/frontends/gguf/src/op_table.cpp
+++ b/src/frontends/gguf/src/op_table.cpp
@@ -41,6 +41,7 @@ std::unordered_map<std::string, CreatorFunction> get_supported_ops() {
{"GGML_OP_CONCAT", op::translate_concat},
{"GGML_OP_CONT", op::translate_cont},
{"GGML_OP_CONV_2D", op::translate_conv_2d},
+ {"GGML_OP_CONV_TRANSPOSE_1D", op::translate_conv_transpose_1d},
{"GGML_OP_COS", op::translate_1to1_match_1_input<v0::Cos>},
{"GGML_OP_CPY", op::translate_cpy},
{"GGML_OP_CUMSUM", op::translate_cumsum},
@@ -77,6 +78,7 @@ std::unordered_map<std::string, CreatorFunction> get_supported_ops() {
{"GGML_OP_SQRT", op::translate_sqrt},
{"GGML_OP_SSM_CONV", op::translate_ssm_conv},
{"GGML_OP_SSM_SCAN", op::translate_ssm_scan},
+ {"GGML_UNARY_OP_STEP", op::translate_unary_step},
{"GGML_OP_SUB", op::translate_1to1_match_2_inputs<v1::Subtract>},
{"GGML_OP_SUM_ROWS", op::translate_sum_rows},
{"GGML_OP_TOP_K", op::translate_top_k},
diff --git a/src/frontends/gguf/src/op_table.hpp b/src/frontends/gguf/src/op_table.hpp
index a9981cfb35f..d0f00a225cc 100644
--- a/src/frontends/gguf/src/op_table.hpp
+++ b/src/frontends/gguf/src/op_table.hpp
@@ -55,6 +55,8 @@ GGUF_OP_CONVERTER(translate_add_id);
GGUF_OP_CONVERTER(translate_argsort);
GGUF_OP_CONVERTER(translate_top_k);
GGUF_OP_CONVERTER(translate_sum_rows);
+GGUF_OP_CONVERTER(translate_conv_transpose_1d);
+GGUF_OP_CONVERTER(translate_unary_step);
// Elementwise clamp and division.
GGUF_OP_CONVERTER(translate_clamp);
diff --git a/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp b/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp
index 440cc8ab21f..b1529fec7eb 100644
--- a/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp
+++ b/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp
@@ -155,6 +155,7 @@ ModelAdapterResult adapt_mmproj(const std::shared_ptr<ov::Model>& model,
const std::string prefix = modality == Modality::VISION ? "vision." : "audio.";
const auto selected = embedding_result(model, modality);
const auto adapter = get_model_adapter(selected);
+ const auto output_names = projector_embedding_outputs(model, modality == Modality::VISION ? "vision" : "audio");
if (layout == Layout::VISION_ENCODERS && !adapter)
read_projector_layout(model);
auto live_before = std::make_shared<std::unordered_set<const ov::Node*>>();
@@ -186,22 +187,19 @@ ModelAdapterResult adapt_mmproj(const std::shared_ptr<ov::Model>& model,
auto embeddings = std::make_shared<ov::op::v0::Squeeze>(selected->input_value(0),
ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
ov::copy_runtime_info({selected, selected->input_value(0).get_node_shared_ptr()}, embeddings);
- size_t auxiliary_count = 0;
- if (modality == Modality::VISION && model->has_rt_info({"gguf_mmproj", "vision.auxiliary_count"}))
- auxiliary_count = size_t(mmproj_int_metadata(model, "vision.auxiliary_count", 0));
- if (auxiliary_count) {
+ if (output_names.size() > 1) {
auto split = std::make_shared<ov::op::v1::Split>(embeddings,
ov::op::v0::Constant::create(ov::element::i64, {}, {2}),
- auxiliary_count + 1);
- for (size_t i = 0; i <= auxiliary_count; ++i) {
- split->output(i).set_names({i == 0 ? "image_features" : "deepstack_features." + std::to_string(i - 1)});
+ output_names.size());
+ ov::copy_runtime_info(embeddings, split);
+ for (size_t i = 0; i < output_names.size(); ++i) {
+ split->output(i).set_names({output_names[i]});
auto result = std::make_shared<ov::op::v0::Result>(split->output(i));
ov::copy_runtime_info(selected, result);
model->add_results({result});
}
} else {
- // Only the tensor that becomes a Result is named; the Split path names output 0 instead.
- embeddings->output(0).set_names({modality == Modality::VISION ? "image_features" : "audio_features"});
+ embeddings->output(0).set_names({output_names.front()});
auto result = std::make_shared<ov::op::v0::Result>(embeddings);
ov::copy_runtime_info(selected, result);
model->add_results({result});
diff --git a/src/frontends/gguf/src/pass/adapt_to_genai.cpp b/src/frontends/gguf/src/pass/adapt_to_genai.cpp
index f183d0c3e97..86e1c64580d 100644
--- a/src/frontends/gguf/src/pass/adapt_to_genai.cpp
+++ b/src/frontends/gguf/src/pass/adapt_to_genai.cpp
@@ -32,6 +32,7 @@
#include "openvino/op/logical_or.hpp"
#include "openvino/op/matmul.hpp"
#include "openvino/op/multiply.hpp"
+#include "openvino/op/non_zero.hpp"
#include "openvino/op/not_equal.hpp"
#include "openvino/op/parameter.hpp"
#include "openvino/op/range.hpp"
@@ -40,6 +41,7 @@
#include "openvino/op/reshape.hpp"
#include "openvino/op/result.hpp"
#include "openvino/op/scaled_dot_product_attention.hpp"
+#include "openvino/op/scatter_nd_update.hpp"
#include "openvino/op/select.hpp"
#include "openvino/op/shape_of.hpp"
#include "openvino/op/slice.hpp"
@@ -147,7 +149,8 @@ public:
auto indices_flat = make_shared<v1::Reshape>(indices_squeeze->input_value(0), indices_flat_shape, false);
auto axis0 = v0::Constant::create(ov::element::i64, {1}, {0});
auto fixed_res = make_shared<v8::Gather>(data_flat, indices_flat, axis0);
- auto fixed_unsqueeze = make_shared<v0::Unsqueeze>(fixed_res, axis0);
+ auto axis1 = v0::Constant::create(ov::element::i64, {1}, {1});
+ auto fixed_unsqueeze = make_shared<v0::Unsqueeze>(fixed_res, axis1);
fixed_unsqueeze->set_friendly_name(unsqueeze->get_friendly_name());
ov::copy_runtime_info(unsqueeze, fixed_unsqueeze);
unsqueeze->output(0).replace(fixed_unsqueeze->output(0));
@@ -223,6 +226,11 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
if (output.get_names().count("embeddings"))
return false;
}
+ auto contract = read_model_contract(model);
+ OPENVINO_ASSERT(contract.genai, "[GGUF] missing GenAI model contract");
+ const auto genai = *contract.genai;
+ if (!contract.supports_genai_adaptation.value_or(genai.enabled))
+ return false;
// Token count is optional: custom builders may leave it unused, so conversion prunes it.
// The remaining inputs identify a GGUF graph that has not already been adapted.
@@ -232,9 +240,6 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
auto token_len_per_seq = find_parameter(model, "token_len_per_seq");
const bool has_recurrent_states = model->get_rt_info().count(gguf_recurrent_states_key()) != 0;
const auto operations = model->get_ops();
- auto contract = read_model_contract(model);
- if (!contract.supports_genai_adaptation.value_or(true))
- return false;
for (const auto& name : contract.sequence_outputs) {
const auto result =
std::find_if(model->get_results().begin(), model->get_results().end(), [&](const auto& output) {
@@ -258,6 +263,34 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
return false;
}
+ OPENVINO_ASSERT(genai.causal_attention || !find_parameter(model, "self_kq_mask_swa") ||
+ !model->get_rt_info().count(gguf_swa_window_key()),
+ "[GGUF] noncausal sliding-window attention is not supported by GenAI adaptation");
+
+ std::vector<std::pair<std::shared_ptr<v0::Result>, ModelContract::GenAIContract::AuxiliaryOutput>>
+ auxiliary_outputs;
+ for (const auto& output : genai.auxiliary_outputs) {
+ std::shared_ptr<v0::Result> found;
+ for (const auto& result : model->get_results()) {
+ if (!result->input_value(0).get_names().count(output.source_tensor))
+ continue;
+ OPENVINO_ASSERT(!found, "[GGUF] ambiguous GenAI output port ", output.source_tensor);
+ found = result;
+ }
+ OPENVINO_ASSERT(found && found != model->get_results().front(),
+ "[GGUF] missing GenAI auxiliary output port ",
+ output.source_tensor);
+ auxiliary_outputs.emplace_back(found, output);
+ }
+
+ std::vector<std::shared_ptr<v0::Parameter>> preserved_inputs;
+ for (const auto& input : genai.preserved_inputs) {
+ auto parameter = find_parameter(model, input);
+ OPENVINO_ASSERT(parameter, "[GGUF] missing preserved GenAI input ", input);
+ if (std::find(preserved_inputs.begin(), preserved_inputs.end(), parameter) == preserved_inputs.end())
+ preserved_inputs.push_back(std::move(parameter));
+ }
+
// Token-only lookups move to the embedding model. FixEmbdAxis replaces them, keeping names.
std::string embedding_name, per_layer_name;
int64_t per_layer_count = 0;
@@ -295,6 +328,16 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
self_correcting_axis_manager.run_passes(model);
std::shared_ptr<v0::Parameter> inputs_embeds, per_layer_inputs;
+ auto native_hidden =
+ find_parameter(model, genai.attention_context_input.empty() ? "hidden_states" : genai.attention_context_input);
+ std::shared_ptr<v0::Parameter> hidden_states;
+ if (native_hidden) {
+ const auto width = native_hidden->get_partial_shape()[3];
+ hidden_states = make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{-1, -1, width});
+ name_output(hidden_states, "hidden_states");
+ native_hidden->output(0).replace(
+ make_shared<v0::Unsqueeze>(hidden_states, v0::Constant::create(ov::element::i64, {1}, {1}))->output(0));
+ }
if (m_mode == InputMode::EMBEDS_TO_LOGITS) {
// rt_info can propagate to helper nodes, so rediscover the lookups by name.
const auto find_boundary = [&](const std::string& name) {
@@ -314,14 +357,26 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
const auto width = embedding->get_output_partial_shape(0)[3].get_length();
// Clone each lookup graph before rewiring the language model. Constants retain shared buffers.
const auto extract = [&](const ov::Output<ov::Node>& lookup, const std::string& name, bool pad_media) {
- auto extracted = make_shared<ov::Model>(ov::OutputVector{lookup}, ov::ParameterVector{inp_tokens})->clone();
+ ov::ParameterVector parameters;
+ std::unordered_set<const ov::Node*> visited;
+ const auto collect = [&](const auto& self, const std::shared_ptr<ov::Node>& node) -> void {
+ if (!visited.insert(node.get()).second)
+ return;
+ if (auto parameter = ov::as_type_ptr<v0::Parameter>(node))
+ parameters.push_back(parameter);
+ for (const auto& input : node->input_values())
+ self(self, input.get_node_shared_ptr());
+ };
+ collect(collect, lookup.get_node_shared_ptr());
+ auto extracted = make_shared<ov::Model>(ov::OutputVector{lookup}, parameters)->clone();
extracted->get_rt_info() = model->get_rt_info();
auto ids = make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});
name_output(ids, "input_ids");
auto lookup_ids = pad_media ? pad_media_placeholders(*model, ids) : ids->output(0);
auto ids4 = make_shared<v0::Unsqueeze>(make_shared<v0::Convert>(lookup_ids, ov::element::i32),
v0::Constant::create(ov::element::i64, {2}, {0, 1}));
- auto old_ids = extracted->get_parameters().front();
+ auto old_ids = find_parameter(extracted, "inp_tokens");
+ OPENVINO_ASSERT(old_ids, "[GGUF] extracted embedding lookup requires token IDs");
old_ids->output(0).replace(ids4->output(0));
extracted->remove_parameter(old_ids);
extracted->add_parameters({ids});
@@ -364,6 +419,62 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
}
}
+ std::shared_ptr<v0::Parameter> deepstack_visual;
+ std::shared_ptr<v0::Parameter> visual_mask;
+ if (inputs_embeds) {
+ if (auto deepstack = find_parameter(model, "deepstack_embeds")) {
+ auto axis_0 = v0::Constant::create(ov::element::i64, {1}, {0});
+ const auto count = deepstack->get_partial_shape()[1].get_length();
+ const auto width = deepstack->get_partial_shape()[3].get_length();
+ deepstack_visual = make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{count, -1, width});
+ visual_mask = make_shared<v0::Parameter>(ov::element::boolean, ov::PartialShape{-1, -1});
+ name_output(deepstack_visual, "deepstack_visual_embeds");
+ name_output(visual_mask, "visual_pos_masks");
+ auto dimensions = get_dimensions(inputs_embeds, {0, 1});
+ auto total =
+ make_shared<v1::ReduceProd>(dimensions, v0::Constant::create(ov::element::i64, {1}, {0}), false);
+ auto target =
+ make_shared<v0::Concat>(ov::OutputVector{v0::Constant::create(ov::element::i64, {1}, {count}),
+ make_shared<v0::Unsqueeze>(total, axis_0),
+ v0::Constant::create(ov::element::i64, {1}, {width})},
+ 0);
+ auto empty = make_shared<v3::Broadcast>(v0::Constant::create(ov::element::f32, {}, {0}), target);
+ auto mask = make_shared<v1::Reshape>(visual_mask, v0::Constant::create(ov::element::i64, {1}, {-1}), false);
+ auto locations = make_shared<v3::NonZero>(mask, ov::element::i64);
+ auto indices = make_shared<v1::Transpose>(locations, v0::Constant::create(ov::element::i64, {2}, {1, 0}));
+ auto token_major =
+ make_shared<v1::Transpose>(empty, v0::Constant::create(ov::element::i64, {3}, {1, 0, 2}));
+ auto updates =
+ make_shared<v1::Transpose>(deepstack_visual, v0::Constant::create(ov::element::i64, {3}, {1, 0, 2}));
+ auto media_count = get_dimensions(indices, {0});
+ auto valid_updates = make_shared<v8::Slice>(updates,
+ v0::Constant::create(ov::element::i64, {1}, {0}),
+ media_count,
+ v0::Constant::create(ov::element::i64, {1}, {1}),
+ axis_0);
+ auto scattered = make_shared<v3::ScatterNDUpdate>(token_major, indices, valid_updates);
+ auto batched_shape = make_shared<v0::Concat>(
+ ov::OutputVector{dimensions, v0::Constant::create(ov::element::i64, {2}, {count, width})},
+ 0);
+ auto batched = make_shared<v1::Reshape>(scattered, batched_shape, false);
+ auto layer_major =
+ make_shared<v1::Transpose>(batched, v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3}));
+ deepstack->output(0).replace(layer_major->output(0));
+ }
+ } else if (auto deepstack = find_parameter(model, "deepstack_embeds")) {
+ const auto count = deepstack->get_partial_shape()[1].get_length();
+ const auto width = deepstack->get_partial_shape()[3].get_length();
+ auto tokens = find_parameter(model, "inp_tokens");
+ OPENVINO_ASSERT(tokens, "[GGUF] DeepStack text mode requires token IDs");
+ auto token_count = get_dimensions(tokens, {3});
+ auto target =
+ make_shared<v0::Concat>(ov::OutputVector{v0::Constant::create(ov::element::i64, {2}, {int64_t{1}, count}),
+ token_count,
+ v0::Constant::create(ov::element::i64, {1}, {width})},
+ 0);
+ deepstack->output(0).replace(
+ make_shared<v3::Broadcast>(v0::Constant::create(ov::element::f32, {}, {0}), target)->output(0));
+ }
if (inputs_embeds)
contract = read_model_contract(model, inputs_embeds->get_partial_shape()[2].get_length());
@@ -375,10 +486,12 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
name_output(input_ids, "input_ids");
auto attention_mask = make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});
name_output(attention_mask, "attention_mask");
+ const bool three_section_positions =
+ genai.position_layout == ModelContract::GenAIContract::PositionLayout::THREE_AXIS;
const bool multimodal_positions = inputs_embeds && model->get_rt_info().count(gguf_imrope_key());
- auto position_ids =
- make_shared<v0::Parameter>(ov::element::i64,
- multimodal_positions ? ov::PartialShape{4, -1, -1} : ov::PartialShape{-1, -1});
+ auto position_ids = make_shared<v0::Parameter>(
+ ov::element::i64,
+ multimodal_positions ? ov::PartialShape{three_section_positions ? 3 : 4, -1, -1} : ov::PartialShape{-1, -1});
name_output(position_ids, "position_ids");
std::shared_ptr<v0::Parameter> token_type_ids;
if (inputs_embeds && contract.image_attention != ModelContract::ImageAttentionMode::CAUSAL) {
@@ -412,6 +525,19 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
: make_shared<v3::ShapeOf>(input_ids, ov::element::i64)->output(0);
auto reduce_axis_0 = v0::Constant::create(ov::element::i64, {1}, {0});
auto seq_len = make_shared<v1::ReduceProd>(ids_shape, reduce_axis_0, true);
+ ov::Output<ov::Node> attention_shape = ids_shape;
+ if (!genai.attention_context_input.empty()) {
+ auto context = find_parameter(model, genai.attention_context_input);
+ OPENVINO_ASSERT(context, "[GGUF] missing attention context input ", genai.attention_context_input);
+ OPENVINO_ASSERT(context == native_hidden && hidden_states,
+ "[GGUF] attention context requires a hidden-state input");
+ auto context_len = get_dimensions(hidden_states, {1});
+ attention_shape =
+ make_shared<v0::Concat>(ov::OutputVector{gather_dims(ids_shape, {0}),
+ make_shared<v1::Add>(gather_dims(ids_shape, {1}), context_len)},
+ 0);
+ seq_len = make_shared<v1::ReduceProd>(attention_shape, reduce_axis_0, true);
+ }
if (token_len_per_seq)
token_len_per_seq->output(0).replace(seq_len->output(0));
@@ -441,11 +567,21 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
ov::Output<ov::Node> pos_i32 = make_shared<v0::Convert>(position_ids, ov::element::i32);
if (multimodal_positions) {
- // GenAI Qwen3.5 supplies [sequence, time, height, width]. ggml's rotary
- // sections are [time, height, width, extra]; the fourth is unused by Qwen.
- pos_i32 = make_shared<v8::Gather>(pos_i32,
- v0::Constant::create(ov::element::i64, {4}, {1, 2, 3, 0}),
- v0::Constant::create(ov::element::i64, {}, {0}));
+ if (three_section_positions) {
+ auto first_section = make_shared<v8::Slice>(pos_i32,
+ v0::Constant::create(ov::element::i64, {1}, {0}),
+ v0::Constant::create(ov::element::i64, {1}, {1}),
+ v0::Constant::create(ov::element::i64, {1}, {1}),
+ v0::Constant::create(ov::element::i64, {1}, {0}));
+ auto zeros = make_shared<v3::Broadcast>(v0::Constant::create(ov::element::i32, {}, {0}),
+ make_shared<v3::ShapeOf>(first_section));
+ pos_i32 = make_shared<v0::Concat>(ov::OutputVector{pos_i32, zeros}, 0);
+ } else {
+ // Move the sequence section behind the three spatial sections.
+ pos_i32 = make_shared<v8::Gather>(pos_i32,
+ v0::Constant::create(ov::element::i64, {4}, {1, 2, 3, 0}),
+ v0::Constant::create(ov::element::i64, {}, {0}));
+ }
// Preserve section-major positions within each sequence. PA moves tokens to
// the leading activation axis, so each token then carries its four sections.
auto section_shape =
@@ -453,13 +589,11 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
pos_i32 = make_shared<v1::Transpose>(make_shared<v1::Reshape>(pos_i32, section_shape, false),
v0::Constant::create(ov::element::i64, {3}, {1, 0, 2}));
} else if (model->get_rt_info().count(gguf_imrope_key())) {
- // M-RoPE (qwen35): inp_pos carries FOUR position sections per token, laid out section-major --
- // make_sin_cos reshapes it to {..,4,tokens} and transposes. GenAI supplies one position per
- // token, so tile it 4x along the token axis. All four sections hold the same value here: the
- // per-section split only differs for image/video input, and a text-only prompt has no spatial
- // axes to differ on (llama.cpp fills all sections with the text position likewise).
- auto tile_repeats = v0::Constant::create(ov::element::i64, {2}, {1, 4});
- pos_i32 = make_shared<v0::Tile>(pos_i32, tile_repeats);
+ auto zeros = make_shared<v3::Broadcast>(v0::Constant::create(ov::element::i32, {}, {0}),
+ make_shared<v3::ShapeOf>(pos_i32));
+ pos_i32 = make_shared<v0::Concat>(
+ ov::OutputVector{pos_i32, pos_i32, pos_i32, three_section_positions ? zeros->output(0) : pos_i32},
+ 1);
}
auto pos_4d = make_shared<v1::Reshape>(pos_i32, shape_keep0_1_1_rest, true);
if (inp_pos)
@@ -470,7 +604,7 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
auto am_shape = make_shared<v3::ShapeOf>(attention_mask, ov::element::i64);
auto kv_len = gather_dims(am_shape, {1});
auto batch_len = gather_dims(ids_shape, {0});
- auto query_len = gather_dims(ids_shape, {1});
+ auto query_len = gather_dims(attention_shape, {1});
// Cached tokens precede the current chunk in attention_mask.
auto past_len = make_shared<v1::Subtract>(kv_len, query_len);
auto one_1 = v0::Constant::create(ov::element::i64, {1}, {1});
@@ -492,7 +626,7 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
make_shared<v0::CumSum>(make_shared<v0::Convert>(attention_mask, ov::element::i32), axis_1),
one_i32);
ov::Output<ov::Node> q_pos = make_shared<v0::Convert>(position_ids, ov::element::i32);
- if (multimodal_positions) {
+ if (multimodal_positions || !genai.attention_context_input.empty()) {
// Spatial coordinates can repeat or decrease; causality follows token order.
q_pos = make_shared<v8::Slice>(key_positions, past_len, kv_len, one_1, one_1);
}
@@ -502,7 +636,11 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
return make_shared<v0::Unsqueeze>(make_shared<v1::Select>(predicate, zero_f, neg_f), one_1);
};
const auto causal = make_shared<v1::LessEqual>(k_row, q_pos_col);
- ov::Output<ov::Node> allowed = causal;
+ ov::Output<ov::Node> allowed =
+ !genai.causal_attention ? make_shared<v3::Broadcast>(v0::Constant::create(ov::element::boolean, {}, {true}),
+ make_shared<v3::ShapeOf>(causal))
+ ->output(0)
+ : causal->output(0);
ov::Output<ov::Node> same_image;
ov::Output<ov::Node> causal_or_query_image = causal;
ov::Output<ov::Node> causal_or_key_image = causal;
@@ -731,6 +869,15 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
ov::replace_node(node, div);
continue;
}
+ if (head_chain.size() == 1 && lm_head->output(0).get_target_inputs().size() == 1) {
+ // Scale activations instead of weights to keep the compressed head visible to GenAI.
+ auto scaled_hidden = make_shared<v1::Multiply>(hidden_3d, scalar);
+ ov::copy_runtime_info(node, scaled_hidden);
+ lm_head->input(0).replace_source_output(scaled_hidden);
+ lm_head->revalidate_and_infer_types();
+ ov::replace_output_update_name(node->output(0), lm_head->output(0));
+ continue;
+ }
node->input(1).replace_source_output(scalar);
}
}
@@ -755,14 +902,32 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
auto new_result = make_shared<v0::Result>(logits);
new_result->set_friendly_name("logits");
- ov::ResultVector outputs{new_result};
- const auto old_results = model->get_results();
- for (const auto& result : old_results) {
- model->remove_result(result);
- if (result != old_result)
- outputs.push_back(result);
+ const auto auxiliary_results = model->get_results();
+ if (genai.logits_first) {
+ for (const auto& result : auxiliary_results)
+ model->remove_result(result);
+ } else {
+ model->remove_result(old_result);
+ }
+ model->add_results({new_result});
+ for (const auto& [result, output] : auxiliary_outputs) {
+ ov::Output<ov::Node> value = result->input_value(0);
+ auto names = value.get_names();
+ const auto& result_names = result->output(0).get_names();
+ names.insert(result_names.begin(), result_names.end());
+ if (output.squeeze_axis)
+ value =
+ make_shared<v0::Squeeze>(value, v0::Constant::create(ov::element::i64, {1}, {*output.squeeze_axis}));
+ names.insert(output.name);
+ name_output(value, output.name);
+ value.set_names(names);
+ result->input(0).replace_source_output(value);
+ result->output(0).set_names({output.name});
}
- model->add_results(outputs);
+ if (genai.logits_first)
+ for (const auto& result : auxiliary_results)
+ if (result != old_result)
+ model->add_results({result});
std::unordered_set<std::string> normalized;
for (const auto& result : model->get_results()) {
@@ -805,12 +970,15 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
// gguf Parameter has had its output rewired (consumers now read the derived subgraph),
// so removing it is safe.
ov::ParameterVector kept{input_ids, attention_mask, position_ids};
- for (const auto& p : {inputs_embeds, per_layer_inputs, token_type_ids})
+ for (const auto& p :
+ {inputs_embeds, per_layer_inputs, token_type_ids, deepstack_visual, visual_mask, hidden_states})
if (p)
kept.push_back(p);
model->add_parameters(kept);
const auto params_snapshot = model->get_parameters(); // copy: remove_parameter mutates the list
for (const auto& p : params_snapshot) {
+ if (std::find(preserved_inputs.begin(), preserved_inputs.end(), p) != preserved_inputs.end())
+ continue;
if (p != beam_idx && std::find(kept.begin(), kept.end(), p) == kept.end())
model->remove_parameter(p);
}
diff --git a/src/frontends/gguf/src/pass/make_stateful.cpp b/src/frontends/gguf/src/pass/make_stateful.cpp
index bc8f6af2c72..c46d50a7675 100644
--- a/src/frontends/gguf/src/pass/make_stateful.cpp
+++ b/src/frontends/gguf/src/pass/make_stateful.cpp
@@ -463,11 +463,29 @@ bool GGUFMakeStateful::run_on_model(const std::shared_ptr<ov::Model>& model) {
auto concat = std::make_shared<v0::Concat>(ov::OutputVector{past, new_rows}, axis);
caches.push_back({read_value, concat.get(), init_shape});
concat->set_friendly_name(write->get_friendly_name());
- auto assign = std::make_shared<v6::Assign>(concat, var);
- copy_cache_write_runtime_info(
- write,
- cache_param,
- {beam_idx, init, read_value, split_shape, new_rows.get_node_shared_ptr(), axis0, past, concat, assign});
+ ov::Output<ov::Node> committed = concat;
+ ov::NodeVector replacements =
+ {beam_idx, init, read_value, split_shape, new_rows.get_node_shared_ptr(), axis0, past, concat};
+ const auto& info = write->get_rt_info();
+ if (const auto it = info.find("gguf.draft_context"); it != info.end()) {
+ ov::Output<ov::Node> context;
+ for (const auto& node : model->get_ordered_ops())
+ if (node->get_friendly_name() == it->second.as<std::string>())
+ context = node;
+ OPENVINO_ASSERT(context.get_node(), "[GGUF] missing draft context boundary");
+ auto shape = std::make_shared<v3::ShapeOf>(context, ov::element::i64);
+ auto count = std::make_shared<v8::Gather>(shape, v0::Constant::create(ov::element::i64, {1}, {2}), axis0);
+ auto context_rows = std::make_shared<v8::Slice>(new_rows,
+ v0::Constant::create(ov::element::i64, {1}, {0}),
+ count,
+ v0::Constant::create(ov::element::i64, {1}, {1}),
+ v0::Constant::create(ov::element::i64, {1}, {axis}));
+ committed = std::make_shared<v0::Concat>(ov::OutputVector{past, context_rows}, axis);
+ replacements.insert(replacements.end(), {shape, count, context_rows, committed.get_node_shared_ptr()});
+ }
+ auto assign = std::make_shared<v6::Assign>(committed, var);
+ replacements.push_back(assign);
+ copy_cache_write_runtime_info(write, cache_param, replacements);
new_sinks.push_back(assign);
// The stateless graph returns each updated cache as a Result; in the stateful form the Assign
diff --git a/src/frontends/gguf/src/quant/gguf_quants.cpp b/src/frontends/gguf/src/quant/gguf_quants.cpp
index eac74b796a6..7a49a3d08ec 100644
--- a/src/frontends/gguf/src/quant/gguf_quants.cpp
+++ b/src/frontends/gguf/src/quant/gguf_quants.cpp
@@ -596,36 +596,44 @@ void fill_q5_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& sc
}
// Store one 32-value group whose source values are q[k] in [0..31], w = d1*q - m1.
- const auto store_group = [&](size_t group, float d1, float m1, const uint8_t* q, uint8_t* dst) {
- if (!zp.is_integer()) {
- scales[group] = ov::float16(d1);
- zp.store(group, zp_from_offset(m1, d1));
- std::copy_n(q, 32, dst);
- return;
- }
- float values[32];
- float lo = 0.0f, hi = 0.0f;
- for (int k = 0; k < 32; ++k) {
- values[k] = d1 * static_cast<float>(q[k]) - m1;
- lo = std::min(lo, values[k]);
- hi = std::max(hi, values[k]);
- }
- const ov::float16 scale_f16((hi - lo) / 255.0f);
- const float scale = static_cast<float>(scale_f16);
- if (!(scale > 0.0f) || !std::isfinite(scale)) {
- // A (near-)zero range: every value rounds to zero.
- scales[group] = ov::float16(0.0f);
- zp.store_integer(group, 0);
- std::fill_n(dst, 32, 0);
- return;
- }
- const long zpi = std::clamp(std::lround(-lo / scale), 0L, 255L);
- scales[group] = scale_f16;
- zp.store_integer(group, static_cast<uint8_t>(zpi));
- for (int k = 0; k < 32; ++k) {
- dst[k] = static_cast<uint8_t>(std::clamp(std::lround(values[k] / scale) + zpi, 0L, 255L));
- }
- };
+ const auto store_group =
+ [&](size_t group, float d1, float m1, float source_min_scale, const uint8_t* q, uint8_t* dst) {
+ if (!zp.is_integer()) {
+ if (d1 == 0.f && m1 != 0.f) {
+ const float scale = std::fabs(source_min_scale);
+ scales[group] = ov::float16(scale);
+ zp.store(group, m1 / scale);
+ std::fill_n(dst, 32, 0);
+ return;
+ }
+ scales[group] = ov::float16(d1);
+ zp.store(group, zp_from_offset(m1, d1));
+ std::copy_n(q, 32, dst);
+ return;
+ }
+ float values[32];
+ float lo = 0.0f, hi = 0.0f;
+ for (int k = 0; k < 32; ++k) {
+ values[k] = d1 * static_cast<float>(q[k]) - m1;
+ lo = std::min(lo, values[k]);
+ hi = std::max(hi, values[k]);
+ }
+ const ov::float16 scale_f16((hi - lo) / 255.0f);
+ const float scale = static_cast<float>(scale_f16);
+ if (!(scale > 0.0f) || !std::isfinite(scale)) {
+ // A (near-)zero range: every value rounds to zero.
+ scales[group] = ov::float16(0.0f);
+ zp.store_integer(group, 0);
+ std::fill_n(dst, 32, 0);
+ return;
+ }
+ const long zpi = std::clamp(std::lround(-lo / scale), 0L, 255L);
+ scales[group] = scale_f16;
+ zp.store_integer(group, static_cast<uint8_t>(zpi));
+ for (int k = 0; k < 32; ++k) {
+ dst[k] = static_cast<uint8_t>(std::clamp(std::lround(values[k] / scale) + zpi, 0L, 255L));
+ }
+ };
ov::parallel_for(n_super_block, [&](size_t i) {
const uint8_t* block_data = data + i * bytes_per_block;
@@ -648,8 +656,8 @@ void fill_q5_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& sc
q1[l] = static_cast<uint8_t>((ql[l] & 0xF) + ((qh[l] & u1) ? 16 : 0));
q2[l] = static_cast<uint8_t>((ql[l] >> 4) + ((qh[l] & u2) ? 16 : 0));
}
- store_group(i * 8 + is, d1, m1, q1, weights + i * 256 + j);
- store_group(i * 8 + is + 1, d2, m2, q2, weights + i * 256 + j + 32);
+ store_group(i * 8 + is, d1, m1, dmin, q1, weights + i * 256 + j);
+ store_group(i * 8 + is + 1, d2, m2, dmin, q2, weights + i * 256 + j + 32);
ql += 32;
is += 2;
u1 <<= 2;
diff --git a/src/frontends/gguf/src/quant/weights.cpp b/src/frontends/gguf/src/quant/weights.cpp
index d4382e152d2..e62452e324c 100644
--- a/src/frontends/gguf/src/quant/weights.cpp
+++ b/src/frontends/gguf/src/quant/weights.cpp
@@ -376,9 +376,8 @@ bool needs_q8_0_c_requant(const std::string& name, GgufTensorType qtype) {
(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.
-// Production leaves this unset and uses the compressed-FC-friendly u4 requantization.
-bool q4_k_f16_zero_point_enabled() {
+// Keep fractional zero points for strict Q4_K / Q4_1 / Q5_K validation.
+bool fractional_zero_point_enabled() {
// Read once: this sits on a per-tensor path (gguf_zero_point_type is consulted for every
// asymmetric weight, twice per tensor during parsing).
static const bool enabled = [] {
@@ -626,7 +625,7 @@ void normalize_u2_zero_points(const std::shared_ptr<ov::Model>& model) {
}
bool native_q5_k_is_symmetric(const std::string& name) {
- return !is_embedding_or_output(name) && ov::util::ends_with(name, ".weight");
+ return !fractional_zero_point_enabled() && !is_embedding_or_output(name) && ov::util::ends_with(name, ".weight");
}
void notify_lossy_weight_approximation(LossyWeightApproximation kind) {
@@ -683,18 +682,22 @@ void notify_lossy_weight_approximation(LossyWeightApproximation kind) {
}
ov::element::Type gguf_zero_point_type(const std::string& name, GgufTensorType qtype) {
+ return gguf_zero_point_type(name, qtype, fractional_zero_point_enabled());
+}
+
+ov::element::Type gguf_zero_point_type(const std::string& name, GgufTensorType qtype, bool fractional_zero_point) {
// The CPU compressed-FullyConnected fast path only folds the dequant when the zero-point is an
// INTEGER constant; a fractional f16 one leaves a ~2x slower kernel, and the GPU oneDNN FC
// rejects it. Q4_K and Q4_1 matmul weights are decoded and requantized to an OpenVINO u4 grid
// and Q5_K ones to a u8 grid, all with an integer zero-point. Strict oracle validation can
- // request the faithful f16 zero-point of both u4 formats via OV_GGUF_Q4_K_ZP_F16. Q2_0's zero-point is exactly
+ // request fractional f16 zero-points for these 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) {
return ov::element::u8;
}
- const bool requantized = qtype == GGUF_TYPE_Q5_K ||
- ((qtype == GGUF_TYPE_Q4_K || qtype == GGUF_TYPE_Q4_1) && !q4_k_f16_zero_point_enabled());
+ const bool requantized =
+ (qtype == GGUF_TYPE_Q4_K || qtype == GGUF_TYPE_Q4_1 || qtype == GGUF_TYPE_Q5_K) && !fractional_zero_point;
return requantized && !is_embedding_or_output(name) ? ov::element::u8 : ov::element::f16;
}
diff --git a/src/frontends/gguf/src/quant/weights.hpp b/src/frontends/gguf/src/quant/weights.hpp
index c34fba0197f..f8c0c8fcdfe 100644
--- a/src/frontends/gguf/src/quant/weights.hpp
+++ b/src/frontends/gguf/src/quant/weights.hpp
@@ -31,8 +31,10 @@ ov::Output<ov::Node> gather_weight_rows(const ov::Output<ov::Node>& data, const
// zero-points for its host dequantizer, including Q2_0 embedding/output tensors.
// Q4_K and Q4_1 matmul weights are faithfully decoded and requantized to u4 with an integer
// zero-point, which keeps the compressed-FullyConnected path available on CPU and GPU. Native
-// Q5_K matmul weights use symmetric i8. token_embd/output keep an f16 zero-point.
+// Q5_K matmul weights use symmetric i8 by default. OV_GGUF_Q4_K_ZP_F16 selects fractional f16
+// zero-points for Q4_K, Q4_1 and Q5_K. token_embd/output keep an f16 zero-point.
ov::element::Type gguf_zero_point_type(const std::string& name, GgufTensorType qtype);
+ov::element::Type gguf_zero_point_type(const std::string& name, GgufTensorType qtype, bool fractional_zero_point);
bool native_q5_k_is_symmetric(const std::string& name);
diff --git a/src/frontends/gguf/src/translate_session.cpp b/src/frontends/gguf/src/translate_session.cpp
index 75fb2747745..03be918fb83 100644
--- a/src/frontends/gguf/src/translate_session.cpp
+++ b/src/frontends/gguf/src/translate_session.cpp
@@ -297,6 +297,11 @@ std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputMo
write_model_contract(resulting_model, gguf_model_decoder->get_model_contract());
if (const auto architecture = gguf_model_decoder->get_architecture(); !architecture.empty())
resulting_model->get_rt_info()["gguf_architecture"] = architecture;
+ if (builder) {
+ const auto info = builder->get_attribute("model_rt_info");
+ for (const auto& [key, value] : info.as<ov::AnyMap>())
+ resulting_model->get_rt_info()[key] = value;
+ }
if (!gguf_model_decoder->get_mmproj_config().empty()) {
resulting_model->get_rt_info()["gguf_mmproj"] = gguf_model_decoder->get_mmproj_config();
}
diff --git a/src/frontends/gguf/tests/CMakeLists.txt b/src/frontends/gguf/tests/CMakeLists.txt
index d62f3920c31..cabfb084e8b 100644
--- a/src/frontends/gguf/tests/CMakeLists.txt
+++ b/src/frontends/gguf/tests/CMakeLists.txt
@@ -126,6 +126,7 @@ set(TEST_SRCS
"${CMAKE_CURRENT_SOURCE_DIR}/test_builder_api.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/test_dequant_vs_ggml.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/test_extensions.cpp"
+ "${CMAKE_CURRENT_SOURCE_DIR}/test_half_experts.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/test_op_coverage.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/test_ops.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/test_gdn_normalization.cpp"
diff --git a/src/frontends/gguf/tests/architecture_oracle.cpp b/src/frontends/gguf/tests/architecture_oracle.cpp
index 3602f9d457d..171dffe2c39 100644
--- a/src/frontends/gguf/tests/architecture_oracle.cpp
+++ b/src/frontends/gguf/tests/architecture_oracle.cpp
@@ -4,17 +4,23 @@
// Build against a CPU-only llama.cpp. See gen_arch_accuracy.py.
#include <algorithm>
+#include <cmath>
#include <cstdint>
+#include <filesystem>
#include <fstream>
#include <stdexcept>
#include <string>
#include <vector>
#include "ggml-backend.h"
+#include "llama-ext.h"
#include "llama.h"
int main(int argc, char** argv) {
- if (argc != 3 && argc != 4)
+ if (argc != 3 && argc != 4 && argc != 5)
+ return 2;
+ if (argc == 5 && std::string(argv[3]) != "--draft" && std::string(argv[3]) != "--dflash" &&
+ std::string(argv[3]) != "--embeddings")
return 2;
llama_backend_init();
ggml_backend_dev_t devices[] = {ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU), nullptr};
@@ -32,14 +38,44 @@ int main(int argc, char** argv) {
cp.n_ubatch = 64;
cp.n_threads = cp.n_threads_batch = 4;
cp.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_DISABLED;
+ std::string dump_path;
+ if (const char* directory = std::getenv("GGUF_ARCH_ORACLE_DUMP")) {
+ std::filesystem::create_directories(directory);
+ dump_path = directory;
+ cp.cb_eval_user_data = &dump_path;
+ cp.cb_eval = [](ggml_tensor* tensor, bool ask, void* data) {
+ if (ask)
+ return tensor->type == GGML_TYPE_F32;
+ std::vector<char> bytes(ggml_nbytes(tensor));
+ ggml_backend_tensor_get(tensor, bytes.data(), 0, bytes.size());
+ std::ofstream file(
+ std::filesystem::path(*static_cast<const std::string*>(data)) / (std::string(tensor->name) + ".bin"),
+ std::ios::binary);
+ file.write(bytes.data(), bytes.size());
+ return true;
+ };
+ }
auto* ctx = llama_init_from_model(model, cp);
if (!ctx)
return 4;
- const int32_t vocab = llama_vocab_n_tokens(llama_model_get_vocab(model));
+ char architecture[64]{};
+ llama_model_meta_val_str(model, "general.architecture", architecture, sizeof(architecture));
+ const int32_t full_vocab = llama_vocab_n_tokens(llama_model_get_vocab(model));
+ const bool tts = std::string(architecture) == "qwen3tts";
+ const int32_t vocab = tts ? 3072 : full_vocab;
+ if (full_vocab < vocab)
+ return 12;
+ const int32_t vocab_offset = tts ? full_vocab - vocab : 0;
std::ofstream out(argv[2], std::ios::binary);
out.write(reinterpret_cast<const char*>(&vocab), sizeof(vocab));
const auto* vocabulary = llama_model_get_vocab(model);
const bool generation = argc == 4;
+ const bool dflash = argc == 5 && std::string(argv[3]) == "--dflash";
+ const bool draft = argc == 5 && (std::string(argv[3]) == "--draft" || dflash);
+ const bool embeddings = argc == 5 && std::string(argv[3]) == "--embeddings";
+ std::ifstream embedding_file;
+ if (embeddings || draft)
+ embedding_file.open(argv[4], std::ios::binary);
std::vector<llama_token> tokens{1, 2, 3};
if (generation) {
const std::string prompt = argv[3];
@@ -57,20 +93,114 @@ int main(int argc, char** argv) {
}
std::ofstream schedule(std::string(argv[2]) + ".tokens");
for (int step = 0; step < (generation ? 13 : 3); ++step) {
+ if (const auto directory = std::getenv("GGUF_ARCH_ORACLE_DUMP")) {
+ const auto path = std::filesystem::path(directory) / std::to_string(step);
+ std::filesystem::create_directories(path);
+ dump_path = path.string();
+ }
schedule << tokens.size();
for (auto token : tokens)
schedule << ' ' << token;
schedule << '\n';
- auto batch = llama_batch_get_one(tokens.data(), static_cast<int32_t>(tokens.size()));
- if (llama_decode(ctx, batch))
+ auto batch = embeddings
+ ? llama_batch_init(static_cast<int32_t>(tokens.size()), llama_model_n_embd_inp(model), 1)
+ : llama_batch_get_one(tokens.data(), static_cast<int32_t>(tokens.size()));
+ auto* allocated_positions = batch.pos;
+ std::vector<llama_pos> positions(4 * tokens.size());
+ if (embeddings) {
+ batch.n_tokens = static_cast<int32_t>(tokens.size());
+ embedding_file.read(reinterpret_cast<char*>(batch.embd),
+ tokens.size() * llama_model_n_embd_inp(model) * sizeof(float));
+ if (!embedding_file)
+ return 8;
+ const int offset = step == 0 ? 0 : step == 1 ? 3 : 4;
+ batch.pos = positions.data();
+ for (size_t i = 0; i < tokens.size(); ++i) {
+ for (size_t section = 0; section < 4; ++section)
+ batch.pos[section * tokens.size() + i] = section < 3 ? offset + static_cast<int>(i) : 0;
+ batch.n_seq_id[i] = 1;
+ batch.seq_id[i][0] = 0;
+ batch.logits[i] = i + 1 == tokens.size();
+ }
+ }
+ if (dflash) {
+ const size_t width = 3 * llama_model_n_embd(model);
+ std::vector<float> features(tokens.size() * width);
+ embedding_file.read(reinterpret_cast<char*>(features.data()), features.size() * sizeof(float));
+ if (!embedding_file)
+ return 8;
+ const int offset = step == 0 ? 0 : step == 1 ? 3 : 4;
+ auto* injection = llama_batch_ext_init(ctx);
+ for (size_t i = 0; i < tokens.size(); ++i) {
+ const auto index = llama_batch_ext_add_embd(injection, 0, {features.data() + i * width, 1, width});
+ const llama_pos position = offset + i;
+ llama_batch_ext_set_pos(injection, index, &position);
+ llama_batch_ext_set_output_embd(injection, index, true);
+ }
+ llama_set_causal_attn(ctx, false);
+ if (llama_process(ctx, LLAMA_PROCESS_TYPE_DECODE, injection))
+ return 9;
+ llama_batch_ext_free(injection);
+ auto* decoder = llama_batch_ext_init(ctx);
+ for (size_t i = 0; i < tokens.size(); ++i) {
+ const auto index = llama_batch_ext_add_token(decoder, 0, tokens[i]);
+ const llama_pos position = offset + tokens.size() + i;
+ llama_batch_ext_set_pos(decoder, index, &position);
+ llama_batch_ext_set_output_logits(decoder, index, true);
+ }
+ if (llama_process(ctx, LLAMA_PROCESS_TYPE_DECODE, decoder))
+ return 10;
+ llama_batch_ext_free(decoder);
+ if (!llama_memory_seq_rm(llama_get_memory(ctx), 0, offset + tokens.size(), -1))
+ return 11;
+ } else if (draft) {
+ const size_t width = 3 * llama_model_n_embd(model);
+ const size_t hidden = llama_model_n_embd(model);
+ std::vector<float> features(tokens.size() * width);
+ embedding_file.read(reinterpret_cast<char*>(features.data()), features.size() * sizeof(float));
+ if (!embedding_file)
+ return 8;
+ llama_set_embeddings_nextn(ctx, true, false);
+ auto* encoder = llama_batch_ext_init(ctx);
+ const int offset = step == 0 ? 0 : step == 1 ? 3 : 4;
+ for (size_t i = 0; i < tokens.size(); ++i) {
+ const auto index = llama_batch_ext_add_embd(encoder, 0, {features.data() + i * width, 1, width});
+ const llama_pos position = offset + i;
+ llama_batch_ext_set_pos(encoder, index, &position);
+ llama_batch_ext_set_output_embd(encoder, index, true);
+ }
+ if (llama_process(ctx, LLAMA_PROCESS_TYPE_ENCODE, encoder))
+ return 9;
+ std::vector<float> fused(llama_get_embeddings_nextn(ctx),
+ llama_get_embeddings_nextn(ctx) + tokens.size() * hidden);
+ llama_batch_ext_free(encoder);
+ auto* decoder = llama_batch_ext_init(ctx);
+ for (size_t i = 0; i < tokens.size(); ++i) {
+ const auto index = llama_batch_ext_add_token(decoder, 0, tokens[i]);
+ llama_batch_ext_set_embd_token(decoder, index, {fused.data() + i * hidden, 1, hidden});
+ const llama_pos position = offset + i;
+ llama_batch_ext_set_pos(decoder, index, &position);
+ llama_batch_ext_set_output_logits(decoder, index, true);
+ }
+ if (llama_process(ctx, LLAMA_PROCESS_TYPE_DECODE, decoder))
+ return 10;
+ llama_batch_ext_free(decoder);
+ } else if (llama_decode(ctx, batch))
return 5;
- const auto* logits = llama_get_logits_ith(ctx, -1);
+ if (embeddings) {
+ batch.pos = allocated_positions;
+ llama_batch_free(batch);
+ }
+ const auto* logits = llama_get_logits_ith(ctx, -1) + vocab_offset;
+ if (tts && !std::all_of(logits, logits + vocab, [](float value) {
+ return std::isfinite(value);
+ }))
+ return 13;
out.write(reinterpret_cast<const char*>(logits), vocab * sizeof(float));
- tokens =
- generation
- ? std::vector<llama_token>{static_cast<llama_token>(std::max_element(logits, logits + vocab) - logits)}
- : step == 0 ? std::vector<llama_token>{4}
- : std::vector<llama_token>{5, 6};
+ tokens = generation ? std::vector<llama_token>{static_cast<llama_token>(
+ std::max_element(logits, logits + vocab) - logits + vocab_offset)}
+ : step == 0 ? std::vector<llama_token>{4}
+ : std::vector<llama_token>{5, 6};
}
llama_free(ctx);
llama_model_free(model);
diff --git a/src/frontends/gguf/tests/gen_arch_accuracy.py b/src/frontends/gguf/tests/gen_arch_accuracy.py
index 163e9aff442..fbbf1ad5965 100644
--- a/src/frontends/gguf/tests/gen_arch_accuracy.py
+++ b/src/frontends/gguf/tests/gen_arch_accuracy.py
@@ -32,6 +32,27 @@ CASES = {
"lfm3-attention-first": {"architecture": "lfm3", "attention_first": True, "fused": True, "post": True},
"lfm3-wide-query": {"architecture": "lfm3", "heads": 6, "post": True},
"qwen35": {}, "qwen35moe": {},
+ "qwen3next": {}, "qwen3next-legacy": {"architecture": "qwen3next", "legacy": True},
+ "qwen3vl": {"qk": True, "mrope": True},
+ "qwen3tts": {"qk": True, "mrope": True, "vocab": 3072, "output_vocab": 3072},
+ "qwen3vlmoe": {"qk": True, "mrope": True, "moe": True},
+ "qwen3vl-deepstack": {"architecture": "qwen3vl", "qk": True, "mrope": True, "layers": 4, "deepstack": 2},
+ "cohere2": {"layer_norm": True, "swa": True, "layers": 4, "tied": True},
+ "gemma3n": {},
+ "eagle3": {"layers": 1},
+ "eagle3-fc-q4_1": {"architecture": "eagle3", "layers": 1,
+ "quantized": {"fc.weight": gguf.GGMLQuantizationType.Q4_1},
+ "q4_1_fc_exact": True, "q8_hidden_exact": True},
+ "eagle3-mapped": {"architecture": "eagle3", "layers": 1, "output_vocab": 16, "norm_before_fc": True,
+ "norm_before_residual": True, "d2t": True},
+ "dflash": {"layers": 2, "qk": True},
+ "dflash-fc-q4_1": {"architecture": "dflash", "layers": 2, "qk": True,
+ "quantized": {"fc.weight": gguf.GGMLQuantizationType.Q4_1},
+ "q4_1_fc_exact": True, "q8_hidden_exact": True},
+ "dflash-post": {"architecture": "dflash", "layers": 2, "qk": True, "post": True,
+ "layer_scale": True, "fc_scale": True, "value_scale": 1.5, "hidden_act": "gelu_pytorch_tanh"},
+ "dflash-shared": {"architecture": "dflash", "layers": 2, "qk": True, "shared_v": True},
+ "dflash-mapped": {"architecture": "dflash", "layers": 2, "qk": True, "output_vocab": 16, "d2t": True},
"qwen35-zero-scales": {"architecture": "qwen35", "zero_scales": True},
"qwen35moe-fused": {"architecture": "qwen35moe", "fused_experts": True},
# Real checkpoints quantize attn_gate apart from ssm_beta/ssm_alpha: F16 here selects the
@@ -79,13 +100,22 @@ CASES = {
}
-def tensor_writer(writer, rng, f16=()):
+def tensor_writer(writer, rng, f16=(), quantized=None, exact_q4_1=False):
"""Uniform random F32 tensors; norm weights are centered at 1. Names containing an `f16`
entry are stored as F16."""
+ quantized = quantized or {}
+
def tensor(name, shape, norm=False):
values = rng.uniform(-1, 1, shape).astype(np.float32)
values = 1 + values * .3 if norm else values * .2
- writer.add_tensor(name, values.astype(np.float16) if any(s in name for s in f16) else values)
+ if exact_q4_1 and name == "fc.weight":
+ codes = (np.arange(shape[0])[:, None] * 5 + np.arange(shape[1])[None, :] * 7) % 16
+ values = -1.0 + codes.astype(np.float32) * np.float32(0.125)
+ quantization = quantized.get(name)
+ if quantization is not None:
+ writer.add_tensor(name, gguf.quants.quantize(values, quantization), raw_dtype=quantization)
+ else:
+ writer.add_tensor(name, values.astype(np.float16) if any(s in name for s in f16) else values)
return tensor
@@ -124,7 +154,7 @@ def write_mamba2_model(path, opts, arch="mamba2"):
tensor(p + "attn_norm.weight", (d,), True)
if hybrid and layer == 1:
for name, width in (("q", 32), ("k", 16), ("v", 16)):
- tensor(p + f"attn_{name}.weight", (width, d))
+ tensor(p + f"attn_{name}.weight", (width, 2 * d if arch == "eagle3" else d))
tensor(p + f"attn_{name}.bias", (width,))
tensor(p + "attn_output.weight", (d, 32))
tensor(p + "attn_output.bias", (d,))
@@ -146,7 +176,7 @@ def write_mamba2_model(path, opts, arch="mamba2"):
finish(w)
-def write_qwen35_model(path, arch, fused_experts=False, f16=(), hadamard=False, zero_scales=False):
+def write_qwen35_model(path, arch, fused_experts=False, f16=(), hadamard=False, legacy=False, zero_scales=False):
w = gguf.GGUFWriter(path, arch)
d, head, heads, kv, ff, vocab = 32, 16, 4, 2, 48, 32
state, groups, vheads, kernel = 8, 2, 4, 4
@@ -161,7 +191,8 @@ def write_qwen35_model(path, arch, fused_experts=False, f16=(), hadamard=False,
w.add_value_length(head)
w.add_rope_dimension_count(8)
w.add_rope_freq_base(10000.)
- w.add_array(arch + ".rope.dimension_sections", [1, 1, 2, 0])
+ if arch != "qwen3next":
+ w.add_array(arch + ".rope.dimension_sections", [1, 1, 2, 0])
w.add_layer_norm_rms_eps(1e-5)
w.add_vocab_size(vocab)
w.add_tokenizer_model("none")
@@ -188,7 +219,7 @@ def write_qwen35_model(path, arch, fused_experts=False, f16=(), hadamard=False,
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"
+ moe = arch in ("qwen35moe", "qwen3next")
if moe:
w.add_expert_count(4)
w.add_expert_used_count(2)
@@ -205,18 +236,24 @@ def write_qwen35_model(path, arch, fused_experts=False, f16=(), hadamard=False,
tensor(p + "attn_norm.weight", (d,), True)
tensor(p + "post_attention_norm.weight", (d,), True)
if layer < 3:
- tensor(p + "attn_qkv.weight", (conv, d))
- tensor(p + "attn_gate.weight", (inner, d))
+ if legacy:
+ tensor(p + "ssm_in.weight", (conv + inner, d))
+ else:
+ tensor(p + "attn_qkv.weight", (conv, d))
+ tensor(p + "attn_gate.weight", (inner, d))
tensor(p + "ssm_conv1d.weight", (conv, kernel))
tensor(p + "ssm_dt.bias", (vheads,))
w.add_tensor(p + "ssm_a", -rng.uniform(.5, 1.5, vheads).astype(np.float32))
- for name in ("beta", "alpha"):
- tensor(p + f"ssm_{name}.weight", (vheads, d))
+ if arch == "qwen3next":
+ tensor(p + "ssm_ba.weight", (2 * vheads, d))
+ else:
+ for name in ("beta", "alpha"):
+ tensor(p + f"ssm_{name}.weight", (vheads, d))
tensor(p + "ssm_norm.weight", (state,), True)
tensor(p + "ssm_out.weight", (d, inner))
else:
for name, width in (("q", 2 * heads * head), ("k", kv * head), ("v", kv * head)):
- tensor(p + f"attn_{name}.weight", (width, d))
+ tensor(p + f"attn_{name}.weight", (width, 2 * d if arch == "eagle3" else d))
for name in ("q", "k"):
tensor(p + f"attn_{name}_norm.weight", (head,), True)
tensor(p + "attn_output.weight", (d, heads * head))
@@ -307,6 +344,51 @@ def write_gemma4_model(path, opts):
finish(w)
+def write_gemma3n_model(path):
+ w = gguf.GGUFWriter(path, "gemma3n")
+ d, heads, kv, head, ff, vocab, layers, pe = 32, 4, 2, 8, 48, 32, 5, 256
+ w.add_context_length(128)
+ w.add_embedding_length(d)
+ w.add_block_count(layers)
+ w.add_head_count(heads)
+ w.add_head_count_kv(kv)
+ w.add_key_length(head)
+ w.add_value_length(head)
+ w.add_feed_forward_length(ff)
+ w.add_layer_norm_rms_eps(1e-6)
+ w.add_sliding_window(2)
+ w.add_sliding_window_pattern(5)
+ w.add_rope_dimension_count(head)
+ w.add_rope_freq_base(100.)
+ w.add_rope_freq_base_swa(100.)
+ w.add_final_logit_softcapping(30.)
+ w.add_vocab_size(vocab)
+ w.add_tokenizer_model("none")
+ tensor = tensor_writer(w, np.random.default_rng(20261020))
+ tensor("token_embd.weight", (vocab, d))
+ tensor("output_norm.weight", (d,), True)
+ tensor("per_layer_token_embd.weight", (vocab, pe * layers))
+ tensor("per_layer_model_proj.weight", (pe * layers, d))
+ tensor("per_layer_proj_norm.weight", (pe,), True)
+ for name in ("altup_proj", "altup_unembd_proj"):
+ tensor(name + ".weight", (3, d, d))
+ for layer in range(layers):
+ p = f"blk.{layer}."
+ for name in ("attn_norm", "post_attention_norm", "ffn_norm", "post_ffw_norm", "post_norm",
+ "altup_correct_scale", "altup_router_norm", "laurel_post_norm"):
+ tensor(p + name + ".weight", (d,), True)
+ for name in ("attn_q_norm", "attn_k_norm"):
+ tensor(p + name + ".weight", (head,), True)
+ for name, shape in (("attn_q", (heads * head, d)), ("attn_k", (kv * head, d)),
+ ("attn_v", (kv * head, d)), ("attn_output", (d, heads * head)),
+ ("ffn_gate", (ff, d)), ("ffn_up", (ff, d)), ("ffn_down", (d, ff)),
+ ("inp_gate", (pe, d)), ("proj", (d, pe)), ("altup_correct_coef", (4, 4)),
+ ("altup_predict_coef", (16, 4)), ("altup_router", (4, d)),
+ ("laurel_l", (64, d)), ("laurel_r", (d, 64))):
+ tensor(p + name + ".weight", shape)
+ finish(w)
+
+
def write_lfm_model(path, arch, opts):
w = gguf.GGUFWriter(path, arch)
d, heads, kv, head, ff, vocab = 32, 4, 2, 8, 48, 32
@@ -384,16 +466,18 @@ def write_lfm_model(path, arch, opts):
def write_model(path, arch, opts):
arch = opts.get("architecture", arch)
+ if arch == "gemma3n":
+ return write_gemma3n_model(path)
if arch in ("lfm2", "lfm2moe", "lfm3"):
return write_lfm_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", ()), opts.get("hadamard", False), opts.get("zero_scales", False))
+ if arch in ("qwen35", "qwen35moe", "qwen3next"):
+ return write_qwen35_model(path, arch, opts.get("fused_experts", False), opts.get("f16", ()), opts.get("hadamard", False), legacy=opts.get("legacy", False), zero_scales=opts.get("zero_scales", False))
if arch in ("mamba2", "nemotron_h"):
return write_mamba2_model(path, opts, arch)
w = gguf.GGUFWriter(path, arch)
- d, heads, head, ff, vocab = opts.get("embedding", 32), 4, 8, 48, 32
+ d, heads, head, ff, vocab = opts.get("embedding", 32), 4, 8, 48, opts.get("vocab", 32)
kv = 1 if opts.get("mqa") else heads if opts.get("full_qk") or arch == "deepseek2-ocr" else 2
layers = opts.get("layers", 2)
w.add_context_length(128)
@@ -408,6 +492,20 @@ def write_model(path, arch, opts):
w.add_value_length(head)
w.add_rope_dimension_count(opts.get("rope_dims", head))
w.add_rope_freq_base(10000.0 if arch == "deepseek2-ocr" else 100.0)
+ if arch in ("eagle3", "dflash"):
+ w.add_array(arch + ".target_layers", [0, 1, 2])
+ w.add_uint32(arch + ".target_hidden_size", d)
+ for name in ("norm_before_fc", "norm_before_residual"):
+ if opts.get(name):
+ w.add_bool(arch + "." + name, True)
+ if opts.get("hidden_act"):
+ w.add_string(arch + ".hidden_activation", opts["hidden_act"])
+ if opts.get("value_scale"):
+ w.add_float32(arch + ".attention.value_scale", opts["value_scale"])
+ if opts.get("deepstack"):
+ w.add_uint32(arch + ".n_deepstack_layers", opts["deepstack"])
+ if opts.get("mrope"):
+ w.add_array(arch + ".rope.dimension_sections", [1, 1, 2, 0])
if opts.get("layer_norm"):
w.add_layer_norm_eps(1e-5)
else:
@@ -431,7 +529,7 @@ def write_model(path, arch, opts):
w.add_attn_temperature_scale(opts.get("temperature", 0.0))
if opts.get("swa"):
w.add_sliding_window(2)
- w.add_sliding_window_pattern(4 if arch == "afmoe" else 2)
+ w.add_sliding_window_pattern(4 if arch in ("cohere2", "afmoe") else 2)
if arch == "plamo3":
w.add_rope_freq_base_swa(100.0)
if opts.get("softcap"):
@@ -439,6 +537,8 @@ def write_model(path, arch, opts):
w.add_final_logit_softcapping(3.0)
if arch == "muse-glimmer":
w.add_logit_scale(1.0)
+ if arch == "cohere2":
+ w.add_logit_scale(0.3)
if arch == "minicpm" and not opts.get("default_logit_scale"):
w.add_logit_scale(d / 256.0)
if opts.get("moe"):
@@ -452,7 +552,7 @@ def write_model(path, arch, opts):
w.add_uint32(arch + ".expert_gating_func", 2 if opts.get("sigmoid") else 1)
if opts.get("expert_scale"):
w.add_expert_weights_scale(opts["expert_scale"])
- if arch not in ("hunyuan-moe", "qwen3moe", "ernie4_5-moe", "mellum", "minimax-m2"):
+ if arch not in ("qwen3vlmoe", "hunyuan-moe", "qwen3moe", "ernie4_5-moe", "mellum", "minimax-m2"):
w.add_expert_weights_norm(arch != "olmoe")
if arch == "bailingmoe2":
w.add_expert_group_count(2)
@@ -460,20 +560,34 @@ def write_model(path, arch, opts):
if arch == "ernie4_5-moe":
w.add_interleave_moe_layer_step(2)
rng = np.random.default_rng(20260907)
- tensor = tensor_writer(w, rng)
+ tensor = tensor_writer(w, rng, quantized=opts.get("quantized"),
+ exact_q4_1=opts.get("q4_1_fc_exact", False))
tensor("token_embd.weight", (vocab, d))
tensor("output_norm.weight", (d,), True)
- if opts.get("layer_norm"):
+ if opts.get("layer_norm") and arch != "cohere2":
tensor("output_norm.bias", (d,))
if not opts.get("tied"):
- tensor("output.weight", (vocab, d))
+ tensor("output.weight", (opts.get("output_vocab", vocab), d))
+ if arch == "dflash":
+ tensor("enc.output_norm.weight", (d,), True)
+ if arch in ("eagle3", "dflash"):
+ tensor("fc.weight", (d, 3 * d))
+ if opts.get("fc_scale"):
+ tensor("fc.scale", (1,), True)
+ if arch == "eagle3":
+ tensor("blk.0.attn_norm_2.weight", (d,), True)
+ if opts.get("norm_before_fc"):
+ tensor("enc.output_norm.weight", (3 * d,), True)
+ if opts.get("d2t"):
+ w.add_tensor("d2t", np.arange(0, vocab, 2, dtype=np.int64))
for layer in range(layers):
p = f"blk.{layer}."
if not opts.get("post_only"):
- for name in ("attn_norm", "post_attention_norm" if opts.get("ffn_post_attn") else "ffn_norm"):
+ norms = ("attn_norm",) if arch == "cohere2" else ("attn_norm", "post_attention_norm" if opts.get("ffn_post_attn") else "ffn_norm")
+ for name in norms:
tensor(p + name + ".weight", (d,), True)
- if opts.get("layer_norm"):
+ if opts.get("layer_norm") and arch != "cohere2":
tensor(p + name + ".bias", (d,))
if opts.get("post") or opts.get("post_only"):
for name in ("post_attention_norm", "post_ffw_norm"):
@@ -482,12 +596,16 @@ def write_model(path, arch, opts):
tensor(p + "attn_qkv.weight", ((heads + 2 * kv) * head, d))
else:
for name, width in (("q", heads * head), ("k", kv * head), ("v", kv * head)):
- tensor(p + f"attn_{name}.weight", (width, d))
+ if name == "v" and opts.get("shared_v"):
+ continue
+ tensor(p + f"attn_{name}.weight", (width, 2 * d if arch == "eagle3" else d))
if opts.get("bias"):
tensor(p + f"attn_{name}.bias", (width,))
tensor(p + "attn_output.weight", (d, heads * head))
- if opts.get("layer_norm"):
+ if opts.get("layer_norm") and arch != "cohere2":
tensor(p + "attn_output.bias", (d,))
+ if opts.get("layer_scale"):
+ tensor(p + "layer_output_scale.weight", (1,), True)
if opts.get("qk") or opts.get("full_qk"):
for name, width in (("q", heads * head), ("k", kv * head)):
tensor(p + f"attn_{name}_norm.weight", (width if opts.get("full_qk") else head,), True)
@@ -515,7 +633,7 @@ def write_model(path, arch, opts):
if opts.get("nextn"):
p = f"blk.{layers}."
for name, width in (("q", heads * head), ("k", kv * head), ("v", kv * head)):
- tensor(p + f"attn_{name}.weight", (width, d))
+ tensor(p + f"attn_{name}.weight", (width, 2 * d if arch == "eagle3" else d))
tensor(p + "attn_output.weight", (d, heads * head))
for name in ("attn_norm", "attn_q_norm", "attn_k_norm", "ffn_norm"):
tensor(p + name + ".weight", (head if "_q_" in name or "_k_" in name else d,), True)
@@ -544,7 +662,32 @@ def main():
reference = model.with_suffix(".bin")
write_model(model, arch, CASES[arch])
oracle = args.embedding_oracle if CASES[arch].get("embedding_output") else args.oracle
- result = subprocess.run([oracle, str(model), str(reference)], capture_output=True)
+ extra = {}
+ command = [oracle, str(model), str(reference)]
+ if CASES[arch].get("architecture", arch) in ("eagle3", "dflash"):
+ feature_shape = (6, 96)
+ if CASES[arch].get("q8_hidden_exact"):
+ codes = (np.arange(feature_shape[0])[:, None] * 47 + np.arange(feature_shape[1])[None, :] * 73) % 255 - 127
+ for block in range(0, feature_shape[1], 32):
+ codes[:, block] = 127
+ codes[:, block + 1] = -127
+ features = codes.astype(np.float32) * np.float32(1 / 512)
+ else:
+ features = np.random.default_rng(20261021).uniform(-.2, .2, feature_shape).astype(np.float32)
+ features.tofile(model.with_suffix(".features"))
+ command += ["--dflash" if CASES[arch].get("architecture", arch) == "dflash" else "--draft", str(model.with_suffix(".features"))]
+ extra["hidden_states"] = features
+ if CASES[arch].get("deepstack"):
+ reader = gguf.GGUFReader(model)
+ embedding = next(t.data for t in reader.tensors if t.name == "token_embd.weight")
+ count = CASES[arch]["deepstack"]
+ width = embedding.shape[1]
+ features = np.random.default_rng(20261019).uniform(-.2, .2, (6, count, width)).astype(np.float32)
+ packed = np.concatenate((embedding[[1, 2, 3, 4, 5, 6]][:, None, :], features), axis=1)
+ packed.tofile(model.with_suffix(".embeddings"))
+ command += ["--embeddings", str(model.with_suffix(".embeddings"))]
+ extra["deepstack"] = features
+ result = subprocess.run(command, capture_output=True)
if result.returncode:
raise RuntimeError(f"{arch}: oracle failed\n{result.stderr.decode()}")
if CASES[arch].get("embedding_output"):
@@ -557,8 +700,13 @@ def main():
continue
vocab = np.fromfile(reference, dtype="<i4", count=1)[0]
logits = np.fromfile(reference, dtype="<f4", offset=4).reshape(3, vocab)
- assert np.isfinite(logits).all() and np.linalg.norm(logits) > 0
- save_npz(args.out_dir / f"{arch}.npz", {"model": np.fromfile(model, dtype=np.uint8), "logits": logits})
+ if CASES[arch].get("d2t"):
+ extra["d2t"] = np.arange(0, vocab, 2, dtype=np.int64)
+ if CASES[arch].get("architecture", arch) != "dflash":
+ logits = logits[:, extra["d2t"]]
+ finite = logits[np.isfinite(logits)]
+ assert not np.isnan(logits).any() and np.linalg.norm(finite) > 0
+ save_npz(args.out_dir / f"{arch}.npz", {"model": np.fromfile(model, dtype=np.uint8), "logits": logits, **extra})
if args.header_dir:
from gen_arch_fixtures import strip_to_header
args.header_dir.mkdir(parents=True, exist_ok=True)
diff --git a/src/frontends/gguf/tests/gen_mmproj_accuracy.py b/src/frontends/gguf/tests/gen_mmproj_accuracy.py
index aff9a887e08..83070043471 100644
--- a/src/frontends/gguf/tests/gen_mmproj_accuracy.py
+++ b/src/frontends/gguf/tests/gen_mmproj_accuracy.py
@@ -26,9 +26,11 @@ SINGLE_GRID = ("gemma3", "gemma3_fused", "gemma3_legacy", "idefics3", "janus_pro
"voxtral_odd", "resampler", "resampler_v2", "resampler_v4")
# Single-grid models rerun here on two grids with different token counts.
REGRIDDED = ("qwen2.5vl_merger_grids", "resampler_grids")
+GEMMA3NV_FAMILIES = ("gemma3nv", "gemma3nv_uir", "gemma3nv_attention")
TWO_GRID = ("muse-glimmer", "pixtral", "pixtral_merge", "phi4", "lfm2", "lfm2_no_norm", "lfm2a", "gemma4v", "gemma4uv", "gemma4uv_low_contrast",
- "gemma4ua", "gemma4v_one_sided", "minicpmv4_6", "minicpmv4_7", "minicpmv4_7_4x", "gemma4a", "deepseekocr", "deepseekocr2",
- "deepseekocr_resize", "deepseekocr_overview", "deepseekocr2_overview", *REGRIDDED)
+ "gemma4ua", "gemma4v_one_sided", "minicpmv4_6", "minicpmv4_7", "minicpmv4_7_4x", "qwen3a", "qwen3tts_spkenc", "gemma3nv", "gemma4a", "deepseekocr", "deepseekocr2",
+ "deepseekocr_resize", "deepseekocr_overview", "deepseekocr2_overview", "gemma3nv_attention",
+ "gemma3nv_uir", *REGRIDDED)
def write_single_grid_model(path, projector, projection_width=6):
@@ -275,7 +277,7 @@ def single_grid_width(projector):
return 128 if projector.startswith("resampler") else 12 if projector == "qwen3vl_merger" else 6
-VARIANTS = ("_4x", "_resize", "_overview", "_one_sided", "_low_contrast")
+VARIANTS = ("_4x", "_resize", "_overview", "_one_sided", "_low_contrast", "_uir")
# mmproj_ops_oracle output file -> test_data .npy name.
OPS_EXPECTATIONS = {
"view_q8_input": "view_q8_input", "view_q8_34": "view_q8_34", "view_q8_102": "view_q8_102",
@@ -374,11 +376,17 @@ def write_grid_model(path, family):
family = "lfm2"
if family == "muse-glimmer":
return write_muse_model(path)
+ if family == "qwen3tts_spkenc":
+ return write_speaker_model(path)
+ attention_fixture = family == "gemma3nv_attention"
+ if attention_fixture:
+ family = "gemma3nv"
family, variants = split_variants(family, *VARIANTS)
+ uir = "_uir" in variants
one_sided = "_one_sided" in variants
low_contrast = "_low_contrast" in variants
- audio = family in {"gemma4ua", "gemma4a"}
- width, heads, hidden, output = 16, 2, 24, 12
+ audio = family in {"gemma4ua", "gemma4a", "qwen3a"}
+ width, heads, hidden, output = 16, 2, 24, 16 if family == "gemma3nv" else 12
prefix, modality = ("a.", "audio") if audio else ("v.", "vision")
w = gguf.GGUFWriter(path, "clip")
t = TensorWriter(w, np.random.default_rng(2718))
@@ -392,7 +400,49 @@ def write_grid_model(path, family):
"projection_dim": output, "attention.head_count": heads}.items():
w.add_uint32(key + name, value)
w.add_float32(key + "attention.layer_norm_epsilon", 1e-5)
- if family == "gemma4a":
+ if family == "gemma3nv":
+ w.add_uint32(key + "image_size", 256)
+ w.add_uint32(key + "patch_size", 1)
+ w.add_array(key + "image_mean", [0., 0., 0.])
+ w.add_array(key + "image_std", [1., 1., 1.])
+ tensor("v.conv_stem.conv.weight", (width, 3, 3, 3))
+ tensor("v.conv_stem.bn.weight", (width,), True)
+ for stage in range(4):
+ p = f"v.blk.{stage}.0."
+ if stage == 0:
+ tensor(p + "conv_exp.weight", (width, width, 3, 3))
+ tensor(p + "conv_pwl.weight", (width, width, 1, 1))
+ norm(p + "bn1", width, False)
+ norm(p + "bn2", width, False)
+ else:
+ if uir and stage == 1:
+ w.add_tensor(p + "dw_start.conv.weight",
+ t.rng.normal(0, t.std, (width, 1, 3, 3)).astype(np.float16))
+ norm(p + "dw_start.bn", width, False)
+ else:
+ tensor(p + "pw_exp.conv.weight", (width, width, 1, 1))
+ w.add_tensor(p + "dw_mid.conv.weight", t.rng.normal(0, t.std, (width, 1, 3, 3)).astype(np.float16))
+ tensor(p + "pw_proj.conv.weight", (width, width, 1, 1))
+ norms = ("dw_mid.bn", "pw_proj.bn") if uir and stage == 1 else (
+ "pw_exp.bn", "dw_mid.bn", "pw_proj.bn")
+ for name in norms:
+ norm(p + name, width, False)
+ if attention_fixture:
+ p = "v.blk.3.1."
+ norm(p + "norm", width, False)
+ for name, channels in (("query", width), ("key", width // 2), ("value", width // 2)):
+ tensor(p + "attn." + name + ".proj.weight", (channels, width, 1, 1))
+ if name != "query":
+ w.add_tensor(p + "attn." + name + ".down_conv.weight",
+ t.rng.normal(0, t.std, (width, 1, 3, 3)).astype(np.float16))
+ norm(p + "attn." + name + ".norm", width, False)
+ tensor(p + "attn.output.proj.weight", (width, width, 1, 1))
+ tensor("v.msfa.ffn.pw_exp.conv.weight", (width, width * 2, 1, 1))
+ tensor("v.msfa.ffn.pw_proj.conv.weight", (width, width, 1, 1))
+ for name in ("v.msfa.ffn.pw_exp.bn", "v.msfa.ffn.pw_proj.bn", "v.msfa.norm", "mm.soft_emb_norm"):
+ norm(name, width, False)
+ linear("mm.input_projection", width, output, False)
+ elif family == "gemma4a":
w.add_uint32(key + "num_mel_bins", 8)
for i, (ci, co) in enumerate(((1, 4), (4, 8))):
tensor(f"a.conv1d.{i}.weight", (co, ci, 3, 3))
@@ -420,6 +470,25 @@ def write_grid_model(path, family):
linear("a.pre_encode.out", width, width)
norm("mm.a.soft_emb_norm", width, False)
linear("mm.a.input_projection", width, output, False)
+ elif family == "qwen3a":
+ w.add_uint32(key + "num_mel_bins", 128)
+ w.add_uint32(key + "projector.stack_factor", 1)
+ for i, (ci, co) in enumerate(((1, 4), (4, 8), (8, 8)), 1):
+ tensor(f"a.conv2d.{i}.weight", (co, ci, 3, 3))
+ tensor(f"a.conv2d.{i}.bias", (co,))
+ linear("a.conv_out", 128, width, False)
+ tensor("a.position_embd.weight", (1500, width))
+ for i in range(2):
+ p = f"a.blk.{i}."
+ norm(p + "ln1", width)
+ norm(p + "ln2", width)
+ for name in ("attn_q", "attn_k", "attn_v", "attn_out"):
+ linear(p + name, width, width, name != "attn_k")
+ linear(p + "ffn_up", width, hidden)
+ linear(p + "ffn_down", hidden, width)
+ norm("a.post_ln", width)
+ linear("mm.a.mlp.1", width, hidden)
+ linear("mm.a.mlp.2", hidden, output)
elif audio:
w.add_uint32(key + "num_mel_bins", 640)
linear("mm.a.input_projection", 640, output, False)
@@ -549,7 +618,38 @@ def write_grid_model(path, family):
return output
-def grid_inputs(family, width, height):
+def write_speaker_model(path):
+ w = gguf.GGUFWriter(path, "clip")
+ w.add_bool("clip.has_audio_encoder", True)
+ w.add_string("clip.audio.projector_type", "qwen3tts_spkenc")
+ for name, value in {"embedding_length": 8, "block_count": 3, "num_mel_bins": 128,
+ "attention.head_count": 1, "feed_forward_length": 16, "projection_dim": 8}.items():
+ w.add_uint32("clip.audio." + name, value)
+ w.add_float32("clip.audio.attention.layer_norm_epsilon", 1e-5)
+ t = TensorWriter(w, np.random.default_rng(3141), std=.02)
+
+ def conv(name, inp, out, kernel=1):
+ t.tensor(name + ".weight", (out, inp, kernel))
+ t.tensor(name + ".bias", (out,))
+
+ conv("a.conv1d.0", 128, 16, 5)
+ for layer in range(1, 4):
+ p = f"a.blk.{layer}."
+ conv(p + "conv_pw1", 16, 16)
+ conv(p + "conv_pw2", 16, 16)
+ conv(p + "se_conv1", 16, 4)
+ conv(p + "se_conv2", 4, 16)
+ for branch in range(7):
+ conv(p + f"res2.{branch}", 2, 2, 3)
+ conv("a.conv_out", 48, 24)
+ conv("a.asp_tdnn", 72, 8)
+ conv("a.asp_attn", 8, 24)
+ conv("mm.a.fc", 48, 8)
+ finish(w)
+ return 8
+
+
+def grid_inputs(family, width, height, seed=42):
if family == "lfm2a":
raw = np.random.default_rng(42).normal(.1, .4, (height, width)).astype(np.float32)
return raw, {"features": raw.reshape(1, 1, height, width),
@@ -563,13 +663,15 @@ def grid_inputs(family, width, height):
return raw, {"pixel_values": raw.transpose(2, 0, 1)[None], **muse_glimmer_indices(height // 2, width // 2, 3)}
family, variants = split_variants(family, *VARIANTS)
overview = "_overview" in variants
- raw = np.random.default_rng(42).normal(.1, .4, (height, width) if family in {"gemma4ua", "gemma4a"} else (height, width, 3)).astype(np.float32)
+ raw = np.random.default_rng(seed).normal(.1, .4, (height, width) if family in {"gemma4ua", "gemma4a", "qwen3a", "qwen3tts_spkenc"} else (height, width, 3)).astype(np.float32)
if "_low_contrast" in variants:
raw[:] = np.array([27, 29, 32], np.float32) / 255
if family == "gemma4ua":
return raw, {"waveform_frames": raw.T.reshape(1, 1, width, height)}
if family == "gemma4a":
return raw, {"features": raw.reshape(1, 1, height, width)}
+ if family in {"qwen3a", "qwen3tts_spkenc"}:
+ return raw, {"features": raw.reshape(1, height, 1, width)}
if family.startswith("deepseekocr"):
# Repeat a nonzero tile to keep large SAM-grid fixtures compact on disk.
raw = np.tile(np.random.default_rng(42).normal(.1, .4, (16, 16, 3)).astype(np.float32), (height // 16, width // 16, 1))
@@ -651,11 +753,16 @@ def two_grid_fixture(oracle, family):
width_out = write_grid_model(path, family)
sizes = {
"deepseekocr2": [(768, 768), (1024, 1024)],
+ "gemma3nv": [(256, 256), (256, 256)],
+ "gemma3nv_uir": [(256, 256), (256, 256)],
+ "gemma3nv_attention": [(256, 256), (256, 256)],
"deepseekocr2_overview": [(768, 768), (1024, 1024)],
"deepseekocr_resize": [(128, 128), (512, 512)],
"deepseekocr_overview": [(256, 256), (256, 256)],
"deepseekocr": [(256, 256), (256, 512)],
"gemma4a": [(49, 8), (101, 8)],
+ "qwen3a": [(100, 128), (200, 128)],
+ "qwen3tts_spkenc": [(24, 128), (37, 128)],
"lfm2a": [(49, 8), (101, 8)],
"gemma4ua": [(3, 640), (5, 640)],
"gemma4uv_low_contrast": [(96, 48), (48, 144)],
@@ -669,7 +776,10 @@ def two_grid_fixture(oracle, family):
values = {"pixel_values": pixels, **values}
embeddings = run_encoder_oracle(oracle, path, projector, width, height, raw, second)
else:
- raw, values = grid_inputs(family, width, height)
+ if family in GEMMA3NV_FAMILIES and step == 1:
+ raw, values = grid_inputs(family, width, height, seed=43)
+ else:
+ raw, values = grid_inputs(family, width, height)
embeddings = run_encoder_oracle(oracle, path, family, width, height, raw, env=environment)
values["embeddings"] = embeddings.reshape(1, 1, -1, width_out)
fixtures.update({f"{step}.{k}": np.ascontiguousarray(v) for k, v in values.items()})
diff --git a/src/frontends/gguf/tests/gen_qwen3tts_accuracy.py b/src/frontends/gguf/tests/gen_qwen3tts_accuracy.py
new file mode 100644
index 00000000000..8ac28675cb1
--- /dev/null
+++ b/src/frontends/gguf/tests/gen_qwen3tts_accuracy.py
@@ -0,0 +1,334 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+"""Generate Qwen3TTS predictor and streaming waveform fixtures using pinned ggml CPU.
+
+PYTHONPATH=<llama.cpp>/gguf-py python3 gen_qwen3tts_accuracy.py --oracle <qwen3tts_oracle>
+"""
+import argparse
+import subprocess
+import tempfile
+from pathlib import Path
+
+import gguf
+import numpy as np
+
+from mmproj_fixtures import finish, save_npz
+
+
+def write_model(path):
+ writer = gguf.GGUFWriter(path, "clip")
+ writer.add_bool("clip.has_gen_audio_encoder", True)
+ writer.add_bool("clip.use_silu", True)
+ writer.add_string("clip.gen.audio.projector_type", "qwen3tts_gen")
+ for key, value in {"projection_dim": 32, "embedding_length": 16, "feed_forward_length": 48,
+ "block_count": 2, "attention.head_count": 2, "attention.head_count_kv": 1}.items():
+ writer.add_uint32("clip.gen.audio." + key, value)
+ writer.add_float32("clip.gen.audio.attention.layer_norm_epsilon", 1e-6)
+ writer.add_int32("general.sampling.top_k", 50)
+ writer.add_float32("general.sampling.top_p", 1.)
+ shapes = {
+ 'a.gen.wav.quant.first.in_proj.weight': (16, 32),
+ 'a.gen.wav.quant.first.out_proj.weight': (32, 16),
+ 'a.gen.wav.quant.first.codebook.weight': (128, 16),
+ 'a.gen.wav.quant.rest.in_proj.weight': (16, 32),
+ 'a.gen.wav.quant.rest.out_proj.weight': (32, 16),
+ 'a.gen.wav.quant.rest.codebook.weight': (15, 128, 16),
+ 'a.gen.wav.pre_conv.weight': (32, 32, 3),
+ 'a.gen.wav.pre_conv.bias': (32,),
+ 'a.gen.wav.tfm.in_proj.weight': (32, 32),
+ 'a.gen.wav.tfm.in_proj.bias': (32,),
+ 'a.gen.wav.tfm.out_proj.weight': (32, 32),
+ 'a.gen.wav.tfm.out_proj.bias': (32,),
+ 'a.gen.wav.tfm.output_norm.weight': (32,),
+ 'a.gen.wav.tfm.blk.0.ln1.weight': (32,),
+ 'a.gen.wav.tfm.blk.0.attn_q.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.0.attn_k.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.0.attn_v.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.0.attn_out.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.0.ls1.weight': (32,),
+ 'a.gen.wav.tfm.blk.0.ln2.weight': (32,),
+ 'a.gen.wav.tfm.blk.0.ffn_gate.weight': (64, 32),
+ 'a.gen.wav.tfm.blk.0.ffn_up.weight': (64, 32),
+ 'a.gen.wav.tfm.blk.0.ffn_down.weight': (32, 64),
+ 'a.gen.wav.tfm.blk.0.ls2.weight': (32,),
+ 'a.gen.wav.tfm.blk.1.ln1.weight': (32,),
+ 'a.gen.wav.tfm.blk.1.attn_q.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.1.attn_k.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.1.attn_v.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.1.attn_out.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.1.ls1.weight': (32,),
+ 'a.gen.wav.tfm.blk.1.ln2.weight': (32,),
+ 'a.gen.wav.tfm.blk.1.ffn_gate.weight': (64, 32),
+ 'a.gen.wav.tfm.blk.1.ffn_up.weight': (64, 32),
+ 'a.gen.wav.tfm.blk.1.ffn_down.weight': (32, 64),
+ 'a.gen.wav.tfm.blk.1.ls2.weight': (32,),
+ 'a.gen.wav.tfm.blk.2.ln1.weight': (32,),
+ 'a.gen.wav.tfm.blk.2.attn_q.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.2.attn_k.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.2.attn_v.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.2.attn_out.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.2.ls1.weight': (32,),
+ 'a.gen.wav.tfm.blk.2.ln2.weight': (32,),
+ 'a.gen.wav.tfm.blk.2.ffn_gate.weight': (64, 32),
+ 'a.gen.wav.tfm.blk.2.ffn_up.weight': (64, 32),
+ 'a.gen.wav.tfm.blk.2.ffn_down.weight': (32, 64),
+ 'a.gen.wav.tfm.blk.2.ls2.weight': (32,),
+ 'a.gen.wav.tfm.blk.3.ln1.weight': (32,),
+ 'a.gen.wav.tfm.blk.3.attn_q.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.3.attn_k.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.3.attn_v.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.3.attn_out.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.3.ls1.weight': (32,),
+ 'a.gen.wav.tfm.blk.3.ln2.weight': (32,),
+ 'a.gen.wav.tfm.blk.3.ffn_gate.weight': (64, 32),
+ 'a.gen.wav.tfm.blk.3.ffn_up.weight': (64, 32),
+ 'a.gen.wav.tfm.blk.3.ffn_down.weight': (32, 64),
+ 'a.gen.wav.tfm.blk.3.ls2.weight': (32,),
+ 'a.gen.wav.tfm.blk.4.ln1.weight': (32,),
+ 'a.gen.wav.tfm.blk.4.attn_q.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.4.attn_k.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.4.attn_v.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.4.attn_out.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.4.ls1.weight': (32,),
+ 'a.gen.wav.tfm.blk.4.ln2.weight': (32,),
+ 'a.gen.wav.tfm.blk.4.ffn_gate.weight': (64, 32),
+ 'a.gen.wav.tfm.blk.4.ffn_up.weight': (64, 32),
+ 'a.gen.wav.tfm.blk.4.ffn_down.weight': (32, 64),
+ 'a.gen.wav.tfm.blk.4.ls2.weight': (32,),
+ 'a.gen.wav.tfm.blk.5.ln1.weight': (32,),
+ 'a.gen.wav.tfm.blk.5.attn_q.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.5.attn_k.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.5.attn_v.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.5.attn_out.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.5.ls1.weight': (32,),
+ 'a.gen.wav.tfm.blk.5.ln2.weight': (32,),
+ 'a.gen.wav.tfm.blk.5.ffn_gate.weight': (64, 32),
+ 'a.gen.wav.tfm.blk.5.ffn_up.weight': (64, 32),
+ 'a.gen.wav.tfm.blk.5.ffn_down.weight': (32, 64),
+ 'a.gen.wav.tfm.blk.5.ls2.weight': (32,),
+ 'a.gen.wav.tfm.blk.6.ln1.weight': (32,),
+ 'a.gen.wav.tfm.blk.6.attn_q.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.6.attn_k.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.6.attn_v.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.6.attn_out.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.6.ls1.weight': (32,),
+ 'a.gen.wav.tfm.blk.6.ln2.weight': (32,),
+ 'a.gen.wav.tfm.blk.6.ffn_gate.weight': (64, 32),
+ 'a.gen.wav.tfm.blk.6.ffn_up.weight': (64, 32),
+ 'a.gen.wav.tfm.blk.6.ffn_down.weight': (32, 64),
+ 'a.gen.wav.tfm.blk.6.ls2.weight': (32,),
+ 'a.gen.wav.tfm.blk.7.ln1.weight': (32,),
+ 'a.gen.wav.tfm.blk.7.attn_q.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.7.attn_k.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.7.attn_v.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.7.attn_out.weight': (32, 32),
+ 'a.gen.wav.tfm.blk.7.ls1.weight': (32,),
+ 'a.gen.wav.tfm.blk.7.ln2.weight': (32,),
+ 'a.gen.wav.tfm.blk.7.ffn_gate.weight': (64, 32),
+ 'a.gen.wav.tfm.blk.7.ffn_up.weight': (64, 32),
+ 'a.gen.wav.tfm.blk.7.ffn_down.weight': (32, 64),
+ 'a.gen.wav.tfm.blk.7.ls2.weight': (32,),
+ 'a.gen.wav.up.blk.0.conv.weight': (32, 32, 2),
+ 'a.gen.wav.up.blk.0.conv.bias': (32,),
+ 'a.gen.wav.up.blk.0.dwconv.weight': (32, 1, 7),
+ 'a.gen.wav.up.blk.0.dwconv.bias': (32,),
+ 'a.gen.wav.up.blk.0.norm.weight': (32,),
+ 'a.gen.wav.up.blk.0.norm.bias': (32,),
+ 'a.gen.wav.up.blk.0.pw1.weight': (4096, 32),
+ 'a.gen.wav.up.blk.0.pw1.bias': (4096,),
+ 'a.gen.wav.up.blk.0.pw2.weight': (32, 4096),
+ 'a.gen.wav.up.blk.0.pw2.bias': (32,),
+ 'a.gen.wav.up.blk.0.gamma': (32,),
+ 'a.gen.wav.up.blk.1.conv.weight': (32, 32, 2),
+ 'a.gen.wav.up.blk.1.conv.bias': (32,),
+ 'a.gen.wav.up.blk.1.dwconv.weight': (32, 1, 7),
+ 'a.gen.wav.up.blk.1.dwconv.bias': (32,),
+ 'a.gen.wav.up.blk.1.norm.weight': (32,),
+ 'a.gen.wav.up.blk.1.norm.bias': (32,),
+ 'a.gen.wav.up.blk.1.pw1.weight': (4096, 32),
+ 'a.gen.wav.up.blk.1.pw1.bias': (4096,),
+ 'a.gen.wav.up.blk.1.pw2.weight': (32, 4096),
+ 'a.gen.wav.up.blk.1.pw2.bias': (32,),
+ 'a.gen.wav.up.blk.1.gamma': (32,),
+ 'a.gen.wav.dac.entry.weight': (1536, 32, 7),
+ 'a.gen.wav.dac.entry.bias': (1536,),
+ 'a.gen.wav.dac.blk.0.snake.alpha': (1536,),
+ 'a.gen.wav.dac.blk.0.snake.beta': (1536,),
+ 'a.gen.wav.dac.blk.0.conv.weight': (1536, 32, 16),
+ 'a.gen.wav.dac.blk.0.conv.bias': (32,),
+ 'a.gen.wav.dac.blk.0.res.0.act1.alpha': (32,),
+ 'a.gen.wav.dac.blk.0.res.0.act1.beta': (32,),
+ 'a.gen.wav.dac.blk.0.res.0.conv1.weight': (32, 32, 7),
+ 'a.gen.wav.dac.blk.0.res.0.conv1.bias': (32,),
+ 'a.gen.wav.dac.blk.0.res.0.act2.alpha': (32,),
+ 'a.gen.wav.dac.blk.0.res.0.act2.beta': (32,),
+ 'a.gen.wav.dac.blk.0.res.0.conv2.weight': (32, 32, 1),
+ 'a.gen.wav.dac.blk.0.res.0.conv2.bias': (32,),
+ 'a.gen.wav.dac.blk.0.res.1.act1.alpha': (32,),
+ 'a.gen.wav.dac.blk.0.res.1.act1.beta': (32,),
+ 'a.gen.wav.dac.blk.0.res.1.conv1.weight': (32, 32, 7),
+ 'a.gen.wav.dac.blk.0.res.1.conv1.bias': (32,),
+ 'a.gen.wav.dac.blk.0.res.1.act2.alpha': (32,),
+ 'a.gen.wav.dac.blk.0.res.1.act2.beta': (32,),
+ 'a.gen.wav.dac.blk.0.res.1.conv2.weight': (32, 32, 1),
+ 'a.gen.wav.dac.blk.0.res.1.conv2.bias': (32,),
+ 'a.gen.wav.dac.blk.0.res.2.act1.alpha': (32,),
+ 'a.gen.wav.dac.blk.0.res.2.act1.beta': (32,),
+ 'a.gen.wav.dac.blk.0.res.2.conv1.weight': (32, 32, 7),
+ 'a.gen.wav.dac.blk.0.res.2.conv1.bias': (32,),
+ 'a.gen.wav.dac.blk.0.res.2.act2.alpha': (32,),
+ 'a.gen.wav.dac.blk.0.res.2.act2.beta': (32,),
+ 'a.gen.wav.dac.blk.0.res.2.conv2.weight': (32, 32, 1),
+ 'a.gen.wav.dac.blk.0.res.2.conv2.bias': (32,),
+ 'a.gen.wav.dac.blk.1.snake.alpha': (32,),
+ 'a.gen.wav.dac.blk.1.snake.beta': (32,),
+ 'a.gen.wav.dac.blk.1.conv.weight': (32, 32, 10),
+ 'a.gen.wav.dac.blk.1.conv.bias': (32,),
+ 'a.gen.wav.dac.blk.1.res.0.act1.alpha': (32,),
+ 'a.gen.wav.dac.blk.1.res.0.act1.beta': (32,),
+ 'a.gen.wav.dac.blk.1.res.0.conv1.weight': (32, 32, 7),
+ 'a.gen.wav.dac.blk.1.res.0.conv1.bias': (32,),
+ 'a.gen.wav.dac.blk.1.res.0.act2.alpha': (32,),
+ 'a.gen.wav.dac.blk.1.res.0.act2.beta': (32,),
+ 'a.gen.wav.dac.blk.1.res.0.conv2.weight': (32, 32, 1),
+ 'a.gen.wav.dac.blk.1.res.0.conv2.bias': (32,),
+ 'a.gen.wav.dac.blk.1.res.1.act1.alpha': (32,),
+ 'a.gen.wav.dac.blk.1.res.1.act1.beta': (32,),
+ 'a.gen.wav.dac.blk.1.res.1.conv1.weight': (32, 32, 7),
+ 'a.gen.wav.dac.blk.1.res.1.conv1.bias': (32,),
+ 'a.gen.wav.dac.blk.1.res.1.act2.alpha': (32,),
+ 'a.gen.wav.dac.blk.1.res.1.act2.beta': (32,),
+ 'a.gen.wav.dac.blk.1.res.1.conv2.weight': (32, 32, 1),
+ 'a.gen.wav.dac.blk.1.res.1.conv2.bias': (32,),
+ 'a.gen.wav.dac.blk.1.res.2.act1.alpha': (32,),
+ 'a.gen.wav.dac.blk.1.res.2.act1.beta': (32,),
+ 'a.gen.wav.dac.blk.1.res.2.conv1.weight': (32, 32, 7),
+ 'a.gen.wav.dac.blk.1.res.2.conv1.bias': (32,),
+ 'a.gen.wav.dac.blk.1.res.2.act2.alpha': (32,),
+ 'a.gen.wav.dac.blk.1.res.2.act2.beta': (32,),
+ 'a.gen.wav.dac.blk.1.res.2.conv2.weight': (32, 32, 1),
+ 'a.gen.wav.dac.blk.1.res.2.conv2.bias': (32,),
+ 'a.gen.wav.dac.blk.2.snake.alpha': (32,),
+ 'a.gen.wav.dac.blk.2.snake.beta': (32,),
+ 'a.gen.wav.dac.blk.2.conv.weight': (32, 32, 8),
+ 'a.gen.wav.dac.blk.2.conv.bias': (32,),
+ 'a.gen.wav.dac.blk.2.res.0.act1.alpha': (32,),
+ 'a.gen.wav.dac.blk.2.res.0.act1.beta': (32,),
+ 'a.gen.wav.dac.blk.2.res.0.conv1.weight': (32, 32, 7),
+ 'a.gen.wav.dac.blk.2.res.0.conv1.bias': (32,),
+ 'a.gen.wav.dac.blk.2.res.0.act2.alpha': (32,),
+ 'a.gen.wav.dac.blk.2.res.0.act2.beta': (32,),
+ 'a.gen.wav.dac.blk.2.res.0.conv2.weight': (32, 32, 1),
+ 'a.gen.wav.dac.blk.2.res.0.conv2.bias': (32,),
+ 'a.gen.wav.dac.blk.2.res.1.act1.alpha': (32,),
+ 'a.gen.wav.dac.blk.2.res.1.act1.beta': (32,),
+ 'a.gen.wav.dac.blk.2.res.1.conv1.weight': (32, 32, 7),
+ 'a.gen.wav.dac.blk.2.res.1.conv1.bias': (32,),
+ 'a.gen.wav.dac.blk.2.res.1.act2.alpha': (32,),
+ 'a.gen.wav.dac.blk.2.res.1.act2.beta': (32,),
+ 'a.gen.wav.dac.blk.2.res.1.conv2.weight': (32, 32, 1),
+ 'a.gen.wav.dac.blk.2.res.1.conv2.bias': (32,),
+ 'a.gen.wav.dac.blk.2.res.2.act1.alpha': (32,),
+ 'a.gen.wav.dac.blk.2.res.2.act1.beta': (32,),
+ 'a.gen.wav.dac.blk.2.res.2.conv1.weight': (32, 32, 7),
+ 'a.gen.wav.dac.blk.2.res.2.conv1.bias': (32,),
+ 'a.gen.wav.dac.blk.2.res.2.act2.alpha': (32,),
+ 'a.gen.wav.dac.blk.2.res.2.act2.beta': (32,),
+ 'a.gen.wav.dac.blk.2.res.2.conv2.weight': (32, 32, 1),
+ 'a.gen.wav.dac.blk.2.res.2.conv2.bias': (32,),
+ 'a.gen.wav.dac.blk.3.snake.alpha': (32,),
+ 'a.gen.wav.dac.blk.3.snake.beta': (32,),
+ 'a.gen.wav.dac.blk.3.conv.weight': (32, 32, 6),
+ 'a.gen.wav.dac.blk.3.conv.bias': (32,),
+ 'a.gen.wav.dac.blk.3.res.0.act1.alpha': (32,),
+ 'a.gen.wav.dac.blk.3.res.0.act1.beta': (32,),
+ 'a.gen.wav.dac.blk.3.res.0.conv1.weight': (32, 32, 7),
+ 'a.gen.wav.dac.blk.3.res.0.conv1.bias': (32,),
+ 'a.gen.wav.dac.blk.3.res.0.act2.alpha': (32,),
+ 'a.gen.wav.dac.blk.3.res.0.act2.beta': (32,),
+ 'a.gen.wav.dac.blk.3.res.0.conv2.weight': (32, 32, 1),
+ 'a.gen.wav.dac.blk.3.res.0.conv2.bias': (32,),
+ 'a.gen.wav.dac.blk.3.res.1.act1.alpha': (32,),
+ 'a.gen.wav.dac.blk.3.res.1.act1.beta': (32,),
+ 'a.gen.wav.dac.blk.3.res.1.conv1.weight': (32, 32, 7),
+ 'a.gen.wav.dac.blk.3.res.1.conv1.bias': (32,),
+ 'a.gen.wav.dac.blk.3.res.1.act2.alpha': (32,),
+ 'a.gen.wav.dac.blk.3.res.1.act2.beta': (32,),
+ 'a.gen.wav.dac.blk.3.res.1.conv2.weight': (32, 32, 1),
+ 'a.gen.wav.dac.blk.3.res.1.conv2.bias': (32,),
+ 'a.gen.wav.dac.blk.3.res.2.act1.alpha': (32,),
+ 'a.gen.wav.dac.blk.3.res.2.act1.beta': (32,),
+ 'a.gen.wav.dac.blk.3.res.2.conv1.weight': (32, 32, 7),
+ 'a.gen.wav.dac.blk.3.res.2.conv1.bias': (32,),
+ 'a.gen.wav.dac.blk.3.res.2.act2.alpha': (32,),
+ 'a.gen.wav.dac.blk.3.res.2.act2.beta': (32,),
+ 'a.gen.wav.dac.blk.3.res.2.conv2.weight': (32, 32, 1),
+ 'a.gen.wav.dac.blk.3.res.2.conv2.bias': (32,),
+ 'a.gen.wav.dac.post_snake.alpha': (32,),
+ 'a.gen.wav.dac.post_snake.beta': (32,),
+ 'a.gen.wav.dac.post_conv.weight': (1, 32, 7),
+ 'a.gen.wav.dac.post_conv.bias': (1,),
+ 'a.gen.code.head.weight': (15, 128, 16),
+ 'a.gen.code.embd.weight': (15, 128, 32),
+ 'a.gen.code.blk.0.ln1.weight': (16,),
+ 'a.gen.code.blk.0.ffn_down.weight': (16, 48),
+ 'a.gen.code.blk.0.ffn_gate.weight': (48, 16),
+ 'a.gen.code.blk.0.ffn_up.weight': (48, 16),
+ 'a.gen.code.blk.0.ln2.weight': (16,),
+ 'a.gen.code.blk.0.attn_k_norm.weight': (4,),
+ 'a.gen.code.blk.0.attn_k.weight': (4, 16),
+ 'a.gen.code.blk.0.attn_out.weight': (16, 8),
+ 'a.gen.code.blk.0.attn_q_norm.weight': (4,),
+ 'a.gen.code.blk.0.attn_q.weight': (8, 16),
+ 'a.gen.code.blk.0.attn_v.weight': (4, 16),
+ 'a.gen.code.blk.1.ln1.weight': (16,),
+ 'a.gen.code.blk.1.ffn_down.weight': (16, 48),
+ 'a.gen.code.blk.1.ffn_gate.weight': (48, 16),
+ 'a.gen.code.blk.1.ffn_up.weight': (48, 16),
+ 'a.gen.code.blk.1.ln2.weight': (16,),
+ 'a.gen.code.blk.1.attn_k_norm.weight': (4,),
+ 'a.gen.code.blk.1.attn_k.weight': (4, 16),
+ 'a.gen.code.blk.1.attn_out.weight': (16, 8),
+ 'a.gen.code.blk.1.attn_q_norm.weight': (4,),
+ 'a.gen.code.blk.1.attn_q.weight': (8, 16),
+ 'a.gen.code.blk.1.attn_v.weight': (4, 16),
+ 'a.gen.code.output_norm.weight': (16,),
+ 'a.gen.code.proj_in.bias': (16,),
+ 'a.gen.code.proj_in.weight': (16, 32),
+ 'a.gen.code.out_embd.weight': (128, 32),
+ }
+ rng = np.random.default_rng(1729)
+ for name, shape in shapes.items():
+ centered = (("norm" in name or ".ln" in name) and name.endswith(".weight")) or name.endswith((".alpha", ".beta"))
+ writer.add_tensor(name, rng.normal(0, .01, shape).astype(np.float32) + int(centered))
+ finish(writer)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--oracle", required=True, type=Path)
+ parser.add_argument("--output", type=Path, default=Path(__file__).parent / "test_data/mmproj_accuracy/qwen3tts_gen.npz")
+ args = parser.parse_args()
+ with tempfile.TemporaryDirectory() as temporary:
+ temporary = Path(temporary)
+ model = temporary / "model.gguf"
+ write_model(model)
+ hidden = np.random.default_rng(42).normal(0, .1, 32).astype(np.float32)
+ hidden.tofile(temporary / "hidden.bin")
+ reference = temporary / "reference"
+ subprocess.run([str(args.oracle.resolve()), str(model), str(temporary / "hidden.bin"), str(reference)], check=True)
+ arrays = {"model": np.frombuffer(model.read_bytes(), np.uint8), "hidden": hidden.reshape(1, 1, 1, 32),
+ "code0": np.array([[[[7]]]], np.int32), "random": np.fromfile(reference / "random.bin", np.float32),
+ "codes": np.fromfile(reference / "codes.bin", np.int32),
+ "feedback": np.fromfile(reference / "feedback.bin", np.float32),
+ "wave_codes": np.fromfile(reference / "wave_codes.bin", np.int32).reshape(72, 16).T.copy().reshape(1, 1, 16, 72)}
+ for group in range(1, 15):
+ arrays[f"logits{group}"] = np.fromfile(reference / f"step_logits-{group}.bin", np.float32)
+ for step in range(2):
+ arrays[f"waveform{step}"] = np.fromfile(reference / f"waveform{step}.bin", np.float32)
+ save_npz(args.output, arrays)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/frontends/gguf/tests/op_test_utils.hpp b/src/frontends/gguf/tests/op_test_utils.hpp
index 321f5633a51..073cb39c0c8 100644
--- a/src/frontends/gguf/tests/op_test_utils.hpp
+++ b/src/frontends/gguf/tests/op_test_utils.hpp
@@ -17,6 +17,7 @@
#pragma once
#include <algorithm>
+#include <array>
#include <cmath>
#include <cstring>
#include <filesystem>
@@ -35,7 +36,9 @@
#include "op_table.hpp"
#include "openvino/core/model.hpp"
#include "openvino/core/partial_shape.hpp"
+#include "openvino/core/type/bfloat16.hpp"
#include "openvino/core/type/element_type.hpp"
+#include "openvino/core/type/float16.hpp"
#include "openvino/core/visibility.hpp"
#include "openvino/frontend/gguf/frontend.hpp"
#include "openvino/op/parameter.hpp"
@@ -44,6 +47,7 @@
#include "openvino/runtime/properties.hpp"
#include "openvino/runtime/tensor.hpp"
#include "openvino/util/file_util.hpp"
+#include "quant/gguf.hpp"
// TEST_DATA_DIR is injected by CMakeLists.txt as an absolute path to the source-tree
// test_data/ directory; used as a fallback when running from the build tree.
@@ -338,6 +342,37 @@ inline const cnpy::NpyArray& npz_array(const cnpy::npz_t& arrays, const std::str
return it->second;
}
+inline void quantize_weight(GgufWeightTable& weights, const std::string& name, GgufTensorType type) {
+ const auto source = weights.at(name).data;
+ OPENVINO_ASSERT(source.get_element_type() == ov::element::f32);
+ const auto* values = source.data<const float>();
+ GgufWeight result;
+ result.shape = source.get_shape();
+ result.qtype = type;
+ result.source_name = name;
+ if (type == GGUF_TYPE_BF16) {
+ ov::Tensor converted(ov::element::bf16, source.get_shape());
+ std::transform(values, values + source.get_size(), converted.data<ov::bfloat16>(), [](float value) {
+ return ov::bfloat16(value);
+ });
+ result.data = std::move(converted);
+ } else {
+ OPENVINO_ASSERT(type == GGUF_TYPE_Q8_0 && !source.get_shape().empty() && source.get_shape().back() % 32 == 0);
+ ov::Tensor packed(ov::element::u8, {source.get_size() / 32 * 34});
+ for (size_t group = 0; group < source.get_size() / 32; ++group) {
+ std::array<int8_t, 32> codes;
+ ov::float16 scale;
+ quantize_row_q8_0_c(values + group * 32, codes.size(), codes.data(), scale);
+ const auto bits = scale.to_bits();
+ auto* block = packed.data<uint8_t>() + group * 34;
+ std::memcpy(block, &bits, sizeof(bits));
+ std::memcpy(block + sizeof(bits), codes.data(), codes.size());
+ }
+ result.data = std::move(packed);
+ }
+ weights.at(name) = std::move(result);
+}
+
// Normalized MSE, the acceptance metric for the accuracy fixtures: sum((a-e)^2) / sum(e^2).
class Nmse {
public:
diff --git a/src/frontends/gguf/tests/pointwise_conv_oracle.cpp b/src/frontends/gguf/tests/pointwise_conv_oracle.cpp
new file mode 100644
index 00000000000..8a29a967849
--- /dev/null
+++ b/src/frontends/gguf/tests/pointwise_conv_oracle.cpp
@@ -0,0 +1,49 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+// Independent ggml CPU reference for the opt-in F16 im2col convolution tests.
+
+#include <cstdio>
+#include <vector>
+
+#include "ggml-backend.h"
+#include "ggml-cpu.h"
+#include "ggml.h"
+
+int main() {
+ const float xv[] = {1.0003f, -2.0006f, 0.3334f, 2.0006f, 0.7002f, -1.0003f};
+ const float wv[] = {1.0003f, 0.3334f, -0.7002f, 1.0003f};
+ for (const auto weight_type : {GGML_TYPE_F32, GGML_TYPE_F16}) {
+ ggml_init_params params{1024 * 1024, nullptr, true};
+ auto* ctx = ggml_init(params);
+ auto* x = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 3, 1, 2, 1);
+ auto* w = ggml_new_tensor_4d(ctx, weight_type, 1, 1, 2, 2);
+ auto* y = ggml_conv_2d(ctx, w, x, 1, 1, 0, 0, 1, 1);
+ auto* graph = ggml_new_graph(ctx);
+ ggml_build_forward_expand(graph, y);
+ auto backend = ggml_backend_cpu_init();
+ ggml_backend_cpu_set_n_threads(backend, 1);
+ auto buffer = ggml_backend_alloc_ctx_tensors(ctx, backend);
+ ggml_backend_tensor_set(x, xv, 0, sizeof(xv));
+ if (weight_type == GGML_TYPE_F32) {
+ ggml_backend_tensor_set(w, wv, 0, sizeof(wv));
+ } else {
+ ggml_fp16_t half[4];
+ ggml_fp32_to_fp16_row(wv, half, 4);
+ ggml_backend_tensor_set(w, half, 0, sizeof(half));
+ }
+ const auto status = ggml_backend_graph_compute(backend, graph);
+ if (status != GGML_STATUS_SUCCESS)
+ return 1;
+ std::vector<float> actual(ggml_nelements(y));
+ ggml_backend_tensor_get(y, actual.data(), 0, actual.size() * sizeof(float));
+ std::printf("%s", ggml_type_name(weight_type));
+ for (float value : actual)
+ std::printf(" %.9g", value);
+ std::printf("\n");
+ ggml_backend_buffer_free(buffer);
+ ggml_backend_free(backend);
+ ggml_free(ctx);
+ }
+ return 0;
+}
diff --git a/src/frontends/gguf/tests/qwen3tts_oracle.cpp b/src/frontends/gguf/tests/qwen3tts_oracle.cpp
new file mode 100644
index 00000000000..eed89645e9e
--- /dev/null
+++ b/src/frontends/gguf/tests/qwen3tts_oracle.cpp
@@ -0,0 +1,125 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <filesystem>
+#include <fstream>
+#include <random>
+#include <string>
+#include <vector>
+
+#include "clip-impl.h"
+#include "clip.h"
+#include "ggml-backend.h"
+
+namespace {
+struct Dump {
+ std::filesystem::path directory;
+ bool waveform = false;
+};
+template <typename T>
+void save(const std::filesystem::path& path, const std::vector<T>& values) {
+ std::ofstream output(path, std::ios::binary);
+ output.write(reinterpret_cast<const char*>(values.data()), values.size() * sizeof(T));
+}
+} // namespace
+
+int main(int argc, char** argv) {
+ if (argc != 4)
+ return 2;
+ const auto directory = std::filesystem::path(argv[3]);
+ std::filesystem::create_directories(directory);
+ Dump dump{directory};
+ ggml_backend_load_all();
+ clip_context_params config{};
+ config.use_gpu = false;
+ config.flash_attn_type = CLIP_FLASH_ATTN_TYPE_DISABLED;
+ config.cb_eval_user_data = &dump;
+ config.cb_eval = [](ggml_tensor* tensor, bool ask, void* data) {
+ const std::string name = tensor->name;
+ const auto& dump = *static_cast<const Dump*>(data);
+ if (ask) {
+ const bool selected = dump.waveform
+ ? name.find("wav_") == 0
+ : name.find("step_logits-") == 0 || name.find("gen_audio_out") == 0 ||
+ name.find("step_proj_in") == 0 || name.find("step_layer_out") == 0;
+ return selected && tensor->type == GGML_TYPE_F32 && ggml_is_contiguous(tensor) &&
+ name.find("(") == std::string::npos;
+ }
+ std::vector<char> bytes(ggml_nbytes(tensor));
+ ggml_backend_tensor_get(tensor, bytes.data(), 0, bytes.size());
+ save(dump.directory / (name + ".bin"), bytes);
+ return true;
+ };
+ auto contexts = clip_init(argv[1], config);
+ auto* context = contexts.ctx_gen_a;
+ if (!context)
+ return 3;
+ clip_image_f32 image;
+ const auto width = clip_n_mmproj_embd(context);
+ image.set_size({width, 1}, false, true);
+ std::vector<float> hidden(size_t(width), 0.f);
+ std::ifstream input(argv[2], std::ios::binary);
+ input.read(reinterpret_cast<char*>(hidden.data()), hidden.size() * sizeof(float));
+ if (!input)
+ return 4;
+ image.cpy_buf(hidden);
+ clip_image_f32_batch batch;
+ batch.is_audio = true;
+ batch.entries.push_back(image);
+ clip_encode_params params;
+ params.imgs = &batch;
+ params.n_threads = 4;
+ params.seed = 1729;
+ params.code0 = 7;
+ params.top_k = 50;
+ params.top_p = 1.f;
+ std::mt19937 rng(params.seed);
+ std::uniform_real_distribution<float> distribution(0.f, 1.f);
+ std::vector<float> random(15);
+ for (auto& value : random)
+ value = distribution(rng);
+ save(directory / "random.bin", random);
+ std::vector<int32_t> codes;
+ std::vector<float> feedback(size_t(width), 0.f);
+ params.out_codes = &codes;
+ params.out_embd = &feedback;
+ params.gen_process = CLIP_GEN_PROCESS_GEN_CODE;
+ if (!clip_encode(context, &params))
+ return 5;
+ save(directory / "codes.bin", codes);
+ save(directory / "feedback.bin", feedback);
+ std::vector<int32_t> wave_codes(72 * 16);
+ for (size_t i = 0; i < wave_codes.size(); ++i)
+ wave_codes[i] = int32_t((i * 7 + 3) % 100);
+ save(directory / "wave_codes.bin", wave_codes);
+ std::vector<uint8_t> state;
+ std::vector<float> waveform;
+ params.out_codes = nullptr;
+ params.out_embd = nullptr;
+ params.codes = &wave_codes;
+ params.out_audio = &waveform;
+ params.state_out = &state;
+ params.gen_process = CLIP_GEN_PROCESS_GEN_WAV;
+ dump.waveform = true;
+ dump.directory = directory / "wave0";
+ std::filesystem::create_directories(dump.directory);
+ if (!clip_encode(context, &params))
+ return 6;
+ save(directory / "waveform0.bin", waveform);
+ save(directory / "state0.bin", state);
+ params.state_in = &state;
+ std::vector<uint8_t> second_state;
+ params.state_out = &second_state;
+ dump.directory = directory / "wave1";
+ std::filesystem::create_directories(dump.directory);
+ if (!clip_encode(context, &params))
+ return 7;
+ save(directory / "waveform1.bin", waveform);
+ save(directory / "state1.bin", second_state);
+ if (contexts.ctx_v)
+ clip_free(contexts.ctx_v);
+ if (contexts.ctx_a)
+ clip_free(contexts.ctx_a);
+ clip_free(context);
+}
diff --git a/src/frontends/gguf/tests/test_adapt_to_genai.cpp b/src/frontends/gguf/tests/test_adapt_to_genai.cpp
index 7ffcbf1f38a..08c4507a546 100644
--- a/src/frontends/gguf/tests/test_adapt_to_genai.cpp
+++ b/src/frontends/gguf/tests/test_adapt_to_genai.cpp
@@ -231,6 +231,41 @@ TEST(GGUFAdaptToGenAI, RewritesIOContract) {
EXPECT_EQ(m.model->get_results()[0]->get_output_partial_shape(0).rank().get_length(), 3);
}
+TEST(GGUFAdaptToGenAI, EmbeddingLookupRetainsBorrowedWeightParameter) {
+ auto m = build_minimal_gguf_model();
+ std::shared_ptr<v8::Gather> lookup;
+ for (const auto& node : m.model->get_ops()) {
+ if (auto gather = ov::as_type_ptr<v8::Gather>(node)) {
+ if (ov::as_type_ptr<v0::Constant>(gather->get_input_node_shared_ptr(0))) {
+ lookup = gather;
+ break;
+ }
+ }
+ }
+ ASSERT_NE(lookup, nullptr);
+ auto table = ov::test::utils::make_param(ov::element::f32, {4, 2}, "gguf.target_token_embedding");
+ lookup->input(0).replace_source_output(table);
+ m.model->add_parameters({table});
+ AdaptToGenAI adapter(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS);
+ ASSERT_TRUE(adapter.run_on_model(m.model));
+ auto extracted = adapter.get_embedding_model();
+ ASSERT_NE(extracted, nullptr);
+ ASSERT_NO_THROW(extracted->validate_nodes_and_infer_types());
+ EXPECT_NE(find_parameter(extracted, "gguf.target_token_embedding"), nullptr);
+ ov::Core core;
+ auto request = core.compile_model(extracted, "CPU").create_infer_request();
+ ov::Tensor ids(ov::element::i64, {1, 2});
+ ids.data<int64_t>()[0] = 1;
+ ids.data<int64_t>()[1] = 3;
+ request.set_tensor("input_ids", ids);
+ request.set_tensor("gguf.target_token_embedding", make_f32_tensor({4, 2}, {0, 1, 2, 3, 4, 5, 6, 7}));
+ request.infer();
+ const auto result = request.get_tensor("inputs_embeds");
+ ASSERT_EQ(result.get_shape(), (ov::Shape{1, 2, 2}));
+ EXPECT_EQ(std::vector<float>(result.data<float>(), result.data<float>() + result.get_size()),
+ (std::vector<float>{2, 3, 6, 7}));
+}
+
TEST(GGUFAdaptToGenAI, AcceptsPrunedTokenCountInput) {
auto m = build_minimal_gguf_model();
auto count = find_parameter(m.model, "token_len_per_seq");
@@ -303,6 +338,64 @@ TEST(GGUFAdaptToGenAI, EmbeddingModeExtractsLookupAndAcceptsInjectedValues) {
EXPECT_FALSE(pass.run_on_model(m.model));
}
+TEST(GGUFAdaptToGenAI, DeepStackScattersMediaFeaturesAcrossBatchesAndAcceptsTextOnly) {
+ auto m = build_minimal_gguf_model(4, 2);
+ auto deepstack = ov::test::utils::make_param(ov::element::f32, ov::PartialShape{-1, 2, -1, 2}, "deepstack_embeds");
+ auto injection = std::make_shared<v1::ReduceSum>(deepstack, v0::Constant::create(ov::element::i64, {1}, {1}), true);
+ auto combined = std::make_shared<v1::Add>(m.embd, injection);
+ m.embd->output(0).replace(combined->output(0));
+ combined->input(0).replace_source_output(m.embd);
+ m.model->add_parameters({deepstack});
+ AdaptToGenAI adapter(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS);
+ ASSERT_TRUE(adapter.run_on_model(m.model));
+ ov::Core core;
+ auto request =
+ core.compile_model(m.model, "CPU", ov::hint::inference_precision(ov::element::f32)).create_infer_request();
+ for (size_t batch : {1, 2}) {
+ for (size_t length : {3, 1, 2}) {
+ ov::Tensor embeds(ov::element::f32, {batch, length, 2});
+ std::fill_n(embeds.data<float>(), embeds.get_size(), 1.f);
+ ov::Tensor positions(ov::element::i64, {batch, length});
+ std::fill_n(positions.data<int64_t>(), positions.get_size(), 0);
+ ov::Tensor attention(ov::element::i64, {batch, length});
+ std::fill_n(attention.data<int64_t>(), attention.get_size(), 1);
+ for (bool media : {true, false}) {
+ for (bool packed : {false, true}) {
+ const ov::Shape token_shape = packed ? ov::Shape{batch * length, 1} : ov::Shape{batch, length};
+ embeds.set_shape({token_shape[0], token_shape[1], 2});
+ positions.set_shape(token_shape);
+ attention.set_shape(token_shape);
+ ov::Tensor mask(ov::element::boolean, {batch, media ? length : 1});
+ std::fill_n(mask.data<bool>(), mask.get_size(), false);
+ if (media)
+ for (size_t b = 0; b < batch; ++b)
+ mask.data<bool>()[b * length + length - 1] = true;
+ ov::Tensor features(ov::element::f32, {2, media ? batch : 1, 2});
+ for (size_t i = 0; i < features.get_size(); ++i)
+ features.data<float>()[i] = float(i + 1);
+ request.set_tensor("inputs_embeds", embeds);
+ request.set_tensor("position_ids", positions);
+ request.set_tensor("attention_mask", attention);
+ request.set_tensor("visual_pos_masks", mask);
+ request.set_tensor("deepstack_visual_embeds", features);
+ request.infer();
+ const auto output = request.get_output_tensor();
+ ASSERT_EQ(output.get_shape(), (ov::Shape{token_shape[0], token_shape[1], 1}));
+ for (size_t b = 0; b < batch; ++b)
+ for (size_t t = 0; t < length; ++t) {
+ float expected = 2.f;
+ if (media && t == length - 1)
+ for (size_t layer = 0; layer < 2; ++layer)
+ for (size_t d = 0; d < 2; ++d)
+ expected += features.data<float>()[(layer * batch + b) * 2 + d];
+ EXPECT_EQ(output.data<float>()[b * length + t], expected);
+ }
+ }
+ }
+ }
+ }
+}
+
TEST(GGUFAdaptToGenAI, EmbeddingModeMovesPerLayerTokenLookupToItsOwnModel) {
auto m = build_minimal_gguf_model(4, 2, false, true);
m.pe_tok->get_rt_info()["gguf.per_layer_token_embedding"] = int64_t{2};
@@ -476,6 +569,320 @@ static void image_attention_contract(const std::shared_ptr<ov::Model>& model, Im
ov::frontend::gguf::write_model_contract(model, contract);
}
+using GenAIContract = ov::frontend::gguf::ModelContract::GenAIContract;
+
+TEST(GGUFAdaptToGenAI, TextPositionsRespectExplicitMultimodalLayout) {
+ for (const auto layout :
+ {GenAIContract::PositionLayout::THREE_AXIS, GenAIContract::PositionLayout::SEQUENCE_THREE_AXIS}) {
+ auto m = build_minimal_gguf_model();
+ m.model->get_rt_info()[ov::frontend::gguf::pass::gguf_imrope_key()] = true;
+ add_probe_result(m.model, find_parameter(m.model, "inp_pos"), "test_probe_positions");
+ ov::frontend::gguf::ModelContract contract;
+ contract.genai.emplace();
+ contract.genai->position_layout = layout;
+ ov::frontend::gguf::write_model_contract(m.model, contract);
+ ASSERT_TRUE(AdaptToGenAI().run_on_model(m.model));
+ name_probe_outputs(m.model);
+ auto inputs = make_genai_inputs(3);
+ const std::vector<int64_t> positions{3, 7, 11};
+ std::copy(positions.begin(), positions.end(), inputs.at("position_ids").data<int64_t>());
+ auto request = ov::Core{}.compile_model(m.model, "CPU").create_infer_request();
+ for (const auto& [name, value] : inputs)
+ request.set_tensor(name, value);
+ request.infer();
+ const auto actual = request.get_tensor("test_probe_positions");
+ ASSERT_EQ(actual.get_shape(), (ov::Shape{1, 1, 1, 12}));
+ const std::vector<int32_t> expected = layout == GenAIContract::PositionLayout::THREE_AXIS
+ ? std::vector<int32_t>{3, 7, 11, 3, 7, 11, 3, 7, 11, 0, 0, 0}
+ : std::vector<int32_t>{3, 7, 11, 3, 7, 11, 3, 7, 11, 3, 7, 11};
+ EXPECT_EQ(std::vector<int32_t>(actual.data<int32_t>(), actual.data<int32_t>() + actual.get_size()), expected);
+ }
+}
+
+TEST(GGUFAdaptToGenAI, RejectsNoncausalSlidingWindowBeforeRewriting) {
+ auto m = build_minimal_gguf_model();
+ auto swa = ov::test::utils::make_param(ov::element::f32, ov::PartialShape{1, 1, -1, -1}, "self_kq_mask_swa");
+ m.model->add_parameters({swa});
+ m.model->get_rt_info()[ov::frontend::gguf::pass::gguf_swa_window_key()] = int64_t{2};
+ ov::frontend::gguf::ModelContract contract;
+ contract.genai.emplace();
+ contract.genai->causal_attention = false;
+ ov::frontend::gguf::write_model_contract(m.model, contract);
+
+ EXPECT_THROW(AdaptToGenAI().run_on_model(m.model), ov::Exception);
+ EXPECT_NE(find_parameter(m.model, "inp_tokens"), nullptr);
+ EXPECT_NE(find_parameter(m.model, "self_kq_mask_swa"), nullptr);
+ EXPECT_EQ(find_parameter(m.model, "input_ids"), nullptr);
+ EXPECT_NO_THROW(m.model->validate_nodes_and_infer_types());
+}
+
+TEST(GGUFAdaptToGenAI, ExplicitPositionLayoutSurvivesIRReloadAndArchitectureRename) {
+ for (const auto layout :
+ {GenAIContract::PositionLayout::THREE_AXIS, GenAIContract::PositionLayout::SEQUENCE_THREE_AXIS}) {
+ for (const std::string architecture : {"unknown-decoder", "qwen3vl", "qwen35"}) {
+ SCOPED_TRACE(architecture);
+ auto m = build_minimal_gguf_model();
+ m.embd->get_input_node_shared_ptr(0)->get_input_node_shared_ptr(0)->set_friendly_name("token_embd.weight");
+ m.model->get_rt_info()[ov::frontend::gguf::pass::gguf_imrope_key()] = true;
+ m.model->get_rt_info()["gguf_architecture"] = "qwen3tts";
+ add_probe_result(m.model, find_parameter(m.model, "inp_pos"), "test_probe_positions");
+ ov::frontend::gguf::ModelContract contract;
+ contract.genai.emplace();
+ contract.genai->position_layout = layout;
+ ov::frontend::gguf::write_model_contract(m.model, contract);
+ auto restored = reload_ir_model(m.model);
+ restored->get_rt_info()["gguf_architecture"] = architecture;
+ ASSERT_TRUE(AdaptToGenAI(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS).run_on_model(restored));
+ name_probe_outputs(restored);
+ const bool three = layout == GenAIContract::PositionLayout::THREE_AXIS;
+ EXPECT_EQ(restored->input("position_ids").get_partial_shape(), (ov::PartialShape{three ? 3 : 4, -1, -1}));
+ auto inputs = make_genai_inputs(2);
+ inputs.erase("input_ids");
+ inputs["inputs_embeds"] = make_f32_tensor({1, 2, 2}, {0, 1, 2, 3});
+ const std::vector<int64_t> positions =
+ three ? std::vector<int64_t>{3, 7, 11, 2, 5, 13} : std::vector<int64_t>{3, 7, 11, 2, 5, 13, 17, 19};
+ ov::Tensor coordinates(ov::element::i64, {three ? size_t{3} : size_t{4}, 1, 2});
+ std::copy(positions.begin(), positions.end(), coordinates.data<int64_t>());
+ inputs["position_ids"] = coordinates;
+ auto request = ov::Core{}.compile_model(restored, "CPU").create_infer_request();
+ for (const auto& [name, value] : inputs)
+ request.set_tensor(name, value);
+ request.infer();
+ const auto actual = request.get_tensor("test_probe_positions");
+ ASSERT_EQ(actual.get_shape(), (ov::Shape{1, 1, 1, 8}));
+ const std::vector<int32_t> expected = three ? std::vector<int32_t>{3, 7, 11, 2, 5, 13, 0, 0}
+ : std::vector<int32_t>{11, 2, 5, 13, 17, 19, 3, 7};
+ EXPECT_EQ(std::vector<int32_t>(actual.data<int32_t>(), actual.data<int32_t>() + actual.get_size()),
+ expected);
+ EXPECT_FALSE(AdaptToGenAI().run_on_model(restored));
+ }
+ }
+}
+
+TEST(GGUFAdaptToGenAI, ExplicitNamedOutputsAndBorrowedInputsSurviveIRReload) {
+ for (const auto& [architecture, logits_first] : std::vector<std::pair<std::string, bool>>{{"unknown-draft", false},
+ {"unknown-draft", true},
+ {"eagle3", true},
+ {"qwen3tts", true}}) {
+ SCOPED_TRACE(architecture + (logits_first ? " logits first" : " logits last"));
+ auto m = build_minimal_gguf_model();
+ auto table = ov::test::utils::make_param(ov::element::f32, {4, 2}, "external_table");
+ m.embd->get_input_node_shared_ptr(0)->input(0).replace_source_output(table);
+ m.embd->output(0).set_names({"opaque_features"});
+ auto mapping = v0::Constant::create(ov::element::i64, {2}, {3, 7});
+ mapping->output(0).set_names({"opaque_mapping"});
+ m.model->add_parameters({table});
+ m.model->add_results({std::make_shared<v0::Result>(m.embd), std::make_shared<v0::Result>(mapping)});
+ m.model->get_rt_info()["gguf_architecture"] = "eagle3";
+ ov::frontend::gguf::ModelContract contract;
+ contract.genai.emplace();
+ contract.genai->logits_first = logits_first;
+ contract.genai->preserved_inputs = {"external_table"};
+ contract.genai->auxiliary_outputs = {{"opaque_features", "last_hidden_state", 1},
+ {"opaque_mapping", "token_mapping", std::nullopt}};
+ ov::frontend::gguf::write_model_contract(m.model, contract);
+ auto restored = reload_ir_model(m.model);
+ restored->get_rt_info()["gguf_architecture"] = architecture;
+ const auto decoded = ov::frontend::gguf::read_model_contract(restored);
+ ASSERT_TRUE(decoded.genai);
+ EXPECT_EQ(decoded.genai->logits_first, logits_first);
+ ASSERT_EQ(decoded.genai->auxiliary_outputs.size(), 2);
+ EXPECT_EQ(decoded.genai->auxiliary_outputs[0].source_tensor, "opaque_features");
+ EXPECT_EQ(decoded.genai->auxiliary_outputs[0].squeeze_axis, std::optional<int64_t>{1});
+ EXPECT_EQ(decoded.genai->preserved_inputs, (std::vector<std::string>{"external_table"}));
+ ASSERT_TRUE(AdaptToGenAI().run_on_model(restored));
+ EXPECT_EQ(restored->output(logits_first ? 0 : 2).get_any_name(), "logits");
+ EXPECT_EQ(restored->output(logits_first ? 1 : 0).get_any_name(), "last_hidden_state");
+ EXPECT_EQ(restored->output(logits_first ? 2 : 1).get_any_name(), "token_mapping");
+ EXPECT_NE(find_parameter(restored, "external_table"), nullptr);
+ auto inputs = make_genai_inputs(2);
+ inputs["external_table"] = make_f32_tensor({4, 2}, {0, 1, 2, 3, 4, 5, 6, 7});
+ auto compiled = ov::Core{}.compile_model(restored, "CPU", ov::hint::inference_precision(ov::element::f32));
+ auto request = compiled.create_infer_request();
+ for (const auto& [name, value] : inputs)
+ request.set_tensor(name, value);
+ request.infer();
+ const auto hidden = request.get_tensor("last_hidden_state");
+ ASSERT_EQ(hidden.get_shape(), (ov::Shape{1, 2, 2}));
+ EXPECT_EQ(std::vector<float>(hidden.data<float>(), hidden.data<float>() + hidden.get_size()),
+ (std::vector<float>{0, 1, 2, 3}));
+ const auto actual_mapping = request.get_tensor("token_mapping");
+ EXPECT_EQ(std::vector<int64_t>(actual_mapping.data<int64_t>(),
+ actual_mapping.data<int64_t>() + actual_mapping.get_size()),
+ (std::vector<int64_t>{3, 7}));
+ }
+}
+
+TEST(GGUFAdaptToGenAI, PreservesInputByFriendlyNameWhenTensorAliasDiffers) {
+ auto m = build_minimal_gguf_model();
+ auto table = ov::test::utils::make_param(ov::element::f32, {4, 2}, "external_table_alias");
+ table->set_friendly_name("external_table_friendly");
+ table->output(0).set_names({"external_table_alias"});
+ m.embd->get_input_node_shared_ptr(0)->input(0).replace_source_output(table);
+ m.model->add_parameters({table});
+
+ ov::frontend::gguf::ModelContract contract;
+ contract.genai.emplace();
+ contract.genai->preserved_inputs = {"external_table_friendly"};
+ ov::frontend::gguf::write_model_contract(m.model, contract);
+
+ ASSERT_TRUE(AdaptToGenAI().run_on_model(m.model));
+ EXPECT_NE(find_parameter(m.model, "external_table_friendly"), nullptr);
+ EXPECT_NE(find_parameter(m.model, "external_table_alias"), nullptr);
+ EXPECT_NO_THROW(m.model->validate_nodes_and_infer_types());
+}
+
+TEST(GGUFAdaptToGenAI, LegacyAuxiliaryOutputsAndBorrowedInputsSurviveIRReload) {
+ for (const std::string architecture : {"eagle3", "qwen3tts"}) {
+ for (const bool older_contract : {false, true}) {
+ SCOPED_TRACE(architecture);
+ auto m = build_minimal_gguf_model();
+ auto table = ov::test::utils::make_param(ov::element::f32, {4, 2}, "gguf.target_token_embedding");
+ m.embd->get_input_node_shared_ptr(0)->input(0).replace_source_output(table);
+ m.embd->set_friendly_name(architecture == "eagle3" ? "eagle3.prenorm" : "qwen3tts.hidden_states");
+ m.model->add_parameters({table});
+ m.model->add_results({std::make_shared<v0::Result>(m.embd)});
+ if (architecture == "eagle3") {
+ auto mapping = v0::Constant::create(ov::element::i64, {2}, {3, 7});
+ mapping->set_friendly_name("d2t");
+ m.model->add_results({std::make_shared<v0::Result>(mapping)});
+ }
+ m.model->get_rt_info()["gguf_architecture"] = architecture;
+ if (older_contract)
+ ov::frontend::gguf::write_model_contract(m.model, {});
+ auto restored = reload_ir_model(m.model);
+ ASSERT_TRUE(AdaptToGenAI().run_on_model(restored));
+ EXPECT_EQ(restored->output("last_hidden_state").get_partial_shape(), (ov::PartialShape{-1, -1, 2}));
+ EXPECT_NE(find_parameter(restored, "gguf.target_token_embedding"), nullptr);
+ auto compiled = ov::Core{}.compile_model(restored, "CPU", ov::hint::inference_precision(ov::element::f32));
+ auto request = compiled.create_infer_request();
+ auto inputs = make_genai_inputs(2);
+ inputs["gguf.target_token_embedding"] = make_f32_tensor({4, 2}, {0, 1, 2, 3, 4, 5, 6, 7});
+ for (const auto& [name, value] : inputs)
+ request.set_tensor(name, value);
+ request.infer();
+ const auto hidden = request.get_tensor("last_hidden_state");
+ EXPECT_EQ(std::vector<float>(hidden.data<float>(), hidden.data<float>() + hidden.get_size()),
+ (std::vector<float>{0, 1, 2, 3}));
+ if (architecture == "eagle3") {
+ EXPECT_EQ(restored->output(0).get_any_name(), "logits");
+ const auto mapping = request.get_tensor("d2t");
+ EXPECT_EQ(std::vector<int64_t>(mapping.data<int64_t>(), mapping.data<int64_t>() + mapping.get_size()),
+ (std::vector<int64_t>{3, 7}));
+ }
+ }
+ }
+}
+
+TEST(GGUFAdaptToGenAI, ExplicitRoleOverridesArchitectureAndLegacyInputNames) {
+ const std::vector<std::tuple<bool, std::optional<bool>, bool>> cases{{false, std::nullopt, false},
+ {true, std::nullopt, true},
+ {false, true, true},
+ {true, false, false}};
+ for (const auto& [nested, capability, enabled] : cases) {
+ auto m = build_minimal_gguf_model();
+ m.model->get_rt_info()["gguf_architecture"] = "dspark";
+ m.model->add_parameters({ov::test::utils::make_param(ov::element::f32, {1, 1, 2, 3}, "dspark_ctx_feat")});
+ ov::frontend::gguf::ModelContract contract;
+ contract.genai.emplace();
+ contract.genai->enabled = nested;
+ contract.supports_genai_adaptation = capability;
+ ov::frontend::gguf::write_model_contract(m.model, contract);
+ m.model->set_rt_info(std::string(nested ? "true" : "false"), {"gguf_model_contract", "genai", "enabled"});
+ if (!capability)
+ m.model->get_rt_info()["gguf_model_contract"].as<ov::AnyMap>().erase("supports_genai_adaptation");
+ auto restored = reload_ir_model(m.model);
+ EXPECT_EQ(AdaptToGenAI().run_on_model(restored), enabled);
+ EXPECT_EQ(find_parameter(restored, enabled ? "input_ids" : "inp_tokens") != nullptr, true);
+ }
+}
+
+TEST(GGUFAdaptToGenAI, PrefixAttentionContractHandlesCachedAndPaddedKeysAfterIRReload) {
+ for (const bool legacy : {false, true}) {
+ SCOPED_TRACE(legacy);
+ auto m = build_minimal_gguf_model();
+ const std::string context_input = legacy ? "hidden_states" : "opaque_context";
+ auto context = ov::test::utils::make_param(ov::element::f32, {1, 1, -1, 3}, context_input);
+ m.model->add_parameters({context});
+ add_probe_result(m.model, find_parameter(m.model, "self_kq_mask"), "test_probe_prefix_mask");
+ add_probe_result(m.model, find_parameter(m.model, "token_len_per_seq"), "test_probe_prefix_count");
+ m.model->get_rt_info()["gguf_architecture"] = legacy ? "dflash" : "unknown-prefix-decoder";
+ ov::frontend::gguf::ModelContract contract;
+ if (!legacy) {
+ contract.genai.emplace();
+ contract.genai->causal_attention = false;
+ contract.genai->attention_context_input = context_input;
+ }
+ ov::frontend::gguf::write_model_contract(m.model, contract);
+ auto restored = reload_ir_model(m.model);
+ ASSERT_TRUE(AdaptToGenAI().run_on_model(restored));
+ name_probe_outputs(restored);
+ auto inputs = make_genai_inputs(3, 4);
+ inputs["attention_mask"].data<int64_t>()[1] = 0;
+ inputs["attention_mask"].data<int64_t>()[6] = 0;
+ inputs["hidden_states"] = make_f32_tensor({1, 2, 3}, std::vector<float>(6, 0.f));
+ auto compiled = ov::Core{}.compile_model(restored, "CPU", ov::hint::inference_precision(ov::element::f32));
+ auto request = compiled.create_infer_request();
+ for (const auto& [name, value] : inputs)
+ request.set_tensor(name, value);
+ request.infer();
+ const auto mask = request.get_tensor("test_probe_prefix_mask");
+ ASSERT_EQ(mask.get_shape(), (ov::Shape{1, 1, 5, 7}));
+ expect_mask(mask.data<float>(), 5, 7, [](size_t, size_t key) {
+ return key != 1 && key != 6;
+ });
+ EXPECT_EQ(request.get_tensor("test_probe_prefix_count").data<int64_t>()[0], 5);
+ }
+}
+
+TEST(GGUFAdaptToGenAI, LegacyGenAIFieldsResolveWhenOnlyOlderContractFieldsExist) {
+ for (const bool older_contract : {false, true}) {
+ auto m = build_minimal_gguf_model();
+ m.model->get_rt_info()["gguf_architecture"] = "qwen3tts";
+ if (older_contract)
+ m.model->get_rt_info()["gguf_model_contract"] =
+ ov::AnyMap{{"image_attention", std::string{"causal"}}, {"batchable_recurrent", std::string{"auto"}}};
+ const auto restored = reload_ir_model(m.model);
+ const auto contract = ov::frontend::gguf::read_model_contract(restored);
+ ASSERT_TRUE(contract.genai);
+ EXPECT_EQ(contract.genai->position_layout, GenAIContract::PositionLayout::THREE_AXIS);
+ EXPECT_TRUE(contract.genai->enabled);
+ restored->get_rt_info()["gguf_architecture"] = "dspark";
+ restored->add_parameters({ov::test::utils::make_param(ov::element::f32, {1, 1, 2, 3}, "dspark_ctx_feat")});
+ EXPECT_FALSE(AdaptToGenAI().run_on_model(restored));
+ }
+}
+
+TEST(GGUFAdaptToGenAI, RejectsMalformedSerializedGenAIContracts) {
+ const std::vector<std::pair<std::string, std::string>> invalid{{"version", "2"},
+ {"enabled", "auto"},
+ {"causal_attention", "yes"},
+ {"logits_first", "1"},
+ {"position_layout", "unknown"},
+ {"output_count", "-1"},
+ {"input_count", "1025"}};
+ for (const auto& [field, value] : invalid) {
+ SCOPED_TRACE(field);
+ auto m = build_minimal_gguf_model();
+ ov::frontend::gguf::ModelContract contract;
+ contract.genai.emplace();
+ ov::frontend::gguf::write_model_contract(m.model, contract);
+ m.model->set_rt_info(value, {"gguf_model_contract", "genai", field});
+ const auto restored = reload_ir_model(m.model);
+ EXPECT_THROW(ov::frontend::gguf::read_model_contract(restored), ov::Exception);
+ }
+ auto m = build_minimal_gguf_model();
+ ov::frontend::gguf::ModelContract contract;
+ contract.genai.emplace();
+ contract.genai->auxiliary_outputs = {{"features", "last_hidden_state", 4}};
+ EXPECT_THROW(ov::frontend::gguf::write_model_contract(m.model, contract), ov::Exception);
+ contract.genai->auxiliary_outputs = {{"features", "last_hidden_state", 1}, {"features", "mapping", std::nullopt}};
+ EXPECT_THROW(ov::frontend::gguf::write_model_contract(m.model, contract), ov::Exception);
+ contract.genai->auxiliary_outputs.clear();
+ contract.genai->preserved_inputs = {"external_table", "external_table"};
+ EXPECT_THROW(ov::frontend::gguf::write_model_contract(m.model, contract), ov::Exception);
+}
+
class GGUFAdaptToGenAIImageMask : public testing::TestWithParam<ImageAttentionMode> {};
TEST_P(GGUFAdaptToGenAIImageMask, RespectsLayerTypeImageGroupsAndCachedPrefix) {
@@ -705,39 +1112,6 @@ TEST(GGUFAdaptToGenAI, EmbdLeadingAxisSelfCorrectsUnderBothLayouts) {
}
}
-// translate_get_rows's inp_out_ids row-selection (attn_out_g/inpSA_g/...) uses a batch_dims=1
-// Gather keyed on the residual stream's leading axis staying literal 1. FixInpOutIdsRowSelect
-// replaces it with a flatten-based selection that works regardless of which axis holds the real
-// token count -- see FixInpOutIdsRowSelect in adapt_to_genai.cpp.
-TEST(GGUFAdaptToGenAI, FixesInpOutIdsRowSelectStructurally) {
- auto m = build_minimal_gguf_model(/*vocab=*/4, /*hidden=*/2, /*with_inp_out_ids=*/true);
-
- ASSERT_TRUE(AdaptToGenAI().run_on_model(m.model));
-
- std::shared_ptr<ov::Node> fixed_row_select;
- std::shared_ptr<ov::Node> fixed_embd;
- for (const auto& op : m.model->get_ordered_ops()) {
- if (op->get_friendly_name() == "Unsqueeze_test_row_select") {
- fixed_row_select = op;
- } else if (op->get_friendly_name() == "Unsqueeze_test_embd") {
- fixed_embd = op; // the *replaced* embd node -- m.embd itself is now a stale, orphaned copy
- }
- }
- ASSERT_NE(fixed_row_select, nullptr);
- ASSERT_NE(fixed_embd, nullptr);
- ASSERT_EQ(fixed_row_select->get_type_name(), std::string("Unsqueeze"));
-
- auto gather = ov::as_type_ptr<v8::Gather>(fixed_row_select->input_value(0).get_node_shared_ptr());
- ASSERT_NE(gather, nullptr);
-
- // Both the activation and the indices are now fed through a Reshape (flatten), not a Squeeze.
- auto data_flat = ov::as_type_ptr<v1::Reshape>(gather->input_value(0).get_node_shared_ptr());
- auto indices_flat = ov::as_type_ptr<v1::Reshape>(gather->input_value(1).get_node_shared_ptr());
- ASSERT_NE(data_flat, nullptr);
- ASSERT_NE(indices_flat, nullptr);
- EXPECT_EQ(data_flat->input_value(0), fixed_embd->output(0)); // still fed by the (now-fixed) embd
-}
-
// Functional regression test: under the pre-PA layout ([1, tokens]), FixInpOutIdsRowSelect must
// still select just the last token's row (the row-selection's whole point -- skip projecting
// every other prompt position to vocab). Under the post-PA layout ([tokens, 1]) each row already
@@ -766,12 +1140,18 @@ TEST(GGUFAdaptToGenAI, InpOutIdsRowSelectionCorrectUnderBothLayouts) {
req.set_tensor("input_ids", t);
req.infer();
auto row_out = req.get_tensor(row_result->output(0));
+ auto logits = req.get_tensor("logits");
ASSERT_EQ(row_out.get_size(), (size_t)hidden);
+ ASSERT_EQ(logits.get_shape(), (ov::Shape{1, 1, 1}));
const float* data = row_out.data<float>();
+ float expected = 0.f;
for (int64_t h = 0; h < hidden; ++h) {
- EXPECT_FLOAT_EQ(data[h], static_cast<float>(tokens.back() * hidden + h));
+ const auto value = static_cast<float>(tokens.back() * hidden + h);
+ EXPECT_FLOAT_EQ(data[h], value);
+ expected += value;
}
+ EXPECT_FLOAT_EQ(logits.data<float>()[0], expected);
}
// Post-PA layout: input_ids [tokens, 1] -- every row already holds one token, so all T rows
@@ -782,13 +1162,19 @@ TEST(GGUFAdaptToGenAI, InpOutIdsRowSelectionCorrectUnderBothLayouts) {
req.set_tensor("input_ids", t);
req.infer();
auto row_out = req.get_tensor(row_result->output(0));
+ auto logits = req.get_tensor("logits");
ASSERT_EQ(row_out.get_size(), T * (size_t)hidden);
+ ASSERT_EQ(logits.get_shape(), (ov::Shape{T, 1, 1}));
const float* data = row_out.data<float>();
for (size_t i = 0; i < T; ++i) {
+ float expected = 0.f;
for (int64_t h = 0; h < hidden; ++h) {
- EXPECT_FLOAT_EQ(data[i * hidden + h], static_cast<float>(tokens[i] * hidden + h));
+ const auto value = static_cast<float>(tokens[i] * hidden + h);
+ EXPECT_FLOAT_EQ(data[i * hidden + h], value);
+ expected += value;
}
+ EXPECT_FLOAT_EQ(logits.data<float>()[i], expected);
}
}
}
@@ -1261,6 +1647,70 @@ TEST_P(GGUFAdaptToGenAILmHead, KeepsHeadFormThroughSDPAToPagedAttention) {
INSTANTIATE_TEST_SUITE_P(Softcap, GGUFAdaptToGenAILmHead, ::testing::Bool());
+class GGUFAdaptToGenAIScaledLmHead : public ::testing::TestWithParam<float> {};
+
+TEST_P(GGUFAdaptToGenAIScaledLmHead, ExposesHeadForTokenSelectionAndPreservesLogits) {
+ const int64_t vocab = 6, hidden = 3;
+ auto m = build_minimal_gguf_model(vocab, hidden);
+ attach_lm_head(m.model, m.embd, vocab, hidden, false);
+ const auto head = m.model->get_results()[0]->input_value(0);
+ auto scaled =
+ std::make_shared<v1::Multiply>(head, v0::Constant::create(ov::element::f32, {1, 1, 1, 1}, {GetParam()}));
+ m.model->get_results()[0]->input(0).replace_source_output(scaled);
+
+ ASSERT_TRUE(AdaptToGenAI().run_on_model(m.model));
+ ASSERT_NE(find_genai_lm_head(m.model, false), nullptr);
+ auto request = ov::Core{}
+ .compile_model(m.model, "CPU", ov::hint::inference_precision(ov::element::f32))
+ .create_infer_request();
+ const size_t length = 3;
+ for (const auto& [name, tensor] : make_genai_inputs(length)) {
+ request.set_tensor(name, tensor);
+ }
+ request.infer();
+ const auto logits = request.get_tensor("logits");
+ ASSERT_EQ(logits.get_shape(), (ov::Shape{1, length, (size_t)vocab}));
+ for (size_t token = 0; token < length; ++token) {
+ for (int64_t v = 0; v < vocab; ++v) {
+ float expected = 0.f;
+ for (int64_t h = 0; h < hidden; ++h) {
+ expected += lm_head_weight(v, h) * static_cast<float>(token * hidden + h);
+ }
+ EXPECT_NEAR(logits.data<float>()[token * vocab + v], expected * GetParam(), 1e-4f);
+ }
+ }
+}
+
+TEST_P(GGUFAdaptToGenAIScaledLmHead, KeepsHeadVisibleAfterPagedAttentionConversion) {
+ const int64_t vocab = 8, hidden = 4;
+ auto model = build_attention_gguf_model(vocab, hidden);
+ attach_lm_head(model, model->get_results()[0]->input_value(0), vocab, hidden, false);
+ const auto head = model->get_results()[0]->input_value(0);
+ auto scaled =
+ std::make_shared<v1::Multiply>(head, v0::Constant::create(ov::element::f32, {1, 1, 1, 1}, {GetParam()}));
+ model->get_results()[0]->input(0).replace_source_output(scaled);
+
+ ASSERT_TRUE(AdaptToGenAI().run_on_model(model));
+ ASSERT_TRUE(ov::pass::SDPAToPagedAttention().run_on_model(model));
+ ASSERT_NE(find_genai_lm_head(model, false), nullptr);
+}
+
+INSTANTIATE_TEST_SUITE_P(OutputScale, GGUFAdaptToGenAIScaledLmHead, ::testing::Values(0.25f, 1.5f));
+
+TEST(GGUFAdaptToGenAI, SharedHeadRetainsSeparateOutputScale) {
+ auto m = build_minimal_gguf_model(6, 3);
+ attach_lm_head(m.model, m.embd, 6, 3, false);
+ const auto head = m.model->get_results()[0]->input_value(0);
+ ov::frontend::gguf::name_output(head.get_node_shared_ptr(), "unscaled_logits");
+ auto scaled = std::make_shared<v1::Multiply>(head, v0::Constant::create(ov::element::f32, {1, 1, 1, 1}, {0.25f}));
+ m.model->get_results()[0]->input(0).replace_source_output(scaled);
+ m.model->add_results({std::make_shared<v0::Result>(head)});
+
+ ASSERT_TRUE(AdaptToGenAI().run_on_model(m.model));
+ EXPECT_NE(ov::as_type_ptr<v1::Multiply>(m.model->get_results()[0]->get_input_node_shared_ptr(0)), nullptr);
+ EXPECT_FALSE(ov::is_type<v1::Multiply>(head.get_node_shared_ptr()->get_input_node_shared_ptr(0)));
+}
+
// The per-layer token lookup becomes a per_layer_inputs input, so the language model takes
// embeddings only, and the unmodified PagedAttention conversion applies as for optimum-intel.
TEST(GGUFAdaptToGenAI, PagedAttentionFlattensEmbeddingsWithPerLayerInputs) {
@@ -1311,6 +1761,8 @@ TEST(GGUFAdaptToGenAI, SequenceOutputsUseDeclaredContractBeforeAndAfterReload) {
native.model->get_rt_info()["gguf_architecture"] = std::string("custom-sequence-decoder");
ov::frontend::gguf::ModelContract contract;
contract.sequence_outputs = {"decoder_features", "features_alias", "decoder_summary"};
+ contract.genai.emplace();
+ contract.genai->auxiliary_outputs = {{"features_alias", "renamed_features", 1}};
ov::frontend::gguf::write_model_contract(native.model, contract);
for (const bool reload : {false, true}) {
for (const auto mode : {AdaptToGenAI::InputMode::IDS_TO_LOGITS, AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS}) {
@@ -1322,6 +1774,7 @@ TEST(GGUFAdaptToGenAI, SequenceOutputsUseDeclaredContractBeforeAndAfterReload) {
EXPECT_EQ(model->output(0).get_any_name(), "logits");
EXPECT_EQ(model->output("features_alias"), model->output("decoder_features"));
EXPECT_EQ(model->output("extra_alias"), model->output("decoder_features"));
+ EXPECT_EQ(model->output("renamed_features"), model->output("decoder_features"));
auto request = ov::Core{}.compile_model(model, "CPU").create_infer_request();
for (const size_t batch : {1, 2}) {
for (const size_t length : {3, 1}) {
diff --git a/src/frontends/gguf/tests/test_arch_accuracy.cpp b/src/frontends/gguf/tests/test_arch_accuracy.cpp
index 968e6811aac..8644ea0166c 100644
--- a/src/frontends/gguf/tests/test_arch_accuracy.cpp
+++ b/src/frontends/gguf/tests/test_arch_accuracy.cpp
@@ -10,11 +10,13 @@
#include <fstream>
#include <limits>
#include <set>
+#include <sstream>
#include <tuple>
#include "builder/api/metadata_store.hpp"
#include "builder/arch/decoder_builder.hpp"
#include "builder/arch/dspark_builder.hpp"
+#include "builder/arch_registry.hpp"
#include "builder/decoder_config.hpp"
#include "builder/decoder_metadata.hpp"
#include "builder/gguf_builder_decoder.hpp"
@@ -25,16 +27,19 @@
#include "common_test_utils/test_assertions.hpp"
#include "gtest/gtest.h"
#include "helper_ops/gguf_constant.hpp"
+#include "model_contract.hpp"
#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"
+#include "openvino/frontend/gguf/extension/architecture.hpp"
#include "openvino/frontend/gguf/extension/genai.hpp"
#include "openvino/frontend/gguf/frontend.hpp"
#include "openvino/frontend/gguf/make_stateful.hpp"
#include "openvino/op/broadcast.hpp"
#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
#include "openvino/op/gated_delta_net.hpp"
#include "openvino/op/matmul.hpp"
#include "openvino/op/multiply.hpp"
@@ -43,10 +48,13 @@
#include "openvino/op/paged_gated_delta_net.hpp"
#include "openvino/op/read_value.hpp"
#include "openvino/op/reshape.hpp"
+#include "openvino/op/scaled_dot_product_attention.hpp"
+#include "openvino/op/transpose.hpp"
#include "openvino/op/unsqueeze.hpp"
#include "openvino/openvino.hpp"
#include "openvino/pass/manager.hpp"
#include "openvino/pass/sdpa_to_paged_attention.hpp"
+#include "openvino/pass/serialize.hpp"
#include "openvino/util/common_util.hpp"
#include "quant/gguf.hpp"
#include "utils.hpp"
@@ -54,6 +62,115 @@
namespace {
class GGUFArchitectureAccuracy : public ::testing::TestWithParam<const char*> {};
+void register_deferred_decoder(ov::frontend::gguf::FrontEnd& frontend, const std::string& family) {
+ using namespace ov::frontend::gguf;
+ if (family == "qwen3next" || family == "qwen3next-legacy")
+ frontend.add_extension(std::make_shared<ArchitectureExtension>("qwen3next", RopeMode::Neox));
+}
+
+class GGUFDraftAdaptation : public ::testing::TestWithParam<const char*> {};
+
+TEST_P(GGUFDraftAdaptation, KeepsBorrowedTargetWeightsWithoutDuplicateParameters) {
+ using namespace ov::frontend::gguf;
+ const std::string architecture = GetParam();
+ const auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/arch_accuracy/" + architecture + ".npz");
+ const ov_gguf_test::TemporaryGguf temporary(ov_gguf_test::npz_array(arrays, "model"));
+ auto loaded = get_gguf_data(temporary.path);
+ auto& weights = std::get<1>(loaded);
+ weights.erase("token_embd.weight");
+ weights.erase("output.weight");
+ detail::MetadataStore metadata{std::get<0>(loaded)};
+ detail::WeightStore tensors{weights};
+ const BuildContext context{GgufMetadata(metadata), architecture, &tensors};
+ const auto definition = ArchRegistry{}.find(context.metadata);
+ ASSERT_TRUE(definition);
+ const auto builder = definition->factory(context);
+ std::shared_ptr<GgufDecoder> decoder = std::make_shared<GgufBuilderDecoder>(builder->build());
+ FrontEnd frontend;
+ frontend.add_extension(std::make_shared<GenAIExtension>(GenAIExtension::InputMode::IDS_TO_LOGITS));
+ auto model = frontend.convert(frontend.load(decoder));
+ EXPECT_EQ(model->input("gguf.target_token_embedding").get_partial_shape(), (ov::PartialShape{-1, 32}));
+ EXPECT_EQ(model->input("gguf.target_lm_head").get_partial_shape(), (ov::PartialShape{-1, 32}));
+ std::set<const ov::Node*> parameters;
+ for (const auto& parameter : model->get_parameters())
+ EXPECT_TRUE(parameters.insert(parameter.get()).second);
+ EXPECT_NO_THROW(model->input("input_ids"));
+ EXPECT_NO_THROW(model->input("hidden_states"));
+}
+
+INSTANTIATE_TEST_SUITE_P(Architectures, GGUFDraftAdaptation, ::testing::Values("dflash", "eagle3"));
+
+TEST(GGUFQwen3TTSAdaptation, NativeHiddenStateContractSurvivesIRReloadAndArchitectureRename) {
+ using namespace ov::frontend::gguf;
+ const auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/arch_accuracy/qwen3tts.npz");
+ const ov_gguf_test::TemporaryGguf temporary(ov_gguf_test::npz_array(arrays, "model"));
+ FrontEnd frontend;
+ frontend.add_extension(std::make_shared<ov::frontend::DecoderTransformationExtension>(pass::GGUFMakeStateful()));
+ const auto raw = frontend.convert(frontend.load(temporary.path));
+ const auto contract = read_model_contract(raw);
+ ASSERT_TRUE(contract.genai);
+ ASSERT_EQ(contract.genai->auxiliary_outputs.size(), 1);
+ EXPECT_EQ(contract.genai->auxiliary_outputs[0].source_tensor, "qwen3tts.hidden_states");
+ EXPECT_EQ(contract.genai->auxiliary_outputs[0].name, "last_hidden_state");
+ ASSERT_EQ(raw->output("qwen3tts.hidden_states").get_partial_shape().rank(), 4);
+ const auto restored = ov_gguf_test::reload_ir_model(raw);
+ ov::Core core;
+ restored->set_rt_info(std::string{"unknown-tts-decoder"}, {"gguf_architecture"});
+ ASSERT_TRUE(pass::AdaptToGenAI().run_on_model(restored));
+ EXPECT_EQ(restored->output("last_hidden_state").get_partial_shape().rank(), 3);
+ const auto compile = [&](const std::shared_ptr<ov::Model>& model) {
+ return core.compile_model(model,
+ "CPU",
+ ov::hint::inference_precision(ov::element::f32),
+ ov::hint::dynamic_quantization_group_size(0),
+ ov::hint::kv_cache_precision(ov::element::f16),
+ ov::inference_num_threads(4));
+ };
+ auto reference = compile(raw).create_infer_request();
+ auto adapted = compile(restored).create_infer_request();
+ ov::Tensor raw_ids(ov::element::i32, {1, 1, 1, 3}), ids(ov::element::i64, {1, 3});
+ ov::Tensor raw_positions(ov::element::i32, {1, 1, 1, 12}), positions(ov::element::i64, {1, 3});
+ for (size_t i = 0; i < 3; ++i) {
+ raw_ids.data<int32_t>()[i] = static_cast<int32_t>(i + 1);
+ ids.data<int64_t>()[i] = static_cast<int64_t>(i + 1);
+ positions.data<int64_t>()[i] = static_cast<int64_t>(i);
+ for (size_t section = 0; section < 4; ++section)
+ raw_positions.data<int32_t>()[section * 3 + i] = section == 3 ? 0 : static_cast<int32_t>(i);
+ }
+ ov::Tensor raw_mask(ov::element::f32, {1, 1, 3, 3}), mask(ov::element::i64, {1, 3});
+ std::fill_n(mask.data<int64_t>(), 3, 1);
+ for (size_t query = 0; query < 3; ++query)
+ for (size_t key = 0; key < 3; ++key)
+ raw_mask.data<float>()[query * 3 + key] = key <= query ? 0.f : -65504.f;
+ ov::Tensor count(ov::element::i64, {1}), last_row(ov::element::i32, {1, 1, 1, 1});
+ count.data<int64_t>()[0] = 3;
+ last_row.data<int32_t>()[0] = 2;
+ ov::Tensor beam(ov::element::i32, {1});
+ beam.data<int32_t>()[0] = 0;
+ reference.set_tensor("inp_tokens", raw_ids);
+ reference.set_tensor("inp_pos", raw_positions);
+ reference.set_tensor("self_kq_mask", raw_mask);
+ if (find_parameter(raw, "token_len_per_seq"))
+ reference.set_tensor("token_len_per_seq", count);
+ reference.set_tensor("inp_out_ids", last_row);
+ reference.set_tensor("beam_idx", beam);
+ adapted.set_tensor("input_ids", ids);
+ adapted.set_tensor("position_ids", positions);
+ adapted.set_tensor("attention_mask", mask);
+ adapted.set_tensor("beam_idx", beam);
+ reference.infer();
+ adapted.infer();
+ const auto expected = reference.get_tensor("qwen3tts.hidden_states");
+ const auto actual = adapted.get_tensor("last_hidden_state");
+ ASSERT_EQ(expected.get_shape().size(), 4);
+ EXPECT_EQ(actual.get_shape(),
+ (ov::Shape{expected.get_shape()[0], expected.get_shape()[2], expected.get_shape()[3]}));
+ ASSERT_EQ(actual.get_size(), expected.get_size());
+ ov_gguf_test::expect_near(
+ actual,
+ std::vector<float>(expected.data<const float>(), expected.data<const float>() + expected.get_size()));
+}
+
TEST(GGUFAFMoE, MissingAndZeroRoutingUseSigmoidDefaults) {
using namespace ov::frontend::gguf;
const auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/arch_accuracy/afmoe.npz");
@@ -720,6 +837,14 @@ void check_batched_decode(const std::shared_ptr<ov::Model>& model) {
a = infer(first, 1, {4}, {1, 1, 1, 1}, {3}, {0});
b = infer(second, 1, {5}, {1, 1, 1}, {2}, {0});
compare(infer(batch, 2, {5, 4}, {0, 1, 1, 1, 1, 1, 1, 1}, {2, 3}, {1, 0}), b, a);
+ for (auto* request : {&first, &second, &batch})
+ for (auto state : request->query_state())
+ state.reset();
+ auto fresh = compiled.create_infer_request();
+ a = infer(fresh, 1, {6, 2}, {1, 1}, {0, 1}, {0});
+ compare(infer(batch, 2, {6, 2, 6, 2}, {1, 1, 1, 1}, {0, 1, 0, 1}, {0, 0}), a, a);
+ compare(infer(first, 1, {6, 2}, {1, 1}, {0, 1}, {0}), a, {});
+ compare(infer(second, 1, {6, 2}, {1, 1}, {0, 1}, {0}), a, {});
}
TEST(GGUFMultimodalBackboneAdaptation, Lfm2SupportsBatchesAndBeamReordering) {
@@ -872,8 +997,15 @@ TEST(GGUFMultimodalBackboneAdaptation, Lfm3SupportsBatchesAndBeamReordering) {
}
TEST(GGUFMultimodalBackboneAdaptation, QwenAndGemmaSupportBatchesAndPagedAttention) {
- for (const auto* family :
- {"qwen35", "bonsai2-hadamard", "qwen35moe", "qwen35moe-fused", "gemma4-mqa", "gemma4-moe", "gemma4-ple"}) {
+ for (const auto* family : {"qwen35",
+ "qwen3next",
+ "qwen3next-legacy",
+ "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"));
@@ -889,6 +1021,7 @@ TEST(GGUFMultimodalBackboneAdaptation, QwenAndGemmaSupportBatchesAndPagedAttenti
}
}
ov::frontend::gguf::FrontEnd frontend;
+ register_deferred_decoder(frontend, family);
frontend.add_extension(std::make_shared<ov::frontend::gguf::GenAIExtension>());
auto model = frontend.convert(frontend.load(temporary.path));
if (std::string(family).find("qwen35") == 0 || std::string(family) == "bonsai2-hadamard") {
@@ -1301,18 +1434,305 @@ TEST(GGUFEmbeddingAccuracy, RealCheckpointTokenEmbeddingsMatchLlamaCPU) {
ov_gguf_test::expect_nmse_below(metric, 1e-5);
}
+class GGUFDecoderPagedAttentionParity : public ::testing::TestWithParam<const char*> {};
+
+TEST_P(GGUFDecoderPagedAttentionParity, MatchesStatefulSDPAFullLogits) {
+#if defined(OPENVINO_ARCH_ARM64)
+ GTEST_SKIP() << "ARM64 PagedAttention does not support the FP16 KV caches required by this parity test";
+#endif
+ const bool gemma3n = std::string(GetParam()) == "gemma3n";
+ const size_t attention_layers = gemma3n ? 5 : 4;
+ const auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/arch_accuracy/" + GetParam() + ".npz");
+ const ov_gguf_test::TemporaryGguf temporary(ov_gguf_test::npz_array(arrays, "model"));
+ const auto vocab = ov_gguf_test::npz_array(arrays, "logits").shape.back();
+ ov::frontend::gguf::FrontEnd frontend;
+ frontend.add_extension(std::make_shared<ov::frontend::gguf::GenAIExtension>(
+ ov::frontend::gguf::GenAIExtension::InputMode::IDS_TO_LOGITS));
+ auto model = frontend.convert(frontend.load(temporary.path));
+ const auto check_contract = [&](const std::shared_ptr<ov::Model>& graph, bool paged) {
+ size_t sdpa_count = 0, pa_count = 0;
+ for (const auto& node : graph->get_ops()) {
+ if (const auto sdpa = ov::as_type_ptr<ov::op::v13::ScaledDotProductAttention>(node)) {
+ ++sdpa_count;
+ if (!gemma3n)
+ continue;
+ EXPECT_EQ(sdpa->get_type_info(), ov::op::v13::ScaledDotProductAttention::get_type_info_static());
+ for (size_t input = 0; input < 3; ++input)
+ EXPECT_EQ(sdpa->get_input_element_type(input), ov::element::f16);
+ EXPECT_EQ(sdpa->get_output_element_type(0), ov::element::f16);
+ bool converts_output_to_f32 = false;
+ for (const auto& consumer : sdpa->output(0).get_target_inputs()) {
+ if (!ov::is_type<ov::op::v1::Transpose>(consumer.get_node()))
+ continue;
+ EXPECT_EQ(consumer.get_node()->get_output_element_type(0), ov::element::f16);
+ for (const auto& output_consumer : consumer.get_node()->output(0).get_target_inputs()) {
+ auto convert = ov::as_type<ov::op::v0::Convert>(output_consumer.get_node());
+ converts_output_to_f32 |= convert && convert->get_convert_element_type() == ov::element::f32;
+ }
+ }
+ EXPECT_TRUE(converts_output_to_f32);
+ }
+ if (const auto pa = ov::as_type_ptr<ov::op::PagedAttentionExtension>(node)) {
+ ++pa_count;
+ if (!gemma3n) {
+ EXPECT_EQ(pa->get_input_partial_shape(1)[1], 16);
+ EXPECT_EQ(pa->get_input_partial_shape(0)[1], 32);
+ }
+ }
+ }
+ EXPECT_EQ(sdpa_count, paged ? 0u : attention_layers);
+ EXPECT_EQ(pa_count, paged ? attention_layers : 0u);
+ };
+ const auto compile = [](ov::Core& core, const std::shared_ptr<ov::Model>& graph) {
+ return core.compile_model(graph,
+ "CPU",
+ ov::hint::inference_precision(ov::element::f32),
+ ov::num_streams(1),
+ ov::inference_num_threads(4),
+ ov::hint::dynamic_quantization_group_size(0),
+ ov::hint::kv_cache_precision(ov::element::f16));
+ };
+ const auto infer_sdpa = [&](ov::InferRequest& request, const std::vector<int64_t>& tokens, size_t past) {
+ ov::Tensor ids(ov::element::i64, {1, tokens.size()});
+ ov::Tensor positions(ov::element::i64, {1, tokens.size()});
+ ov::Tensor mask(ov::element::i64, {1, past + tokens.size()});
+ ov::Tensor beam(ov::element::i32, {1});
+ *beam.data<int32_t>() = 0;
+ std::copy(tokens.begin(), tokens.end(), ids.data<int64_t>());
+ for (size_t i = 0; i < tokens.size(); ++i)
+ positions.data<int64_t>()[i] = static_cast<int64_t>(past + i);
+ std::fill_n(mask.data<int64_t>(), mask.get_size(), 1);
+ request.set_tensor("input_ids", ids);
+ request.set_tensor("position_ids", positions);
+ request.set_tensor("attention_mask", mask);
+ request.set_tensor("beam_idx", beam);
+ request.infer();
+ const auto output = request.get_tensor("logits");
+ OPENVINO_ASSERT(output.get_element_type() == ov::element::f32);
+ OPENVINO_ASSERT(output.get_shape() == ov::Shape({1, gemma3n ? tokens.size() : 1, vocab}));
+ return std::vector<float>(output.data<const float>(), output.data<const float>() + output.get_size());
+ };
+ const std::vector<std::vector<int64_t>> schedule{{1, 2, 3}, {4}, {5, 6}};
+ check_contract(model, false);
+ ov::Core core;
+ auto sdpa_compiled = compile(core, model);
+ auto sdpa_request = sdpa_compiled.create_infer_request();
+ std::vector<std::vector<float>> sdpa_logits;
+ size_t sdpa_past = 0;
+ for (const auto& tokens : schedule) {
+ sdpa_logits.push_back(infer_sdpa(sdpa_request, tokens, sdpa_past));
+ sdpa_past += tokens.size();
+ }
+ std::vector<std::vector<float>> cohere_prefill_logits;
+ if (!gemma3n) {
+ auto single_token_request = sdpa_compiled.create_infer_request();
+ for (size_t i = 0; i < schedule.front().size(); ++i)
+ cohere_prefill_logits.push_back(infer_sdpa(single_token_request, {schedule.front()[i]}, i));
+ }
+ const auto check_logits = [&](const std::vector<float>& output, size_t token, const std::vector<float>& expected) {
+ ASSERT_GE(output.size(), token * vocab + expected.size());
+ const auto metric = ov_gguf_test::nmse(output.data() + token * vocab, expected.data(), expected.size());
+ ASSERT_TRUE(metric.all_finite());
+ ASSERT_GT(metric.reference_norm(), 1e-12);
+ EXPECT_LT(metric.value(), 1e-5) << "Consumer equivalence against CPU stateful SDPA: token=" << token;
+ };
+ if (!gemma3n) {
+ auto batched = sdpa_compiled.create_infer_request();
+ std::vector<ov::InferRequest> independent{sdpa_compiled.create_infer_request(),
+ sdpa_compiled.create_infer_request()};
+ const std::vector<std::vector<std::vector<int64_t>>> batches{{{1, 2, 3}, {3, 2, 1}}, {{4}, {5}}};
+ size_t past = 0;
+ for (const auto& batch : batches) {
+ const auto count = batch[0].size();
+ ov::Tensor ids(ov::element::i64, {2, count});
+ ov::Tensor positions(ov::element::i64, {2, count});
+ ov::Tensor mask(ov::element::i64, {2, past + count});
+ ov::Tensor beam(ov::element::i32, {2});
+ for (size_t row = 0; row < batch.size(); ++row) {
+ std::copy(batch[row].begin(), batch[row].end(), ids.data<int64_t>() + row * count);
+ for (size_t i = 0; i < count; ++i)
+ positions.data<int64_t>()[row * count + i] = static_cast<int64_t>(past + i);
+ beam.data<int32_t>()[row] = static_cast<int32_t>(row);
+ }
+ std::fill_n(mask.data<int64_t>(), mask.get_size(), 1);
+ batched.set_tensor("input_ids", ids);
+ batched.set_tensor("position_ids", positions);
+ batched.set_tensor("attention_mask", mask);
+ batched.set_tensor("beam_idx", beam);
+ batched.infer();
+ const auto logits = batched.get_tensor("logits");
+ ASSERT_EQ(logits.get_shape(), (ov::Shape{2, 1, vocab}));
+ const std::vector<float> actual(logits.data<const float>(), logits.data<const float>() + logits.get_size());
+ for (size_t row = 0; row < batch.size(); ++row)
+ check_logits(actual, row, infer_sdpa(independent[row], batch[row], past));
+ past += count;
+ }
+ }
+ const auto paged_offset = [&](size_t token, size_t step) {
+ return token + schedule[step].size() - sdpa_logits[step].size() / vocab;
+ };
+ const auto run_sdpa_schedule = [&](ov::InferRequest& request) {
+ size_t past = 0;
+ for (size_t step = 0; step < schedule.size(); ++step) {
+ SCOPED_TRACE("SDPA schedule step=" + std::to_string(step));
+ check_logits(infer_sdpa(request, schedule[step], past), 0, sdpa_logits[step]);
+ past += schedule[step].size();
+ }
+ };
+ const auto states = sdpa_request.query_state();
+ ASSERT_FALSE(states.empty());
+ for (auto state : states)
+ state.reset();
+ run_sdpa_schedule(sdpa_request);
+ auto fresh_sdpa_request = sdpa_compiled.create_infer_request();
+ run_sdpa_schedule(fresh_sdpa_request);
+ ov::Core fresh_core;
+ auto restored = ov_gguf_test::reload_ir_model(model->clone());
+ check_contract(restored, false);
+ auto restored_request = compile(fresh_core, restored).create_infer_request();
+ run_sdpa_schedule(restored_request);
+
+ ASSERT_TRUE(ov::pass::SDPAToPagedAttention(false, false, false).run_on_model(model));
+ check_contract(model, true);
+ auto compiled = compile(core, model);
+ const auto reset_caches = [&](ov::InferRequest& request) {
+ size_t cache_count = 0;
+ for (const auto& input : compiled.inputs()) {
+ const auto name = input.get_any_name();
+ if (name.find("key_cache.") != 0 && name.find("value_cache.") != 0)
+ continue;
+ auto shape = input.get_partial_shape();
+ ASSERT_EQ(shape.rank(), 4);
+ ASSERT_EQ(shape[2], 32);
+ if (gemma3n) {
+ ASSERT_EQ(input.get_element_type(), ov::element::f16);
+ }
+ shape[0] = 2;
+ ASSERT_TRUE(shape.is_static());
+ ov::Tensor tensor(input.get_element_type(), shape.get_shape());
+ std::memset(tensor.data(), 0, tensor.get_byte_size());
+ request.set_tensor(input, tensor);
+ ++cache_count;
+ }
+ EXPECT_EQ(cache_count, 2 * attention_layers);
+ };
+ const auto infer = [&](ov::InferRequest& request,
+ const std::vector<std::vector<int64_t>>& tokens,
+ const std::vector<int32_t>& past,
+ const std::vector<int32_t>& blocks) {
+ std::vector<int64_t> ids, positions;
+ std::vector<int32_t> begins{0}, block_begins{0};
+ int32_t max_context = 0;
+ for (size_t sequence = 0; sequence < tokens.size(); ++sequence) {
+ ids.insert(ids.end(), tokens[sequence].begin(), tokens[sequence].end());
+ for (size_t i = 0; i < tokens[sequence].size(); ++i)
+ positions.push_back(past[sequence] + static_cast<int64_t>(i));
+ begins.push_back(static_cast<int32_t>(ids.size()));
+ block_begins.push_back(static_cast<int32_t>(sequence + 1));
+ max_context = std::max(max_context, past[sequence] + static_cast<int32_t>(tokens[sequence].size()));
+ }
+ for (const auto& input : compiled.inputs()) {
+ const auto name = input.get_any_name();
+ if (name.find("key_cache.") == 0 || name.find("value_cache.") == 0)
+ continue;
+ if (name == "input_ids" || name == "position_ids") {
+ const auto& values = name == "input_ids" ? ids : positions;
+ ov::Tensor tensor(input.get_element_type(), {values.size()});
+ if (input.get_element_type() == ov::element::i64)
+ std::copy(values.begin(), values.end(), tensor.data<int64_t>());
+ else
+ std::transform(values.begin(), values.end(), tensor.data<int32_t>(), [](int64_t value) {
+ return static_cast<int32_t>(value);
+ });
+ request.set_tensor(input, tensor);
+ continue;
+ }
+ std::vector<int32_t> values;
+ if (name == "past_lens")
+ values = past;
+ else if (name == "subsequence_begins")
+ values = begins;
+ else if (name == "block_indices")
+ values = blocks;
+ else if (name == "block_indices_begins")
+ values = block_begins;
+ else if (name == "max_context_len")
+ values = {max_context};
+ else
+ OPENVINO_THROW("Unexpected PagedAttention input: ", name);
+ ov::Tensor tensor(ov::element::i32,
+ input.get_partial_shape().rank() == 0 ? ov::Shape{} : ov::Shape{values.size()});
+ std::copy(values.begin(), values.end(), tensor.data<int32_t>());
+ request.set_tensor(input, tensor);
+ }
+ request.infer();
+ const auto output = request.get_tensor("logits");
+ OPENVINO_ASSERT(output.get_element_type() == ov::element::f32);
+ OPENVINO_ASSERT(output.get_size() == ids.size() * vocab);
+ if (!gemma3n)
+ OPENVINO_ASSERT(output.get_shape() == ov::Shape({ids.size(), 1, vocab}));
+ return std::vector<float>(output.data<const float>(), output.data<const float>() + output.get_size());
+ };
+ auto request = compiled.create_infer_request();
+ const auto run_schedule = [&](ov::InferRequest& current) {
+ int32_t past = 0;
+ for (size_t step = 0; step < schedule.size(); ++step) {
+ SCOPED_TRACE("PA schedule step=" + std::to_string(step));
+ const auto output = infer(current, {schedule[step]}, {past}, {0});
+ check_logits(output, paged_offset(0, step), sdpa_logits[step]);
+ if (step == 0) {
+ for (size_t token = 0; token < cohere_prefill_logits.size(); ++token)
+ check_logits(output, token, cohere_prefill_logits[token]);
+ }
+ past += static_cast<int32_t>(schedule[step].size());
+ }
+ };
+ reset_caches(request);
+ run_schedule(request);
+ check_logits(infer(request, {schedule.front()}, {0}, {0}), paged_offset(0, 0), sdpa_logits[0]);
+ reset_caches(request);
+ run_schedule(request);
+ auto fresh_request = compiled.create_infer_request();
+ reset_caches(fresh_request);
+ run_schedule(fresh_request);
+ reset_caches(request);
+ check_logits(infer(request, {{1, 2, 3}}, {0}, {0}), paged_offset(0, 0), sdpa_logits[0]);
+ const auto mixed = infer(request, {{4}, {1, 2, 3}}, {3, 0}, {0, 1});
+ check_logits(mixed, paged_offset(0, 1), sdpa_logits[1]);
+ check_logits(mixed, paged_offset(1, 0), sdpa_logits[0]);
+ const auto continuation = infer(request, {{5, 6}, {4}}, {4, 3}, {0, 1});
+ check_logits(continuation, paged_offset(0, 2), sdpa_logits[2]);
+ check_logits(continuation, paged_offset(2, 1), sdpa_logits[1]);
+}
+
+INSTANTIATE_TEST_SUITE_P(Architectures, GGUFDecoderPagedAttentionParity, ::testing::Values("cohere2", "gemma3n"));
+
TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {
const char* override_dir = std::getenv("OV_GGUF_ACCURACY_DATA");
+ const bool legacy_hadamard = std::string(GetParam()) == "qwen3next-legacy-hadamard";
+ const std::string fixture_family = legacy_hadamard ? "qwen3next-legacy" : GetParam();
const bool mamba = std::string(GetParam()).find("mamba2") == 0 || std::string(GetParam()) == "nemotron_h" ||
std::string(GetParam()).find("lfm2") == 0 || std::string(GetParam()).find("lfm3") == 0;
const bool lfm2 = std::string(GetParam()).find("lfm2") == 0 || std::string(GetParam()).find("lfm3") == 0;
- const auto directory = override_dir ? std::filesystem::path(override_dir)
- : std::filesystem::path(ov_gguf_test::test_data_dir()) / "arch_accuracy";
+ const auto directory = override_dir && !legacy_hadamard
+ ? std::filesystem::path(override_dir)
+ : std::filesystem::path(ov_gguf_test::test_data_dir()) / "arch_accuracy";
ASSERT_TRUE(std::filesystem::exists(directory)) << "Missing architecture reference data: " << directory;
- const auto base = directory / GetParam();
- const bool real_checkpoint = override_dir && !std::filesystem::exists(base.string() + ".npz");
+ const auto base = directory / fixture_family;
+ const bool real_checkpoint = override_dir && !legacy_hadamard && !std::filesystem::exists(base.string() + ".npz");
+ const bool gemma3n_fixture = !real_checkpoint && GetParam() == std::string("gemma3n");
+ // Gemma3n half attention rounding differs across CPU kernels and the nonflash llama.cpp oracle.
+#if defined(OPENVINO_ARCH_ARM64)
+ const double nmse_tolerance = gemma3n_fixture ? 3e-4 : 1e-5;
+#else
+ const double nmse_tolerance = gemma3n_fixture ? 2e-5 : 1e-5;
+#endif
std::vector<std::vector<int64_t>> schedule{{1, 2, 3}, {4}, {5, 6}};
std::vector<float> reference;
+ std::vector<float> draft_features;
+ size_t draft_width = 0;
+ std::vector<float> deepstack_reference;
+ size_t deepstack_layers = 0, hidden_width = 0;
int32_t vocab = 0;
std::string model_path = base.string() + ".gguf";
std::unique_ptr<ov_gguf_test::TemporaryGguf> temporary;
@@ -1350,12 +1770,88 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {
vocab = static_cast<int32_t>(logits.shape[1]);
const auto* values = logits.data<float>();
reference.assign(values, values + 3 * vocab);
+ if (const auto it = std::find_if(arrays.begin(),
+ arrays.end(),
+ [](const auto& item) {
+ return item.first == "deepstack";
+ });
+ it != arrays.end()) {
+ deepstack_layers = it->second.shape[1];
+ hidden_width = it->second.shape[2];
+ deepstack_reference.assign(it->second.data<float>(), it->second.data<float>() + it->second.num_vals);
+ }
+ if (std::any_of(arrays.begin(), arrays.end(), [](const auto& item) {
+ return item.first == "hidden_states";
+ })) {
+ const auto& features = array("hidden_states");
+ draft_width = features.shape[1];
+ draft_features.assign(features.data<float>(), features.data<float>() + features.num_vals);
+ }
temporary = std::make_unique<ov_gguf_test::TemporaryGguf>(array("model"));
model_path = temporary->path;
}
ov::frontend::gguf::FrontEnd fe;
- fe.add_extension(std::make_shared<ov::frontend::gguf::GenAIExtension>());
- auto model = fe.convert(fe.load(model_path));
+ register_deferred_decoder(fe, fixture_family);
+ using GenAIExtension = ov::frontend::gguf::GenAIExtension;
+ auto extension = std::make_shared<GenAIExtension>(deepstack_layers ? GenAIExtension::InputMode::EMBEDS_TO_LOGITS
+ : GenAIExtension::InputMode::IDS_TO_LOGITS);
+ fe.add_extension(extension);
+ std::shared_ptr<ov::Model> model;
+ if (legacy_hadamard) {
+ using namespace ov::frontend::gguf;
+ auto loaded = get_gguf_data(model_path);
+ auto& metadata = std::get<0>(loaded);
+ auto& weights = std::get<1>(loaded);
+ const std::vector<std::string> names{"blk.0.ssm_in.weight", "blk.0.ssm_ba.weight"};
+ constexpr size_t block_size = 8;
+ // The symmetric, self-inverse rotation preserves the original reference logits.
+ for (const auto& name : names) {
+ auto& weight = weights.at(name);
+ ASSERT_EQ(weight.data.get_element_type(), ov::element::f32);
+ ASSERT_EQ(weight.shape.size(), 2u);
+ const auto width = weight.shape[1];
+ ASSERT_EQ(width % block_size, 0u);
+ ov::Tensor rotated(ov::element::f32, weight.shape);
+ const auto* original = weight.data.data<const float>();
+ auto* transformed = rotated.data<float>();
+ for (size_t row = 0; row < weight.shape[0]; ++row) {
+ for (size_t base = 0; base < width; base += block_size) {
+ for (size_t col = 0; col < block_size; ++col) {
+ float sum = 0.f;
+ for (size_t k = 0; k < block_size; ++k) {
+ const auto bits = col & k;
+ const auto parity = ((bits & 1) + ((bits >> 1) & 1) + ((bits >> 2) & 1)) % 2;
+ sum += (parity ? -1.f : 1.f) * original[row * width + base + k];
+ }
+ transformed[row * width + base + col] = sum / std::sqrt(static_cast<float>(block_size));
+ }
+ }
+ }
+ weight = GgufWeight(rotated);
+ weight.source_name = name;
+ }
+ const auto scalar = [](uint32_t value) {
+ ov::Tensor tensor(ov::element::u32, ov::Shape{});
+ *tensor.data<uint32_t>() = value;
+ return tensor;
+ };
+ metadata["prism.hadamard.version"] = scalar(1);
+ metadata["prism.hadamard.block_size"] = scalar(block_size);
+ metadata["prism.hadamard.transform"] = std::string("normalized-sylvester-walsh-hadamard");
+ metadata["prism.hadamard.axis"] = std::string("input-last-dimension");
+ metadata["prism.hadamard.sign_mode"] = std::string("identity");
+ metadata["prism.hadamard.weight_names"] = names;
+ detail::MetadataStore store{metadata};
+ detail::WeightStore tensors{weights};
+ const GgufMetadata metadata_view(store);
+ const auto parameters = resolve_decoder_parameters(metadata_view, RopeMode::Neox);
+ const BuildContext context{metadata_view, parameters.architecture, &tensors};
+ DecoderBuilder builder(context, parameters);
+ std::shared_ptr<GgufDecoder> decoder = std::make_shared<GgufBuilderDecoder>(builder.build());
+ model = fe.convert(fe.load(decoder));
+ } else {
+ model = fe.convert(fe.load(model_path));
+ }
if (mamba) {
EXPECT_EQ(model->input("input_ids").get_partial_shape(), (ov::PartialShape{lfm2 ? -1 : 1, -1}));
EXPECT_NO_THROW(model->input("beam_idx"));
@@ -1369,20 +1865,60 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {
ov::hint::dynamic_quantization_group_size(0),
ov::hint::kv_cache_precision(ov::element::f16));
auto request = compiled.create_infer_request();
+ ov::InferRequest lookup;
+ if (!real_checkpoint && GetParam() == std::string("eagle3-mapped")) {
+ auto mapping = ov::as_type_ptr<ov::op::v0::Constant>(
+ model->output("d2t").get_node()->input_value(0).get_node_shared_ptr());
+ ASSERT_TRUE(mapping);
+ const auto values = mapping->cast_vector<int64_t>();
+ ASSERT_EQ(values.size(), 16u);
+ for (size_t i = 0; i < values.size(); ++i)
+ EXPECT_EQ(values[i], static_cast<int64_t>(2 * i));
+ }
+ if (deepstack_layers)
+ lookup = core.compile_model(extension->get_embedding_model(), "CPU").create_infer_request();
const auto infer = [&](const std::vector<int64_t>& tokens, size_t past) {
const auto count = tokens.size();
+ const auto attention_count = std::string(GetParam()).find("dflash") == 0 ? 2 * count : count;
ov::Tensor ids(ov::element::i64, {1, count});
- ov::Tensor positions(ov::element::i64, ids.get_shape());
- ov::Tensor mask(ov::element::i64, {1, past + count});
+ ov::Tensor positions(ov::element::i64, {1, attention_count});
+ ov::Tensor mask(ov::element::i64, {1, past + attention_count});
ov::Tensor beam(ov::element::i32, {1});
*beam.data<int32_t>() = 0;
for (size_t i = 0; i < count; ++i) {
ids.data<int64_t>()[i] = tokens[i];
- positions.data<int64_t>()[i] = static_cast<int64_t>(past + i);
}
+ for (size_t i = 0; i < attention_count; ++i)
+ positions.data<int64_t>()[i] = static_cast<int64_t>(past + i);
std::fill_n(mask.data<int64_t>(), mask.get_size(), 1);
- request.set_tensor("input_ids", ids);
- request.set_tensor("position_ids", positions);
+ if (deepstack_layers) {
+ lookup.set_tensor("input_ids", ids);
+ lookup.infer();
+ request.set_tensor("inputs_embeds", lookup.get_output_tensor());
+ ov::Tensor media_mask(ov::element::boolean, {1, count});
+ std::fill_n(media_mask.data<bool>(), count, true);
+ ov::Tensor features(ov::element::f32, {deepstack_layers, count, hidden_width});
+ for (size_t l = 0; l < deepstack_layers; ++l)
+ for (size_t t = 0; t < count; ++t)
+ for (size_t d = 0; d < hidden_width; ++d)
+ features.data<float>()[(l * count + t) * hidden_width + d] =
+ deepstack_reference[((past + t) * deepstack_layers + l) * hidden_width + d];
+ request.set_tensor("deepstack_visual_embeds", features);
+ request.set_tensor("visual_pos_masks", media_mask);
+ ov::Tensor multimodal_positions(ov::element::i64, {3, 1, count});
+ for (size_t section = 0; section < 3; ++section)
+ for (size_t t = 0; t < count; ++t)
+ multimodal_positions.data<int64_t>()[section * count + t] = past + t;
+ request.set_tensor("position_ids", multimodal_positions);
+ } else {
+ request.set_tensor("input_ids", ids);
+ request.set_tensor("position_ids", positions);
+ }
+ if (draft_width) {
+ ov::Tensor hidden(ov::element::f32, {1, count, draft_width});
+ std::copy_n(draft_features.data() + past * draft_width, hidden.get_size(), hidden.data<float>());
+ request.set_tensor("hidden_states", hidden);
+ }
request.set_tensor("attention_mask", mask);
if (std::any_of(compiled.inputs().begin(), compiled.inputs().end(), [](const ov::Output<const ov::Node>& p) {
return p.get_names().count("beam_idx");
@@ -1401,7 +1937,22 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {
ASSERT_GE(result.get_size(), static_cast<size_t>(vocab));
const auto* actual = result.data<const float>() + result.get_size() - vocab;
const auto* expected = reference.data() + step++ * vocab;
- const auto metric = ov_gguf_test::nmse(actual, expected, static_cast<size_t>(vocab));
+ std::vector<float> mapped_actual, mapped_expected;
+ if (GetParam() == std::string("dflash-mapped")) {
+ for (int row = 0; row < vocab; ++row) {
+ if (row % 2) {
+ EXPECT_EQ(actual[row], -std::numeric_limits<float>::infinity());
+ EXPECT_EQ(expected[row], -std::numeric_limits<float>::infinity());
+ } else {
+ mapped_actual.push_back(actual[row]);
+ mapped_expected.push_back(expected[row]);
+ }
+ }
+ }
+ const auto metric =
+ mapped_actual.empty()
+ ? ov_gguf_test::nmse(actual, expected, static_cast<size_t>(vocab))
+ : ov_gguf_test::nmse(mapped_actual.data(), mapped_expected.data(), mapped_actual.size());
ASSERT_TRUE(metric.all_finite());
ASSERT_GT(metric.reference_norm(), 1e-12) << "Reference must contain nonzero logits";
const auto predicted = std::max_element(actual, actual + vocab) - actual;
@@ -1416,7 +1967,10 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {
EXPECT_EQ(predicted, wanted);
}
} else {
- EXPECT_LT(metric.value(), 1e-5) << "Normalized MSE against llama.cpp CPU";
+ EXPECT_LT(metric.value(), nmse_tolerance) << "Normalized MSE against llama.cpp CPU";
+ if (gemma3n_fixture) {
+ EXPECT_EQ(predicted, wanted);
+ }
}
past += tokens.size();
}
@@ -1443,8 +1997,25 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {
INSTANTIATE_TEST_SUITE_P(Architectures,
GGUFArchitectureAccuracy,
- ::testing::Values("afmoe",
- "qwen35",
+ ::testing::Values("qwen35",
+ "qwen3next",
+ "qwen3next-legacy",
+ "qwen3next-legacy-hadamard",
+ "qwen3vl",
+ "qwen3vl-deepstack",
+ "qwen3vlmoe",
+ "qwen3tts",
+ "cohere2",
+ "gemma3n",
+ "eagle3",
+ "eagle3-mapped",
+ "eagle3-fc-q4_1",
+ "dflash",
+ "dflash-fc-q4_1",
+ "dflash-post",
+ "dflash-shared",
+ "dflash-mapped",
+ "afmoe",
"qwen35-zero-scales",
"lfm2",
"lfm2-tied",
diff --git a/src/frontends/gguf/tests/test_arch_conversion.cpp b/src/frontends/gguf/tests/test_arch_conversion.cpp
index 315c5cf1864..dd74626ab67 100644
--- a/src/frontends/gguf/tests/test_arch_conversion.cpp
+++ b/src/frontends/gguf/tests/test_arch_conversion.cpp
@@ -212,6 +212,8 @@ const std::map<std::string, Fingerprint>& fingerprints() {
{"smollm3-dense.gguf.hdr", {389, 10}},
{"jais2-dense.gguf.hdr", {334, 10}},
{"lfm3.gguf.hdr", {702, 12}},
+ {"qwen3vl-dense.gguf.hdr", {469, 10}},
+ {"qwen3vlmoe-moe.gguf.hdr", {620, 10}},
};
return fp;
}
diff --git a/src/frontends/gguf/tests/test_architecture_extension.cpp b/src/frontends/gguf/tests/test_architecture_extension.cpp
index 9144b8e8af6..63390b0c4bc 100644
--- a/src/frontends/gguf/tests/test_architecture_extension.cpp
+++ b/src/frontends/gguf/tests/test_architecture_extension.cpp
@@ -14,12 +14,15 @@
#include <vector>
#include "builder/api/metadata_store.hpp"
+#include "builder/arch_registry.hpp"
+#include "builder/gguf_builder_decoder.hpp"
#include "builder/gguf_graph.hpp"
#include "common_test_utils/common_utils.hpp"
#include "common_test_utils/file_utils.hpp"
#include "common_test_utils/test_assertions.hpp"
#include "gguf_writer.hpp"
#include "gtest/gtest.h"
+#include "op_test_utils.hpp"
#include "openvino/frontend/extension/conversion.hpp"
#include "openvino/frontend/extension/decoder_transformation.hpp"
#include "openvino/frontend/gguf/adapt_to_genai.hpp"
@@ -111,6 +114,16 @@ std::string write_decoder_gguf(const std::string& dir,
return writer.write(path) ? path : std::string{};
}
+std::string write_qwen3vl_gguf(const std::string& dir, const std::vector<std::string>& tags) {
+ const auto path = ov::util::path_join({dir, "qwen3vl.gguf"}).string();
+ GgufWriter writer;
+ writer.kv_str("general.architecture", "qwen3vl");
+ writer.kv_str_array("general.tags", tags);
+ writer.kv_u32("qwen3vl.n_deepstack_layers", 0);
+ writer.filled_tensor("token_embd.weight", {8, 16});
+ return writer.write(path) ? path : std::string{};
+}
+
constexpr const char* kUnknownArch = "my-qwen3";
std::shared_ptr<ov::Model> convert_with(const std::string& path,
@@ -142,6 +155,70 @@ TEST(GGUFArchitectureExtension, UnknownArchitectureIsRejectedWithoutAnExtension)
testing::HasSubstr("ArchitectureExtension")));
}
+TEST(GGUFArchitectureExtension, DeferredArchitecturesAreRejectedWithoutAnExtension) {
+ for (const auto* architecture : {"qwen3next"}) {
+ SCOPED_TRACE(architecture);
+ ScratchDir scratch;
+ const auto path = write_decoder_gguf(scratch.path(), architecture);
+ ASSERT_FALSE(path.empty());
+ ov::frontend::gguf::FrontEnd frontend;
+ OV_EXPECT_THROW(frontend.load(path),
+ ov::Exception,
+ testing::AllOf(testing::HasSubstr("native GGUF builder does not support architecture"),
+ testing::HasSubstr(architecture)));
+ frontend.add_extension(std::make_shared<ArchitectureExtension>(architecture, RopeMode::Neox));
+ EXPECT_NO_THROW(frontend.load(path));
+ }
+}
+
+TEST(GGUFArchitectureExtension, BuiltInDecodersAcceptSupportedTensorTypes) {
+ using namespace ov::frontend::gguf;
+ ov::Core core;
+ for (const auto* architecture : {"afmoe", "qwen3tts", "qwen3vlmoe"}) {
+ SCOPED_TRACE(architecture);
+ const auto arrays = cnpy::npz_load(test_data_dir() + "/arch_accuracy/" + architecture + ".npz");
+ const TemporaryGguf fixture(npz_array(arrays, "model"));
+ for (const auto type : {GGUF_TYPE_BF16, GGUF_TYPE_Q8_0}) {
+ SCOPED_TRACE(type);
+ auto loaded = get_gguf_data(fixture.path);
+ auto& weights = std::get<1>(loaded);
+ quantize_weight(weights, "token_embd.weight", type);
+ const detail::MetadataStore meta_store{std::get<0>(loaded)};
+ const GgufMetadata meta(meta_store);
+ const auto definition = ArchRegistry{}.find(meta);
+ ASSERT_TRUE(definition);
+ detail::WeightStore store{weights};
+ const auto builder = definition->factory(BuildContext{meta, architecture, &store});
+ std::shared_ptr<GgufDecoder> decoder = std::make_shared<GgufBuilderDecoder>(builder->build());
+ FrontEnd frontend;
+ frontend.add_extension(std::make_shared<GenAIExtension>(GenAIExtension::InputMode::IDS_TO_LOGITS));
+ const auto model = frontend.convert(frontend.load(decoder));
+ EXPECT_NO_THROW(core.compile_model(model,
+ "CPU",
+ ov::hint::inference_precision(ov::element::f32),
+ ov::hint::dynamic_quantization_group_size(0)));
+ }
+ }
+}
+
+TEST(GGUFArchitectureExtension, Qwen3ASRTaskTagRemainsRegistered) {
+ ScratchDir scratch;
+ const auto path = write_qwen3vl_gguf(scratch.path(), {"automatic-speech-recognition"});
+ ASSERT_FALSE(path.empty());
+ ov::frontend::gguf::FrontEnd frontend;
+ EXPECT_NO_THROW(frontend.load(path));
+}
+
+TEST(GGUFArchitectureExtension, Qwen3VLDenseWithoutDeepStackRemainsRegistered) {
+ for (const auto& tags : {std::vector<std::string>{}, std::vector<std::string>{"image-text-to-text"}}) {
+ ScratchDir scratch;
+ const auto path = write_qwen3vl_gguf(scratch.path(), tags);
+ ASSERT_FALSE(path.empty());
+ ov::frontend::gguf::FrontEnd frontend;
+ EXPECT_NO_THROW(frontend.load(path));
+ }
+}
+
TEST(GGUFArchitectureExtension, UnsupportedDiagnosticIncludesRegisteredArchitectures) {
ScratchDir scratch;
const auto path = write_decoder_gguf(scratch.path(), "unknown-decoder");
diff --git a/src/frontends/gguf/tests/test_builder_api.cpp b/src/frontends/gguf/tests/test_builder_api.cpp
index 1ea27973a5a..46ec5a29c9a 100644
--- a/src/frontends/gguf/tests/test_builder_api.cpp
+++ b/src/frontends/gguf/tests/test_builder_api.cpp
@@ -13,6 +13,7 @@
#include "builder/gguf_builder_decoder.hpp"
#include "builder/gguf_graph.hpp"
#include "gtest/gtest.h"
+#include "model_contract.hpp"
#include "openvino/core/type/float16.hpp"
#include "openvino/frontend/gguf/builder/graph_context.hpp"
#include "openvino/frontend/gguf/frontend.hpp"
@@ -81,6 +82,40 @@ ArchitectureDefinition handler(const std::string& id, ArchitectureDefinition::Ma
}
} // namespace
+TEST(GGUFBuilderAPI, ArchitectureExtensionOverridesPersistedGenAIContract) {
+ Environment env;
+ env.architecture("eagle3");
+ struct ContractBuilder : ModelBuilder {
+ GgufGraphContext graph;
+ explicit ContractBuilder(const BuildContext& context) : graph(context) {}
+ std::shared_ptr<GgufGraph> build() override {
+ auto input = graph.add_input("opaque_input", ov::element::f32, {1, 1, 2, 3});
+ graph.set_output(input, "opaque_features");
+ ModelContract contract;
+ contract.genai.emplace();
+ contract.genai->enabled = false;
+ contract.genai->position_layout = ModelContract::GenAIContract::PositionLayout::THREE_AXIS;
+ contract.genai->auxiliary_outputs = {{"opaque_features", "features", 1}};
+ graph.configure_model_contract(contract);
+ return graph.finish();
+ }
+ };
+ ArchitectureDefinition replacement{"eagle3", "eagle3", [](const BuildContext& context) {
+ return std::make_shared<ContractBuilder>(context);
+ }};
+ ArchRegistry registry;
+ registry.add_extension(std::make_shared<ArchitectureExtension>(replacement, RegistrationMode::Replace));
+ const auto selected = registry.find(env.context.metadata);
+ ASSERT_TRUE(selected);
+ const auto model = convert(selected->factory(env.context)->build());
+ const auto contract = read_model_contract(model);
+ ASSERT_TRUE(contract.genai);
+ EXPECT_FALSE(contract.genai->enabled);
+ EXPECT_EQ(contract.genai->position_layout, ModelContract::GenAIContract::PositionLayout::THREE_AXIS);
+ ASSERT_EQ(contract.genai->auxiliary_outputs.size(), 1);
+ EXPECT_EQ(contract.genai->auxiliary_outputs[0].source_tensor, model->output().get_any_name());
+}
+
TEST(GGUFBuilderAPI, MetadataReadsReuseNumericConversionAcrossWidths) {
Environment env;
const auto& metadata = env.context.metadata;
@@ -311,6 +346,153 @@ TEST(GGUFBuilderAPI, RejectsInvalidRopeScalingFactors) {
}
}
+TEST(GGUFBuilderAPI, RetainedFamilyDefaultsAndTypedOverrides) {
+ Environment cohere;
+ cohere.decoder();
+ cohere.real("test.attention.layer_norm_epsilon", 1e-5f);
+ cohere.integer("test.attention.sliding_window", 128);
+ cohere.architecture("cohere2");
+ auto parameters = cohere.parameters();
+ DecoderConfig config(parameters, cohere.weights);
+ EXPECT_TRUE(config.layer_norm);
+ EXPECT_TRUE(config.parallel_ffn);
+ EXPECT_TRUE(config.rope_on_swa_only);
+ EXPECT_EQ(config.swa_layer_pattern, 4);
+ parameters.parallel_ffn = false;
+ EXPECT_FALSE(DecoderConfig(parameters, cohere.weights).parallel_ffn);
+
+ Environment gemma;
+ gemma.decoder();
+ gemma.integer("test.block_count", 30);
+ gemma.integer("test.attention.sliding_window", 128);
+ gemma.real("test.rope.scaling.factor", 4.f);
+ gemma.architecture("gemma3n");
+ parameters = gemma.parameters();
+ DecoderConfig gemma_config(parameters, gemma.weights);
+ EXPECT_FLOAT_EQ(parameters.scales.attention, 1.0f);
+ EXPECT_FLOAT_EQ(gemma_config.layer_kq_scale(0), 1.0f);
+ EXPECT_TRUE(gemma_config.is_geglu);
+ EXPECT_TRUE(gemma_config.has_v_norm);
+ EXPECT_TRUE(gemma_config.embedding_scale_tokens_only);
+ EXPECT_EQ(gemma_config.n_embd_per_layer, 256);
+ EXPECT_EQ(gemma_config.shared_kv_layers, 10);
+ EXPECT_EQ(gemma_config.swa_layer_pattern, 5);
+ EXPECT_FLOAT_EQ(gemma_config.final_logit_soft_cap, 30.f);
+ EXPECT_FLOAT_EQ(gemma_config.layer_rope_config(0).freq_scale, 0.25f);
+ parameters.dimensions.per_layer_embedding = 128;
+ parameters.dimensions.shared_kv_layers = 0;
+ parameters.normalization.value_norm = false;
+ parameters.scales.attention = 0.25f;
+ DecoderConfig overridden(parameters, gemma.weights);
+ EXPECT_EQ(overridden.n_embd_per_layer, 128);
+ EXPECT_EQ(overridden.shared_kv_layers, 0);
+ EXPECT_FALSE(overridden.has_v_norm);
+ EXPECT_FLOAT_EQ(overridden.layer_kq_scale(0), 0.25f);
+}
+
+TEST(GGUFBuilderAPI, DraftFeaturesAndDeepStackUseTypedMetadata) {
+ Environment env;
+ env.decoder();
+ env.architecture("eagle3");
+ env.metadata["eagle3.target_layers"] = std::vector<int32_t>{0, 1, 2};
+ env.integer("eagle3.norm_before_fc", 1);
+ env.integer("eagle3.norm_before_residual", 1);
+ auto parameters = env.parameters();
+ EXPECT_EQ(parameters.draft.target_layers, (std::vector<int32_t>{0, 1, 2}));
+ EXPECT_TRUE(parameters.draft.norm_before_fc);
+ EXPECT_TRUE(parameters.draft.norm_before_residual);
+ parameters.draft.norm_before_fc = false;
+ EXPECT_FALSE(DecoderConfig(parameters, env.weights).draft_norm_before_fc);
+ env.metadata["eagle3.norm_before_fc"] = 0.5f;
+ EXPECT_THROW(env.parameters(), ov::Exception);
+
+ Environment visual;
+ visual.decoder();
+ visual.architecture("qwen3vl");
+ visual.integer("qwen3vl.n_deepstack_layers", 1);
+ DecoderConfig config(visual.parameters(RopeMode::Interleaved), visual.weights);
+ EXPECT_EQ(config.deepstack_layers, 1);
+ visual.integer("qwen3vl.n_deepstack_layers", std::numeric_limits<int>::max());
+ EXPECT_THROW(DecoderConfig(visual.parameters(RopeMode::Interleaved), visual.weights), ov::Exception);
+ visual.integer("qwen3vl.n_deepstack_layers", std::numeric_limits<uint32_t>::max());
+ EXPECT_THROW(visual.parameters(), ov::Exception);
+}
+
+TEST(GGUFBuilderAPI, ExpertProbeDoesNotOverflowAtMaximumDenseLead) {
+ Environment env;
+ env.decoder();
+ auto parameters = env.parameters();
+ parameters.experts.dense_lead = std::numeric_limits<int>::max();
+ parameters.experts.layer_step = 1;
+ EXPECT_NO_THROW(DecoderConfig(parameters, env.weights));
+ parameters.experts.layer_step = std::numeric_limits<int>::max();
+ EXPECT_NO_THROW(DecoderConfig(parameters, env.weights));
+}
+
+TEST(GGUFBuilderAPI, RejectsUnsupportedDFlashAuxiliaryTensors) {
+ for (const auto* name : {"markov_w1.weight",
+ "conf_proj.weight",
+ "selector_hidden.weight",
+ "lilicorr.token_proj.weight",
+ "blk.0.attn_conv_proj.weight",
+ "blk.0.ffn_conv_base.weight"}) {
+ SCOPED_TRACE(name);
+ Environment env;
+ env.decoder();
+ env.architecture("dflash");
+ env.weights[name] = ov::Tensor(ov::element::f32, {1});
+ try {
+ (void)DecoderConfig(env.parameters(), env.weights);
+ FAIL() << "Expected unsupported DFlash auxiliary tensor";
+ } catch (const ov::Exception& error) {
+ EXPECT_NE(std::string(error.what()).find("unsupported DFlash auxiliary tensor"), std::string::npos);
+ EXPECT_NE(std::string(error.what()).find(name), std::string::npos);
+ }
+ auto parameters = env.parameters();
+ parameters.architecture = "dspark";
+ EXPECT_NO_THROW(DecoderConfig(parameters, env.weights));
+ }
+}
+
+TEST(GGUFBuilderAPI, RejectsUnsupportedDFlashAuxiliaryMetadata) {
+ for (const auto* name : {"dflash.conv_kernel_size",
+ "dflash.conv_group_size",
+ "dflash.selector_rank",
+ "dflash.selector_top_k",
+ "lilicorr.hidden_size",
+ "dflash.markov_rank"}) {
+ SCOPED_TRACE(name);
+ Environment env;
+ env.decoder();
+ env.architecture("dflash");
+ env.integer(name, 1);
+ try {
+ (void)env.parameters();
+ FAIL() << "Expected unsupported DFlash auxiliary metadata";
+ } catch (const ov::Exception& error) {
+ EXPECT_NE(std::string(error.what()).find("unsupported DFlash auxiliary metadata"), std::string::npos);
+ EXPECT_NE(std::string(error.what()).find(name), std::string::npos);
+ }
+ }
+}
+
+TEST(GGUFBuilderAPI, BaseDFlashMetadataDoesNotSelectAuxiliaryVariants) {
+ Environment env;
+ env.decoder();
+ env.architecture("dflash");
+ env.integer("dflash.block_size", 16);
+ env.integer("dflash.sample_from_anchor", 1);
+ for (const auto* name :
+ {"dflash.conv_kernel_size", "dflash.conv_group_size", "dflash.selector_rank", "dflash.selector_top_k"})
+ env.integer(name, 0);
+ env.metadata["dflash.target_layers"] = std::vector<int32_t>{2, 7, 12};
+ env.real("dflash.attention.value_scale", 0.5f);
+ const auto parameters = env.parameters(RopeMode::Neox);
+ EXPECT_FALSE(parameters.causal_attention);
+ EXPECT_EQ(parameters.draft.target_layers, (std::vector<int32_t>{2, 7, 12}));
+ EXPECT_FLOAT_EQ(DecoderConfig(parameters, env.weights).attention_value_scale, 0.5f);
+}
+
TEST(GGUFBuilderAPI, RopeScalingPreservesTypedDefaultsWithoutAnOverride) {
Environment env;
env.decoder();
@@ -1089,8 +1271,15 @@ TEST(GGUFBuilderAPI, ExpertNormalizationMetadataOverridesBuilderDefaults) {
}
TEST(GGUFBuilderAPI, BuiltinExpertNormalizationPreservesLlamaPolicyAndOptions) {
- for (const auto* architecture :
- {"hunyuan-moe", "minimax-m2", "qwen3moe", "qwen35moe", "ernie4_5-moe", "mellum", "gemma4"}) {
+ for (const auto* architecture : {"hunyuan-moe",
+ "minimax-m2",
+ "qwen3moe",
+ "qwen3next",
+ "qwen3vlmoe",
+ "qwen35moe",
+ "ernie4_5-moe",
+ "mellum",
+ "gemma4"}) {
SCOPED_TRACE(architecture);
Environment env;
env.decoder();
@@ -1158,6 +1347,10 @@ TEST(GGUFBuilderAPI, TypedCustomLayerNormScalesAndLayerSettingsAreResolvedTogeth
parameters.layers[1].rope = local_rope;
parameters.model_contract.batchable_recurrent = true;
parameters.model_contract.image_attention = ModelContract::ImageAttentionMode::SLIDING_ONLY;
+ parameters.model_contract.genai.emplace();
+ parameters.model_contract.genai->position_layout = ModelContract::GenAIContract::PositionLayout::THREE_AXIS;
+ parameters.model_contract.genai->causal_attention = false;
+ parameters.model_contract.genai->attention_context_input = "custom_context";
DecoderConfig resolved(parameters, env.weights);
EXPECT_TRUE(resolved.layer_norm);
EXPECT_FLOAT_EQ(resolved.rms_eps, 3e-4f);
@@ -1188,6 +1381,10 @@ TEST(GGUFBuilderAPI, TypedCustomLayerNormScalesAndLayerSettingsAreResolvedTogeth
EXPECT_EQ(built->swa_window_size, 17);
EXPECT_TRUE(built->model_contract.batchable_recurrent);
EXPECT_EQ(built->model_contract.image_attention, ModelContract::ImageAttentionMode::SLIDING_ONLY);
+ ASSERT_TRUE(built->model_contract.genai);
+ EXPECT_EQ(built->model_contract.genai->position_layout, ModelContract::GenAIContract::PositionLayout::THREE_AXIS);
+ EXPECT_FALSE(built->model_contract.genai->causal_attention);
+ EXPECT_EQ(built->model_contract.genai->attention_context_input, "custom_context");
}
TEST(GGUFBuilderAPI, TypedSettingsRejectPartialLayersAndIncompatiblePresentMetadata) {
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/README.md b/src/frontends/gguf/tests/test_data/arch_accuracy/README.md
index 49ae735cf0d..5d77124ab00 100644
--- a/src/frontends/gguf/tests/test_data/arch_accuracy/README.md
+++ b/src/frontends/gguf/tests/test_data/arch_accuracy/README.md
@@ -7,7 +7,16 @@ Embedding fixtures contain `embeddings` instead of `logits`, and cover causal/bi
per-token output plus mean, first-token and last-token pooling.
OpenVINO does not participate in reference generation.
-The 40 decoder fixtures and five embedding fixtures include Muse Glimmer, Qwen3.5 dense/MoE (separate and fused
+`eagle3-fc-q4_1` and `dflash-fc-q4_1` use packed Q4_1 FC weights with logical
+input width 96. Their integer zero points, binary-exact scales and Q8_0-representable
+hidden features isolate packed-weight geometry from requantization and reference
+activation rounding. Both use CPU revision `098ce526b546b5a190327c1da82929cee051b9ac`
+and the unchanged `1e-5` gate; they do not establish arbitrary quantized-checkpoint parity.
+
+DFlash fixtures cover `dflash`, `dflash-mapped`, `dflash-fc-q4_1`, `dflash-post` and
+`dflash-shared`. Convolution, selector, LiLiCorr and Markov variants are deferred.
+
+The decoder and embedding fixtures include Muse Glimmer, Qwen3.5 dense/MoE (separate and fused
expert projections, and F16 Gated-DeltaNet gate/beta projections that disable the frontend's
projection merges as mixed quantization does in real checkpoints), Gemma4 mixed-head MQA/MoE variants and an E2B/E4B-style Gemma4 with
per-layer embeddings and shared KV layers that omit unused K/V weights (`gemma4-ple`). Reference revisions are:
@@ -89,6 +98,8 @@ PYTHONPATH="$LLAMA_SRC/gguf-py" python3 gen_dspark_accuracy.py --oracle ./dspark
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.
+The `qwen3next-legacy-hadamard` case rotates the legacy fixture's fused weights and reuses its
+original logits; it always uses the committed fixture, even when `OV_GGUF_ACCURACY_DATA` is set.
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"`.
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/cohere2.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/cohere2.npz
new file mode 100644
index 00000000000..0b2f037ce65
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/cohere2.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/dflash-fc-q4_1.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/dflash-fc-q4_1.npz
new file mode 100644
index 00000000000..0092f8742ed
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/dflash-fc-q4_1.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/dflash-mapped.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/dflash-mapped.npz
new file mode 100644
index 00000000000..3de59c3f604
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/dflash-mapped.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/dflash-post.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/dflash-post.npz
new file mode 100644
index 00000000000..c612bcacc39
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/dflash-post.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/dflash-shared.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/dflash-shared.npz
new file mode 100644
index 00000000000..b722386786a
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/dflash-shared.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/dflash.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/dflash.npz
new file mode 100644
index 00000000000..2b722cc3d41
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/dflash.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/eagle3-fc-q4_1.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/eagle3-fc-q4_1.npz
new file mode 100644
index 00000000000..446eb3ba65b
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/eagle3-fc-q4_1.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/eagle3-mapped.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/eagle3-mapped.npz
new file mode 100644
index 00000000000..7987e416474
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/eagle3-mapped.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/eagle3.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/eagle3.npz
new file mode 100644
index 00000000000..b1edfa3c6c2
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/eagle3.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/gemma3n.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/gemma3n.npz
new file mode 100644
index 00000000000..7762e6291a9
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/gemma3n.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3next-legacy.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3next-legacy.npz
new file mode 100644
index 00000000000..b4ae11d6826
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3next-legacy.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3next.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3next.npz
new file mode 100644
index 00000000000..fa87ff67c6e
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3next.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3tts.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3tts.npz
new file mode 100644
index 00000000000..c4540eeadba
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3tts.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3vl-deepstack.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3vl-deepstack.npz
new file mode 100644
index 00000000000..a57eed56634
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3vl-deepstack.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3vl.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3vl.npz
new file mode 100644
index 00000000000..dfb90d40591
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3vl.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3vlmoe.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3vlmoe.npz
new file mode 100644
index 00000000000..de91539b6fa
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3vlmoe.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_fixtures/manifest.txt b/src/frontends/gguf/tests/test_data/arch_fixtures/manifest.txt
index c04222c2eeb..2f04d364c69 100644
--- a/src/frontends/gguf/tests/test_data/arch_fixtures/manifest.txt
+++ b/src/frontends/gguf/tests/test_data/arch_fixtures/manifest.txt
@@ -62,6 +62,7 @@ jamba-dense.gguf.hdr 6061856 reject
kimi-linear-moe.gguf.hdr 2833984 reject
lfm2-dense.gguf.hdr 4731520 convert
lfm2moe-moe.gguf.hdr 5913248 convert
+lfm3.gguf.hdr 139296 convert
llada-dense.gguf.hdr 4735104 reject
llada-moe-moe.gguf.hdr 7096192 reject
llama-dense.gguf.hdr 4741248 convert
@@ -101,8 +102,8 @@ qwen35-dense.gguf.hdr 5271040 convert
qwen35moe-moe.gguf.hdr 9995904 convert
qwen3moe-moe.gguf.hdr 7096192 convert
qwen3next-moe.gguf.hdr 11044416 reject
-qwen3vl-dense.gguf.hdr 4733824 reject
-qwen3vlmoe-moe.gguf.hdr 7096192 reject
+qwen3vl-dense.gguf.hdr 4733824 convert
+qwen3vlmoe-moe.gguf.hdr 7096192 convert
refact-dense.gguf.hdr 4741248 reject
refact-moe.gguf.hdr 7096448 reject
rnd1-moe.gguf.hdr 7096192 reject
@@ -114,4 +115,3 @@ starcoder-dense.gguf.hdr 4087296 reject
starcoder2-dense.gguf.hdr 3956480 reject
talkie-dense.gguf.hdr 4725760 reject
xverse-dense.gguf.hdr 4730752 reject
-lfm3.gguf.hdr 139296 convert
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/README.md b/src/frontends/gguf/tests/test_data/mmproj_accuracy/README.md
index 58d8c52907d..32675b67d02 100644
--- a/src/frontends/gguf/tests/test_data/mmproj_accuracy/README.md
+++ b/src/frontends/gguf/tests/test_data/mmproj_accuracy/README.md
@@ -17,6 +17,12 @@ feature layers, whole-tensor QK norms, an odd frame count, one-sided clipping bo
overview separators. Both suites compare the raw encoder and its `AdaptMmprojToGenAI` form
with normalized MSE below `1e-5`.
+The three Gemma3nv dynamic fixtures use distinct deterministic 256x256 image inputs
+(seeds 42 and 43) and CPU revision `098ce526b546b5a190327c1da82929cee051b9ac`.
+`gemma3nv_uir` exercises a MobileNet UIR block with depthwise-start convolution
+and no optional pointwise expansion. Each fixture compares native and GenAI-adapted
+features across two images and request reuse.
+
The standalone op tests in `test_ops.cpp` read `../mmproj_*.npy`, `../vision_rope_expected.npy`
and `../multimodal_imrope_expected.npy`: window partition, SAM relative positions,
vision/interleaved RoPE, antialiased bilinear resize and 2D im2col.
@@ -59,6 +65,12 @@ See [testing](../../../docs/testing.md#real-checkpoints) for pytest commands, de
oracle caches, and local-file lists, and [coverage limits](../../../docs/mmproj.md#validation-coverage)
for checkpoint tolerance overrides and skipped cases.
+`qwen3tts_gen.npz` contains a tiny F32 predictor with two query heads, one KV head,
+16 codebooks, and the full waveform topology. `gen_qwen3tts_accuracy.py` regenerates it
+with `qwen3tts_oracle.cpp` against CPU revision `098ce526b546b5a190327c1da82929cee051b9ac`
+(`GGML_OPENVINO=OFF`). The regression checks exact sampled codes/feedback, full logits,
+two streaming chunks and reset of all 38 states at the existing `1e-5` NMSE gate.
+
`lfm2` and `lfm2_no_norm` use the same pinned oracle revision above and the two-grid
generator seed 2718. They cover SigLIP, resized positions, spatial unshuffle and the
optional input LayerNorm at 16x8 and 8x24 pixels, through both native and embedding-adapted IO.
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma3nv.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma3nv.npz
new file mode 100644
index 00000000000..dbd47e9154d
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma3nv.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma3nv_attention.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma3nv_attention.npz
new file mode 100644
index 00000000000..35cfe215c48
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma3nv_attention.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma3nv_uir.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma3nv_uir.npz
new file mode 100644
index 00000000000..67a98d06388
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma3nv_uir.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen3a.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen3a.npz
new file mode 100644
index 00000000000..55f9ce4357a
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen3a.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen3tts_gen.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen3tts_gen.npz
new file mode 100644
index 00000000000..e416a3bc7e1
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen3tts_gen.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen3tts_spkenc.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen3tts_spkenc.npz
new file mode 100644
index 00000000000..683ee1e274f
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen3tts_spkenc.npz differ
diff --git a/src/frontends/gguf/tests/test_half_experts.cpp b/src/frontends/gguf/tests/test_half_experts.cpp
new file mode 100644
index 00000000000..b93f9d5e590
--- /dev/null
+++ b/src/frontends/gguf/tests/test_half_experts.cpp
@@ -0,0 +1,350 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <algorithm>
+#include <cstring>
+#include <tuple>
+
+#include "helper_ops/gguf_constant.hpp"
+#include "node_context.hpp"
+#include "op_test_utils.hpp"
+#include "openvino/core/type/bfloat16.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/pass/manager.hpp"
+#include "ov_ops/gather_matmul.hpp"
+#include "pass/materialize_weights.hpp"
+#include "transformations/fp16_compression/mark_decompression_convert_constant_folding.hpp"
+#include "transformations/rt_info/decompression.hpp"
+
+using namespace ov_gguf_test;
+
+namespace {
+
+enum class WeightStorage { DIRECT, CONVERTED, NATIVE_DEFERRED, CGRAPH_DEFERRED };
+using HalfExpertCase = std::tuple<ov::element::Type, bool, WeightStorage, bool>;
+
+std::shared_ptr<ov::Model> expert_model(const ov::element::Type& precision,
+ bool rank4,
+ WeightStorage storage,
+ bool per_expert,
+ const std::vector<float>& values) {
+ const ov::Shape weight_shape = rank4 ? ov::Shape{1, 3, 2, 2} : ov::Shape{3, 2, 2};
+ auto constant = ov::op::v0::Constant::create(precision, weight_shape, values);
+ constant->set_friendly_name("expert_storage");
+ ov::Output<ov::Node> weights = constant;
+ if (storage == WeightStorage::CONVERTED) {
+ weights = std::make_shared<ov::op::v0::Convert>(weights, ov::element::f32);
+ } else if (storage == WeightStorage::NATIVE_DEFERRED || storage == WeightStorage::CGRAPH_DEFERRED) {
+ ov::Tensor data(precision, weight_shape);
+ std::memcpy(data.data(), constant->get_data_ptr(), data.get_byte_size());
+ ov::frontend::gguf::GgufWeight source(data);
+ source.native = storage == WeightStorage::NATIVE_DEFERRED;
+ weights = std::make_shared<ov::frontend::gguf::GGUFConstant>(source);
+ }
+ const ov::PartialShape acts_shape{1, ov::Dimension::dynamic(), per_expert ? 2 : 1, 2};
+ const ov::PartialShape ids_shape{1, 1, ov::Dimension::dynamic(), 2};
+ auto acts = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, acts_shape);
+ auto ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ids_shape);
+ auto decoder = SingleOpBuilder()
+ .op("GGML_OP_MUL_MAT_ID")
+ .input("w", weights.get_element_type(), weight_shape)
+ .input("a", ov::element::f32, acts_shape)
+ .input("ids", ov::element::i32, ids_shape)
+ .output("out", ov::element::f32, {1, ov::Dimension::dynamic(), 2, 2})
+ .decoder();
+ auto tensors = std::make_shared<TensorMap>();
+ (*tensors)["w"] = weights;
+ (*tensors)["a"] = acts;
+ (*tensors)["ids"] = ids;
+ NodeContext context(decoder, tensors);
+ auto outputs = get_supported_ops().at("GGML_OP_MUL_MAT_ID")(context);
+ return std::make_shared<ov::Model>(outputs, ov::ParameterVector{acts, ids});
+}
+
+std::shared_ptr<ov::Model> routing_model(const ov::PartialShape& acts_shape, const ov::PartialShape& ids_shape) {
+ const ov::Shape weight_shape{3, 2, 2};
+ auto decoder = SingleOpBuilder()
+ .op("GGML_OP_MUL_MAT_ID")
+ .input("w", ov::element::f16, weight_shape)
+ .input("a", ov::element::f32, acts_shape)
+ .input("ids", ov::element::i32, ids_shape)
+ .output("out", ov::element::f32, {1, ids_shape[2], 2, 2})
+ .decoder();
+ auto acts = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, acts_shape);
+ auto ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ids_shape);
+ auto tensors = std::make_shared<TensorMap>();
+ (*tensors)["w"] = ov::op::v0::Constant::create(ov::element::f16,
+ weight_shape,
+ std::vector<float>{1, 0, 0, 1, 2, 0, 0, 2, 3, 0, 0, 3});
+ (*tensors)["a"] = acts;
+ (*tensors)["ids"] = ids;
+ NodeContext context(decoder, tensors);
+ return std::make_shared<ov::Model>(get_supported_ops().at("GGML_OP_MUL_MAT_ID")(context),
+ ov::ParameterVector{acts, ids});
+}
+
+void check_expert_graph(const std::shared_ptr<ov::Model>& model, bool deferred) {
+ size_t gmm_count = 0;
+ size_t deferred_count = 0;
+ for (const auto& node : model->get_ordered_ops()) {
+ if (const auto gmm = ov::as_type_ptr<ov::op::internal::GatherMatmul>(node)) {
+ ++gmm_count;
+ EXPECT_EQ(gmm->get_input_partial_shape(1), (ov::PartialShape{3, 2, 2}));
+ EXPECT_EQ(gmm->get_output_element_type(0), ov::element::f32);
+ }
+ deferred_count += ov::is_type<ov::frontend::gguf::GGUFConstant>(node);
+ }
+ EXPECT_EQ(gmm_count, 1);
+ EXPECT_EQ(deferred_count, deferred ? 1 : 0);
+}
+
+void infer_tokens(ov::InferRequest& request,
+ size_t tokens,
+ bool per_expert,
+ const std::vector<float>& expected_two_tokens) {
+ const std::vector<float> acts =
+ per_expert ? std::vector<float>{1, 2, 3, 4, 5, 6, 7, 8} : std::vector<float>{1, 2, 3, 4};
+ const std::vector<int32_t> selected{0, 1, 2, 0};
+ std::vector<float> inputs;
+ std::vector<float> expected;
+ ov::Tensor ids(ov::element::i32, {1, 1, tokens, 2});
+ const size_t values_per_token = per_expert ? 4 : 2;
+ for (size_t token = 0; token < tokens; ++token) {
+ const size_t source = token % 2;
+ inputs.insert(inputs.end(),
+ acts.begin() + source * values_per_token,
+ acts.begin() + (source + 1) * values_per_token);
+ std::copy_n(selected.begin() + source * 2, 2, ids.data<int32_t>() + token * 2);
+ expected.insert(expected.end(),
+ expected_two_tokens.begin() + source * 4,
+ expected_two_tokens.begin() + (source + 1) * 4);
+ }
+ request.set_input_tensor(0, make_f32_tensor({1, tokens, per_expert ? 2u : 1u, 2}, inputs));
+ request.set_input_tensor(1, ids);
+ request.infer();
+ const auto output = request.get_output_tensor();
+ EXPECT_EQ(output.get_element_type(), ov::element::f32);
+ EXPECT_EQ(output.get_shape(), (ov::Shape{1, tokens, 2, 2}));
+ expect_near(output, expected);
+}
+
+class GGUFHalfExperts : public ::testing::TestWithParam<HalfExpertCase> {};
+
+TEST_P(GGUFHalfExperts, UsesGatherMatmulAndPreservesDynamicTokenValues) {
+ const auto [precision, rank4, storage, per_expert] = GetParam();
+ // These are the independent expected values of GGUFOps.MulMatIdNused2 and ActivationsPerExpert.
+ const std::vector<float> weights{1, 0, 0, 1, 2, 0, 0, 2, 3, 0, 0, 3};
+ const std::vector<float> expected =
+ per_expert ? std::vector<float>{1, 2, 6, 8, 15, 18, 7, 8} : std::vector<float>{1, 2, 2, 4, 9, 12, 3, 4};
+ auto model = expert_model(precision, rank4, storage, per_expert, weights);
+ const bool deferred = storage == WeightStorage::NATIVE_DEFERRED || storage == WeightStorage::CGRAPH_DEFERRED;
+ check_expert_graph(model, deferred);
+ if (deferred) {
+ EXPECT_TRUE(ov::frontend::gguf::pass::MaterializeGGUFWeights().run_on_model(model));
+ model->validate_nodes_and_infer_types();
+ check_expert_graph(model, false);
+ }
+ ov::pass::Manager manager;
+ manager.register_pass<ov::pass::MarkCompressedFloatConstants>();
+ manager.run_passes(model);
+ if (storage != WeightStorage::DIRECT) {
+ size_t marked = 0;
+ for (const auto& node : model->get_ordered_ops()) {
+ if (const auto convert = ov::as_type_ptr<ov::op::v0::Convert>(node);
+ convert && convert->get_input_element_type(0) == precision && ov::is_decompression(convert)) {
+ ++marked;
+ }
+ }
+ EXPECT_EQ(marked, 1);
+ }
+ ov::Core core;
+ const ov::AnyMap properties{{"INFERENCE_PRECISION_HINT", ov::element::f32}, {"DYNAMIC_QUANTIZATION_GROUP_SIZE", 0}};
+ auto compiled = core.compile_model(model, "CPU", properties);
+ auto request = compiled.create_infer_request();
+ for (const size_t tokens : {1u, 4u, 1u, 2u, 0u, 1u}) {
+ SCOPED_TRACE(tokens);
+ infer_tokens(request, tokens, per_expert, expected);
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(Storage,
+ GGUFHalfExperts,
+ ::testing::Combine(::testing::Values(ov::element::f16, ov::element::bf16),
+ ::testing::Bool(),
+ ::testing::Values(WeightStorage::DIRECT,
+ WeightStorage::CONVERTED,
+ WeightStorage::NATIVE_DEFERRED,
+ WeightStorage::CGRAPH_DEFERRED),
+ ::testing::Bool()),
+ ([](const ::testing::TestParamInfo<HalfExpertCase>& info) {
+ const auto& [precision, rank4, storage, per_expert] = info.param;
+ const auto storage_name = storage == WeightStorage::DIRECT ? "_direct"
+ : storage == WeightStorage::CONVERTED ? "_converted"
+ : storage == WeightStorage::NATIVE_DEFERRED ? "_native"
+ : "_cgraph";
+ return std::string(precision.get_type_name()) + (rank4 ? "_rank4" : "_rank3") +
+ storage_name + (per_expert ? "_down" : "_shared");
+ }));
+
+TEST(GGUFHalfExpertsRouting, StaticActivationLayoutsAndTokenCounts) {
+ struct Case {
+ ov::Shape activations_shape;
+ size_t tokens;
+ bool per_expert;
+ };
+ const std::vector<int32_t> ids_values{0, 1, 2, 0};
+ const std::vector<Case> cases{{{2, 2}, 2, false},
+ {{1, 2, 2}, 2, false},
+ {{1, 1, 2, 2}, 2, false},
+ {{2, 2, 2}, 2, true},
+ {{1, 2, 2, 2}, 2, true},
+ {{2, 1, 2, 2}, 2, true},
+ {{1, 2, 1, 2, 2}, 2, true},
+ {{2, 2}, 1, true}};
+ for (const auto& [activations_shape, tokens, per_expert] : cases) {
+ SCOPED_TRACE(activations_shape);
+ SCOPED_TRACE(tokens);
+ const ov::Shape ids_shape{1, 1, tokens, 2};
+ const ov::Shape output_shape{1, tokens, 2, 2};
+ auto model = routing_model(activations_shape, ids_shape);
+ auto request = ov::Core{}
+ .compile_model(model, "CPU", ov::hint::inference_precision(ov::element::f32))
+ .create_infer_request();
+ std::vector<float> values =
+ per_expert ? std::vector<float>{1, 2, 3, 4, 5, 6, 7, 8} : std::vector<float>{1, 2, 3, 4};
+ std::vector<float> expected =
+ per_expert ? std::vector<float>{1, 2, 6, 8, 15, 18, 7, 8} : std::vector<float>{1, 2, 2, 4, 9, 12, 3, 4};
+ values.resize(ov::shape_size(activations_shape));
+ expected.resize(tokens * 4);
+ request.set_input_tensor(0, make_f32_tensor(activations_shape, values));
+ ov::Tensor selected(ov::element::i32, ids_shape);
+ std::copy_n(ids_values.begin(), tokens * 2, selected.data<int32_t>());
+ request.set_input_tensor(1, selected);
+ request.infer();
+ EXPECT_EQ(request.get_output_tensor().get_shape(), output_shape);
+ expect_near(request.get_output_tensor(), expected);
+ }
+}
+
+TEST(GGUFHalfExpertsRouting, StaticActivationsAndDynamicIds) {
+ const ov::PartialShape ids_shape{1, 1, ov::Dimension::dynamic(), 2};
+ const std::vector<int32_t> ids_values{0, 1, 2, 0};
+ for (const auto& acts_shape : {ov::Shape{2, 2}, ov::Shape{1, 2, 2}, ov::Shape{1, 1, 2, 2}}) {
+ SCOPED_TRACE(acts_shape);
+ auto model = routing_model(acts_shape, ids_shape);
+ size_t gmm_count = 0;
+ for (const auto& node : model->get_ordered_ops()) {
+ if (const auto gmm = ov::as_type_ptr<ov::op::internal::GatherMatmul>(node)) {
+ ++gmm_count;
+ EXPECT_EQ(gmm->get_input_partial_shape(0)[0], ov::Dimension(2));
+ }
+ }
+ EXPECT_EQ(gmm_count, 1);
+ auto request = ov::Core{}
+ .compile_model(model, "CPU", ov::hint::inference_precision(ov::element::f32))
+ .create_infer_request();
+ request.set_input_tensor(0, make_f32_tensor(acts_shape, {1, 2, 3, 4}));
+ for (const size_t tokens : {2u, 1u}) {
+ ov::Tensor selected(ov::element::i32, {1, 1, tokens, 2});
+ std::copy_n(ids_values.begin(), tokens * 2, selected.data<int32_t>());
+ request.set_input_tensor(1, selected);
+ request.infer();
+ EXPECT_EQ(request.get_output_tensor().get_shape(), (ov::Shape{1, tokens, 2, 2}));
+ expect_near(request.get_output_tensor(),
+ tokens == 2 ? std::vector<float>{1, 2, 2, 4, 9, 12, 3, 4} : std::vector<float>{1, 2, 6, 8});
+ }
+ }
+}
+
+TEST(GGUFHalfExpertsRouting, DynamicActivationsAndStaticIds) {
+ const ov::PartialShape acts_shape{1, ov::Dimension::dynamic(), 2, 2};
+ const ov::Shape ids_shape{1, 1, 2, 2};
+ auto model = routing_model(acts_shape, ids_shape);
+ auto request =
+ ov::Core{}.compile_model(model, "CPU", ov::hint::inference_precision(ov::element::f32)).create_infer_request();
+ ov::Tensor selected(ov::element::i32, ids_shape);
+ const std::vector<int32_t> ids_values{0, 1, 2, 0};
+ std::copy(ids_values.begin(), ids_values.end(), selected.data<int32_t>());
+ request.set_input_tensor(1, selected);
+ request.set_input_tensor(0, make_f32_tensor({1, 1, 2, 2}, {1, 2, 3, 4}));
+ request.infer();
+ EXPECT_EQ(request.get_output_tensor().get_shape(), (ov::Shape{1, 2, 2, 2}));
+ expect_near(request.get_output_tensor(), {1, 2, 2, 4, 9, 12, 3, 4});
+ request.set_input_tensor(0, make_f32_tensor({1, 2, 2, 2}, {1, 2, 3, 4, 5, 6, 7, 8}));
+ request.infer();
+ EXPECT_EQ(request.get_output_tensor().get_shape(), (ov::Shape{1, 2, 2, 2}));
+ expect_near(request.get_output_tensor(), {1, 2, 6, 8, 15, 18, 7, 8});
+ request.set_input_tensor(0, make_f32_tensor({1, 3, 2, 2}, std::vector<float>(12, 1)));
+ EXPECT_THROW(request.infer(), ov::Exception);
+}
+
+TEST(GGUFHalfExpertsRouting, DynamicLeadingBatchAxis) {
+ const ov::PartialShape acts_shape{ov::Dimension::dynamic(), 1, 2, 2};
+ const ov::Shape ids_shape{1, 1, 2, 2};
+ auto model = routing_model(acts_shape, ids_shape);
+ auto request =
+ ov::Core{}.compile_model(model, "CPU", ov::hint::inference_precision(ov::element::f32)).create_infer_request();
+ ov::Tensor selected(ov::element::i32, ids_shape);
+ const std::vector<int32_t> ids_values{0, 1, 2, 0};
+ std::copy(ids_values.begin(), ids_values.end(), selected.data<int32_t>());
+ request.set_input_tensor(1, selected);
+ request.set_input_tensor(0, make_f32_tensor({1, 1, 2, 2}, {1, 2, 3, 4}));
+ request.infer();
+ EXPECT_EQ(request.get_output_tensor().get_shape(), (ov::Shape{1, 2, 2, 2}));
+ expect_near(request.get_output_tensor(), {1, 2, 2, 4, 9, 12, 3, 4});
+ request.set_input_tensor(0, make_f32_tensor({2, 1, 2, 2}, {1, 2, 3, 4, 5, 6, 7, 8}));
+ request.infer();
+ EXPECT_EQ(request.get_output_tensor().get_shape(), (ov::Shape{1, 2, 2, 2}));
+ expect_near(request.get_output_tensor(), {1, 2, 6, 8, 15, 18, 7, 8});
+}
+
+TEST(GGUFHalfExpertsRouting, MixedLayoutWithEmptyTokens) {
+ const ov::PartialShape acts_shape{1, ov::Dimension::dynamic(), 2, 2};
+ const ov::Shape ids_shape{1, 1, 0, 2};
+ auto model = routing_model(acts_shape, ids_shape);
+ auto request =
+ ov::Core{}.compile_model(model, "CPU", ov::hint::inference_precision(ov::element::f32)).create_infer_request();
+ request.set_input_tensor(0, make_f32_tensor({1, 0, 2, 2}, {}));
+ request.set_input_tensor(1, ov::Tensor(ov::element::i32, ids_shape));
+ request.infer();
+ EXPECT_EQ(request.get_output_tensor().get_shape(), (ov::Shape{1, 0, 2, 2}));
+}
+
+TEST(GGUFHalfExpertsRepresented, Bf16ValuesMatchAnalyticAndF32Path) {
+ const std::vector<float>
+ original{1.003f, -0.701f, 0.334f, 2.007f, -3.011f, 0.127f, 0.913f, 1.009f, 2.019f, -1.117f, 0.703f, -0.227f};
+ std::vector<float> represented;
+ std::transform(original.begin(), original.end(), std::back_inserter(represented), [](float value) {
+ return static_cast<float>(ov::bfloat16(value));
+ });
+ const auto dot = [&](size_t expert, size_t row, float x, float y) {
+ return represented[expert * 4 + row * 2] * x + represented[expert * 4 + row * 2 + 1] * y;
+ };
+ const std::vector<float> expected{dot(0, 0, 1, 2),
+ dot(0, 1, 1, 2),
+ dot(1, 0, 3, 4),
+ dot(1, 1, 3, 4),
+ dot(2, 0, 5, 6),
+ dot(2, 1, 5, 6),
+ dot(0, 0, 7, 8),
+ dot(0, 1, 7, 8)};
+ ov::Core core;
+ for (const auto& precision : {ov::element::bf16, ov::element::f32}) {
+ SCOPED_TRACE(precision.get_type_name());
+ auto model = expert_model(precision,
+ false,
+ precision == ov::element::bf16 ? WeightStorage::CONVERTED : WeightStorage::DIRECT,
+ true,
+ represented);
+ auto compiled = core.compile_model(
+ model,
+ "CPU",
+ {{"INFERENCE_PRECISION_HINT", ov::element::f32}, {"DYNAMIC_QUANTIZATION_GROUP_SIZE", 0}});
+ auto request = compiled.create_infer_request();
+ infer_tokens(request, 2, true, expected);
+ }
+}
+
+} // namespace
diff --git a/src/frontends/gguf/tests/test_mmproj.cpp b/src/frontends/gguf/tests/test_mmproj.cpp
index d3bd017a44c..c80840b972d 100644
--- a/src/frontends/gguf/tests/test_mmproj.cpp
+++ b/src/frontends/gguf/tests/test_mmproj.cpp
@@ -7,9 +7,12 @@
#include <cstring>
#include <filesystem>
#include <sstream>
+#include <unordered_map>
#include "builder/api/metadata_store.hpp"
+#include "builder/arch/mmproj_builder.hpp"
#include "builder/arch_registry.hpp"
+#include "builder/gguf_builder_decoder.hpp"
#include "builder/projector_registry.hpp"
#include "cnpy.h"
#include "common_test_utils/common_utils.hpp"
@@ -19,6 +22,8 @@
#include "model_adapter_attribute.hpp"
#include "model_contract.hpp"
#include "op_test_utils.hpp"
+#include "openvino/core/type/bfloat16.hpp"
+#include "openvino/core/type/float16.hpp"
#include "openvino/frontend/gguf/adapt_mmproj_to_genai.hpp"
#include "openvino/frontend/gguf/adapt_to_genai.hpp"
#include "openvino/frontend/gguf/extension/projector.hpp"
@@ -38,6 +43,7 @@
#include "openvino/op/shape_of.hpp"
#include "openvino/op/slice.hpp"
#include "openvino/op/tensor_iterator.hpp"
+#include "openvino/op/topk.hpp"
#include "openvino/op/transpose.hpp"
#include "openvino/op/unsqueeze.hpp"
#include "openvino/openvino.hpp"
@@ -105,6 +111,17 @@ protected:
ov::frontend::gguf::FrontEnd frontend;
return frontend.convert(frontend.load(path));
}
+ void gemma3n_vision() {
+ writer.kv_bool("clip.has_vision_encoder", true);
+ writer.kv_str("clip.vision.projector_type", "gemma3nv");
+ writer.kv_u32("clip.vision.embedding_length", 8);
+ writer.kv_u32("clip.vision.image_size", 8);
+ weight("v.conv_stem.conv.weight", {3, 3, 3, 8});
+ weight("v.blk.0.0.conv_exp.weight", {3, 3, 8, 8});
+ weight("v.blk.0.0.conv_pwl.weight", {1, 1, 8, 8});
+ weight("mm.soft_emb_norm.weight", {8}, true);
+ weight("mm.input_projection.weight", {8, 6});
+ }
};
TEST_F(GGUFMMProj, MiniCPMLearnedPositionGridIsIndependentOfResizeMetadata) {
@@ -119,6 +136,110 @@ TEST_F(GGUFMMProj, MiniCPMLearnedPositionGridIsIndependentOfResizeMetadata) {
EXPECT_EQ(restored->get_rt_info<std::string>({"gguf_mmproj", "vision.position_grid_size"}), "70");
}
+TEST_F(GGUFMMProj, BuiltInProjectorsAcceptSupportedTensorTypes) {
+ using namespace ov::frontend::gguf;
+ ProjectorRegistry registry;
+ for (const auto& [type, name] : {std::pair{"minicpmv4_7", "mm.up.weight"},
+ std::pair{"qwen3a", "a.conv_out.weight"},
+ std::pair{"qwen3tts_spkenc", "mm.a.fc.weight"}}) {
+ const auto modality = std::string(type) == "minicpmv4_7" ? "vision" : "audio";
+ const auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/mmproj_accuracy/" + type + ".npz");
+ const ov_gguf_test::TemporaryGguf file(ov_gguf_test::npz_array(arrays, "model"));
+ for (const auto qtype : {GGUF_TYPE_BF16, GGUF_TYPE_Q8_0}) {
+ if (std::string(type) == "qwen3tts_spkenc" && qtype == GGUF_TYPE_Q8_0)
+ continue;
+ SCOPED_TRACE(std::string(type) + ":" + std::to_string(qtype));
+ auto loaded = get_gguf_data(file.path);
+ ov_gguf_test::quantize_weight(std::get<1>(loaded), name, qtype);
+ const detail::MetadataStore meta_store{std::get<0>(loaded)};
+ const GgufMetadata metadata(meta_store);
+ detail::WeightStore store{std::get<1>(loaded)};
+ const auto definition = registry.find(metadata, modality, type);
+ ASSERT_TRUE(definition);
+ GgufGraphContext graph(BuildContext{metadata, "clip", &store, &registry});
+ const auto result = definition->build(graph);
+ ASSERT_TRUE(result.output);
+ EXPECT_EQ(result.output.type(), ov::element::f32);
+ }
+ }
+}
+
+TEST_F(GGUFMMProj, TensorSourceTypesSurviveWeightConversion) {
+ using namespace ov::frontend::gguf;
+ std::unordered_map<std::string, GGUFMetaData> metadata;
+ const detail::MetadataStore meta_store{metadata};
+ GgufWeightTable weights{{"conv.weight", ov::Tensor(ov::element::bf16, {1})},
+ {"norm.bias", ov::Tensor(ov::element::f32, {1})}};
+ detail::WeightStore store{weights};
+ GgufGraphContext graph(BuildContext{GgufMetadata(meta_store), "clip", &store});
+ EXPECT_EQ(graph.tensors().require("conv.weight").type(), ov::element::f32);
+ EXPECT_EQ(graph.tensors().source_type("conv.weight"), std::optional<uint32_t>{GGUF_TYPE_BF16});
+ EXPECT_EQ(graph.tensors().source_type("norm.bias"), std::optional<uint32_t>{GGUF_TYPE_F32});
+ EXPECT_FALSE(graph.tensors().source_type("missing.weight"));
+ EXPECT_EQ(graph.tensors().source_types(), (std::set<uint32_t>{GGUF_TYPE_F32, GGUF_TYPE_BF16}));
+}
+
+TEST_F(GGUFMMProj, GeneratedAudioAcceptsSupportedTensorTypes) {
+ using namespace ov::frontend::gguf;
+ const auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/mmproj_accuracy/qwen3tts_gen.npz");
+ const ov_gguf_test::TemporaryGguf file(ov_gguf_test::npz_array(arrays, "model"));
+ for (const auto type : {GGUF_TYPE_BF16, GGUF_TYPE_Q8_0}) {
+ SCOPED_TRACE(type);
+ auto loaded = get_gguf_data(file.path);
+ ov_gguf_test::quantize_weight(std::get<1>(loaded), "a.gen.wav.tfm.in_proj.weight", type);
+ const detail::MetadataStore meta_store{std::get<0>(loaded)};
+ detail::WeightStore store{std::get<1>(loaded)};
+ auto builder = make_mmproj_builder(BuildContext{GgufMetadata(meta_store), "clip", &store});
+ std::shared_ptr<GgufDecoder> decoder = std::make_shared<GgufBuilderDecoder>(builder->build());
+ FrontEnd frontend;
+ const auto model = frontend.convert(frontend.load(decoder));
+ EXPECT_NO_THROW(model->output("gen_audio.waveform"));
+ EXPECT_NO_THROW(model->output("gen_audio.codes"));
+ }
+}
+
+TEST_F(GGUFMMProj, Qwen3TTSCombinedProjectorExposesAllGenAIComponents) {
+ using namespace ov::frontend::gguf;
+ const auto generation_arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/mmproj_accuracy/qwen3tts_gen.npz");
+ const auto speaker_arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/mmproj_accuracy/qwen3tts_spkenc.npz");
+ const ov_gguf_test::TemporaryGguf generation_file(ov_gguf_test::npz_array(generation_arrays, "model"));
+ const ov_gguf_test::TemporaryGguf speaker_file(ov_gguf_test::npz_array(speaker_arrays, "model"));
+ auto generation = get_gguf_data(generation_file.path);
+ auto speaker = get_gguf_data(speaker_file.path);
+ auto& metadata = std::get<0>(generation);
+ auto& weights = std::get<1>(generation);
+ for (const auto& [name, value] : std::get<0>(speaker)) {
+ if (name == "clip.has_audio_encoder" || name.rfind("clip.audio.", 0) == 0)
+ metadata[name] = value;
+ }
+ for (const auto& [name, weight] : std::get<1>(speaker))
+ ASSERT_TRUE(weights.emplace(name, weight).second);
+ const detail::MetadataStore meta_store{metadata};
+ detail::WeightStore store{weights};
+ auto builder = make_mmproj_builder(BuildContext{GgufMetadata(meta_store), "clip", &store});
+ std::shared_ptr<GgufDecoder> decoder = std::make_shared<GgufBuilderDecoder>(builder->build());
+ FrontEnd frontend;
+ const auto converted = frontend.convert(frontend.load(decoder));
+ for (const auto& source : {converted, ov_gguf_test::reload_ir_model(converted)}) {
+ const auto models = adapt_to_genai(source);
+ ASSERT_EQ(models.size(), 3);
+ EXPECT_NO_THROW(models.at("audio_embeddings")->output("audio_features"));
+ EXPECT_NO_THROW(models.at("audio_generation_predictor")->output("gen_audio.codes"));
+ EXPECT_NO_THROW(models.at("audio_generation_codec")->output("gen_audio.waveform"));
+ EXPECT_NO_THROW(models.at("audio_generation_codec")->input("gen_audio.state_in.tfm_pos"));
+ EXPECT_NO_THROW(models.at("audio_generation_codec")->output("gen_audio.state_out.tfm_pos"));
+ }
+}
+
+TEST_F(GGUFMMProj, GeneratedAudioRejectsUnknownType) {
+ writer.kv_bool("clip.has_gen_audio_encoder", true);
+ writer.kv_str("clip.gen.audio.projector_type", "unknown_gen");
+ weight("test.weight", {1});
+ OV_EXPECT_THROW(convert(),
+ ov::Exception,
+ testing::HasSubstr("unsupported generated audio projector 'unknown_gen'"));
+}
+
TEST_F(GGUFMMProj, MiniCPMRejectsNonSquareLearnedPositionGrid) {
encoder("vision", "minicpmv4_7", 15);
OV_EXPECT_THROW(convert(), ov::Exception, testing::HasSubstr("square learned position grid"));
@@ -883,6 +1004,94 @@ TEST_F(GGUFMMProj, Gemma3CompilesAndMetadataSurvivesSerialization) {
EXPECT_GT(energy, 0.01);
}
+namespace {
+std::shared_ptr<ov::Model> embedding_output_contract_model() {
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, 1, 2, 6});
+ input->set_friendly_name("vision.values");
+ input->output(0).set_names({"vision.values"});
+ auto output = std::make_shared<ov::op::v1::Add>(input, ov::op::v0::Constant::create(ov::element::f32, {}, {0}));
+ output->output(0).set_names({"vision.embeddings"});
+ auto model = std::make_shared<ov::Model>(ov::OutputVector{output}, ov::ParameterVector{input});
+ model->set_rt_info("custom_architecture", {"gguf_architecture"});
+ model->set_rt_info("custom_projector", {"gguf_mmproj", "vision.projector"});
+ return model;
+}
+} // namespace
+
+TEST_F(GGUFMMProj, NamedEmbeddingOutputsSurviveIRAndOverrideLegacyHints) {
+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;
+ for (const bool explicit_contract : {false, true}) {
+ SCOPED_TRACE(explicit_contract);
+ auto model = embedding_output_contract_model();
+ model->set_rt_info(explicit_contract ? "99" : "1", {"gguf_mmproj", "vision.auxiliary_count"});
+ if (explicit_contract) {
+ model->set_rt_info("2", {"gguf_mmproj", "vision.embedding_output_count"});
+ model->set_rt_info("custom_primary", {"gguf_mmproj", "vision.embedding_output.0"});
+ model->set_rt_info("custom_auxiliary", {"gguf_mmproj", "vision.embedding_output.1"});
+ }
+ ov::serialize(model, path + ".xml", path + ".bin");
+ auto restored = ov::Core{}.read_model(path + ".xml");
+ restored->get_results().front()->get_rt_info()[ov::FusedNames::get_type_info_static()] =
+ ov::FusedNames("packed_vision_result");
+ ASSERT_TRUE(Adapter(Adapter::Modality::VISION).run_on_model(restored));
+ ASSERT_EQ(restored->outputs().size(), 2);
+ EXPECT_EQ(restored->output(0).get_any_name(), explicit_contract ? "custom_primary" : "image_features");
+ EXPECT_EQ(restored->output(1).get_any_name(), explicit_contract ? "custom_auxiliary" : "deepstack_features.0");
+ for (const auto& result : restored->get_results()) {
+ const auto found = result->get_rt_info().find(ov::FusedNames::get_type_info_static());
+ ASSERT_NE(found, result->get_rt_info().end());
+ const auto names = found->second.as<ov::FusedNames>().getVectorNames();
+ EXPECT_NE(std::find(names.begin(), names.end(), "packed_vision_result"), names.end());
+ }
+ const auto split = restored->get_results().front()->input_value(0).get_node_shared_ptr();
+ const auto found = split->get_rt_info().find(ov::FusedNames::get_type_info_static());
+ ASSERT_NE(found, split->get_rt_info().end());
+ const auto names = found->second.as<ov::FusedNames>().getVectorNames();
+ EXPECT_NE(std::find(names.begin(), names.end(), "packed_vision_result"), names.end());
+ auto request = ov::Core{}
+ .compile_model(restored, "CPU", ov::hint::inference_precision(ov::element::f32))
+ .create_infer_request();
+ ov::Tensor values(ov::element::f32, {1, 1, 2, 6});
+ for (size_t i = 0; i < values.get_size(); ++i)
+ values.data<float>()[i] = float(i);
+ request.set_input_tensor(values);
+ request.infer();
+ for (size_t output = 0; output < 2; ++output) {
+ const auto actual = request.get_output_tensor(output);
+ EXPECT_EQ(actual.get_shape(), (ov::Shape{1, 2, 3}));
+ for (size_t token = 0; token < 2; ++token)
+ for (size_t channel = 0; channel < 3; ++channel)
+ EXPECT_FLOAT_EQ(actual.data<const float>()[token * 3 + channel],
+ values.data<const float>()[token * 6 + output * 3 + channel]);
+ }
+ }
+}
+
+TEST_F(GGUFMMProj, InvalidEmbeddingOutputContractPreservesOriginalGraph) {
+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;
+ const auto expect_rejected = [](const std::shared_ptr<ov::Model>& model) {
+ const auto results = model->get_results();
+ const auto parameters = model->get_parameters();
+ EXPECT_THROW(Adapter(Adapter::Modality::VISION).run_on_model(model), ov::Exception);
+ EXPECT_EQ(model->get_results(), results);
+ EXPECT_EQ(model->get_parameters(), parameters);
+ };
+ for (const auto* count : {"0", "-1", "2"}) {
+ SCOPED_TRACE(count);
+ auto model = embedding_output_contract_model();
+ model->set_rt_info(count, {"gguf_mmproj", "vision.embedding_output_count"});
+ model->set_rt_info("same", {"gguf_mmproj", "vision.embedding_output.0"});
+ model->set_rt_info("same", {"gguf_mmproj", "vision.embedding_output.1"});
+ expect_rejected(model);
+ }
+ for (const std::string count : {"-1", "invalid"}) {
+ SCOPED_TRACE(count);
+ auto model = embedding_output_contract_model();
+ model->set_rt_info(count, {"gguf_mmproj", "vision.auxiliary_count"});
+ expect_rejected(model);
+ }
+}
+
TEST_F(GGUFMMProj, MixedFileHasIndependentVisionAndAudioBranches) {
encoder("vision", "gemma3");
encoder("audio", "qwen2a");
@@ -1246,6 +1455,7 @@ TEST(GGUFMMProjLayout, DeclaredAuxiliaryOutputsSurviveSplitMergerAndIR) {
contract.component_groups["vision"] = {"encoder", {{"encoder", {{"vision.embeddings", "vision.lengths"}, ""}}}};
write_model_contract(model, contract);
model->set_rt_info(std::string(deepstack ? "1" : "0"), {"gguf_mmproj", "vision.auxiliary_count"});
+ model->set_rt_info(std::string(deepstack ? "2" : "1"), {"gguf_mmproj", "vision.embedding_output_count"});
Adapter adapter(Adapter::Modality::VISION, Adapter::Layout::VISION_ENCODERS);
ASSERT_TRUE(adapter.run_on_model(model));
ASSERT_EQ(model->get_results().size(), deepstack ? 3 : 2);
@@ -1351,6 +1561,70 @@ TEST_F(GGUFMMProj, UnsupportedSecondModalityIsNotSilentlyDiscarded) {
OV_EXPECT_THROW(convert(), ov::Exception, testing::HasSubstr("unsupported_audio"));
}
+TEST_F(GGUFMMProj, Gemma3nCombinedFileBuildsVisionAndRecordsUnsupportedAudio) {
+ gemma3n_vision();
+ writer.kv_bool("clip.has_audio_encoder", true);
+ writer.kv_str("clip.audio.projector_type", "gemma3na");
+ auto model = convert();
+ ASSERT_EQ(model->inputs().size(), 1);
+ ASSERT_EQ(model->outputs().size(), 1);
+ EXPECT_EQ(model->input().get_any_name(), "vision.pixel_values");
+ EXPECT_EQ(model->output().get_any_name(), "vision.embeddings");
+ EXPECT_EQ(model->get_rt_info<std::string>({"gguf_mmproj", "vision.projector"}), "gemma3nv");
+ EXPECT_EQ(model->get_rt_info<std::string>({"gguf_mmproj", "audio.projector"}), "gemma3na");
+ EXPECT_EQ(model->get_rt_info<std::string>({"gguf_mmproj", "audio.supported"}), "false");
+ ov::serialize(model, path + ".xml", path + ".bin");
+ auto restored = ov::Core{}.read_model(path + ".xml");
+ EXPECT_EQ(restored->get_rt_info<std::string>({"gguf_mmproj", "audio.projector"}), "gemma3na");
+ EXPECT_EQ(restored->get_rt_info<std::string>({"gguf_mmproj", "audio.supported"}), "false");
+ for (const auto& source : {model, restored}) {
+ const auto components = ov::frontend::gguf::adapt_to_genai(source->clone());
+ ASSERT_EQ(components.size(), 1);
+ EXPECT_EQ(components.count("vision_embeddings"), 1);
+ EXPECT_EQ(components.count("audio_embeddings"), 0);
+ }
+}
+
+TEST_F(GGUFMMProj, Gemma3nAudioExtensionTakesPrecedenceOverVisionFallback) {
+ using namespace ov::frontend::gguf;
+ gemma3n_vision();
+ writer.kv_bool("clip.has_audio_encoder", true);
+ writer.kv_str("clip.audio.projector_type", "gemma3na");
+ ASSERT_TRUE(writer.write(path));
+ FrontEnd frontend;
+ frontend.add_extension(std::make_shared<ProjectorExtension>(
+ ProjectorDefinition{"clip.audio.gemma3na.custom",
+ "clip",
+ "audio",
+ "gemma3na",
+ [](GgufGraphContext& graph) {
+ return ProjectorResult{graph.add_input("audio.custom", ov::element::f32, {1, 1, 2, 6}),
+ {{"audio.merge", "1"}}};
+ },
+ {}}));
+ auto model = frontend.convert(frontend.load(path));
+ ASSERT_EQ(model->inputs().size(), 2);
+ ASSERT_EQ(model->outputs().size(), 2);
+ EXPECT_NO_THROW(model->input("audio.custom"));
+ EXPECT_NO_THROW(model->output("audio.embeddings"));
+ EXPECT_EQ(model->get_rt_info<std::string>({"gguf_mmproj", "audio.projector"}), "gemma3na");
+ EXPECT_FALSE(model->has_rt_info({"gguf_mmproj", "audio.supported"}));
+}
+
+TEST_F(GGUFMMProj, Gemma3nAudioFallbackRejectsOtherVisionProjectors) {
+ encoder("vision", "gemma3");
+ writer.kv_bool("clip.has_audio_encoder", true);
+ writer.kv_str("clip.audio.projector_type", "gemma3na");
+ OV_EXPECT_THROW(convert(), ov::Exception, testing::HasSubstr("gemma3na"));
+}
+
+TEST_F(GGUFMMProj, Gemma3nVisionRejectsOtherUnsupportedAudioProjectors) {
+ gemma3n_vision();
+ writer.kv_bool("clip.has_audio_encoder", true);
+ writer.kv_str("clip.audio.projector_type", "unsupported_audio");
+ OV_EXPECT_THROW(convert(), ov::Exception, testing::HasSubstr("unsupported_audio"));
+}
+
TEST_F(GGUFMMProj, LegacyGlobalProjectorTakesPrecedence) {
encoder("vision", "unused_modality_key");
writer.kv_str("clip.projector_type", "gemma3");
@@ -1448,6 +1722,156 @@ protected:
}
};
+TEST_F(GGUFMMProj, Qwen3TTSMatchesCPUAndResetsStreamingState) {
+ const auto arrays = cnpy::npz_load(
+ (std::filesystem::path(ov_gguf_test::test_data_dir()) / "mmproj_accuracy/qwen3tts_gen.npz").string());
+ const auto array = [&](const std::string& name) -> const cnpy::NpyArray& {
+ return ov_gguf_test::npz_array(arrays, name);
+ };
+ ov_gguf_test::TemporaryGguf file(array("model"));
+ ov::frontend::gguf::FrontEnd frontend;
+ auto full = frontend.convert(frontend.load(file.path));
+ const auto components = ov::frontend::gguf::adapt_to_genai(full);
+ ASSERT_EQ(components.size(), 2);
+ const auto component = [&](bool waveform) {
+ const auto& model = components.at(waveform ? "audio_generation_codec" : "audio_generation_predictor");
+ return ov::Core{}
+ .compile_model(model,
+ "CPU",
+ ov::hint::inference_precision(ov::element::f32),
+ ov::hint::dynamic_quantization_group_size(0),
+ ov::inference_num_threads(2))
+ .create_infer_request();
+ };
+ const auto tensor = [&](const std::string& name, ov::element::Type type) {
+ const auto& values = array(name);
+ ov::Tensor output(type, values.shape);
+ std::memcpy(output.data(), values.data<char>(), output.get_byte_size());
+ return output;
+ };
+ const auto compare = [&](const ov::Tensor& actual, const std::string& name) {
+ const auto& expected = array(name);
+ 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);
+ };
+ auto predictor = component(false);
+ predictor.set_tensor("gen_audio.hidden_states", tensor("hidden", ov::element::f32));
+ predictor.set_tensor("gen_audio.code0", tensor("code0", ov::element::i32));
+ for (size_t group = 0; group < 15; ++group) {
+ ov::Tensor random(ov::element::f32, {1, 1, 1, 1});
+ *random.data<float>() = array("random").data<float>()[group];
+ predictor.set_tensor("gen_audio.random." + std::to_string(group), random);
+ }
+ for (int repeat = 0; repeat < 2; ++repeat) {
+ predictor.infer();
+ const auto codes = predictor.get_tensor("gen_audio.codes");
+ ASSERT_EQ(codes.get_size(), array("codes").num_vals);
+ for (size_t i = 0; i < codes.get_size(); ++i)
+ EXPECT_EQ(codes.data<const int32_t>()[i], array("codes").data<int32_t>()[i]);
+ compare(predictor.get_tensor("gen_audio.embeddings"), "feedback");
+ for (int group = 1; group < 15; ++group)
+ compare(predictor.get_tensor("gen_audio.logits." + std::to_string(group)),
+ "logits" + std::to_string(group));
+ }
+ auto wave = component(true);
+ wave.set_tensor("gen_audio.audio_codes", tensor("wave_codes", ov::element::i32));
+ for (int repeat = 0; repeat < 2; ++repeat) {
+ size_t states = 0;
+ for (const auto& input : wave.get_compiled_model().inputs()) {
+ if (input.get_any_name().find("gen_audio.state_in.") != 0)
+ continue;
+ ov::Tensor state(input.get_element_type(), input.get_shape());
+ std::memset(state.data(), 0, state.get_byte_size());
+ wave.set_tensor(input.get_any_name(), state);
+ ++states;
+ }
+ EXPECT_EQ(states, 38u);
+ for (int step = 0; step < 2; ++step) {
+ wave.infer();
+ compare(wave.get_tensor("gen_audio.waveform"), "waveform" + std::to_string(step));
+ for (const auto& output : wave.get_compiled_model().outputs()) {
+ const auto name = output.get_any_name();
+ if (name.find("gen_audio.state_out.") != 0)
+ continue;
+ const auto value = wave.get_tensor(name);
+ ov::Tensor copied(value.get_element_type(), value.get_shape());
+ value.copy_to(copied);
+ wave.set_tensor("gen_audio.state_in." + name.substr(std::string("gen_audio.state_out.").size()),
+ copied);
+ }
+ }
+ }
+}
+
+TEST_F(GGUFMMProj, Qwen3TTSSamplingUpperTailStaysInRetainedCandidates) {
+ using namespace ov::frontend::gguf;
+ const auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/mmproj_accuracy/qwen3tts_gen.npz");
+ const ov_gguf_test::TemporaryGguf file(ov_gguf_test::npz_array(arrays, "model"));
+ for (const auto top_p : {1.f, .22f}) {
+ SCOPED_TRACE(top_p);
+ auto loaded = get_gguf_data(file.path);
+ auto& metadata = std::get<0>(loaded);
+ metadata["general.sampling.top_k"] = 50;
+ metadata["general.sampling.top_p"] = top_p;
+ auto& head = std::get<1>(loaded).at("a.gen.code.head.weight");
+ auto head_shape = head.shape;
+ head_shape[1] = 50;
+ ov::Tensor uniform_head(head.data.get_element_type(), head_shape);
+ std::memset(uniform_head.data(), 0, uniform_head.get_byte_size());
+ head = GgufWeight(uniform_head);
+ head.source_name = "a.gen.code.head.weight";
+ const detail::MetadataStore meta_store{metadata};
+ detail::WeightStore store{std::get<1>(loaded)};
+ auto builder = make_mmproj_builder(BuildContext{GgufMetadata(meta_store), "clip", &store});
+ std::shared_ptr<GgufDecoder> decoder = std::make_shared<GgufBuilderDecoder>(builder->build());
+ FrontEnd frontend;
+ auto full = frontend.convert(frontend.load(decoder));
+ ov::OutputVector outputs{full->output("gen_audio.codes")};
+ if (top_p < 1.f) {
+ for (const auto& node : full->get_ordered_ops())
+ if (const auto topk = ov::as_type_ptr<ov::op::v11::TopK>(node))
+ outputs.push_back(topk->output(1));
+ ASSERT_EQ(outputs.size(), 16u);
+ }
+ auto codes = std::make_shared<ov::Model>(outputs, full->get_parameters())->clone();
+ const auto parameters = codes->get_parameters();
+ for (const auto& parameter : parameters)
+ if (parameter->output(0).get_target_inputs().empty())
+ codes->remove_parameter(parameter);
+ auto request = ov::Core{}
+ .compile_model(codes,
+ "CPU",
+ ov::hint::inference_precision(ov::element::f32),
+ ov::hint::dynamic_quantization_group_size(0),
+ ov::inference_num_threads(2))
+ .create_infer_request();
+ for (const auto& input : codes->inputs()) {
+ const auto name = input.get_any_name();
+ ov::Tensor values(input.get_element_type(), input.get_shape());
+ if (name.find("gen_audio.random.") == 0)
+ *values.data<float>() = std::nextafter(1.f, 0.f);
+ else
+ std::memset(values.data(), 0, values.get_byte_size());
+ request.set_tensor(name, values);
+ }
+ request.infer();
+ const auto output = request.get_output_tensor(0);
+ ASSERT_EQ(output.get_size(), 16u);
+ EXPECT_EQ(output.data<const int32_t>()[0], 0);
+ for (size_t group = 1; group < output.get_size(); ++group) {
+ if (top_p == 1.f) {
+ EXPECT_EQ(output.data<const int32_t>()[group], 49);
+ } else {
+ const auto candidates = request.get_output_tensor(group);
+ ASSERT_EQ(candidates.get_size(), 50u);
+ EXPECT_EQ(output.data<const int32_t>()[group], candidates.data<const int32_t>()[11]);
+ }
+ }
+ }
+}
+
TEST_P(GGUFMMProjAccuracy, EmbeddingsMatchLlamaCPU) {
if (std::string(GetParam()).find("resampler") == 0) {
const std::string name = GetParam();
@@ -1578,6 +2002,13 @@ double dynamic_accuracy_limit(const std::string& family) {
}
TEST_P(GGUFMMProjDynamicAccuracy, ReusesCompiledModelAcrossGrids) {
+ const std::string family = GetParam();
+ if (family == "gemma3nv" || family == "gemma3nv_uir" || family == "gemma3nv_attention") {
+ const auto& first = array("0.pixel_values");
+ const auto& second = array("1.pixel_values");
+ ASSERT_EQ(first.shape, second.shape);
+ EXPECT_FALSE(std::equal(first.data<float>(), first.data<float>() + first.num_vals, second.data<float>()));
+ }
for (bool adapt : {false, true}) {
auto current = model->clone();
const bool audio = model->has_rt_info({"gguf_mmproj", "audio.projector"});
@@ -1625,6 +2056,11 @@ INSTANTIATE_TEST_SUITE_P(Reference,
"minicpmv4_6",
"minicpmv4_7",
"minicpmv4_7_4x",
+ "qwen3a",
+ "qwen3tts_spkenc",
+ "gemma3nv",
+ "gemma3nv_uir",
+ "gemma3nv_attention",
"gemma4a",
"deepseekocr",
"deepseekocr2",
@@ -1632,6 +2068,41 @@ INSTANTIATE_TEST_SUITE_P(Reference,
"deepseekocr_overview",
"deepseekocr2_overview"));
+class GGUFMMProjAddedGenAIContracts : public GGUFMMProjAccuracy {};
+
+TEST_P(GGUFMMProjAddedGenAIContracts, PublicAdaptationMatchesReferenceAfterIRReload) {
+ const bool vision = std::string(GetParam()).find("gemma3nv") == 0;
+ for (const auto& source : {model, ov_gguf_test::reload_ir_model(model)}) {
+ const auto models = ov::frontend::gguf::adapt_to_genai(source->clone());
+ ASSERT_EQ(models.size(), 1u);
+ const auto& adapted = models.at(vision ? "vision_embeddings" : "audio_embeddings");
+ ASSERT_EQ(adapted->inputs().size(), 1u);
+ ASSERT_EQ(adapted->outputs().size(), 1u);
+ EXPECT_NO_THROW(adapted->input(vision ? "pixel_values" : "features"));
+ EXPECT_NO_THROW(adapted->output(vision ? "image_features" : "audio_features"));
+ auto request = compile(adapted);
+ for (const auto step : {0, 1, 0}) {
+ const auto prefix = std::to_string(step) + ".";
+ request.set_tensor(vision ? "pixel_values" : "features",
+ tensor(prefix + (vision ? "pixel_values" : "features"), ov::element::f32));
+ request.infer();
+ const auto output = request.get_output_tensor();
+ const auto& expected = array(prefix + "embeddings");
+ auto shape = expected.shape;
+ shape.erase(shape.begin());
+ ASSERT_EQ(output.get_shape(), shape);
+ ov_gguf_test::expect_nmse_below(
+ ov_gguf_test::nmse(output.data<const float>(), expected.data<float>(), output.get_size()),
+ 1e-5);
+ }
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(
+ Reference,
+ GGUFMMProjAddedGenAIContracts,
+ ::testing::Values("gemma3nv", "gemma3nv_uir", "gemma3nv_attention", "qwen3a", "qwen3tts_spkenc"));
+
INSTANTIATE_TEST_SUITE_P(Reference,
GGUFMMProjAccuracy,
::testing::Values("gemma3",
@@ -2005,6 +2476,20 @@ TEST(GGUFMMProjContract, DeclaredComponentsPreservePrimaryNamesStateAndIR) {
EXPECT_EQ(audio->input("audio.cache.counter").get_any_name(), "audio.cache.counter");
}
run_stream(audio, "samples", "audio_features", "audio.cache.counter", {1, 2, 2});
+ const auto public_models = ov::frontend::gguf::adapt_to_genai(source->clone());
+ ASSERT_EQ(public_models.size(), 4);
+ EXPECT_EQ(public_models.at("audio_generation_score")->get_parameters().size(), 1);
+ EXPECT_EQ(public_models.at("audio_generation_lookup")->get_parameters().size(), 1);
+ run_stream(public_models.at("audio_embeddings"),
+ "samples",
+ "audio_features",
+ "audio.cache.counter",
+ {1, 2, 2});
+ run_stream(public_models.at("audio_generation_renderer"),
+ "render_input",
+ "rendered",
+ "speech.cache.counter",
+ {1, 1, 2, 2});
Adapter adapter(Adapter::Modality::AUDIO_GENERATION);
ASSERT_TRUE(adapter.run_on_model(source));
const auto& models = adapter.get_audio_generation_models();
diff --git a/src/frontends/gguf/tests/test_ops.cpp b/src/frontends/gguf/tests/test_ops.cpp
index 2fe7b69e3a7..d4d10e1c702 100644
--- a/src/frontends/gguf/tests/test_ops.cpp
+++ b/src/frontends/gguf/tests/test_ops.cpp
@@ -11,16 +11,20 @@
#include <algorithm>
#include <cmath>
#include <functional>
+#include <sstream>
#include "common_test_utils/test_assertions.hpp"
#include "op_table.hpp"
#include "op_test_utils.hpp"
#include "openvino/core/type/bfloat16.hpp"
#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/convolution.hpp"
#include "openvino/op/divide.hpp"
#include "openvino/op/extractimagepatches.hpp"
#include "openvino/op/eye.hpp"
#include "openvino/op/greater_eq.hpp"
+#include "openvino/op/group_conv.hpp"
#include "openvino/op/multiply.hpp"
#include "openvino/op/reshape.hpp"
#include "openvino/op/result.hpp"
@@ -32,6 +36,7 @@
#include "openvino/op/transpose.hpp"
#include "openvino/op/unsqueeze.hpp"
#include "openvino/pass/manager.hpp"
+#include "openvino/pass/serialize.hpp"
#include "transformations/common_optimizations/fuse_rotary_positional_embeddings.hpp"
#include "transformations/convert_precision.hpp"
#include "transformations/rt_info/disable_precision_conversion.hpp"
@@ -292,6 +297,79 @@ INSTANTIATE_TEST_SUITE_P(GGUFOps,
return std::string(i.param.name);
});
+TEST(GGUFOps, StepIncludesNeitherZeroNorNegativeValues) {
+ auto model = SingleOpBuilder()
+ .op("GGML_UNARY_OP_STEP")
+ .input("x", ov::element::f32, {1, 5})
+ .output("out", ov::element::f32, {1, 5})
+ .build();
+ auto output = run_on_cpu(model, {{"x", make_f32_tensor({1, 5}, {-2.f, -0.f, 0.f, 1e-6f, 3.f})}});
+ expect_near(output, {0.f, 0.f, 0.f, 1.f, 1.f}, 0.f);
+}
+
+TEST(GGUFOps, ConvTranspose1DAccumulatesOverlappingTaps) {
+ auto model = SingleOpBuilder()
+ .op("GGML_OP_CONV_TRANSPOSE_1D")
+ .input("w", ov::element::f32, {2, 1, 3})
+ .input("x", ov::element::f32, {1, 2, 2})
+ .output("out", ov::element::f32, {1, 1, 5})
+ .attr<int64_t>("stride", 2)
+ .build();
+ auto output = run_on_cpu(model,
+ {{"w", make_f32_tensor({2, 1, 3}, {1.f, 2.f, 3.f, 4.f, 5.f, 6.f})},
+ {"x", make_f32_tensor({1, 2, 2}, {1.f, 2.f, 3.f, 4.f})}});
+ expect_near(output, {13.f, 17.f, 39.f, 24.f, 30.f}, 0.f);
+}
+
+TEST(GGUFOps, ConvTranspose1DUsesTwoDimensionalConvolution) {
+ auto model = SingleOpBuilder()
+ .op("GGML_OP_CONV_TRANSPOSE_1D")
+ .input("w", ov::element::f32, {2, 1, 3})
+ .input("x", ov::element::f32, {1, 2, -1})
+ .output("out", ov::element::f32, {1, 1, -1})
+ .attr<int64_t>("stride", 1)
+ .build();
+ const auto ops = model->get_ordered_ops();
+ const auto it = std::find_if(ops.begin(), ops.end(), [](const auto& node) {
+ return ov::is_type<ov::op::v1::ConvolutionBackpropData>(node);
+ });
+ ASSERT_NE(it, ops.end());
+ EXPECT_EQ((*it)->get_input_partial_shape(0), (ov::PartialShape{1, 2, 1, -1}));
+ EXPECT_EQ((*it)->get_input_partial_shape(1), (ov::PartialShape{2, 1, 1, 3}));
+ expect_near(run_on_cpu(model,
+ {{"w", make_f32_tensor({2, 1, 3}, {1.f, 2.f, 3.f, 4.f, 5.f, 6.f})},
+ {"x", make_f32_tensor({1, 2, 2}, {1.f, 2.f, 3.f, 4.f})}}),
+ {13.f, 35.f, 45.f, 30.f},
+ 0.f);
+}
+
+TEST(GGUFOps, ConvTranspose1DPreservesChannelsAndDynamicLength) {
+ auto model = SingleOpBuilder()
+ .op("GGML_OP_CONV_TRANSPOSE_1D")
+ .input("w", ov::element::f16, {1, 2, 3})
+ .input("x", ov::element::f32, {1, 1, -1})
+ .output("out", ov::element::f32, {1, 2, -1})
+ .attr<int64_t>("stride", 2)
+ .build();
+ ov::Core core;
+ auto request =
+ core.compile_model(model, "CPU", ov::hint::inference_precision(ov::element::f32)).create_infer_request();
+ ov::Tensor weights(ov::element::f16, {1, 2, 3});
+ const std::vector<float> taps{1.f, 2.f, 3.f, 4.f, 5.f, 6.f};
+ std::transform(taps.begin(), taps.end(), weights.data<ov::float16>(), [](float value) {
+ return ov::float16(value);
+ });
+ request.set_tensor("w", weights);
+ request.set_tensor("x", make_f32_tensor({1, 1, 2}, {1.f, 2.f}));
+ request.infer();
+ ASSERT_EQ(request.get_output_tensor().get_shape(), (ov::Shape{1, 2, 5}));
+ expect_near(request.get_output_tensor(), {1.f, 2.f, 5.f, 4.f, 6.f, 4.f, 5.f, 14.f, 10.f, 12.f}, 0.f);
+ request.set_tensor("x", make_f32_tensor({1, 1, 1}, {3.f}));
+ request.infer();
+ ASSERT_EQ(request.get_output_tensor().get_shape(), (ov::Shape{1, 2, 3}));
+ expect_near(request.get_output_tensor(), {3.f, 6.f, 9.f, 12.f, 15.f, 18.f}, 0.f);
+}
+
// Scale: out = in * scale + bias (scale/bias in op-params slots 0,1).
TEST(GGUFOps, Scale) {
const float scale = 2.5f;
@@ -3290,6 +3368,110 @@ TEST(GGUFOps, MultimodalPoolingAndConvolution) {
expect_near(run_on_cpu(conv, {{"x", x}, {"w", make_f32_tensor({1, 1, 2, 2}, {1, 2, 3, 4})}}), {44, 64}, 1e-6f);
}
+TEST(GGUFOps, DepthwiseConv2DAllowsPartiallyDynamicWeights) {
+ auto model = SingleOpBuilder()
+ .op("GGML_OP_CONV_2D")
+ .input("w", ov::element::f32, ov::PartialShape{2, 1, -1, -1})
+ .input("x", ov::element::f32, {1, 2, 3, 3})
+ .output("out", ov::element::f32, ov::PartialShape{1, 2, -1, -1})
+ .attr<std::vector<int64_t>>("conv_params", {1, 1, 0, 0, 1, 1})
+ .attr<bool>("depthwise", true)
+ .build();
+
+ const auto ordered_ops = model->get_ordered_ops();
+ const auto group_conv = std::find_if(ordered_ops.begin(), ordered_ops.end(), [](const auto& node) {
+ return ov::is_type<ov::op::v1::GroupConvolution>(node);
+ });
+ ASSERT_NE(group_conv, ordered_ops.end());
+ EXPECT_EQ((*group_conv)->get_input_partial_shape(1), (ov::PartialShape{2, 1, 1, -1, -1}));
+}
+
+TEST(GGUFOps, Conv2DF16Im2colRoundingSurvivesSerialization) {
+ // Reference: pointwise_conv_oracle.cpp, ggml CPU F32/F16 convolution.
+ const std::vector<float> x{1.0003f, -2.0006f, 0.3334f, 2.0006f, 0.7002f, -1.0003f};
+ const std::vector<float> w{1.0003f, 0.3334f, -0.7002f, 1.0003f};
+ std::vector<float> expected(6);
+ for (size_t oc = 0; oc < 2; ++oc) {
+ for (size_t t = 0; t < 3; ++t) {
+ expected[oc * 3 + t] = float(ov::float16(w[oc * 2])) * float(ov::float16(x[t])) +
+ float(ov::float16(w[oc * 2 + 1])) * float(ov::float16(x[3 + t]));
+ }
+ }
+ for (const auto& weight_type : {ov::element::f32, ov::element::f16}) {
+ SCOPED_TRACE(weight_type.get_type_name());
+ auto model = SingleOpBuilder()
+ .op("GGML_OP_CONV_2D")
+ .input("w", weight_type, {2, 2, 1, 1})
+ .input("x", ov::element::f32, {1, 2, 1, 3})
+ .output("out", ov::element::f32, {1, 2, 1, 3})
+ .attr<std::vector<int64_t>>("conv_params", {1, 1, 0, 0, 1, 1})
+ .attr<bool>("im2col_precision_f16", true)
+ .build();
+ const std::map<std::string, ov::Tensor> inputs{
+ {"x", make_f32_tensor({1, 2, 1, 3}, x)},
+ {"w",
+ weight_type == ov::element::f32 ? make_f32_tensor({2, 2, 1, 1}, w) : make_f16_tensor({2, 2, 1, 1}, w)}};
+ const auto check_rounding = [&](const std::shared_ptr<ov::Model>& candidate) {
+ size_t protected_casts = 0;
+ for (const auto& node : candidate->get_ordered_ops()) {
+ if (ov::is_conversion_disabled(node, ov::element::f16, ov::element::f32)) {
+ ++protected_casts;
+ EXPECT_TRUE(ov::is_type<ov::op::v0::Convert>(node));
+ EXPECT_EQ(node->get_input_element_type(0), ov::element::f32);
+ EXPECT_EQ(node->get_output_element_type(0), ov::element::f16);
+ }
+ }
+ EXPECT_EQ(protected_casts, 2);
+ expect_near(run_on_cpu(candidate, inputs), expected, 1e-6f);
+ };
+ check_rounding(model);
+ check_rounding(reload_ir_model(model));
+ }
+}
+
+TEST(GGUFOps, Conv2DF16Im2colRoundingRequiresOptInAndSupportedWeightType) {
+ const std::vector<float> x{1.0003f, -2.0006f, 0.3334f, 2.0006f, 0.7002f, -1.0003f};
+ const std::vector<float> w{1.0003f, 0.3334f, -0.7002f, 1.0003f};
+ for (int scenario = 0; scenario < 4; ++scenario) {
+ SCOPED_TRACE(scenario);
+ const bool depthwise = scenario == 2;
+ const auto weight_type = scenario == 3 ? ov::element::bf16 : ov::element::f32;
+ const ov::Shape weight_shape = depthwise ? ov::Shape{2, 1, 1, 1} : ov::Shape{2, 2, 1, 1};
+ auto builder = SingleOpBuilder()
+ .op("GGML_OP_CONV_2D")
+ .input("w", weight_type, weight_shape)
+ .input("x", ov::element::f32, {1, 2, 1, 3})
+ .output("out", ov::element::f32, {1, 2, 1, 3})
+ .attr<std::vector<int64_t>>("conv_params", {1, 1, 0, 0, 1, 1});
+ if (scenario != 0)
+ builder.attr<bool>("im2col_precision_f16", scenario != 1);
+ builder.attr<bool>("depthwise", depthwise);
+ auto model = builder.build();
+ for (const auto& node : model->get_ordered_ops()) {
+ EXPECT_FALSE(ov::is_conversion_disabled(node, ov::element::f16, ov::element::f32));
+ EXPECT_NE(node->get_output_element_type(0), ov::element::f16);
+ }
+ std::vector<float> represented_w = depthwise ? std::vector<float>{w[0], w[3]} : w;
+ ov::Tensor weights(weight_type, weight_shape);
+ if (weight_type == ov::element::bf16) {
+ for (size_t i = 0; i < represented_w.size(); ++i) {
+ weights.data<ov::bfloat16>()[i] = ov::bfloat16(represented_w[i]);
+ represented_w[i] = float(weights.data<ov::bfloat16>()[i]);
+ }
+ } else {
+ std::copy(represented_w.begin(), represented_w.end(), weights.data<float>());
+ }
+ std::vector<float> expected(6);
+ for (size_t oc = 0; oc < 2; ++oc) {
+ for (size_t t = 0; t < 3; ++t) {
+ expected[oc * 3 + t] = depthwise ? represented_w[oc] * x[oc * 3 + t]
+ : represented_w[oc * 2] * x[t] + represented_w[oc * 2 + 1] * x[3 + t];
+ }
+ }
+ expect_near(run_on_cpu(model, {{"x", make_f32_tensor({1, 2, 1, 3}, x)}, {"w", weights}}), expected, 1e-6f);
+ }
+}
+
TEST(GGUFOps, GeluErf) {
auto model = SingleOpBuilder()
.op("GGML_UNARY_OP_GELU_ERF")
diff --git a/src/frontends/gguf/tests/test_weights.cpp b/src/frontends/gguf/tests/test_weights.cpp
index 5f288a15945..ae9d7aa7a79 100644
--- a/src/frontends/gguf/tests/test_weights.cpp
+++ b/src/frontends/gguf/tests/test_weights.cpp
@@ -12,11 +12,12 @@
// test_dequant_vs_ggml.cpp.
#include <cmath>
+#include <cstdlib>
#include <cstring>
-#include <fstream>
#include <vector>
#include "common_test_utils/file_utils.hpp"
+#include "gguf_writer.hpp"
#include "helper_ops/gguf_constant.hpp"
#include "node_context.hpp"
#include "op_test_utils.hpp"
@@ -937,6 +938,78 @@ TEST(GGUFWeight, UsesIntegerZeroPointForRequantizedMatmulWeights) {
EXPECT_EQ(gguf_zero_point_type("blk.0.attn_q.weight", GGUF_TYPE_PTQ1_0), ov::element::f16);
}
+TEST(GGUFWeight, SelectsFractionalZeroPointsForStrictMatmulWeights) {
+ using namespace ov::frontend::gguf;
+
+ for (const auto qtype : {GGUF_TYPE_Q4_K, GGUF_TYPE_Q4_1, GGUF_TYPE_Q5_K}) {
+ SCOPED_TRACE(qtype);
+ EXPECT_EQ(gguf_zero_point_type("blk.2.ffn_down_exps.weight", qtype, false), ov::element::u8);
+ EXPECT_EQ(gguf_zero_point_type("blk.2.ffn_down_exps.weight", qtype, true), ov::element::f16);
+ EXPECT_EQ(gguf_zero_point_type("token_embd.weight", qtype, false), ov::element::f16);
+ EXPECT_EQ(gguf_zero_point_type("output.weight", qtype, true), ov::element::f16);
+ }
+ EXPECT_EQ(gguf_zero_point_type("blk.2.ffn_down.weight", GGUF_TYPE_Q2_0, true), ov::element::u8);
+ for (const auto qtype : {GGUF_TYPE_PQ2_0, GGUF_TYPE_PTQ1_0}) {
+ EXPECT_EQ(gguf_zero_point_type("blk.2.ffn_down.weight", qtype, true), ov::element::f16);
+ }
+}
+
+TEST(GGUFWeight, FractionalQ5KPreservesSourceCodesAndMatchesGgmlToFloat) {
+ using namespace ov::frontend::gguf;
+
+ const auto bytes = load_npy<uint8_t>("q5_k_qbytes");
+ const auto reference = load_npy<float>("q5_k_deq");
+ GgufTensor tensor;
+ tensor.type = GGUF_TYPE_Q5_K;
+ tensor.bsize = bytes.size();
+ tensor.num_weights = kRows * kCols;
+ tensor.weights_data = bytes.data();
+ WeightTensors extracted{
+ ov::Tensor(ov::element::u8, {kRows, kCols}),
+ ov::Tensor(ov::element::f16, {kRows, kCols / 32}),
+ ov::Tensor(gguf_zero_point_type("blk.2.ffn_down_exps.weight", GGUF_TYPE_Q5_K, true), {kRows, kCols / 32})};
+ gguf_fill_asym(tensor, extracted.weight, extracted.scales, extracted.zero_point);
+ for (size_t i = 0; i < extracted.weight.get_size(); ++i) {
+ EXPECT_LE(extracted.weight.data<uint8_t>()[i], 31);
+ }
+ const auto node = make_weight_node(extracted, GGUF_TYPE_Q5_K, "blk.2.ffn_down_exps.weight");
+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{node}, ov::ParameterVector{});
+ const auto output = run_on_cpu(model, {});
+ ASSERT_EQ(output.get_size(), reference.size());
+ for (size_t i = 0; i < reference.size(); ++i) {
+ EXPECT_NEAR(output.data<float>()[i], reference[i], kTolFaithful);
+ }
+}
+
+TEST(GGUFWeight, FractionalQ5KPreservesNonzeroOffsetWhenScaleIsZero) {
+ using namespace ov::frontend::gguf;
+ constexpr size_t block_size = 176;
+ std::vector<uint8_t> bytes(block_size);
+ const uint16_t one = ov::float16(1.f).to_bits();
+ std::memcpy(bytes.data(), &one, sizeof(one));
+ std::memcpy(bytes.data() + 2, &one, sizeof(one));
+ bytes[8] = 1;
+
+ GgufTensor tensor;
+ tensor.type = GGUF_TYPE_Q5_K;
+ tensor.bsize = bytes.size();
+ tensor.num_weights = kCols;
+ tensor.weights_data = bytes.data();
+ WeightTensors extracted{ov::Tensor(ov::element::u8, {1, kCols}),
+ ov::Tensor(ov::element::f16, {1, kCols / 32}),
+ ov::Tensor(ov::element::f16, {1, kCols / 32})};
+ gguf_fill_asym(tensor, extracted.weight, extracted.scales, extracted.zero_point);
+
+ const auto node = make_weight_node(extracted, GGUF_TYPE_Q5_K, "blk.0.attn_q.weight");
+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{node}, ov::ParameterVector{});
+ const auto output = run_on_cpu(model, {});
+ ASSERT_EQ(output.get_size(), kCols);
+ for (size_t i = 0; i < 32; ++i)
+ EXPECT_FLOAT_EQ(output.data<const float>()[i], -1.f);
+ for (size_t i = 32; i < kCols; ++i)
+ EXPECT_FLOAT_EQ(output.data<const float>()[i], 0.f);
+}
+
class GGUFQ5KNative : public ::testing::Test {
protected:
void SetUp() override {
@@ -946,38 +1019,22 @@ protected:
ov::test::utils::removeFile(path);
}
void write_tensor(const std::string& name, const std::vector<uint8_t>& bytes) {
- std::ofstream out(path, std::ios::binary);
- ASSERT_TRUE(out);
- const auto put = [&out](auto value) {
- out.write(reinterpret_cast<const char*>(&value), sizeof(value));
- };
- put(uint32_t{0x46554747});
- put(uint32_t{3});
- put(uint64_t{1});
- put(uint64_t{0});
- put(uint64_t{name.size()});
- out.write(name.data(), name.size());
- put(uint32_t{3});
- put(uint64_t{kCols});
- put(uint64_t{2});
- put(uint64_t{2});
- put(uint32_t{ov::frontend::gguf::GGUF_TYPE_Q5_K});
- put(uint64_t{0});
- while (static_cast<size_t>(out.tellp()) % 32 != 0)
- out.put('\0');
- out.write(reinterpret_cast<const char*>(bytes.data()), bytes.size());
- ASSERT_TRUE(out);
+ GgufWriter writer;
+ writer.raw_tensor(name, {kCols, 2, 2}, ov::frontend::gguf::GGUF_TYPE_Q5_K, bytes);
+ ASSERT_TRUE(writer.write(path));
}
std::string path;
};
-TEST_F(GGUFQ5KNative, KeepsDiskTypeAndUsesSymmetricStorageForMatrices) {
+TEST_F(GGUFQ5KNative, KeepsDiskTypeAndUnpacksByTensorRole) {
using namespace ov::frontend::gguf;
+ const auto* mode = std::getenv("OV_GGUF_Q4_K_ZP_F16");
+ const bool fractional = mode && *mode && std::strcmp(mode, "0") != 0;
const auto bytes = load_npy<uint8_t>("q5_k_qbytes");
for (const std::string name : {"blk.0.ffn_up", "token_embd", "output", "blk.0.attn_q.bias"}) {
SCOPED_TRACE(name);
const auto full_name = name == "blk.0.attn_q.bias" ? name : name + ".weight";
- const bool symmetric = name == "blk.0.ffn_up";
+ const bool symmetric = name == "blk.0.ffn_up" && !fractional;
ASSERT_NO_FATAL_FAILURE(write_tensor(full_name, bytes));
const auto loaded = get_gguf_data(path);
const auto& source = std::get<1>(loaded).at(full_name);
@@ -988,8 +1045,20 @@ TEST_F(GGUFQ5KNative, KeepsDiskTypeAndUsesSymmetricStorageForMatrices) {
EXPECT_EQ(static_cast<bool>(tensors.zero_point), !symmetric);
EXPECT_NO_THROW(make_weight_node(tensors, GGUF_TYPE_Q5_K, full_name));
if (!symmetric) {
- EXPECT_EQ(tensors.zero_point.get_element_type(),
- name == "blk.0.attn_q.bias" ? ov::element::u8 : ov::element::f16);
+ const auto zp_type = name == "blk.0.attn_q.bias" && !fractional ? ov::element::u8 : ov::element::f16;
+ EXPECT_EQ(tensors.zero_point.get_element_type(), zp_type);
+ }
+ if (fractional && name == "blk.0.ffn_up") {
+ const auto reference = load_npy<float>("q5_k_deq");
+ const auto model =
+ std::make_shared<ov::Model>(ov::OutputVector{make_weight_node(tensors, GGUF_TYPE_Q5_K, full_name)},
+ 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_LE(tensors.weight.data<const uint8_t>()[i], 31);
+ EXPECT_NEAR(output.data<const float>()[i], reference[i], kTolFaithful);
+ }
}
}
}