Skip to content

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

[GGUF] Support multimodal projectors and GenAI adaptation (#38358)

Maxim Vafin630516e04893
diff --git a/.claude/skills/ov-gguf-add-architecture/SKILL.md b/.claude/skills/ov-gguf-add-architecture/SKILL.md
deleted file mode 100644
index de1ece74838..00000000000
--- a/.claude/skills/ov-gguf-add-architecture/SKILL.md
+++ /dev/null
@@ -1,15 +0,0 @@
----
-name: ov-gguf-add-architecture
-description: >
- Enable a new model architecture/family in the OpenVINO GGUF frontend's native .gguf builder,
- or check whether a GGUF model is supported. Use when the user asks to enable, support or bring
- up a GGUF/llama.cpp model (llama, qwen, phi, gemma, MoE and similar decoder-only families),
- when a .gguf file is rejected as an unsupported architecture, or when working on
- arch_registry / DecoderBuilder in src/frontends/gguf/src/builder/. Do NOT use for adding
- a single ggml op translator or for debugging wrong output from an already-supported model.
----
-
-1. Read [src/frontends/gguf/docs/adding_an_architecture.md](../../../src/frontends/gguf/docs/adding_an_architecture.md) — most architectures in the transformer family need **no code**, only a `general.architecture` string added to `arch_registry.cpp` plus the correct RoPE type. It also lists exactly which structural features are auto-detected from the tensor table and metadata, and how to verify a new arch.
-2. Check [src/frontends/gguf/docs/supported_models.md](../../../src/frontends/gguf/docs/supported_models.md) first to see whether the architecture is already accepted and how support was verified.
-3. Only if the family is structurally novel, consult the "10% case" section before adding builder code.
-4. Verify as that document prescribes, including the graph-fingerprint check, and re-run the other supported architectures after any change to shared builder logic.
diff --git a/.claude/skills/ov-gguf-debug-accuracy/SKILL.md b/.claude/skills/ov-gguf-debug-accuracy/SKILL.md
deleted file mode 100644
index 503b9815e0a..00000000000
--- a/.claude/skills/ov-gguf-debug-accuracy/SKILL.md
+++ /dev/null
@@ -1,15 +0,0 @@
----
-name: ov-gguf-debug-accuracy
-description: >
- Debug wrong or degraded output from a GGUF model running through the OpenVINO GGUF frontend or
- the ggml-openvino backend. Use when a GGUF model converts but produces garbage, repeated or
- drifting tokens, a cosine-similarity cliff between layers, output that diverges from llama.cpp
- CPU, or a broadcast/shape crash that appears only at decode or only for one architecture. Do
- NOT use for ops that fail to convert at all ("Translation for operation type ... is not
- implemented"), or for build and CMake failures.
----
-
-1. Read [src/frontends/gguf/docs/debugging_accuracy.md](../../../src/frontends/gguf/docs/debugging_accuracy.md) — the coarse-to-fine bisection strategy, the ggml-CPU oracle technique, the catalogue of bug archetypes with their generalizable lessons, the debug env vars, and the checklist.
-2. Apply its one governing rule before anything else: every accuracy claim is a comparison against the **real llama.cpp CPU implementation**, never a hand-derived reference. If you are about to write out an op's math to form an expectation, generate it from ggml instead.
-3. Work the bisection steps in order and do not open a debugger until they have cornered the bug. Check the bug archetypes first when a cosine cliff or dynamic-shape crash points near one.
-4. After any fix to a shared path — especially a VIEW or `op_case` predicate — re-run the other supported architectures and confirm their classification and output are unchanged.
diff --git a/.claude/skills/ov-gguf-enable-op/SKILL.md b/.claude/skills/ov-gguf-enable-op/SKILL.md
deleted file mode 100644
index 7bbe765ef04..00000000000
--- a/.claude/skills/ov-gguf-enable-op/SKILL.md
+++ /dev/null
@@ -1,15 +0,0 @@
----
-name: ov-gguf-enable-op
-description: >
- Enable a ggml operation in the OpenVINO GGUF frontend by adding or fixing an op translator.
- Use when conversion fails with "Translation for operation type GGML_OP_* is not implemented",
- when the user asks to add/implement/fix a GGUF or ggml op translator or an op_case, or when
- working on src/frontends/gguf/src/op/. Do NOT use for enabling a new model architecture
- (that is usually just a name in arch_registry.cpp), for wrong numerical output from an op that
- already converts, or for GGUF quantization format work.
----
-
-1. Read [src/frontends/gguf/docs/how_to_add_op.md](../../../src/frontends/gguf/docs/how_to_add_op.md) — the five-file checklist (including the test CMake source list, which is not globbed), the `NodeContext` API, the mandatory op-coverage gate, where reference values must come from, and the build/test commands (`-DENABLE_OV_GGUF_FRONTEND=ON`).
-2. Confirm a translator is really what is missing: a new architecture usually needs only a name in `arch_registry.cpp`, and a structurally different use of an existing op is an `op_case`. Both are covered in that document.
-3. Find the closest existing op with `grep -n "GGML_" src/frontends/gguf/src/op_table.cpp` and the closest test with `grep -n "^TEST(" src/frontends/gguf/tests/test_ops.cpp`, then read only those ranges — do not read `test_ops.cpp` in full.
-4. Implement, then build and run `ov_gguf_frontend_tests` — filtered while iterating, unfiltered before finishing so the coverage gate runs.
diff --git a/.claude/skills/ov-gguf/SKILL.md b/.claude/skills/ov-gguf/SKILL.md
new file mode 100644
index 00000000000..0f5529d8c62
--- /dev/null
+++ b/.claude/skills/ov-gguf/SKILL.md
@@ -0,0 +1,53 @@
+---
+name: ov-gguf
+description: >
+ Develop and troubleshoot the OpenVINO GGUF frontend (src/frontends/gguf) and the llama.cpp
+ ggml-openvino backend that uses it. Use when checking whether a .gguf or mmproj model is
+ supported; when a .gguf file is rejected as an unsupported architecture; when enabling a
+ llama.cpp model family (llama, qwen, gemma, phi, MoE, hybrid/recurrent) through arch_registry,
+ DecoderBuilder, a ModelBuilder or an ArchitectureExtension; when adding a vision/audio projector or
+ ProjectorExtension; when conversion fails with "Translation for operation type GGML_OP_* is not
+ implemented" or an op translator/op_case in src/op/ needs work; when making a converted model
+ stateful or GenAI/PagedAttention-ready; or when a GGUF model converts but gives garbage, drifting
+ tokens, a llama.cpp mismatch or a decode-only shape failure. Not for general llama.cpp usage or
+ unrelated build/CI failures.
+---
+
+Paths are relative to `src/frontends/gguf/`. Read only the route the task needs. First identify the
+input path: a native `.gguf` file or a supplied `GgufDecoder` (llama.cpp cgraph). They share
+converters; builders and validation differ. Registration or conversion alone never establishes accuracy.
+
+| Task | Read |
+|---|---|
+| Is a model supported? | [supported_models.md](../../../src/frontends/gguf/docs/supported_models.md) or [mmproj.md](../../../src/frontends/gguf/docs/mmproj.md#supported-projectors); quote the checkpoint result and limitations, not just the catalog entry |
+| Load a model, make it stateful/GenAI/PA-ready, tokenizer, IR export | [runtime.md](../../../src/frontends/gguf/docs/runtime.md) |
+| Add or port an architecture | [architectures.md](../../../src/frontends/gguf/docs/architectures.md); [extensions.md](../../../src/frontends/gguf/docs/extensions.md) when shipping it as a plugin |
+| Add or replace an mmproj branch | [extensions.md](../../../src/frontends/gguf/docs/extensions.md#extend-mmproj-with-a-projector-component), then the graph contracts in [mmproj.md](../../../src/frontends/gguf/docs/mmproj.md) |
+| Missing ggml operation or `op_case` | [how_to_add_op.md](../../../src/frontends/gguf/docs/how_to_add_op.md) |
+| Wrong numbers | [debugging_accuracy.md](../../../src/frontends/gguf/docs/debugging_accuracy.md) |
+| Unsupported weight type | [quantization.md](../../../src/frontends/gguf/docs/quantization.md); the fix belongs in `src/quant/`, not a builder |
+| Build, run tests, regenerate fixtures | [testing.md](../../../src/frontends/gguf/docs/testing.md) |
+
+## Easy to miss
+
+- **Which layer is missing.** An unclaimed `general.architecture` needs a catalog row or
+ `ArchitectureExtension`; a new mmproj type needs a `ProjectorExtension`; a structurally different
+ use of an existing op needs an `op_case`. Only a genuinely new GGML op needs a translator.
+- **Registration timing.** Architecture/projector extensions before `load()`; converters and passes
+ before `convert()`, on the same frontend instance. `GGUFMakeStateful` and `AdaptToGenAI` are C++ only.
+- **Test build.** New translator or builder sources go into the explicit `FRONTEND_SRCS` list in
+ `tests/CMakeLists.txt`, or the test binary fails to link. Run `ov_gguf_frontend_tests` unfiltered
+ before finishing: the op-coverage gate runs in teardown, so check the exit status.
+ `GGUFArchConversion` skips silently without generated headers (`tests/gen_arch_fixtures.py --fetch`).
+- **References.** Layout-sensitive expectations come from real ggml CPU via a committed oracle under
+ `tests/`, with several heads/tokens and unequal Q/KV dimensions; NumPy or single-head tests can
+ share the bug. Do not tighten `expect_near` tolerances from an x86-only run.
+- **Comparisons.** Use full logits or features on identical inputs and token histories, with
+ `INFERENCE_PRECISION_HINT=f32`, `DYNAMIC_QUANTIZATION_GROUP_SIZE=0` and the reference's KV precision.
+ Set `OV_GGUF_Q4_K_ZP_F16=1` before the process starts. Report quantized-CPU and represented-F32
+ comparisons separately and keep failed results. `GGML_OPENVINO_*` variables configure only the
+ llama.cpp backend.
+- **Shared changes.** Translator, VIEW/`op_case` or shared block changes rerun
+ `GGUFArchitectureAccuracy`, `GGUFArchConversion` and the mmproj suites, not just the target model.
+- **Long runs.** Redirect output to a file, keep the launched PID and stop only that process. Large Q2
+ MoE checkpoints expand at CPU compilation; check memory before starting one.
diff --git a/.github/workflows/job_gguf_models_tests.yml b/.github/workflows/job_gguf_models_tests.yml
index 954be774041..5d7c1a9af9f 100644
--- a/.github/workflows/job_gguf_models_tests.yml
+++ b/.github/workflows/job_gguf_models_tests.yml
@@ -29,7 +29,7 @@ jobs:
GGUF_Models_Tests:
name: GGUF Models tests
# The nightly scope downloads several 7B-30B checkpoints, so it needs far more time
- # than the precommit scope (18 models of <=~4B).
+ # than the precommit scope (small checkpoints and projector files, plus one llama.cpp CPU build).
timeout-minutes: ${{ inputs.model_scope == 'precommit' && 60 || 240 }}
runs-on: ${{ inputs.runner }}
container:
diff --git a/src/frontends/gguf/README.md b/src/frontends/gguf/README.md
index 018dc8aae70..580cd2721e9 100644
--- a/src/frontends/gguf/README.md
+++ b/src/frontends/gguf/README.md
@@ -1,75 +1,57 @@
# OpenVINO GGUF Frontend
-The GGUF frontend converts native `.gguf` model files and graphs supplied through
-the `GgufDecoder` interface into `ov::Model` objects. It supports two input paths:
+The GGUF frontend converts models into `ov::Model` from two input paths that share operation
+translators:
-* **Native GGUF:** parses the file's metadata and weights, selects a model builder
- from the architecture registry, and constructs a graph for conversion.
-* **Supplied decoder:** consumes a `GgufDecoder`, such as the graph decoder used by
- the llama.cpp OpenVINO backend.
+* **Native GGUF:** parses a `.gguf` file's metadata and weights and builds the graph through the
+ architecture registry. llama.cpp is not needed.
+* **Supplied decoder:** consumes a `GgufDecoder`, such as the graph decoder of the llama.cpp
+ OpenVINO backend.
-Both paths use the same operation translators. Their architecture coverage is
-validated separately; consult [supported models and limitations](docs/supported_models.md)
-for verified configurations and experimental support.
+Architecture coverage is validated separately for each path; see [supported models](docs/supported_models.md)
+and, for multimodal projector files, [supported projectors](docs/mmproj.md#supported-projectors).
## Loading a model
-Select this frontend explicitly by name:
+The frontend is hidden from automatic discovery, so `ov.Core.read_model()` does not select it for
+`.gguf` files. Select it by name:
```python
from openvino.frontend import FrontEndManager
-manager = FrontEndManager()
-frontend = manager.load_by_framework("gguf")
-input_model = frontend.load("model.gguf")
-model = frontend.convert(input_model)
+frontend = FrontEndManager().load_by_framework("gguf")
+model = frontend.convert(frontend.load("model.gguf"))
```
-The GGUF frontend is currently hidden from automatic frontend discovery, so
-`ov.Core.read_model()` does not select it for `.gguf` files. See the
-[frontend manager](../common/src/manager.cpp) and
-[GGUF frontend implementation](src/frontend.cpp).
-
-Conversion produces a stateless graph by default. Callers that need an OpenVINO
-KV cache can register a decoder transformation extension using
-[`GGUFMakeStateful`](include/openvino/frontend/gguf/make_stateful.hpp).
-The [frontend API](include/openvino/frontend/gguf/frontend.hpp) documents supported
-extensions; [internal operation guidance](docs/internal_ops.md) describes lowering
-and serialization constraints.
+The result is a stateless graph with llama.cpp-style inputs and explicit cache inputs/outputs.
+In C++, register [`GenAIExtension`](include/openvino/frontend/gguf/extension/genai.hpp) to obtain a stateful model with the
+OpenVINO GenAI interface; this extension is not available from Python. Tokenizer metadata is attached
+to the converted model's rt_info. See [running converted models](docs/runtime.md) for both contracts.
+Projector files convert to encoder models; see [multimodal conversion](docs/mmproj.md).
## Source layout
| Location | Purpose |
| --- | --- |
-| [include](include/openvino/frontend/gguf/) | Frontend, decoder, tokenizer metadata, and conversion-pass interfaces |
-| [dev_api](dev_api/openvino/frontend/gguf/) | Model-builder and architecture-extension APIs; compatibility across releases is not guaranteed |
-| [src/builder](src/builder/) | Architecture registry, native model builders, and graph construction |
-| [src/quant](src/quant/) | GGUF parsing, weight loading, and quantization handling |
+| [include](include/openvino/frontend/gguf/) | Frontend, decoder, tokenizer metadata and conversion-pass interfaces |
+| [dev_api](dev_api/openvino/frontend/gguf/) | Builder, architecture and projector extension APIs; no cross-release compatibility |
+| [src/builder](src/builder/) | Registries, native model builders and graph construction |
+| [src/quant](src/quant/) | GGUF parsing, weight loading and quantization |
| [src/op](src/op/) and [op_table.cpp](src/op_table.cpp) | Operation translators and their registration |
-| [src/pass](src/pass/) | Stateful conversion, GenAI adaptation, and graph cleanup |
-| [tests](tests/) | Operation, architecture, quantization, and extension tests and fixtures |
-| [examples](examples/) | Architecture-extension example |
-
-## Development guides
-
-* [Add an operation translator](docs/how_to_add_op.md).
-* [Add a built-in architecture](docs/adding_an_architecture.md).
-* [Port a llama.cpp model or build an external architecture extension](docs/porting_a_llama_cpp_model.md).
-* [Debug accuracy differences](docs/debugging_accuracy.md).
-* [Generate architecture accuracy fixtures](tests/test_data/arch_accuracy/README.md).
-
-## Building and testing
-
-Follow the repository [build guide](../../../docs/dev/build.md) for prerequisites.
-The frontend is controlled by `ENABLE_OV_GGUF_FRONTEND`. From the repository root,
-configure a shared-library build with tests enabled:
-
-```sh
-cmake -S . -B build -DENABLE_OV_GGUF_FRONTEND=ON -DENABLE_TESTS=ON -DBUILD_SHARED_LIBS=ON
-cmake --build build --target openvino_gguf_frontend ov_gguf_frontend_tests
-```
-
-The GGUF frontend unit-test target is unavailable in static builds. See
-[test configuration](tests/CMakeLists.txt) for fixture requirements and the
-[operation testing guide](docs/how_to_add_op.md#test-and-the-coverage-gate) for
-reference generation and coverage checks.
+| [src/pass](src/pass/) | Stateful conversion, GenAI adaptation and graph cleanup |
+| [tests](tests/) | Unit, accuracy and extension tests, fixtures, generators and llama.cpp oracles |
+| [examples](examples/) | Architecture and projector extension examples |
+
+## Guides
+
+* [Run converted models: state, GenAI, tokenizer, internal operations](docs/runtime.md)
+* [Supported models](docs/supported_models.md) and [multimodal projectors](docs/mmproj.md)
+* [Add or port an architecture](docs/architectures.md)
+* [Register extensions and build plugins](docs/extensions.md), with [runnable examples](examples/architecture_extension/README.md)
+* [Add an operation translator](docs/how_to_add_op.md)
+* [Weight formats and precision](docs/quantization.md)
+* [Debug accuracy differences](docs/debugging_accuracy.md)
+* [Build, test and regenerate references](docs/testing.md)
+
+The frontend is enabled by default. C++ tests need `ENABLE_TESTS=ON` and a shared-library build;
+architecture fingerprint tests skip unless their generated headers are present.
diff --git a/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/graph_context.hpp b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/graph_context.hpp
index ef8b133e3e9..b49efa7a131 100644
--- a/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/graph_context.hpp
+++ b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/graph_context.hpp
@@ -72,6 +72,7 @@ public:
void set_output(const GgufValue& logits);
// Put the data output before auxiliary cache outputs registered by decoder blocks.
void set_primary_output(const GgufValue& value);
+ void set_output(const GgufValue& value, const std::string& name);
// Record the sliding window for normalization passes.
void set_sliding_window(int64_t tokens);
// Registers an overwritten state, automatically marking the update as a model output.
diff --git a/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/model_builder.hpp b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/model_builder.hpp
index 03e2ce8d3cb..6c3fd18c043 100644
--- a/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/model_builder.hpp
+++ b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/model_builder.hpp
@@ -13,6 +13,7 @@
namespace ov::frontend::gguf {
// Opaque graph produced by GgufGraphContext; defined in builder/gguf_graph.hpp.
+class ProjectorRegistry;
struct GgufGraph;
namespace detail {
@@ -29,10 +30,11 @@ struct GGUF_FRONTEND_API BuildContext {
// Opaque weight tables accessed through GgufTensors.
detail::WeightStore* weights = nullptr;
+ const ProjectorRegistry* projectors = nullptr;
};
// Whole-model builder for any family, registered through ArchitectureDefinition.
-// See docs/porting_a_llama_cpp_model.md for external and built-in registration.
+// See docs/architectures.md for external and built-in registration.
class GGUF_FRONTEND_API ModelBuilder {
public:
virtual ~ModelBuilder();
diff --git a/src/frontends/gguf/dev_api/openvino/frontend/gguf/extension/architecture.hpp b/src/frontends/gguf/dev_api/openvino/frontend/gguf/extension/architecture.hpp
index 1ca92b0ceef..89f94666bcb 100644
--- a/src/frontends/gguf/dev_api/openvino/frontend/gguf/extension/architecture.hpp
+++ b/src/frontends/gguf/dev_api/openvino/frontend/gguf/extension/architecture.hpp
@@ -15,10 +15,9 @@
namespace ov::frontend::gguf {
-enum class Maturity { Experimental, Verified };
enum class RegistrationMode { Add, Replace };
-// Shared by built-in and external registration; promotion preserves the factory and builder.
+// Shared by built-in and external registration.
struct GGUF_FRONTEND_API ArchitectureDefinition {
using BuilderFactory = std::function<std::shared_ptr<ModelBuilder>(const BuildContext&)>;
using MatchFn = std::function<bool(const GgufMetadata&)>;
@@ -27,7 +26,6 @@ struct GGUF_FRONTEND_API ArchitectureDefinition {
std::string architecture; // Required general.architecture, e.g. "clip".
BuilderFactory factory;
MatchFn match; // Optional additional constraint within this architecture.
- Maturity maturity = Maturity::Experimental;
bool matches(const GgufMetadata& metadata) const;
};
@@ -36,8 +34,7 @@ struct GGUF_FRONTEND_API ArchitectureDefinition {
using DecoderOptionsFn = std::function<DecoderOptions(const GgufMetadata&)>;
GGUF_FRONTEND_API ArchitectureDefinition make_decoder_architecture(std::string architecture,
RopeMode rope,
- DecoderOptionsFn options = {},
- Maturity maturity = Maturity::Experimental);
+ DecoderOptionsFn options = {});
class GGUF_FRONTEND_API ArchitectureExtension : public ov::Extension {
public:
@@ -45,7 +42,7 @@ public:
using Ptr = std::shared_ptr<ArchitectureExtension>;
explicit ArchitectureExtension(ArchitectureDefinition definition, RegistrationMode mode = RegistrationMode::Add);
- ArchitectureExtension(std::string architecture, RopeMode rope, Maturity maturity = Maturity::Experimental);
+ ArchitectureExtension(std::string architecture, RopeMode rope);
~ArchitectureExtension() override;
const ArchitectureDefinition& definition() const {
@@ -55,6 +52,9 @@ public:
return m_mode;
}
+protected:
+ explicit ArchitectureExtension(RegistrationMode mode);
+
private:
ArchitectureDefinition m_definition;
RegistrationMode m_mode;
diff --git a/src/frontends/gguf/dev_api/openvino/frontend/gguf/extension/projector.hpp b/src/frontends/gguf/dev_api/openvino/frontend/gguf/extension/projector.hpp
new file mode 100644
index 00000000000..6523cbdecb5
--- /dev/null
+++ b/src/frontends/gguf/dev_api/openvino/frontend/gguf/extension/projector.hpp
@@ -0,0 +1,50 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <map>
+
+#include "openvino/frontend/gguf/builder/graph_context.hpp"
+#include "openvino/frontend/gguf/extension/architecture.hpp"
+
+namespace ov::frontend::gguf {
+
+struct GGUF_FRONTEND_API ProjectorResult {
+ GgufValue output;
+ std::map<std::string, std::string> config;
+};
+
+struct GGUF_FRONTEND_API ProjectorDefinition {
+ using BuildFn = std::function<ProjectorResult(GgufGraphContext&)>;
+
+ std::string id;
+ std::string architecture;
+ std::string modality;
+ std::string projector_type;
+ BuildFn build;
+ ArchitectureDefinition::MatchFn match;
+};
+
+class GGUF_FRONTEND_API ProjectorExtension : public ArchitectureExtension {
+public:
+ OPENVINO_RTTI("gguf::ProjectorExtension", "", ArchitectureExtension);
+ using Ptr = std::shared_ptr<ProjectorExtension>;
+ explicit ProjectorExtension(ProjectorDefinition definition, RegistrationMode mode = RegistrationMode::Add);
+ ~ProjectorExtension() override;
+
+ const ProjectorDefinition& projector_definition() const {
+ return m_projector;
+ }
+
+private:
+ ProjectorDefinition m_projector;
+};
+
+// Append one built-in encoder/projector branch; the caller owns outputs and finish().
+GGUF_FRONTEND_API ProjectorResult build_builtin_projector(GgufGraphContext& graph,
+ const std::string& modality,
+ const std::string& projector_type);
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/docs/adding_an_architecture.md b/src/frontends/gguf/docs/adding_an_architecture.md
deleted file mode 100644
index 6672fac0b8c..00000000000
--- a/src/frontends/gguf/docs/adding_an_architecture.md
+++ /dev/null
@@ -1,180 +0,0 @@
-# Adding a new architecture to the GGUF frontend
-
-The native `.gguf` path builds an OpenVINO graph from a GGUF file with **no llama.cpp
-dependency**. It emits nodes in the GGML op vocabulary (`GGML_OP_MUL_MAT`, `GGML_OP_ROPE`,
-`GGML_OP_FLASH_ATTN_EXT`, ...) that reproduce llama.cpp's cgraph topology, so the same op
-translators (`src/op/*.cpp`) run for both the native path and the llama.cpp cgraph path.
-
-## How the builder is laid out
-
-`src/builder/` is layered; each layer knows strictly less than the one above it:
-
-| File | Responsibility | Knows about |
-|---|---|---|
-| [`graph_emitter.hpp`](../src/builder/graph_emitter.hpp) | `add_op` / `add_input` / `add_weight`, using shared converters and OpenVINO shape inference | nothing about transformers |
-| [`blocks/`](../src/builder/blocks) | reusable graph fragments: `common` (norm/scale/bias), `ffn` (dense/GeGLU/MoE), `attention`, `gated_delta_net`, `qkv_repack` | a decoder layer |
-| [`decoder_config.hpp`](../src/builder/decoder_config.hpp) | all per-architecture detection + per-layer accessors | one model's hyperparameters |
-| [`arch/decoder_builder.cpp`](../src/builder/arch/decoder_builder.cpp) | the order a decoder is assembled in | the whole decoder family |
-| [`arch_registry.cpp`](../src/builder/arch_registry.cpp) | which architectures are accepted, and their RoPE mode | architecture definitions |
-| [`model_kind.hpp`](../src/builder/model_kind.hpp) | family diagnosis for an unclaimed file | raw metadata |
-| [`gguf_builder.cpp`](../src/builder/gguf_builder.cpp) | parse → resolve definition → invoke its `ModelBuilder` | the entry point |
-
-A single generic `DecoderBuilder` covers the whole "llama family" of decoder-only transformers.
-This is deliberately **not** llama.cpp's one-file-per-architecture layout: llama.cpp needs that
-because every architecture enumerates its tensors by hand, whereas this builder derives them from
-the tensor table, so a same-family architecture costs zero lines of code.
-
-## Two routes: in-tree, or an extension
-
-Both routes use `ArchitectureDefinition`, the same factory, and the same conversion pipeline.
-An external library wraps its definition in `ArchitectureExtension`; the frontend registers that
-same definition in `builtin_architectures()`. See
-[porting_a_llama_cpp_model.md](porting_a_llama_cpp_model.md) for the builder API and integration steps.
-
-## The 90% case: add a decoder definition
-
-For an existing decoder topology, add a row to the `decoders` catalog in
-[`arch_registry.cpp`](../src/builder/arch_registry.cpp):
-
-```cpp
-{"your-arch", RopeMode::Neox, Maturity::Experimental},
-```
-
-The catalog owns the architecture name, RoPE mode and maturity together. `verified_archs()` and
-`experimental_archs()` are derived views, not separate registration sites. Check the RoPE mode
-against the reference implementation.
-
-For an architecture requiring overrides, define it with `make_decoder_architecture` and a callback
-returning `DecoderOptions`, then add the definition to `builtin_architectures()`. The exact same
-function can be shipped externally. Overrides are applied before dependent configuration is resolved.
-`qk_norm_after_rope`, `post_norm_only`, `normalize_expert_weights` and `rope_skip_period`
-cover order and routing semantics that tensor names alone cannot determine. For example,
-EXAONE4's `post_attention_norm` is a post-norm, while GPT-OSS uses the same name for a
-pre-FFN norm. Reuse the shared blocks with explicit options for such differences.
-
-### What is auto-detected (no code needed)
-
-`DecoderConfig` infers structure from the presence of layer-0 weight tensors and from metadata:
-
-| Feature | Detected from |
-|---|---|
-| Per-head Q/K norm (qwen3, hunyuan; ordering is architecture-specific) | `blk.0.attn_q_norm.weight` |
-| Full-width Q/K norm (OLMoE) | `attn_q_norm.weight` width == `n_head*head_size` |
-| Q/K/V projection biases (qwen2) | `blk.0.attn_q.bias` |
-| Output-projection bias | `blk.0.attn_output.bias` |
-| Fused QKV (phi-3, minicpm) | `blk.0.attn_qkv.weight` |
-| Fused gate+up FFN (phi-3) | absence of `blk.0.ffn_gate.weight` |
-| MoE routing (OLMoE, gpt-oss, qwen3moe) | `ffn_gate_exps.weight` on the first routed layer |
-| Shared experts | `ffn_*_shexp.weight`, including files without `expert_shared_count` |
-| Hybrid dense-lead MoE | `leading_dense_block_count` and `interleave_moe_layer_step` metadata |
-| RoPE freq factors (llama-3, phi-3) | `rope_freqs.weight` |
-| Scalar scales (minicpm) | `embedding_scale` / `residual_scale` / `logit_scale` metadata |
-| Soft-caps (gemma2/3) | `attn_logit_softcapping` / `final_logit_softcapping` metadata |
-| Sliding-window attention | `attention.sliding_window(_pattern)` metadata, or sinks |
-| Per-layer KV heads | `attention.head_count_kv` as an array |
-
-All hyperparameters are read once in `decoder_config_from_meta()`
-([`src/quant/gguf.cpp`](../src/quant/gguf.cpp)) and resolved once in `DecoderConfig`; the topology
-builder never re-reads GGUF metadata.
-
-## Per-layer values: use the accessors, don't inline
-
-Architectures with per-layer variation (SWA layers, variable KV heads, per-layer head sizes)
-are handled by the per-layer accessors on `DecoderConfig` — the single source of truth,
-so the topology stays declarative:
-
-- `layer_is_swa(il)` — sliding-window layer? (per-layer flag array or period)
-- `layer_is_moe(il)` — routed experts? (dense lead and interleaving stride)
-- `layer_head_size(il)` — head size (SWA layers may differ, e.g. gemma4)
-- `layer_n_head_kv(il)` — KV head count (may vary per layer)
-- `layer_kq_scale(il)` — attention softmax scale (`1/sqrt(layer_head_size(il))` unless overridden)
-- `layer_rope_config(il)` — RoPE config (SWA layers may use a different freq_base / n_dims)
-- `is_recurrent_layer(il)` — linear-attention (GDN) layer of a hybrid stack
-
-If a new arch adds a per-layer dimension, extend these accessors rather than adding a new
-inline ternary in `build_layer()`.
-
-## The 10% case: structurally novel architectures need code
-
-The generic decoder builder assumes the standard block: `norm -> QKV -> RoPE -> attention ->
-norm -> FFN/MoE -> residual`. Architectures that break this shape need a new detected flag on
-`DecoderConfig` plus a branch in the relevant block. Examples of what required code in the past:
-
-- **MoE routing** — `blocks::moe_ffn()` (`MUL_MAT_ID` lowering, top-k, gated activation).
-- **gpt-oss** — attention sinks (5th `FLASH_ATTN_EXT` input), OAI gated activation
- (`GGML_GLU_OP_SWIGLU_OAI`), softmax-after-topk gating.
-- **gemma2/3** — post-attention / post-FFN norms, attention & final-logit soft-caps.
-- **gemma4** — per-layer input embeddings, shared-KV layers, per-op RoPE (SWA vs global differ).
-- **qwen35** — a hybrid stack where 3 of every 4 layers are a Gated DeltaNet block
- (`blocks::gated_delta_net()`) instead of attention. It returns the same thing the attention
- block returns — the sublayer output before the residual — so the shared FFN tail is reused.
-
-To add such a feature:
-1. Add a detection line in `DecoderConfig`'s constructor (prefer weight-presence over an
- arch-name check — it generalizes to future archs; only fall back to `arch == "..."` when the
- tensor table is genuinely ambiguous, e.g. GeGLU-vs-SwiGLU).
-2. Add the emission behind that flag in the relevant `blocks/` function, or in
- `DecoderBuilder::build_layer()` when it is about the ORDER of sublayers rather than their
- contents.
-3. Add the op translator in `src/op/` if the feature needs a GGML op not yet handled, and
- register it in `op_table.cpp`.
-
-## Adding a new model FAMILY (mmproj, audio, encoder-decoder)
-
-An architecture definition selects a builder; a **family** supplies its topology. A family is a distinct graph shape with its own
-inputs and its own notion of a layer — a vision/mmproj encoder and an audio encoder are each one,
-and neither is a causal decoder. Do **not** add flags to `DecoderConfig` for them.
-
-A family does not have to live in this frontend, though. An `ArchitectureExtension` can supply a
-whole `ModelBuilder` and claim the files it owns by a metadata predicate, which is how a vision or
-audio encoder is added without touching anything here; see
-[porting_a_llama_cpp_model.md](porting_a_llama_cpp_model.md). The steps below are for a family that
-should ship in-tree; the builder itself is written the same way either way.
-
-1. Implement a `ModelBuilder` with the generic `GgufGraphContext::node` API. It invokes the
- registered frontend converter directly; new operations need no builder-side support.
- A non-decoder reads its own metadata and does not call `configure_decoder`.
-2. Return an `ArchitectureDefinition` with a unique handler id, GGUF architecture name, factory,
- and optional metadata predicate. Predicates distinguish, for example, vision and audio files
- that both name themselves `clip`.
-3. Add that definition to `builtin_architectures()` in `arch_registry.cpp`. Family detection is
- only a diagnostic fallback when no definition matches; no new dispatch branch is needed.
-
-Nothing in the decoder family changes.
-
-The downstream side already tolerates a non-decoder graph: `TranslateSession`'s LLM-specific
-preprocessing is self-gating (`add_rope_sin_cos` only fires when `inp_pos` exists,
-`add_sliced_mask` only when the mask and `token_len_per_seq` inputs exist), and the LLM-specific
-passes (`MakeStateful`, `AdaptToGenAI`) are caller-registered rather than built in.
-
-## Verifying a new architecture
-
-Use the existing suites for different kinds of coverage:
-
-| Suite | What it checks |
-|---|---|
-| [`tests/model_hub_tests/gguf`](../../../../tests/model_hub_tests/gguf) | Real checkpoints: download, conversion, compilation, finite logits and KV-cache updates |
-| [`test_arch_accuracy.cpp`](../tests/test_arch_accuracy.cpp) | Small offline fixtures: full-logit agreement with llama.cpp CPU through prefill and cached decode |
-| Builder API and architecture extension tests | Registration, custom builders, metadata validation, dynamic shapes, operation types and shared-library loading |
-
-Model-hub smoke tests do not compare predicted tokens or logits with a reference and do not
-register architecture extensions. Keep focused regression tests for those behaviors; add real
-checkpoint coverage to the existing model-hub lists.
-
-1. **Converts + compiles**: convert through the frontend, then `core.compile_model(m, "CPU")`.
- The frontend is not auto-selectable, so ask for it by name:
- `fe = FrontEndManager().load_by_framework("gguf"); m = fe.convert(fe.load("model.gguf"))`.
-2. **Graph is sane**: check the op-type histogram — attention should collapse to a single SDPA op
- and MoE routing to a single grouped-matmul op, not a long chain of primitives.
-3. **Numerics**: run generation through OpenVINO GenAI (`greedy_causal_lm model.gguf "..."`) and
- compare to native llama.cpp (`build-ref/bin/llama-cli`) on the same prompt — the greedy tokens
- should match (small drift after ~dozens of tokens is expected from kernel differences).
-4. **No graph regression** for existing archs: `tests/test_arch_conversion.cpp` converts every
- architecture fixture and asserts a pinned `(op count, input count)` fingerprint, so any
- restructuring of a supported architecture shows up there.
-
-5. **Numerical regression**: add a nonzero fixture to `tests/gen_arch_accuracy.py`, evaluate it
- with `tests/architecture_oracle.cpp` linked to real llama.cpp CPU, and commit its NPZ.
- Register the case in `test_arch_accuracy.cpp`. Exercise distinct query/KV heads, nonzero
- token positions, and prefill plus cached decode. Architecture promotion also requires a
- real-checkpoint comparison; synthetic conversion alone is insufficient.
diff --git a/src/frontends/gguf/docs/architectures.md b/src/frontends/gguf/docs/architectures.md
new file mode 100644
index 00000000000..2be6d8e06bc
--- /dev/null
+++ b/src/frontends/gguf/docs/architectures.md
@@ -0,0 +1,351 @@
+# Adding and porting architectures
+
+The native `.gguf` path builds an OpenVINO graph with no llama.cpp dependency. Builders emit nodes in
+the GGML operation vocabulary (`GGML_OP_MUL_MAT`, `GGML_OP_ROPE`, ...), so the same converters in
+[`src/op/`](../src/op) serve native files and llama.cpp cgraphs.
+
+Every architecture is an `ArchitectureDefinition`: a handler id, the `general.architecture` string,
+a `ModelBuilder` factory and an optional metadata predicate. The built-in catalog and an external
+`ArchitectureExtension` consume the same definition and pipeline, so code written as a plugin can be
+promoted unchanged. Registration and packaging are covered in [extensions.md](extensions.md).
+A vision/audio branch inside an mmproj file is a [projector component](extensions.md#extend-mmproj-with-a-projector-component), not an architecture.
+
+## Choose the smallest implementation
+
+| Requirement | Implementation |
+|---|---|
+| Existing decoder topology, new name | Catalog row or `make_decoder_architecture(name, rope)` |
+| Decoder facts that tensors/metadata cannot determine | Add a callback returning `DecoderOptions` |
+| Custom layer order using existing sublayers | `ModelBuilder` with `configure_decoder`, `decoder_attention`, `decoder_ffn` |
+| Different model family | `ModelBuilder` with generic operations; follow [porting from llama.cpp](#port-from-llamacpp) |
+
+Prefer structural detection to options. A custom topology owns its embedding, normalization,
+residual and output ordering; the shared sublayer methods do not assemble those.
+
+## Builder layout
+
+| File | Responsibility |
+|---|---|
+| [`graph_emitter.hpp`](../src/builder/graph_emitter.hpp) | `add_op` / `add_input` / `add_weight` through the shared converters and shape inference |
+| [`blocks/`](../src/builder/blocks) | Reusable fragments: `common`, `ffn` (dense/GeGLU/MoE), `attention`, `gated_delta_net`, `qkv_repack` |
+| [`decoder_config.hpp`](../src/builder/decoder_config.hpp) | Per-architecture detection and per-layer accessors |
+| [`arch/decoder_builder.cpp`](../src/builder/arch/decoder_builder.cpp) | Decoder assembly order |
+| [`arch_registry.cpp`](../src/builder/arch_registry.cpp) | The `architectures` catalog returned by `builtin_architectures()` |
+| [`model_kind.hpp`](../src/builder/model_kind.hpp) | Diagnostic family detection for an unclaimed file |
+| [`gguf_builder.cpp`](../src/builder/gguf_builder.cpp) | Parse, resolve the definition, invoke its builder |
+
+One generic `DecoderBuilder` covers the llama family. Unlike llama.cpp it derives tensors from the
+file's tensor table, so a compatible architecture needs only registration.
+
+## Reuse the decoder
+
+Add a catalog row in [`arch_registry.cpp`](../src/builder/arch_registry.cpp) with the RoPE mode from
+the reference implementation (`Normal` rotates pairs, `Neox` halves, `Interleaved` is multimodal RoPE):
+
+```cpp
+{"your-arch", RopeMode::Neox},
+```
+
+Custom builders such as Mamba and `clip` register a factory instead and own their positional encoding:
+
+```cpp
+{"mamba2", make_mamba2_builder},
+```
+
+When tensor names cannot determine a choice, define the architecture with
+`make_decoder_architecture(name, rope, options_callback)` and register its factory in the catalog.
+Options in [`decoder_options.hpp`](../dev_api/openvino/frontend/gguf/builder/decoder_options.hpp)
+such as `qk_norm_after_rope`, `post_norm_only`, `normalize_expert_weights` and `rope_skip_period`
+describe ordering and routing facts, not execution plans. Unset fields keep native detection; the
+callback runs before dependent SWA, RoPE and KV configuration is resolved. For example, EXAONE4's
+`post_attention_norm` is a post-norm, while GPT-OSS uses the same name for a pre-FFN norm.
+
+### Auto-detected features
+
+`decoder_config_from_meta()` reads hyperparameters once and `DecoderConfig` resolves them; the
+topology builder never rereads metadata.
+
+| Feature | Detected from |
+|---|---|
+| Per-head Q/K norm (qwen3, hunyuan) | `blk.0.attn_q_norm.weight` |
+| Full-width Q/K norm (OLMoE, MiniMax M2) | `attn_q_norm.weight` width == `n_head*head_size` |
+| Q/K/V and output biases | `blk.0.attn_q.bias`, `blk.0.attn_output.bias` |
+| Fused QKV (phi-3, minicpm) | `blk.0.attn_qkv.weight` |
+| Fused gate+up FFN (phi-3) | Absence of `blk.0.ffn_gate.weight` |
+| MoE routing | `ffn_gate_exps.weight` on the first routed layer |
+| Shared experts | `ffn_*_shexp.weight`, including files without `expert_shared_count` |
+| Dense-lead / interleaved MoE | `leading_dense_block_count`, `interleave_moe_layer_step` |
+| RoPE frequency factors | `rope_freqs.weight` |
+| Scalar scales (minicpm) | `embedding_scale` / `residual_scale` / `logit_scale` |
+| Soft-caps (gemma2/3) | `attn_logit_softcapping` / `final_logit_softcapping` |
+| Sliding-window attention | `attention.sliding_window(_pattern)`, or sinks |
+| Per-layer KV heads | `attention.head_count_kv` as an array |
+
+Per-layer variation goes through `DecoderConfig` accessors, not inline ternaries in `build_layer()`:
+`layer_is_swa`, `layer_is_moe`, `layer_head_size`, `layer_n_head_kv`, `layer_kq_scale`,
+`layer_rope_config` and `is_recurrent_layer`. Extend them for a new per-layer dimension.
+
+### Extend the decoder topology
+
+The generic block is `norm -> QKV -> RoPE -> attention -> norm -> FFN/MoE -> residual`. Past
+extensions include MoE routing (`blocks::moe_ffn()`), gpt-oss sinks and OAI SwiGLU, jais2 biased
+LayerNorm and ReLU² FFN, gemma2/3 post-norms and soft-caps, gemma4 per-layer embeddings and shared KV,
+and qwen35 Gated DeltaNet layers that return the same sublayer output as attention. To add one:
+
+1. Add detection in `DecoderConfig`. Prefer weight presence; use `arch == "..."` only when the tensor
+ table is ambiguous (for example GeGLU versus SwiGLU).
+2. Emit it behind that flag in the relevant `blocks/` function, or in `DecoderBuilder::build_layer()`
+ when it changes sublayer order.
+3. Add a converter only if a GGML operation is missing; see [how_to_add_op.md](how_to_add_op.md).
+
+Do not add `DecoderConfig` flags for non-decoder families such as encoders; write a `ModelBuilder`.
+
+## Write a custom builder
+
+Implement `ModelBuilder::build()` with a `GgufGraphContext`. `BuildContext` borrows metadata and
+weights for the synchronous factory/build call; a builder may copy it but must not use it afterward.
+The returned graph retains weight storage.
+
+- Scalar getters `get_int`, `get_float`, `get_bool`, `get_str` return `std::optional`; use
+ `value_or` only for defaults present in the reference. Array getters return typed vectors.
+- `tensors.require(name)` loads a mandatory weight, `tensors(name)` returns an empty value for an
+ absent optional weight, and `tensors.has(name)` checks presence without emitting a node.
+- Inputs have a known rank of at most four; dimensions may be dynamic.
+
+For a custom decoder layer order, initialize the shared blocks once:
+
+```cpp
+auto dimensions = graph.configure_decoder(RopeMode::Neox, options);
+graph.build_inp_pos();
+graph.build_attn_inp_kv();
+// Inside the custom layer loop, after the appropriate normalization:
+auto attention = graph.decoder_attention(layer, normalized_input);
+auto feed_forward = graph.decoder_ffn(layer, normalized_ffn_input);
+```
+
+These call the existing attention, Gated DeltaNet and dense/GeGLU/MoE blocks. The returned dimensions
+are a snapshot. `decoder_layer_parameters(layer)` supplies resolved heads, scale and RoPE parameters
+for a custom attention fragment. The Qwen3 builder in
+[`test_architecture_extension.cpp`](../tests/test_architecture_extension.cpp) owns its layer order
+this way; `VisionEncoderBuilder` in the same file is a larger non-decoder family.
+
+### Declare model contracts
+
+Graph nodes alone do not tell consumers how to maintain state or form masks:
+
+- `configure_decoder` records resolved RoPE and sliding-window metadata automatically.
+- For custom RoPE, call `configure_rope(config)` before emitting nodes. Set `config.per_op` for
+ per-node tables and `config.is_imrope` for multimodal positions, then pass a matching `rope_config`.
+- `set_sliding_window(tokens)` records the window of a custom attention implementation.
+- `add_recurrent_state(input, update)` declares an overwritten state for `GGUFMakeStateful`. It is not
+ the declaration for an append-only KV cache; reuse the shared attention blocks for that.
+- `set_output(value)` appends an output; `set_primary_output(value)` puts it before auxiliary outputs
+ such as KV caches. `finish()` validates the graph and seals the context.
+
+State and GenAI adaptation remain caller choices; see [runtime.md](runtime.md).
+
+## Port from llama.cpp
+
+Use this route when the shared decoder blocks cannot express the computation: a new encoder, a
+different recurrent network or an encoder-decoder family. llama.cpp is the reference and oracle,
+not a dependency of the result.
+
+### 1. Trace the reference
+
+Record the llama.cpp revision, checkpoint, quantization, preprocessing and runtime options. Paths are
+relative to that checkout:
+
+| Source | What to extract |
+|---|---|
+| `src/models/<arch>.cpp`: `load_arch_hparams` | Required metadata, defaults, variants |
+| Same file: `load_arch_tensors` | Tensor names and dimensions, optional and tied weights |
+| Same file: `build_arch_graph` | Inputs, layer order, branches, residuals, output selection |
+| `src/llama-model.cpp`, `src/llama-arch.cpp`, `src/llama-hparams.h` | Shared metadata, `LLM_KV_*` / `LLM_TENSOR_*` names, derived dimensions |
+| `src/llama-graph.cpp` and the memory implementation | Helper bodies, masks, cache and recurrent updates |
+| `tools/mtmd/models/` | Vision/audio graphs, patching, pooling and projection |
+| Conversion scripts and `gguf-py/gguf/` | Exported names, packing, transpositions |
+
+```sh
+rg -n 'load_arch_hparams|load_arch_tensors|build_arch_graph|::graph' src/models/<architecture>.cpp
+rg -n 'build_lora_mm|build_norm|build_ffn|build_attn' src/llama-graph.cpp
+```
+
+Expand every helper: `build_lora_mm` can add a weight scale and LoRA updates, and `build_norm` selects
+RMS, layer or group normalization with optional bias. Write down the full input-to-output sequence,
+including embedding scales, learned positions, final norm, pooling, output rows and logit transforms.
+Matching tensor names do not imply the same computation.
+
+### 2. Define the file and model interface
+
+Write down the literal `general.architecture` and any distinguishing predicate; required metadata,
+types and defaults; required and optional tensors with logical GGML dimensions; each input's name,
+type and dynamic axes; outputs; and cache/state, positions and masks. Reject missing mandatory fields.
+Derive weight dimensions from `GgufValue::ne` or its shape, not packed byte sizes. GGML
+`[width, items, 1, 1]` is OpenVINO `[1, 1, items, width]`; that is not a batch guarantee.
+
+An encoder need not call `configure_decoder` or emit logits. An encoder-decoder port must build both
+computations and their connection; registration does not generate them.
+
+### 3. Translate graph construction
+
+Port one fragment at a time, keeping operand order. Use shared blocks only where semantics match.
+
+| llama.cpp | Builder |
+|---|---|
+| `create_tensor(tn(...))` | Look up the GGUF name through `GgufTensors` |
+| `ggml_new_tensor_*` for runtime data | `add_input(name, type, shape)` |
+| `ggml_add` / `ggml_sub` / `ggml_mul` | `node("GGML_OP_ADD" / "GGML_OP_SUB" / "GGML_OP_MUL", {a, b})` |
+| `ggml_mul_mat(ctx, weight, x)` | `node("GGML_OP_MUL_MAT", {weight, x})` |
+| `ggml_rms_norm(ctx, x, eps)` | `node("GGML_OP_RMS_NORM", {x}, 0, {{"eps", eps}})`; learned scale is a separate multiply |
+| `ggml_reshape_*` | `GGML_OP_RESHAPE` case 6 with OpenVINO-order `reshape_target`, optional `special_zero` |
+| `ggml_permute` | `GGML_OP_PERMUTE` case 1 with OpenVINO-order `perm` |
+| `ggml_view_*` | Converter attributes describing the logical slice; never a ggml pointer |
+| `ggml_top_k(ctx, scores, k)` | `GGML_OP_TOP_K` with `int64_t` attribute `k` |
+| `ggml_cpy` / `ggml_set*` for state | The updated tensor and its state relationship, not an in-place side effect |
+| `cb(...)`, scheduling | Nothing to emit |
+
+Layout rules:
+
+- `ggml_permute` gives each source axis's destination; OpenVINO `perm` lists source axes in output
+ order. For GGML axes `axes[i]`, `perm[3 - axes[i]] = 3 - i`. Derive it from axis meanings.
+- VIEW case 3 accepts `view_slice = {ov_axis, start, length}` and optional `view_reshape` for a
+ contiguous subrange. Strided views need a suitable converter or explicit layout operations.
+- CONT case 1 is a passthrough, but `ggml_cont_2d/3d/4d` still carries a reshape. Keep real transposes.
+- Preserve dynamic token/item axes. A one-token graph does not validate broadcasting.
+
+### 4. Implement a whole-model builder
+
+This complete builder implements an **illustrative** `example-encoder` contract. Its reference reads
+`block_count`, `embedding_length` and an RMS epsilon (default `1e-5`), consumes feature vectors and
+applies `cur += down(silu(gate(norm(cur))) * up(norm(cur)))` per layer with tensors
+`blk.N.{norm,gate,up,down}.weight`, optional `.bias` and `output_norm.weight`:
+
+```cpp
+#include "openvino/core/except.hpp"
+#include "openvino/frontend/gguf/builder/graph_context.hpp"
+#include "openvino/frontend/gguf/extension/architecture.hpp"
+
+namespace example {
+using namespace ov::frontend::gguf;
+
+class FeatureEncoder : public ModelBuilder {
+public:
+ explicit FeatureEncoder(const BuildContext& context) : m_context(context) {}
+
+ std::shared_ptr<GgufGraph> build() override {
+ GgufGraphContext graph(m_context);
+ const auto& metadata = graph.metadata();
+ const auto count = metadata.get_int("example-encoder.block_count");
+ const auto width = metadata.get_int("example-encoder.embedding_length");
+ OPENVINO_ASSERT(count && *count > 0, "Missing or invalid block_count");
+ OPENVINO_ASSERT(width && *width > 0, "Missing or invalid embedding_length");
+ const auto eps = static_cast<float>(
+ metadata.get_float("example-encoder.attention.layer_norm_rms_epsilon").value_or(1e-5));
+ OPENVINO_ASSERT(eps > 0, "RMS epsilon must be positive");
+ auto tensors = graph.tensors();
+ auto cur = graph.add_input("features", ov::element::f32, {1, 1, -1, *width});
+
+ const auto linear = [&](const std::string& base, const GgufValue& input) {
+ auto out = graph.node("GGML_OP_MUL_MAT", {tensors.require(base + ".weight"), input});
+ if (auto bias = tensors(base + ".bias")) {
+ out = graph.node("GGML_OP_ADD", {out, bias});
+ }
+ return out;
+ };
+
+ for (int64_t layer = 0; layer < *count; ++layer) {
+ const auto prefix = "blk." + std::to_string(layer) + ".";
+ const auto residual = cur;
+ auto norm = graph.build_norm(cur, tensors.require(prefix + "norm.weight"), eps);
+ auto gate = graph.node("GGML_UNARY_OP_SILU", {linear(prefix + "gate", norm)});
+ auto up = linear(prefix + "up", norm);
+ auto down = linear(prefix + "down", graph.node("GGML_OP_MUL", {gate, up}));
+ cur = graph.node("GGML_OP_ADD", {residual, down});
+ }
+
+ graph.set_output(graph.build_norm(cur, tensors.require("output_norm.weight"), eps));
+ return graph.finish();
+ }
+
+private:
+ BuildContext m_context;
+};
+
+ArchitectureDefinition new_family_architecture() {
+ return {"example.feature-encoder", "example-encoder", [](const BuildContext& context) {
+ return std::make_shared<FeatureEncoder>(context);
+ }};
+}
+} // namespace example
+```
+
+Replace the contract and layer body with the traced reference. Do not keep its activation,
+normalization or residual order because dimensions happen to match. The
+[projector example](../examples/architecture_extension/projector.cpp) is a smaller runnable family.
+
+### 5. Handle missing operations and state
+
+Inventory the operations in the expanded reference helpers against [`op_table.cpp`](../src/op_table.cpp).
+For a missing one, express it exactly with existing nodes or add a converter: externally as a
+[`ConversionExtension`](extensions.md#add-or-override-an-operation-converter)
+(`ConverterRegisteredAfterLoadInfersBuilderValues` is a working test), or built in through
+[how_to_add_op.md](how_to_add_op.md). Converters are the only operation-support layer: never add a
+builder-specific enum, shape rule or `GgufGraphContext` method. An unsupported quantization format
+belongs to the weight loader in [`src/quant/`](../src/quant).
+
+For state, make previous-state inputs, the update and retained outputs explicit and declare them as
+in [Declare model contracts](#declare-model-contracts).
+
+## Tensor operations and shapes
+
+`node` is the single operation API: it invokes the registered converter immediately, and the
+resulting `GgufValue` exposes OpenVINO's inferred `shape()`, `type()` and reversed-GGML `ne(i)`.
+
+```cpp
+auto sum = graph.node("GGML_OP_ADD", {a, b});
+auto projected = graph.node("GGML_OP_MUL_MAT", {weight, sum});
+auto experts = graph.node("GGML_OP_TOP_K", {scores}, 0, {{"k", int64_t{2}}});
+auto heads = graph.node("GGML_OP_RESHAPE", {projected}, 6,
+ {{"reshape_target", std::vector<int64_t>{0, -1, n_heads, head_size}},
+ {"special_zero", true}});
+auto merged = graph.node("GGML_OP_RESHAPE", {heads}, 2, {{"merge_heads", true}});
+auto half = graph.node("GGML_OP_CPY", {input}, 0, {{"dst_type", ov::element::f16}});
+```
+
+Operands follow GGML order (weight before activation). `op_case` selects a converter's semantic
+variant; attributes carry operation parameters (`reshape_target`, `perm`, `view_slice`, `repeats`,
+GGML-order `concat_axis`, TopK `k`), never inferred output metadata. Architecture code does not supply
+output types; converters apply the [result-type rules](how_to_add_op.md#translator-shape), and only
+casts and `IM2COL` take `dst_type`. The builder API is not a drop-in `llm_graph_context`; local
+functions may name repeated fragments without extending it.
+
+## Promote an extension into OpenVINO
+
+1. Move the definition source and header into `src/builder/arch/`, unchanged.
+2. Include the header in `arch_registry.cpp` and add the name, factory and optional predicate to the
+ `architectures` catalog. A plain decoder needs only a name and RoPE row.
+3. Add the source to the explicit `FRONTEND_SRCS` list in `tests/CMakeLists.txt` and keep its tests.
+4. Upstream any plugin converters into the shared table.
+5. Update [supported_models.md](supported_models.md) with the validation actually run.
+
+No dispatch branch or alternate graph implementation is needed. The tests compile the projector
+example both as a library and into the catalog.
+
+## Validate
+
+Follow [testing.md](testing.md) for commands and [acceptance](testing.md#acceptance), in increasing
+scope:
+
+1. **Interface:** load a small nonzero fixture through the actual plugin; check missing-field errors,
+ optional/tied weights, inputs and outputs, and CPU compilation.
+2. **Fragments:** compare new layouts and operations against real ggml CPU with distinct dimensions
+ and nonuniform values. llama.cpp's `cb` labels help match intermediates.
+3. **Whole graph:** compare identical inputs. Decoders: full logits through prefill and several cached
+ decode steps, multiple lengths, nonzero positions, state resets and window boundaries. Encoders:
+ features or projections directly.
+4. **Real checkpoint:** repeat with the real model and quantization, aligned tokenizer, preprocessing
+ and precision. Record tested and untested variants.
+5. **Regression:** keep a fixture. Decoders reuse [`gen_arch_accuracy.py`](../tests/gen_arch_accuracy.py)
+ ([instructions](../tests/test_data/arch_accuracy/README.md)); a new family needs its own oracle.
+ Update the fixture manifest and fingerprints, and add model-hub coverage. Shared changes rerun the
+ existing architecture regressions.
diff --git a/src/frontends/gguf/docs/debugging_accuracy.md b/src/frontends/gguf/docs/debugging_accuracy.md
index 1d1811e9889..97b3932bfe5 100644
--- a/src/frontends/gguf/docs/debugging_accuracy.md
+++ b/src/frontends/gguf/docs/debugging_accuracy.md
@@ -1,362 +1,150 @@
-# Debugging Accuracy Issues in the GGUF Frontend / OpenVINO Backend
-
-How to find *why* a GGUF model produces wrong output through the OpenVINO frontend +
-`ggml-openvino` backend, versus the reference llama.cpp CPU path.
-
-A field guide, not a spec: the techniques that have paid off and the traps that wasted
-time. Read it before reaching for a debugger.
-
----
-
-## The one rule: always have an authoritative reference
-
-Every accuracy claim is a comparison, and the reference must be **the real llama.cpp CPU
-implementation** — never one you derived by hand. A hand-written reference (numpy, a C++
-recurrence from the paper) encodes *your* understanding of the op's layout; if that is wrong
-the same way the frontend is, the two agree and the bug hides — or, worse, a correct frontend
-"fails" against your buggy reference and you chase a phantom.
-
-If you catch yourself typing out an op's math to build an expectation, stop and generate it
-from ggml instead (see [The ggml-CPU oracle](#the-ggml-cpu-oracle)).
-
-> Trap: with one head (`H=1`) many layout orders coincide, so a single-head unit test can pass
-> against a wrong reference and give false confidence. Test at real dimensions (step 9).
-
----
-
-## Bisection strategy, coarse to fine
-
-Work from the cheapest, coarsest signal to the finest; each step narrows the search space for
-the next. Don't open a debugger until these have cornered the bug.
-
-### 1. Is it an OpenVINO bug at all?
-
-When the output *text* is bad but the graph runs end-to-end, first decide whether OV is even at
-fault, by comparing against a genuine ggml-CPU run of the **same model at the same commit**.
-
-> ⚠️ **A build with `-DGGML_OPENVINO=ON` has no CPU backend.** The OV backend registers as a
-> ggml *device* (`OPENVINO0`); no CPU device is registered (`llama-cli --list-devices` shows
-> only `OPENVINO0`). So every "CPU" knob silently runs OV: `env -u GGML_OPENVINO` and
-> `GGML_OPENVINO=""` do nothing (it's a device, not gated by that var), `--device none` runs
-> OV, and `GGML_OPENVINO_DEVICE=CPU` runs OV-on-CPU. "I compared CPU vs OV and they matched" is
-> really OV vs OV — a conclusion that has wasted days.
-
-The only reliable CPU reference is a second build with OV compiled out, at the same commit:
-
-```
-cmake -B build-cpu -DGGML_OPENVINO=OFF -DCMAKE_BUILD_TYPE=Release -DLLAMA_CURL=OFF
-cmake --build build-cpu --target llama-simple llama-eval-callback -j$(nproc)
-```
-
-Compare greedy on **`llama-simple`** (raw completion, no chat template — see the gotcha below):
-
-```
-./build-cpu/bin/llama-simple -m <model>.gguf -n 20 "The capital of France is" # true ggml CPU
-./build-ov/bin/llama-simple -m <model>.gguf -n 20 "The capital of France is" # OpenVINO
+# Debugging GGUF accuracy
+
+First identify the conversion path and failing boundary. Use the cheapest relevant comparison;
+there is no requirement to complete every diagnostic before inspecting the implicated code.
+
+| Execution path | Start with | Compare |
+|---|---|---|
+| Native decoder | [Architecture fixtures](../tests/test_data/arch_accuracy/README.md) | Full logits on identical histories: prefill, one-token decode, then cache append |
+| Native mmproj | [Encoder fixtures](../tests/test_data/mmproj_accuracy/README.md) | Same preprocessed pixels/features and indices, each modality, raw and adapted embeddings |
+| llama.cpp OpenVINO backend | [Backend isolation](#llamacpp-backend-isolation) below | Genuine ggml CPU execution versus the OpenVINO backend |
+
+Native builders and supplied cgraph decoders share converters, but have different graph construction
+and state/IO adaptation. Backend environment variables do not configure native frontend inference.
+See [testing](testing.md) for commands, acceptance criteria, and how to recognize skipped coverage.
+
+## Reference and precision
+
+Use the real llama.cpp/ggml CPU implementation as the reference for model outputs and
+layout-sensitive operations. A hand-written recurrence or NumPy layout transformation can repeat
+the implementation's misunderstanding. Simple elementwise checks with unambiguous closed forms
+may compute their expectations inline; see [operation tests](how_to_add_op.md#test-and-the-coverage-gate).
+
+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.
+
+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
+weights preserves the file's original quantization error; it does not recover the publisher's
+F32 weights. Keep these measurements separate and retain failed comparisons. See
+[quantization](quantization.md) for conversion losses, native precision controls, and memory costs.
+
+## Localize the failing boundary
+
+1. **Inputs:** align tokenization, prompts, chat templates, masks, positions, and preprocessing.
+ For mmproj, check temporal pairs, patch/window order, image range, audio frame layout, and
+ feature packing against [the input contracts](mmproj.md#graph-boundary).
+2. **Time or shape:** compare prefill with decode, then several sequence/image sizes on the
+ same request. Exercise nonzero positions, window boundaries, and state reset. A decode-only
+ failure suggests cache updates or shape-dependent indexing, but does not prove their guilt.
+3. **Adaptation:** compare native outputs before and after `GGUFMakeStateful`, `AdaptToGenAI`,
+ or `AdaptMmprojToGenAI` as appropriate. Use independent clones/requests and retain the same
+ logical inputs. For combined mmproj files, isolate vision and audio separately.
+4. **Intermediates:** compare corresponding tensors in element order using NMSE, absolute/relative
+ error, and cosine where norms are nonzero. Inspect the first material divergence, then test
+ whether correcting or bypassing it fixes the final output.
+5. **Regression:** reproduce the implicated operation at realistic dimensions and keep an oracle
+ fixture. Test all affected converter paths and rerun shared architecture/projector regressions.
+
+A cosine cliff localizes a discrepancy; it does not establish a permutation bug. A smooth slope
+can suggest accumulated numerical error but is not sufficient to exonerate structure. Sums,
+means, minima, and maxima cannot detect permutations. Equal sorted buffers with different element
+order support a layout hypothesis; unequal sorted buffers can also mean the wrong source region
+was selected. Check shapes, strides, offsets, and candidate source tensors before blaming arithmetic.
+
+Near an MoE boundary, compare router logits, selected expert IDs, and the selection cutoff margin.
+A small change near a tie can select another expert and amplify later differences. Identifying
+this sensitivity does not waive the agreed accuracy threshold.
+
+## llama.cpp backend isolation
+
+Use a compatible backend revision; the repository/ref used by CI are recorded in
+[the backend workflow](../../../../.github/workflows/job_gguf_llamacpp_validation.yml).
+For a model comparison, build ggml CPU and OpenVINO variants from the same llama.cpp revision.
+`GGML_OPENVINO_DEVICE=CPU` selects OpenVINO on CPU, not the ggml CPU oracle. Do not assume
+`--device none` or unsetting an unrelated variable bypasses a compiled-in backend.
+
+From that llama.cpp checkout, create an independent CPU reference build:
+
+```sh
+cmake -S . -B build-cpu -DGGML_OPENVINO=OFF -DCMAKE_BUILD_TYPE=Release -DLLAMA_CURL=OFF
+cmake --build build-cpu --target llama-simple llama-eval-callback --parallel
+./build-cpu/bin/llama-simple -m model.gguf -n 12 "The capital of France is"
+./build-ov/bin/llama-simple -m model.gguf -n 12 "The capital of France is"
```
-- **Both good** → port correct, done.
-- **CPU good, OV bad** → a genuine OV bug; localize with the steps below against `build-cpu`.
-- **Both bad** → only now may it be a shared llama.cpp/model/template issue; confirm the CPU
- build is genuinely OV-free (`--list-devices`) before believing it.
-
-> **The chat template hides the signal.** `llama-cli`/`llama-completion` apply the model's chat
-> template; a thinking model then emits `<think>` and reasons instead of completing, so greedy
-> output looks degenerate even when the math is fine. Use `llama-simple` for bisection; reserve
-> `llama-cli` for judging end-user quality *after* the math is verified.
-
-### 2. Graph bug or quantization?
-
-Run the **same quantized weights** through the CPU reference and OV, both greedy, and compare
-the first token. Reference right + OV wrong on identical weights ⇒ quantization is ruled out,
-it's a graph/conversion bug. Don't download a higher-precision model to "check quantization" —
-this already answered it for free (and big models often OOM in the frontend; see Gotchas).
-
-### 3. Prefill or decode?
-
-`-n 1` (prefill only) vs `-n 12` (prefill + decode). First token already wrong → the bug is in
-the prefill graph; ignore all state/KV/decode machinery. Prefill right, later tokens drift →
-suspect stateful bookkeeping, the KV/recurrent-state round-trip, or a decode-only path.
-
-### 4. First-divergence diff (highest-yield localization)
-
-Dump every node's output on both backends and diff in graph order. `llama-eval-callback` fires
-per ggml node and prints name, op, shapes and a per-tensor **`sum`** — a cheap, position-stable
-fingerprint. Node names repeat across layers/experts, so align the two logs **positionally**,
-not by name.
-
-```
-./build-cpu/bin/llama-eval-callback -m <model>.gguf -p "The capital of France is" -n 1 > /tmp/cb_ref.log 2>&1
-GGML_OPENVINO_DEVICE=CPU GGML_OPENVINO_STATEFUL_EXECUTION=1 \
- ./build-ov/bin/llama-eval-callback -m <model>.gguf -p "The capital of France is" -n 1 > /tmp/cb_ov.log 2>&1
-
-awk '/cb_eval:/{n=$2} /sum = /{print n"\t"$3}' /tmp/cb_ref.log > /tmp/ref_pos.txt
-awk '/cb_eval:/{n=$2} /sum = /{print n"\t"$3}' /tmp/cb_ov.log > /tmp/ov_pos.txt
-paste /tmp/ov_pos.txt /tmp/ref_pos.txt | awk -F'\t' '{
- d=$2-$4; if(d<0)d=-d; b=($4<0?-$4:$4); if(b<1)b=1; rel=d/b;
- flag=($1!=$3)?" NAME-MISMATCH":(rel>0.001?" <<< DIFF":"");
- printf "%3d %-26s ov=%-12s ref=%-12s%s\n", NR,$1,$2,$4,flag }'
-```
-
-Judgement calls, all learned the hard way:
-
-- **The first *visible* divergence is usually not the root cause** — often benign kernel
- rounding (a sub-0.2% matmul diff). Confirm a candidate by *eliminating* it (steps 6–7) and
- seeing the output change; never assume.
-- **Only tensors at subgraph boundaries carry real data** (see the trustworthy-tensor rule in
- step 5); interior nodes read `0` or stale, so a zero-vs-nonzero "difference" there is an
- artifact.
-- **The callback perturbs OV's graph split** (it forces boundaries) and may crash OV early, but
- the prefix is usually enough to find the *first* divergence. For a full-depth sweep that
- doesn't perturb the split, use `GGML_OPENVINO_DEBUG_OUTPUT` (step 5).
-- **Positional alignment holds only until node order/count diverges** between backends. Past the
- first genuine name mismatch, trust only rows where both names still agree.
-
-### 5. Per-layer sweep — element-wise cosine, never Min/Max/Mean
-
-> ⚠️ **A permutation-invariant statistic cannot see a permutation bug.** `sum`, mean, min and
-> max are unchanged when a tensor's elements are *reordered*. A whole class of bugs only reorders
-> correct values — partial-rotary rope rotating the wrong slice, a head-scramble from a bad
-> reshape/transpose, interleaved-vs-split-halves, any layout error on an axis a size-1 dim would
-> collapse. A statistic-based per-layer sweep then reports "small diffuse drift, no single broken
-> layer" — a false verdict that has sent debugging down a precision rabbit hole for a day.
-> **Never conclude "drift" from a permutation-invariant metric.**
-
-`GGML_OPENVINO_DEBUG_OUTPUT=1` prints First/Min/Max/Mean per *subgraph output* at its natural
-boundary (no split perturbation, no early crash), covering every layer to `result_output`. But
-compute **element-wise cosine** against the reference, not the printed statistics:
-
-```
-cos = dot(ov, ref) / (norm(ov) * norm(ref))
-```
+Here `build-ov` is the separately configured OpenVINO build. Raw completion avoids chat-template
+differences during bisection; test chat behavior separately with matched templates. If both runs
+fail, check the reference/model setup before attributing the problem to OpenVINO. If both produce
+coherent text, continue with the required numerical comparisons.
-Cosine is ~1.0 when the buffers agree elementwise and collapses the instant elements are
-reordered. Sweep it per layer on full-width, same-named, genuine-boundary tensors. The shape of
-the curve *is* the diagnosis:
+### Capturing intermediates
-- **A sharp cliff** at one layer (e.g. 0.999997 → 0.43 between neighbours) = a **localized
- structural bug** there. Align the cliff to what that layer does differently (e.g. "first layer
- downstream of a rope layer") to point at the op.
-- **A gentle monotone slope** from ~1.0 = genuine accumulating precision drift — a verdict you
- earn only when cosine *also* shows a smooth slope.
+`llama-eval-callback` captures ggml node outputs during execution. Its printed sums are useful
+for a preliminary scan; obtain full tensors for an elementwise comparison. Match node identity,
+shape, and execution step: names may repeat, and positional alignment ends when graphs diverge.
-To place both backends at every layer despite OV crashing early under the eval-callback, match
-the complete ggml-CPU eval-callback `sum` per layer (÷ element count) against the OV
-`DEBUG_OUTPUT` mean for the same layer: a small, one-signed, compounding diff with no single jump
-is a mildly biased op applied every layer; a single jump is a localized bug. (To gauge severity,
-bias logits with `-l <TOKEN_ID>±N` and bisect N until top-1 flips — a tight reference margin but
-a large OV displacement means real distortion, not a rounding-broken tie.)
+Backend instrumentation lives in `ggml/src/ggml-openvino/`, with CPU callback instrumentation in
+`common/debug.cpp`. Check the selected checkout for each control before using it; these are
+backend implementation details, not frontend API guarantees.
-> **Trustworthy-tensor rule (applies to steps 4, 5, 8).** ggml reuses scratch buffers, so an
-> interior tensor promoted to an output can read memory already clobbered by a later op — you get
-> plausible garbage. Only **persistent buffers** are safe to compare cross-backend: the
-> KV/recurrent-state caches (`cache_k/v/r/s`) and genuine subgraph-boundary outputs. A pure
-> `TRANSPOSE` that appears to change its element `sum` is diagnostic *of this artifact*, not of a
-> transpose bug. Promote at most **one** interior tensor per run; several at once perturb
-> allocation and corrupt each other. Confirming a cache write matches the reference also *bounds*
-> the bug: everything feeding it is correct, so the fault is downstream.
-
-### 6. Quant-path isolation — `GGML_OPENVINO_DISABLE_TYPES`
-
-Forcing a *type* to CPU is surgical: it moves only that quant type's tensors to ggml while
-leaving graph structure intact (unlike forcing an op, step 7). Two high-value moves:
-
-- Disable **one** suspect type to test whether that quant kernel is the culprit.
-- Disable **all** materialized quant types at once
- (`Q4_0,Q4_1,Q4_K,Q5_K,Q8_0,Q6_K,Q5_1,MXFP4`): every weight matmul then runs on ggml with
- bit-identical weights and OV executes only the f32/f16 structural ops. Still wrong ⇒ the bug is
- **structural**, every quant kernel decisively ruled out — a narrowing no single op-force gives.
-
-### 7. Op-family isolation — `GGML_OPENVINO_DISABLE_OPS`
-
-`ggml_backend_openvino_device_supports_op()` decides per op whether OV claims it or ggml's CPU
-kernel runs. `GGML_OPENVINO_DISABLE_OPS=SSM_CONV,DIV` forces the listed ops to CPU; binary-search
-the suspect set. For a novel arch, start with the arch-specific ops (shared ops are already
-exercised by working models).
-
-- **Output correct** → that op (or its glue) was the bug.
-- **Output unchanged** → op exonerated.
-- **New crash / shape error** → *inconclusive*, not guilt: forcing an op re-splits the graph and
- can surface an unrelated boundary bug. Try another combination, or go to the op-level test.
-
-### 8. Pinpoint a layout / wrong-source bug — full-element dumps, multiset, distribution matching
-
-A cosine cliff (step 5) says *where* the graph scrambles and *that* the bug is a permutation, not
-arithmetic. It doesn't say *what* the wrong tensor is a permutation *of* — usually the whole
-answer, because a scramble means the op read the **wrong source region** (a neighbouring head,
-the sibling half of a joint projection, a strided window read as contiguous).
-
-Dump full element order (not statistics) on both backends:
-
-- OV: `GGML_OPENVINO_DUMP_TENSOR=<name-substr>` → `/tmp/ov_dump_*`, one float per line.
-- CPU: `GGML_DUMP_TENSOR=<name-substr>` (ggml eval-callback) → `/tmp/ref_dump_*`.
-
-Then two comparisons in order:
-
-1. **Multiset (sorted) comparison — layout vs math.** Sort both dumps' nonzero values and
- compare. Sorted-match ≈ 1.0 but position-wise cosine low ⇒ the numbers are right, only
- positions wrong: a pure layout/read bug — look at layout, not any kernel's math. Sorted-match
- also low ⇒ the values differ: a real arithmetic bug — back to steps 6–7 and the oracle.
-2. **Distribution matching against multiple candidate references — the wrong-source finder.**
- When step 1 says "right numbers, wrong place," the values came from *somewhere*. Dump several
- candidate reference tensors near the suspect (the sibling projection half, the adjacent head,
- the pre-/post-transform version) and compare the OV tensor's distribution (sorted multiset;
- range/mean/std as a quick fingerprint) to each. "OV's X matches the reference's *Y*, not X"
- names the region the op wrongly grabbed. (Obey the trustworthy-tensor rule.)
-
-Then read the offending op's layout directly. Very often it's a `VIEW`/reshape: dump its ggml
-geometry (`ne[]`, `nb[]` strides, offset) and the `op_case` the decoder assigned. A view whose
-source is strided/gapped (stride ≠ extent, a sub-block of a larger group) but classified as a
-*dense contiguous* window is the bug — the contiguous handler slices through the gap and
-scrambles elements. Fix the **classification** (a stride/density check that routes the strided
-case to a stride-aware handler), not the consumer. `GGML_OPENVINO_DUMP_CGRAPH=1` gives `ne[]`; a
-temporary `getenv`-gated `fprintf` at the classification site gives `nb[]`/offset/op_case.
-
-### 9. Reproduce at the op level with a ggml oracle
-
-Once an op is implicated, stop testing through the full model and reproduce it in the frontend's
-unit tests (`tests/test_ops.cpp`), which build a one-op `ov::Model` via `SingleOpBuilder` and run
-on CPU in milliseconds. This is where the bug is pinned and the regression test lives.
-
-Feed **real model dimensions**, not `1×1×1` — most layout bugs live on an axis a size-1 dim
-collapses: multi-head (`H>1`), GQA repeat (`H_v ≠ H_k`), multi-token (`T>1`), batch (`B>1`). Pull
-the real shapes from a cgraph dump (`GGML_OPENVINO_DUMP_CGRAPH=1`). A test that passes at `H=1`
-proves nothing about a model that uses `H=32`.
-
----
+| Control | Purpose |
+|---|---|
+| `GGML_OPENVINO_STATEFUL_EXECUTION=1` | Exercise backend KV/recurrent state handling |
+| `GGML_OPENVINO_DUMP_CGRAPH=1` | Inspect subgraph operations and tensor geometry |
+| `GGML_OPENVINO_DEBUG_INPUT=1` / `GGML_OPENVINO_DEBUG_OUTPUT=1` | Inspect bound subgraph inputs/outputs and summary statistics |
+| `GGML_OPENVINO_DUMP_TENSOR=<substring>` | Capture matching OV outputs in element order |
+| `GGML_DUMP_TENSOR=<substring>` | Capture matching CPU eval-callback tensors |
+| `GGML_OPENVINO_DUMP_IR=1` | Inspect serialized graphs, subject to [internal-op limits](runtime.md#internal-operations-and-serialization) |
+| `GGML_OPENVINO_FORCE_F32=1` | Investigate backend precision differences |
+| `GGML_OPENVINO_DISABLE_TYPES=Q8_0,Q6_K` | Isolate handling of selected quantized types |
+| `GGML_OPENVINO_DISABLE_OPS=SSM_CONV,DIV` | Investigate selected operation families through backend fallback |
+
+Capture tensors while their buffers are valid. ggml scratch memory can be reused after an
+operation, so a later read of an interior tensor can be stale. Genuine boundary outputs and
+appropriately captured caches are useful comparison points. Promoting extra outputs or enabling
+callbacks can change allocation and graph partitioning; a new crash under instrumentation is
+inconclusive. Matching a cache write bounds only the compared branch, not every parallel path.
+
+Fallback experiments can change graph partitioning, precision, and boundary handling. Correct
+output after disabling an operation implicates that path or its integration, not necessarily
+the kernel itself. Unchanged output does not exonerate it if another error masks its effect.
+Enumerate the types actually present before attempting to isolate quantization; a fixed list
+of formats is not proof that every quantized operation has been bypassed.
## The ggml-CPU oracle
-For ground-truth op values, build a tiny C program that links `libggml` + `libggml-cpu`, builds a
-one-node graph, runs it on CPU, and prints the output — those numbers become the `expected`
-array. `tests/gdn_oracle.c` is a worked example; copy its structure.
+Build a small program linking the same ggml CPU libraries as the reference. Construct a graph,
+fill asymmetric inputs, run it, and save all outputs. Existing examples include
+[`gdn_oracle.c`](../tests/gdn_oracle.c), [`ssm_scan_oracle.c`](../tests/ssm_scan_oracle.c), and
+[`imrope_oracle.c`](../tests/imrope_oracle.c). With `LLAMA_SRC` and `LLAMA_BUILD` pointing to the
+CPU-only checkout and build:
-```
-gcc <op>_oracle.c -o <op>_oracle \
- -I <llama.cpp>/ggml/include \
- -L <llama.cpp>/build-ov/bin -lggml -lggml-base -lggml-cpu -lm \
- -Wl,-rpath,<llama.cpp>/build-ov/bin
-LD_LIBRARY_PATH=<llama.cpp>/build-ov/bin ./<op>_oracle
+```sh
+cc op_oracle.c -o op_oracle -I "$LLAMA_SRC/ggml/include" \
+ -L "$LLAMA_BUILD/bin" -Wl,-rpath,"$LLAMA_BUILD/bin" -lggml -lggml-base -lggml-cpu -lm
+./op_oracle
```
-- **Link against the same `libggml` the backend uses.** A stale tree can assert on a different
- shape than the source you're reading.
-- Set `no_alloc = true` when using `ggml_backend_alloc_ctx_tensors`.
-- Read the op's shape contract from the **header** (`ggml.h`); don't guess `ne[]` order.
-- Fill inputs with distinct, asymmetric values so a transposed/mis-strided axis changes a number.
-- If the op has more than one conversion path (e.g. a fused internal op and a decomposed Loop
- fallback), assert **both** against the oracle — matching a shared oracle proves both correct.
+Read the operation's dimension contract in `ggml.h`; use `no_alloc = true` with
+`ggml_backend_alloc_ctx_tensors`. Include multiple heads/tokens and unequal query/KV dimensions
+where relevant. Assert fused and decomposed converter paths against the oracle. Model and encoder
+oracles have separate [regeneration instructions](testing.md#fixtures-and-oracles).
----
+## Recurring failure patterns
-## Bug archetypes
-
-Concrete structural bugs seen so far, each with the generalizable lesson. When a cosine cliff or
-a dynamic-shape crash points near one, check it first.
-
-**A. Geometry read from the tensor instead of the config.** Partial-rotary rope: a head is 256
-wide but only the first 64 dims rotate; taking the rotary width from the tensor's last dim (256)
-rotates the pass-through tail and corrupts every layer using that op. *Lesson: an op must read
-its geometry (rotary width, head count) from the model config, not a tensor dim — the two differ
-whenever a dimension is partial. A test at full width can't catch it.*
-
-**B. A shared precomputed table built with the wrong config flag.** A sin/cos table computed once
-and shared across layers must be built with the same per-op config its consumers assume; a mode
-flag defaulting wrong makes the table's token axis mismatch the data and broadcast-crashes at the
-consuming `Multiply`. *Lesson: a shared/precomputed value must be built with the consumer's
-config; the symptom is a shape/broadcast mismatch, not a wrong number.*
-
-**C. A dynamic-axis slice with a baked absolute offset.** A tail slice (the last *k* columns of a
-window whose length varies prefill vs decode) emitted with an absolute start computed at prefill
-over-reads at decode. *Lesson: anchor a slice to the end it's pinned to — negative start, open
-end — never to an offset baked at prefill.*
-
-**D. A strided VIEW mis-classified as contiguous.** An interleaved layout
-(`[A_h0, B_h0, A_h1, B_h1, …]`) gives a per-`A` view a group stride larger than its extent;
-classified as a dense window, the contiguous handler slices through the gap and scrambles heads.
-*Lesson: a VIEW's handler must be chosen from its strides (`nb[]`), not its element count — two
-views with identical shape and offset but different strides need different handlers.*
-
-> Meta-pattern behind all four: a value *correct for prefill / the common case* (full head, one
-> rope mode, prefill length, a contiguous layout) is hard-coded instead of read from the true
-> per-op/per-step geometry, so it silently breaks at decode or on a different architecture.
-
-> **After any shared-path fix — especially a VIEW/`op_case` predicate — re-run the other
-> supported models and confirm their classification/output is unchanged.** A stride/density guard
-> that fixes arch A can reject arch B's legitimately-contiguous view.
-
----
-
-## Debug env vars
-
-Backend seams live in `ggml/src/ggml-openvino/`. Gate any new debug output on a `getenv` check
-and write to `stderr`.
-
-| Env var | Effect |
+| Pattern | What to inspect |
|---|---|
-| `GGML_OPENVINO_DEVICE=CPU` | Run OV on CPU. (Still OV, not ggml — see step 1.) |
-| `GGML_OPENVINO_STATEFUL_EXECUTION=1` | Enable the stateful KV/recurrent-state path (real decode flow). |
-| `GGML_OPENVINO_DUMP_CGRAPH=1` | Dump each OV subgraph as `cgraph_ov_N.txt` — ops, names, per-tensor `ne[]`. Primary tool for real op dimensions and how the graph split. |
-| `GGML_OPENVINO_DUMP_IR=1` | Serialize each compiled subgraph to `model_*.xml`. Unavailable for models with internal (non-serializable) ops. |
-| `GGML_OPENVINO_DEBUG_INPUT=1` / `_DEBUG_OUTPUT=1` | Print each bound input / output tensor (name, shape, First/Min/Max/Mean). |
-| `GGML_OPENVINO_DUMP_TENSOR=<substr>` | Dump **full element order** of each matching OV output to `/tmp/ov_dump_*` (one float/line) — for the position-wise + multiset compare of step 8; not permutation-invariant. |
-| `GGML_DUMP_TENSOR=<substr>` (ggml `common/debug.cpp`) | CPU-reference counterpart: matching tensors from the ggml eval-callback, in element order. |
-| `GGML_OPENVINO_DISABLE_OPS=SSM_CONV,DIV` | Force listed ggml ops to CPU (step 7). Re-splits the graph — a new crash is inconclusive. |
-| `GGML_OPENVINO_DISABLE_TYPES=Q8_0,Q6_K` | Force listed quant types to CPU without changing graph structure (step 6). |
-| `GGML_OPENVINO_FORCE_F32=1` | Pin the plugin to f32 ACCURACY mode to test bf16 rounding accumulation. |
-| `GGML_OPENVINO_PROFILING=1` | Per-stage timing (decode/convert/compile/infer). |
-| `GGML_OPENVINO_PRINT_CGRAPH_TENSOR_ADDRESS=1` | Tensor address map (trace pointer aliasing between subgraphs). |
-
-The frontend converter carries no env-var debug seams — keep them in the backend. When an op has
-two conversion strategies, expose the alternate as an op attribute (e.g. GatedDeltaNet's
-`force_ref` selects the serializable Loop path) so a unit test can pick it via `SingleOpBuilder`
-without touching process env or the production default.
-
----
-
-## Gotchas
-
-- **Big models OOM in the frontend, not just in weight RAM.** Quant types in `supported_types`
- are materialized as OV constants *in addition to* ggml's copy, ~doubling peak compile memory.
- Reducing `-c` doesn't help (the blow-up is per-subgraph compilation, not the KV cache). A Q4_K
- model can OOM where the same-arch Q2_K runs (Q2_K isn't in `supported_types`, stays on CPU).
- Exit 137 = OOM-killed.
-- **Iterate on a small quant.** BF16 of a 4B model can take ~25 min to load/compile; Q4_K_M loads
- in seconds and reproduces the same *structural* bugs. Reach for higher precision only if step 2
- implicates quantization.
-- **Per-subgraph vs shared runtime state.** A model that splits into many subgraphs per token step
- must not share single-value bookkeeping across them (e.g. `stateful_kv_size` belongs on the
- per-subgraph context, not the shared one) — a shared counter advances once per subgraph and
- mis-slices state. Symptom: a ROI error at the *second* decode step, not the first.
-- **An old reference build can predate the arch** and segfault on load — then it can't be the
- reference; use a fresh `-DGGML_OPENVINO=OFF` build at the current commit (step 1).
-- **Shell:** piped `llama-*` output buffers and never flushes — redirect to a file and grep it.
- `cd` doesn't persist between calls (use absolute paths). `pkill -9 -f llama` between runs so
- stale processes don't starve cores.
-
----
-
-## Checklist
-
-1. **Is it an OV bug?** `build-cpu` (`-DGGML_OPENVINO=OFF`) vs `build-ov`, greedy, on
- `llama-simple`. CPU good + OV bad = OV bug. Both bad = shared (build/tokenizer/template), stop
- debugging OV.
-2. **Graph or quant?** Same weights, CPU ref vs OV. Wrong on OV only → graph bug, not quant.
-3. **Prefill or decode?** `-n 1` vs `-n 12`.
-4. **First-divergence diff** (`llama-eval-callback`, positional `sum` diff) → first node past
- rounding. Highest-yield step.
-5. **Per-layer sweep with element-wise cosine**, never Min/Max/Mean. Cliff = localized structural
- bug; smooth slope = drift. Never conclude "drift" from a permutation-invariant metric.
-6. **`DISABLE_TYPES=<all quant>`** → still wrong ⇒ structural (f32) bug, quant ruled out.
-7. **`DISABLE_OPS`** to force a suspect op to CPU; binary-search. Correct = culprit; new crash =
- inconclusive (re-split artifact).
-8. **Layout pinpoint:** full-element dumps → multiset compare. Sorted-match high + cosine low =
- layout/wrong-source bug; match the distribution against candidate references to name the
- source. For a `VIEW`, inspect `nb[]` + `op_case`, not just `ne[]`.
-9. **Op-level test** in `test_ops.cpp` at real dimensions (H, GQA, T, B not collapsed), against a
- **ggml-CPU oracle**, never a hand-derived reference; assert every conversion path; leave it as
- a regression guard.
-10. **Cross-arch regression:** after any shared-path fix, re-run the other supported models.
-
-> Only a divergence you can *eliminate* — and thereby fix the output — is the real culprit; the
-> first visible one is often benign rounding.
+| Partial rotary geometry | Read rotary width/offset from the operation configuration; do not rotate a whole head when only part is rotary |
+| Shared RoPE tables | The table and each consumer must agree on mode, dimensions, and position sections |
+| Dynamic tail slices | Derive offsets from the live length; a prefill offset can overrun during decode |
+| Strided VIEW treated as dense | Inspect `ne[]`, `nb[]`, element offset, and semantic `op_case`; shape alone does not establish contiguity |
+| Recurrent state shared across subgraphs | Keep per-subgraph bookkeeping separate and test beyond the first decode step |
+| Media adaptation mismatch | Check modality pruning, removed input prefixes, DeepStack splitting, and separate Gemma4 per-layer embeddings |
+
+Use small fixtures while localizing. Compilation may materialize additional weight buffers;
+reducing context length does not resolve weight-related memory pressure. Record peak memory for
+large checkpoints. Redirect long-running command output to a file; retain the launched PID and
+terminate that process if necessary, rather than killing every process matching a model runner name.
diff --git a/src/frontends/gguf/docs/extensions.md b/src/frontends/gguf/docs/extensions.md
new file mode 100644
index 00000000000..18b51d86564
--- /dev/null
+++ b/src/frontends/gguf/docs/extensions.md
@@ -0,0 +1,199 @@
+# Extending the GGUF frontend
+
+Extensions add architecture or projector builders, operation converters or normalization passes to
+one GGUF frontend instance, as C++ objects or from a shared library, without rebuilding OpenVINO.
+The builder headers in [`dev_api/openvino/frontend/gguf`](../dev_api/openvino/frontend/gguf) ship
+with the frontend development package (`openvino::frontend::gguf`) and have no compatibility
+guarantee across releases: build against the release that will load the extension (C++17).
+
+## Choose an extension
+
+| What you need | Extension | Register before |
+|---|---|---|
+| New architecture with the existing decoder topology | `ov::frontend::gguf::ArchitectureExtension` with a decoder definition | `load()` |
+| Different topology or model family | `ArchitectureExtension` with a `ModelBuilder` factory | `load()` |
+| Add or override one mmproj encoder/projector branch | `ov::frontend::gguf::ProjectorExtension` | `load()` |
+| Add or override an operation converter | `ov::frontend::ConversionExtension` | `convert()` |
+| Prepare a stateful decoder with GenAI IO | `ov::frontend::gguf::GenAIExtension` | `convert()` |
+| Change state handling or the model interface | `ov::frontend::DecoderTransformationExtension` | `convert()` |
+
+Architecture and projector extensions apply only to native `.gguf` files; converters and passes
+apply to both input paths. None of them add quantization formats, tokenization, preprocessing or a
+device backend. Extensions attached to an `ov::BaseOpExtension` and shared-library wrappers are
+unwrapped; a bare custom operation supplies no GGML converter. `TelemetryExtension` is stored but
+never invoked; other types are ignored.
+
+## Lifecycle
+
+Use one frontend instance for registration, loading and conversion:
+
+```cpp
+#include "openvino/frontend/gguf/extension/architecture.hpp"
+#include "openvino/frontend/manager.hpp"
+
+ov::frontend::FrontEndManager manager;
+auto frontend = manager.load_by_framework("gguf");
+frontend->add_extension(std::make_shared<ov::frontend::gguf::ArchitectureExtension>(
+ "my-decoder", ov::frontend::gguf::RopeMode::Neox));
+auto model = frontend->convert(frontend->load("my-decoder.gguf"));
+```
+
+1. `load()` parses the file, resolves the architecture handler and saves it with a snapshot of the
+ projector registry. Later registrations affect only later loads.
+2. `convert()` merges built-in and registered converters, builds a fresh graph through the selected
+ `ModelBuilder`, and resolves each mmproj modality against the saved projector registry.
+ `GgufGraphContext::node()` invokes converters immediately, so builders see inferred shapes.
+3. Normalization runs extension passes in registration order, after marking compressed constants and
+ before `LowerSetRowsStateless` and the remaining cleanup.
+
+Registrations on another frontend, or on a consumer that does not forward them, have no effect.
+
+## Architecture extensions
+
+The short constructor takes the literal `general.architecture` and its RoPE mode. When tensors and
+metadata cannot determine a choice, pass a definition with options:
+
+```cpp
+using namespace ov::frontend::gguf;
+auto definition = make_decoder_architecture(
+ "my-decoder", RopeMode::Neox,
+ [](const GgufMetadata&) {
+ DecoderOptions options;
+ options.geglu = true;
+ return options;
+ });
+frontend->add_extension(std::make_shared<ArchitectureExtension>(definition));
+```
+
+`ArchitectureExtension(ArchitectureDefinition)` also accepts a custom `ModelBuilder` factory with no
+RoPE mode. See [architectures.md](architectures.md) for options, builders, porting and validation.
+
+### Matching and replacement
+
+A handler matches on `general.architecture`, then its optional predicate. Handlers with different
+ids may share an architecture only with disjoint predicates; if two claim one file, loading fails
+regardless of order. For mmproj branches use `ProjectorExtension`, not another `clip` handler.
+
+`RegistrationMode::Add` (default) rejects a duplicate id. To replace a handler, including a built-in,
+keep its id and register with `RegistrationMode::Replace`:
+
+```cpp
+frontend->add_extension(std::make_shared<ArchitectureExtension>(definition, RegistrationMode::Replace));
+```
+
+Replacing an unknown id fails; a new id for a claimed architecture causes an ambiguous match.
+Replacement affects only this frontend's registry, and `ArchRegistry::supported_archs()` reflects it.
+
+## Extend mmproj with a projector component
+
+`ProjectorExtension` derives from `ArchitectureExtension` and is packaged the same way, but registers
+in a separate projector registry. It builds one vision or audio branch; the `clip` coordinator
+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.
+
+A `ProjectorDefinition` has `id`, `architecture`, `modality` (`vision` or `audio`),
+`projector_type`, `build` and optional `match`. `build` appends to the shared `GgufGraphContext` and
+returns `ProjectorResult`: the output and optional string configuration under the modality prefix.
+It must not call `finish()` or register the primary output; extra inputs need unique names. A
+predicate may distinguish variants of one resolved type; two matching handlers are an error.
+
+Reuse a built-in topology for a new projector type when the metadata and weights are compatible:
+
+```cpp
+#include "openvino/frontend/gguf/extension/projector.hpp"
+
+using namespace ov::frontend::gguf;
+ProjectorDefinition definition{
+ "clip.vision.my-gemma3", "clip", "vision", "my-gemma3",
+ [](GgufGraphContext& graph) {
+ return build_builtin_projector(graph, "vision", "gemma3");
+ },
+ {}};
+frontend->add_extension(std::make_shared<ProjectorExtension>(definition));
+```
+
+A new topology instead builds its branch from `graph.metadata()`, `graph.tensors()` and `graph.node()`:
+
+```cpp
+ProjectorDefinition audio{
+ "clip.audio.example", "clip", "audio", "example-audio",
+ [](GgufGraphContext& graph) {
+ auto input = graph.add_input("audio.example_input", ov::element::f32, {1, 1, -1, 8});
+ auto output = graph.node("GGML_OP_SCALE", {input}, 0, {{"scale", 2.0f}, {"bias", 0.0f}});
+ return ProjectorResult{output, {{"audio.merge", "1"}}};
+ },
+ {}};
+```
+
+To replace one built-in branch, reuse its id (for example `clip.vision.gemma3`) with
+`RegistrationMode::Replace`; other branches and the `clip.mmproj` coordinator stay active. The
+component list comes from `ArchRegistry::projectors().supported_projectors()`. An architecture other
+than `clip` would also need its own whole-model coordinator.
+
+## Add or override an operation converter
+
+Register an `ov::frontend::ConversionExtension` whose converter takes `const NodeContext&` and returns
+an indexed `ov::OutputVector`; named-output overloads are unused. Match the exact emitted string:
+
+```cpp
+#include "openvino/frontend/extension/conversion.hpp"
+#include "openvino/op/negative.hpp"
+
+frontend->add_extension(std::make_shared<ov::frontend::ConversionExtension>(
+ "EXAMPLE_NEGATE",
+ [](const ov::frontend::NodeContext& context) -> ov::OutputVector {
+ OPENVINO_ASSERT(context.get_input_size() == 1, "EXAMPLE_NEGATE requires one input");
+ auto result = std::make_shared<ov::op::v0::Negative>(context.get_input(0));
+ result->set_friendly_name(context.get_name());
+ return {result};
+ }));
+```
+
+A builder can then call `graph.node("EXAMPLE_NEGATE", {value})`. Use the base `NodeContext`
+interface (`get_attribute<int>("op_case", 0)` for the case); GGUF's concrete one is internal. A
+same-named extension overrides the built-in converter and the last registration wins. Preserve the
+operation's semantics, types and layout. For a built-in converter see [how_to_add_op.md](how_to_add_op.md).
+
+## Register normalization passes
+
+`DecoderTransformationExtension` wraps a pass or a `std::shared_ptr<ov::Model>` function and runs
+during normalization, before built-in lowerings. For a GenAI-ready decoder, register
+`GenAIExtension` instead: it owns stateful conversion and adaptation after normalization.
+Do not also register `GGUFMakeStateful` or `AdaptToGenAI` on that frontend. Register one
+`GenAIExtension` per frontend instance; it applies to every conversion on that instance.
+Its embedding lookup getters describe the latest successful conversion.
+See [runtime.md](runtime.md#stateful-and-genai-conversion).
+
+## Build and load a shared library
+
+Export extensions with `OPENVINO_CREATE_EXTENSIONS`, as in
+[`extension.cpp`](../examples/architecture_extension/extension.cpp); one list may mix all types.
+The [example README](../examples/architecture_extension/README.md) builds the decoder, whole-model
+projection and mmproj plugins and runs them. Load a library through the base frontend interface:
+
+```cpp
+frontend->add_extension("/tmp/gguf-extensions/libgguf_projector_extension.so");
+auto model = frontend->convert(frontend->load("projector.gguf"));
+```
+
+Loaded input models keep the libraries their builder needs alive.
+
+## Validate and troubleshoot
+
+Load the actual library, convert a matching file and compare with the reference as described in
+[architectures.md](architectures.md#validate). Existing coverage lives in
+[`test_architecture_extension.cpp`](../tests/test_architecture_extension.cpp),
+[`test_builder_api.cpp`](../tests/test_builder_api.cpp),
+[`test_extensions.cpp`](../tests/test_extensions.cpp),
+[`test_mmproj.cpp`](../tests/test_mmproj.cpp) and `ov_gguf_architecture_library_tests`.
+
+| Symptom | Check |
+|---|---|
+| GGUF absent from automatic frontend selection | Use `load_by_framework("gguf")`; the frontend is hidden from `read_model()` |
+| Unsupported architecture | Register before `load()`; check the literal string and predicate |
+| Duplicate id or unknown replacement | `Add` for new ids, `Replace` only for existing ids |
+| Two handlers claim a file | Make predicates disjoint or replace the existing handler |
+| Unsupported mmproj projector | Register a `ProjectorExtension` before `load()`; check modality and resolved type |
+| Missing operation converter | Register the exact string on the same frontend before `convert()` |
+| Cache remains stateless | Register `GenAIExtension` for GenAI IO, or `GGUFMakeStateful` for GGUF IO, before `convert()` |
+| Outputs differ from the reference | Follow [debugging_accuracy.md](debugging_accuracy.md) |
diff --git a/src/frontends/gguf/docs/how_to_add_op.md b/src/frontends/gguf/docs/how_to_add_op.md
index afaeb917f71..72908a45275 100644
--- a/src/frontends/gguf/docs/how_to_add_op.md
+++ b/src/frontends/gguf/docs/how_to_add_op.md
@@ -1,23 +1,27 @@
# Adding an op translator to the GGUF frontend
-Procedure for enabling a ggml operation. For the *concepts* behind it — the two decoder paths, the
-`GGML_OP_NONE` weight convention, `op_case` numbering, the memory model — read
-`frontend_design.md` first; this document does not repeat them.
+Procedure for enabling a ggml operation. Start with the [two input paths](../README.md),
+[tensor/layout contracts](architectures.md#tensor-operations-and-shapes), and
+[weight representations](quantization.md). Weight leaves use `GGML_OP_NONE` and supply data
+to `translate_weight`; input leaves use the same op name but are resolved to Parameters first.
-Related: [adding_an_architecture.md](adding_an_architecture.md) (enabling a model family, which
+Related: [architectures.md](architectures.md) (enabling a model family, which
usually needs *no* new op), [debugging_accuracy.md](debugging_accuracy.md) (when a translator
converts but produces wrong numbers).
+To supply a converter from an external library without modifying the built-in table, use
+[`ConversionExtension`](extensions.md#add-or-override-an-operation-converter). Register it on the
+same frontend as any architecture or projector extension before conversion.
+
## Before writing a translator
Check that an op translator is actually what is missing:
-- **A new architecture** normally needs only an entry in `arch_registry.cpp` — see
- [adding_an_architecture.md](adding_an_architecture.md). Reach for a translator only when the graph
- genuinely contains a ggml op the table does not have.
+- **A new architecture or projector** needs an appropriate [builder registration](extensions.md#choose-an-extension).
+ Add a translator only when its computation needs an operation missing from the table.
- **A structurally different use of an existing op** is an `op_case`, not a new translator. Read the
- `op_case` section of `frontend_design.md` before adding a case — a case that
- exists only to mean "this came from the builder" is a defect.
+ [tensor operation contracts](architectures.md#tensor-operations-and-shapes) before
+ adding a case. Its number selects a converter's semantic variant, not the decoder's identity.
- Both decoder paths (native builder and llama.cpp cgraph) share translator bodies, so a change here
affects both. Keep the body path-agnostic; branch on `op_case`, never on "which decoder made this".
@@ -63,6 +67,11 @@ Always finish with `rename_outputs_with_suffix(..., context.get_name())`: the wa
the `TensorMap` under the decoder's output names, and stable friendly names are what the passes and
the graph-fingerprint gate rely on.
+A ggml node has one output. A native builder may declare more with `add_op(..., extra_outputs)`;
+the translator then returns one output per name, in order. `GATED_DELTA_NET` uses this
+(`split_outputs`) to return the attention and the new recurrent state separately instead of
+ggml's packed tensor.
+
`NodeContext` ([`src/node_context.hpp`](../src/node_context.hpp)):
| Call | Purpose |
@@ -146,15 +155,13 @@ TEST(GGUFOps, Scale) {
`SingleOpBuilder` drives the real `FrontEnd::convert` through an in-memory `SingleOpDecoder`, so no
`.gguf` file is involved. Helpers are in [`op_test_utils.hpp`](../tests/op_test_utils.hpp).
-**Where the expected values come from matters more than the test's shape.** Per the one rule in
-[debugging_accuracy.md](debugging_accuracy.md), the reference must come from real ggml, not from
-your own reading of the op's math:
+Use the [reference policy](debugging_accuracy.md#reference-and-precision):
- Simple elementwise ops with an unambiguous closed form — compute inline in the test.
- Anything with layout, geometry or head structure (rope, conv, attention, views) — generate the
- reference from ggml-CPU: an `.npy` fixture via `gen_ggml_reference.c`,
- or a standalone oracle such as `ssm_conv_oracle.c` / `imrope_oracle.c`, and paste its output with a
- comment naming the oracle.
+ reference from ggml-CPU with a standalone oracle such as `ssm_conv_oracle.c` / `imrope_oracle.c`
+ (see [the ggml-CPU oracle](debugging_accuracy.md#the-ggml-cpu-oracle)). Commit the oracle with the
+ test and name it in a comment next to the pasted or `.npy` expectations.
Test at realistic dimensions. With one head many layout orders coincide, so a single-head test can
pass against a wrong reference.
@@ -166,32 +173,15 @@ tuned only on fp32 x86 will fail there.
To find the closest existing example without reading the whole (large) file:
```bash
-grep -n "^TEST(" src/frontends/gguf/tests/test_ops.cpp
+rg -n '^TEST\(' src/frontends/gguf/tests/test_ops.cpp
```
## Build and run
-The frontend is **off by default** (`ENABLE_OV_GGUF_FRONTEND` in
-[`cmake/features.cmake`](../../../../cmake/features.cmake)); without it the test target does not
-exist.
-
-```bash
-cmake -B build -DENABLE_OV_GGUF_FRONTEND=ON -DENABLE_TESTS=ON
-cmake --build build --target ov_gguf_frontend_tests -j$(nproc)
-
-# iterate on one op ...
-./build/bin/*/*/ov_gguf_frontend_tests --gtest_filter='GGUFOps.<Name>*'
-# ... then unfiltered, so the coverage gate actually runs
-./build/bin/*/*/ov_gguf_frontend_tests
-```
-
-CI runs the same binary in the "GGUF frontend tests" step of
-[`job_cxx_unit_tests.yml`](../../../../.github/workflows/job_cxx_unit_tests.yml), ungated by Smart CI.
-
-For a change that touches a shared translator or a VIEW/`op_case` predicate, also re-run the
-graph-fingerprint check ([`tests/graph_fingerprint.py`](../tests/graph_fingerprint.py)) across the
-supported architectures: a guard that fixes one arch can reject another's legitimately-contiguous
-view.
+Follow [testing.md](testing.md) for build flags, binary paths, filters, and CI coverage.
+Run the frontend binary unfiltered before finishing so the operation-coverage gate executes.
+Shared translator or VIEW/`op_case` changes also need architecture fingerprints and numerical
+regressions: a guard that fixes one model can reject another's legitimately contiguous view.
## Bringing up a model that hits a missing op
diff --git a/src/frontends/gguf/docs/internal_ops.md b/src/frontends/gguf/docs/internal_ops.md
deleted file mode 100644
index 4a8de472000..00000000000
--- a/src/frontends/gguf/docs/internal_ops.md
+++ /dev/null
@@ -1,74 +0,0 @@
-# GGUF Frontend — Internal Operations Policy
-
-## Summary
-
-OpenVINO frontends are, as a rule, thin translators: they emit only ops from the
-public opsets so that the produced `ov::Model` is portable and serializable to IR.
-The GGUF frontend makes a **scoped, deliberate exception**: it is allowed to emit
-ops from the shared internal opset (`ov::op::internal`, defined in `core`'s
-`dev_api`) when doing so materially simplifies translation or lets the target device
-use a fused kernel instead of a hand-built subgraph.
-
-This is a pragmatic tradeoff, not a general license. It applies to the GGUF frontend
-only, and only to ops that already ship as part of OpenVINO core (with registered
-`type_info`, shape inference, a reference implementation, and plugin support). The
-frontend never defines its own operations.
-
-## Why this is acceptable here
-
-Unlike a frontend-private op, a shared `ov::op::internal` op is known to the rest of
-the stack:
-
-- It has a registered `type_info`, so plugins link against it, and passes,
- matchers, and `visualize_tree` recognize it.
-- Plugins that support it natively keep it (e.g. the fused CPU/GPU
- `GatedDeltaNet` kernels); plugins that do not can decompose it in their own
- pipeline. No mandatory frontend-side decomposition is forced on every consumer.
-- Shape inference and a reference `evaluate` already exist and are tested in core,
- so `PartialShape` propagation and CPU fallback work without extra frontend code.
-
-The GGUF frontend is also a `LINKABLE_FRONTEND` consumed directly by the
-`llama.cpp` `ggml-openvino` backend and by OpenVINO GenAI, both of which build and
-run the model in-process on a device. Neither relies on IR serialization, so the
-main cost of internal ops (below) does not affect the primary use cases.
-
-## The cost: models are not IR-serializable
-
-An `ov::op::internal` op is **not** part of any IR serialization opset. A model that
-contains one cannot round-trip through `ov::save_model` / the IR frontend, which also
-means the following flows do not work for such a model:
-
-- `ov::save_model`, `ovc`, and `benchmark_app -o`
-- model caching (`ov::cache_dir`) and offline `compile_model` blob export
-- weightless-cache flows
-
-**Important behavioral note:** serialization does not currently fail loudly. An
-internal op has no opset `version_id`, so `ov::pass::Serialize` writes it with
-`version="experimental"` and `save_model` *succeeds*. The resulting IR is unloadable
-and fails only later, at deserialize time, with an opaque "operation is not
-registered" error. Do not rely on serialization to reject these models — treat any
-model that went through an internal-op translation path as non-serializable by
-construction.
-
-If a serializable model is required, use a translation path built only from public
-opset ops. Where an internal-op path has a core-op fallback, that fallback is
-serializable — see the example below.
-
-## Current internal ops emitted
-
-| Op | GGML op | Path | Fallback |
-|---|---|---|---|
-| `ov::op::internal::SelectiveSSM` | `GGML_OP_SSM_SCAN` | `translate_ssm_scan` (Mamba 2 scalar decay) | No frontend decomposition |
-| `ov::op::internal::GatedDeltaNet` | `GGML_OP_GATED_DELTA_NET` | `translate_gated_delta_net` (scalar gate) | `translate_gated_delta_net_ref` — a serializable `Loop` scan, used for per-key-dimension gating (`kda`) and as a portable fallback |
-
-See [`src/op/gated_delta_net.cpp`](../src/op/gated_delta_net.cpp).
-
-## Guidance for adding a new internal-op path
-
-1. Only emit ops that already exist in `ov::op::internal` (core `dev_api`) with
- plugin support — do not define new ops in the frontend.
-2. Prefer keeping a core-op-only reference path (as `translate_<op>_ref`) so callers
- that need serialization, or devices without native support, have a route.
-3. Update the table above and note the non-serializable consequence.
-4. Be aware `dev_api` internal ops are marked "under development and subject to
- change"; their inputs/attributes may shift between releases.
diff --git a/src/frontends/gguf/docs/mmproj.md b/src/frontends/gguf/docs/mmproj.md
new file mode 100644
index 00000000000..a1fa1bcab5a
--- /dev/null
+++ b/src/frontends/gguf/docs/mmproj.md
@@ -0,0 +1,179 @@
+# Native GGUF multimodal conversion
+
+A llama.cpp multimodal projector file (`general.architecture = clip`, usually named
+`mmproj-*.gguf`) converts to an `ov::Model` that runs its vision and/or audio encoder and
+projector. The language model is a separate `.gguf` converted by the regular decoder path.
+
+## Supported projectors
+
+Projector support is separate from the architecture list: `clip` selects the mmproj coordinator,
+and the per-frontend projector registry selects each vision/audio branch. Built-in entries come
+from `projector_catalog` in
+[`mmproj_builder.cpp`](../src/builder/arch/mmproj_builder.cpp). Every entry has a small
+numerical fixture checked against the llama.cpp CPU encoder (see
+[the fixture README](../tests/test_data/mmproj_accuracy/README.md)).
+
+| 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 | `minicpmv4_6` | window attention, two-stage merging |
+| 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 | `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 | `qwen2a`, `ultravox`, `voxtral`, `musicflamingo`, `meralion`, `glma` | Whisper-derived encoders |
+
+InternViT-6B (width 3200, 45 layers) uses RMS norms like the reference, but has no fixture.
+
+Not implemented: `ldp`, `ldpv2`, `adapter`, `step3vl`, `gemma3nv`, `llama4`, `qwen3a`, `lfm2`,
+`kimivl`, `paddleocr`, `lightonocr`, `cogvlm`, `dots_ocr`, `lfm2a`, `glm4v`, `youtuvl`, `yasa2`,
+`kimik25`, `nemotron_v2_vl`, `exaone4_5`, `hunyuanvl`, `granite_speech`, `mimovl`,
+`granite4_vision`. `gemma3na` has no graph builder in the reference.
+
+## Validation coverage
+
+| Evidence | Scope and limits |
+|---|---|
+| Offline numerical fixtures | Every catalog projector has a small CPU encoder reference; tests compare raw and GenAI-adapted features |
+| Dynamic fixtures | Multiple sizes reuse one compiled model; variants are listed in the [fixture README](../tests/test_data/mmproj_accuracy/README.md) |
+| Real-checkpoint lists | [Precommit](../../../../tests/model_hub_tests/gguf/gguf_mmproj_precommit) and [nightly](../../../../tests/model_hub_tests/gguf/gguf_mmproj_nightly) select checkpoints, including combined Gemma4 and Qwen2.5-Omni files |
+| Qwen2-VL real checkpoint | CPU NMSE limit is explicitly relaxed to `2e-4`; the list records reference patch-embedding arithmetic as the reason |
+| DeepSeek-OCR real checkpoint | Skipped: model-hub input preparation does not yet implement SAM tiles/views; offline OCR fixtures remain covered |
+| Full media application | Encoder fixtures and generated-input checkpoint tests do not validate host preprocessing, media insertion, or complete VLM/audio generation |
+
+See [testing](testing.md) for commands and acceptance. A catalog entry is not a claim of coverage
+for every checkpoint, resolution, quantization, or device.
+
+## Files with vision and audio encoders
+
+A projector file holds at most one vision and one audio encoder; Gemma4 E2B/E4B/12B files carry
+both. Conversion builds every encoder the file declares into one model:
+
+1. `clip.has_vision_encoder` and `clip.has_audio_encoder` select the encoders. A file with
+ neither fails conversion.
+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,
+ so no declared modality is dropped silently.
+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`.
+
+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.
+
+## Graph boundary
+
+Preprocessing belongs to the caller. Activations are F32 and indices I32, except the
+explicit F32 positional inputs below. Dynamic encoders accept different spatial sizes;
+fixed-resolution encoders retain the size recorded in metadata.
+
+| Family | Inputs |
+|---|---|
+| Fixed-resolution vision | `vision.pixel_values [1,3,S,S]`, normalized NCHW |
+| MiniCPM resampler | `vision.pixel_values [1,3,H,W]`, learned `vision.position_ids [1,1,1,T]`, F32 `vision.position_h` / `vision.position_w [1,1,T,1]` |
+| Qwen vision | `vision.pixel_values [2,3,H,W]` (a temporal pair; repeat a still image), `vision.patch_indices [1,1,1,T]`, `vision.position_ids [1,1,1,4*T]` |
+| Qwen2.5 vision | also `vision.attention_mask [1,1,T,T]` (additive window mask) and `vision.output_indices [1,1,1,T/4]` |
+| Pixtral / Phi4 / Gemma4 vision | `vision.pixel_values [1,3,H,W]`; Pixtral and Gemma4 also `vision.position_x`, `vision.position_y [1,1,1,T]` |
+| Muse Glimmer | pixels; `patch_indices` in window order with each window padded to `window_size²` slots; one-based `position_x` / `position_y` per slot; `output_indices`; pixel-shuffle `merge_indices`; additive key mask `window_mask [W,1,1,window_size²]` that hides the padding |
+| MiniCPM-V 4.6 | pixels, position IDs, `window_indices`, `inverse_window_indices`, `attention_mask`, `vit_merger.indices.N`, `merger.indices.N` |
+| DeepSeek-OCR / OCR2 | `vision.pixel_values [B,3,H,W]` (independent square tiles), local/global relative-position indices, `vision.output_indices`; OCR1 `position_indices`, OCR2 `query_indices`, `query_output_indices`, `position_ids`, `attention_mask` |
+| Gemma4 audio | `audio.features [1,1,mel,frames]` |
+| Gemma4 unified audio | `audio.waveform_frames [1,1,T,640]`, 16 kHz waveform in 640-sample frames |
+| Whisper-derived audio | `audio.features [1,mel,1,frames]`, `audio.position_ids [1,1,1,ceil(frames/2)]` |
+
+Index inputs reorder patches the way the reference does: spatial grouping and windows before
+the encoder, the inverse order after it. Qwen sizes must be divisible by patch size times merge
+size. Gemma4 vision takes pixels in [0,1] and applies the reference's `2*x-1` inside the graph;
+unified vision uses patch size times projector scale factor. Gemma4 audio builds its
+12-position causal horizon and relative positions in the graph as `[T,T]` tensors, so memory
+grows quadratically with the number of frames. Missing/zero `clip.minicpmv_version` selects 2; missing/zero `clip.minicpmv_query_num`
+selects 96 queries for version 2 and 64 otherwise, and an explicit count must match the query
+tensor.
+
+Outputs are `vision.embeddings` and/or `audio.embeddings`, `[1,1,T,D]`. `qwen3vl_merger` packs
+the DeepStack features after the primary ones along `D`.
+
+## Runtime metadata
+
+Model rt_info `gguf_mmproj` keeps every source `clip.*` key and adds `<modality>.projector`,
+`<modality>.merge`, `vision.auxiliary_count`, `vision.window_size` (Muse Glimmer) and
+`vision.minicpmv_version` / `vision.query_count` (resampler). Values are strings: numeric
+arrays are comma-separated, and string arrays are `length:value` entries flagged by a
+`<key>.encoding` companion. The metadata survives IR serialization and adaptation; supplied
+cgraph decoders return an empty map.
+
+## Preprocessing real media
+
+`GGUFMMProjAccuracy` and `GGUFMMProjDynamicAccuracy` run every projector offline from committed
+inputs and llama.cpp outputs; see [testing.md](testing.md).
+
+For real files, [model-hub commands](testing.md#real-checkpoints) reproduce encoder comparisons
+with generated inputs. [`checkpoint_inputs`](../tests/mmproj_fixtures.py) illustrates supported
+index construction; it creates random pixels/features and is not a media preprocessor.
+For real Gemma3 images, reproduce the reference resize/crop and RGB channel normalization from
+`clip.vision.image_mean` / `clip.vision.image_std` before supplying NCHW pixels. Whisper-derived
+audio needs the reference mel extraction and frame padding before `audio.features`; Gemma4 unified
+audio instead takes consecutive 640-sample frames from a 16 kHz waveform, without mel extraction.
+
+## Using the encoders and a language model
+
+[`AdaptMmprojToGenAI`](../include/openvino/frontend/gguf/adapt_mmproj_to_genai.hpp) keeps one
+modality, drops the other branch's inputs and prefixes, and exposes `[1,T,D]` outputs named
+`image_features` and `deepstack_features.N`, or `audio_features`. It rewrites the model in place,
+so run it on a separate clone for each modality of a combined file.
+
+[`AdaptToGenAI`](../include/openvino/frontend/gguf/adapt_to_genai.hpp) in `EMBEDS_TO_LOGITS`
+mode prepares the language model for media injection:
+
+- the token lookup moves to `get_embedding_model()`, sharing its weights, and the language model
+ takes `inputs_embeds [B,T,D]`; token-embedding scaling is applied once;
+- Gemma4 E2B/E4B use a separate `get_per_layer_embedding_model()` whose output feeds
+ `per_layer_inputs [B,T,layers,width]`; it is not a second output of `get_embedding_model()`;
+- Gemma3 and Gemma4 without per-layer embeddings take `token_type_ids [B,T]`: image tokens attend
+ bidirectionally within their image, in every Gemma3 layer and in Gemma4 sliding-window layers;
+- interleaved M-RoPE models take `position_ids [4,B,T]`: GenAI's sequence, time, height and width
+ sections.
+
+Register `GenAIExtension` before converting the language model, as described in
+[runtime.md](runtime.md#stateful-and-genai-conversion). In C++, with a `FrontEndManager manager`
+and an already converted combined `mmproj` model:
+
+```cpp
+#include <openvino/frontend/gguf/adapt_mmproj_to_genai.hpp>
+#include <openvino/frontend/gguf/extension/genai.hpp>
+
+using namespace ov::frontend::gguf::pass;
+auto vision = mmproj->clone();
+auto audio = mmproj->clone();
+AdaptMmprojToGenAI(AdaptMmprojToGenAI::Modality::VISION).run_on_model(vision);
+AdaptMmprojToGenAI(AdaptMmprojToGenAI::Modality::AUDIO).run_on_model(audio);
+auto frontend = manager.load_by_framework("gguf");
+auto genai = std::make_shared<ov::frontend::gguf::GenAIExtension>(
+ ov::frontend::gguf::GenAIExtension::InputMode::EMBEDS_TO_LOGITS);
+frontend->add_extension(genai);
+auto language = frontend->convert(frontend->load("language.gguf"));
+auto token_lookup = genai->get_embedding_model();
+auto per_layer_lookup = genai->get_per_layer_embedding_model();
+```
+
+`per_layer_lookup` is null for models without that branch. Compile the selected encoders and
+lookup models; the consumer inserts their raw features into `inputs_embeds` at the model's media
+token positions and supplies masks, positions, and any per-layer inputs. Keep model-specific
+placeholder handling and DeepStack delivery in the consumer. These passes expose graph contracts;
+they do not construct tokenizers, media preprocessing, or a complete GenAI pipeline.
+
+## 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`.
diff --git a/src/frontends/gguf/docs/porting_a_llama_cpp_model.md b/src/frontends/gguf/docs/porting_a_llama_cpp_model.md
deleted file mode 100644
index b54c4d18263..00000000000
--- a/src/frontends/gguf/docs/porting_a_llama_cpp_model.md
+++ /dev/null
@@ -1,522 +0,0 @@
-# Architecture definitions: external plugins and built-in support
-
-An architecture is described by an `ArchitectureDefinition`. The native catalog and runtime
-extensions consume the **same definition**, invoke the same factory, and use the same conversion
-and normalization pipeline. `ArchitectureExtension` is only the runtime registration adapter.
-
-Build extensions against the OpenVINO release they will run with. The builder API does not promise
-compatibility across releases. Loading an extension does not require rebuilding OpenVINO.
-
-## Choose the smallest implementation
-
-| Requirement | Implementation |
-|---|---|
-| Existing decoder topology, new architecture name | `make_decoder_architecture(name, rope)` |
-| Decoder needs different architecture facts | Supply a callback returning `DecoderOptions` |
-| Custom layer order using existing decoder sublayers | `ModelBuilder` using `configure_decoder`, `decoder_attention`, `decoder_ffn` |
-| Different model family | `ModelBuilder` using generic graph operations and its own metadata; follow the [full porting walkthrough](#port-a-fully-new-architecture-from-llamacpp) |
-
-Prefer structural detection to overriding an option. Tensor presence, metadata, and the native
-configuration resolver already handle the supported decoder features. A custom topology owns its
-embedding, normalization, residual, and output ordering; the shared sublayer methods do not assemble
-those automatically. `decoder_layer_parameters(layer)` supplies resolved head counts, attention
-scale and RoPE parameters when implementing a custom attention fragment.
-
-## Define a decoder
-
-```cpp
-#include "openvino/frontend/gguf/extension/architecture.hpp"
-
-ov::frontend::gguf::ArchitectureDefinition my_architecture() {
- using namespace ov::frontend::gguf;
- return make_decoder_architecture(
- "my-arch", RopeMode::Neox,
- [](const GgufMetadata& metadata) {
- DecoderOptions options;
- options.geglu = true;
- return options;
- });
-}
-```
-
-Omit the callback when no overrides are required. `RopeMode` explicitly distinguishes consecutive
-pairs (`Normal`), rotate-halves (`Neox`), and interleaved multimodal RoPE (`Interleaved`). Verify the
-mode against the architecture's reference implementation.
-
-`DecoderOptions` contains supported architectural overrides, not mutable dimensions or execution
-plans. The callback runs before configuration resolution. The native resolver validates the options
-and derives the SWA RoPE configuration and KV plan afterward. There is no separate hyperparameter
-reader: both built-in and custom decoder topologies use `decoder_config_from_meta` and
-`DecoderConfig`, including their defaults and RoPE scaling rules. The resolved configuration stays
-internal to the frontend. Options also cover QK-norm placement (`qk_norm_after_rope`),
-post-norm-only blocks (`post_norm_only`), selected expert normalization
-(`normalize_expert_weights`), and periodic NoPE layers (`rope_skip_period`, zero to disable).
-
-## Define a custom builder
-
-Implement `ModelBuilder::build()` with a `GgufGraphContext`. The `BuildContext` is a borrowed view of
-metadata and weights, valid for the synchronous factory/build call. Do not retain it afterward.
-
-Read scalar metadata with `get_int`, `get_float`, `get_bool`, or `get_str`; they return
-`std::optional`, so defaults use standard `value_or`, e.g.
-`metadata.get_int("my-arch.block_count").value_or(1)`. Array getters return typed vectors.
-Numeric conversion reuses OpenVINO's tensor utilities rather than a separate type dispatcher.
-
-The [projector example](../examples/architecture_extension/projector.cpp) is a complete small
-non-decoder family. It reads a weight, accepts a variable number of input embeddings and projects
-them into another space. Its architecture definition is separate from the plugin entry point.
-
-For custom decoder layer order, initialize the shared decoder blocks once:
-
-```cpp
-auto dimensions = graph.configure_decoder(RopeMode::Neox, options);
-graph.build_inp_pos();
-graph.build_attn_inp_kv();
-// Inside the custom layer loop, after constructing the appropriate normalization:
-auto attention = graph.decoder_attention(layer, normalized_input);
-auto feed_forward = graph.decoder_ffn(layer, normalized_ffn_input);
-```
-
-These methods call the existing `blocks::attention` / `blocks::gated_delta_net` and dense/GeGLU/MoE
-FFN implementations. Configuration chooses the applicable sublayer. There is no separate
-implementation of those blocks. Decoder dimensions are returned as a value snapshot; modifying it
-does not mutate the resolved model. See the custom decoder in
-[`test_architecture_extension.cpp`](../tests/test_architecture_extension.cpp).
-
-## Port a fully new architecture from llama.cpp
-
-Use this route when the model's computation cannot be expressed by the shared decoder blocks:
-for example, a new encoder, a different recurrent network, or an encoder-decoder family. Implement
-its whole graph in a `ModelBuilder`. The native frontend reads the GGUF file; your builder describes
-the computation using `node` and any applicable shared blocks. llama.cpp supplies the reference
-implementation and numerical oracle, but is not a dependency of the resulting extension.
-
-### 1. Trace the reference from the file format to the outputs
-
-Start with a llama.cpp revision that loads the target checkpoint correctly. Record its commit,
-checkpoint, quantization, input preprocessing and runtime options so comparisons are reproducible.
-The source locations below are relative to that llama.cpp checkout; older revisions may combine
-these implementations in larger files.
-
-| Source to inspect | What to extract |
-|---|---|
-| `src/models/<architecture>.cpp`: `load_arch_hparams` | Required metadata, defaults, architectural variants and constraints |
-| The same file: `load_arch_tensors` | Tensor names and dimensions; required/optional weights; aliases and tied weights |
-| The same file: `build_arch_graph` and its graph constructor | Inputs, layer order, branches, residuals, final projection and output selection |
-| `src/llama-model.cpp`, `src/llama-arch.cpp` and `src/llama-hparams.h` | Common metadata loading, expansion of `LLM_KV_*` / `LLM_TENSOR_*` names and derived dimensions |
-| `src/llama-graph.cpp` and the relevant memory implementation | Bodies of called helpers, attention masks, cache reads/writes and recurrent updates |
-| `tools/mtmd/models/` and their shared helpers | Vision/audio graph construction, patch processing, pooling and projection, when outside the language model |
-| GGUF conversion code and `gguf-py/gguf/` | Actual exported names, tensor packing, transpositions and weight transformations |
-
-For example, in a checkout with separate model files:
-
-```sh
-rg -n 'load_arch_hparams|load_arch_tensors|build_arch_graph|::graph' src/models/<architecture>.cpp
-rg -n 'build_lora_mm|build_norm|build_ffn|build_attn' src/llama-graph.cpp
-rg -n 'LLM_KV_<KEY>|LLM_TENSOR_<TENSOR>' src/llama-arch.cpp
-```
-
-Follow every helper used by the architecture. `build_lora_mm`, for example, can include an
-additional weight scale and active LoRA updates after the base matrix multiplication. Replacing
-it with `MUL_MAT` reproduces the base path only when those additions are absent. Likewise,
-`build_norm` selects RMS, layer or group normalization and may apply both a weight and a bias.
-A helper's name alone does not establish its semantics.
-
-Write down the complete input-to-output sequence before coding. Include operations outside the
-layer loop: embedding scales, learned positions, final normalization, pooling, output-row selection
-and logit transforms. A GGUF model name or matching tensor names do not imply the same computation.
-For multimodal models, identify which file holds each graph and which preprocessing steps happen
-on the host; supporting a projection graph does not automatically support the whole pipeline.
-
-### 2. Define the file and model interface
-
-Create a small contract alongside the port:
-
-- The literal `general.architecture`, plus metadata predicates needed to distinguish variants.
-- Required metadata and its types, source-defined defaults, and per-layer arrays or schedules.
-- Required tensors, optional tensors and their fallback behavior, with **logical** GGML dimensions.
-- Each model input's name, element type, axis meanings and variable dimensions.
-- Outputs and how the consumer interprets them: logits, embeddings, encoded features or state.
-- Cache/state inputs, their updates, position indices and masks, if applicable.
-
-Read a new family's own keys with `graph.metadata()`. Reject missing mandatory fields rather than
-silently inventing dimensions; use `value_or` only for defaults present in the reference. Derive
-weight-dependent dimensions from `GgufValue::ne` or its inferred shape, not from packed byte sizes.
-`tensors.require(name)` loads a mandatory weight, `tensors(name)` returns an empty value when an
-optional weight is absent, and `tensors.has(name)` checks presence without emitting a node.
-Implement tied-weight fallbacks explicitly where the reference does so.
-
-The builder API accepts named model inputs with a known rank of at most four; dimensions may be dynamic.
-Use the layouts expected by the selected converters. For example, GGML `[width, items, 1, 1]`
-corresponds to OpenVINO `[1, 1, items, width]`. This is not an implicit batch-capability guarantee:
-the model's operations, state and consumer must all support the batch layout you expose.
-
-A new encoder need not call `configure_decoder`, create token/position inputs, or emit logits.
-An encoder-decoder port must describe both its encoding and decoding computations and their
-connection, including cross-attention and state where needed; registration does not generate them.
-
-### 3. Translate graph construction, preserving operation semantics
-
-Port one reference fragment at a time, retaining its operand order and branches. Use shared
-attention/FFN blocks only where their semantics match. Otherwise express the fragment with generic
-nodes. Local functions can name repeated architectural fragments without adding methods to the builder API.
-
-| llama.cpp construction | Builder equivalent or porting action |
-|---|---|
-| `create_tensor(tn(...), ...)` / a layer weight pointer | Look up the actual GGUF name through `GgufTensors`; parsing and dequantization are already handled |
-| `ggml_new_tensor_*` for runtime data | `add_input(name, type, shape)`; supply values at inference time |
-| `ggml_add`, `ggml_sub`, `ggml_mul` | `node("GGML_OP_ADD" / "GGML_OP_SUB" / "GGML_OP_MUL", {a, b})` |
-| `ggml_mul_mat(ctx, weight, x)` | `node("GGML_OP_MUL_MAT", {weight, x})` |
-| `ggml_silu(ctx, x)` | `node("GGML_UNARY_OP_SILU", {x})` |
-| `ggml_rms_norm(ctx, x, eps)` | `node("GGML_OP_RMS_NORM", {x}, 0, {{"eps", eps}})`; learned scaling remains a separate multiply |
-| `ggml_reshape_*` | `GGML_OP_RESHAPE`, case 6, with an OpenVINO-order `reshape_target`; use `special_zero` when copying an input dimension |
-| `ggml_permute` | `GGML_OP_PERMUTE`, case 1, with an OpenVINO-order `perm`; translate the axis mapping |
-| `ggml_view_*` | Describe the logical slice/layout with the converter's attributes; do not reproduce a ggml pointer or allocator |
-| `ggml_top_k(ctx, scores, k)` | `GGML_OP_TOP_K` with explicit `int64_t` attribute `k`; its converter selects I32 indices |
-| `ggml_cpy`, `ggml_set*` used for state | Preserve the updated tensor and its consumer/state relationship, not an in-place memory side effect |
-| `cb(...)`, graph expansion and backend scheduling | Reference diagnostics and execution infrastructure; no corresponding model computation to emit |
-
-Inspect [`src/op_table.cpp`](../src/op_table.cpp) and the selected converter in
-[`src/op/`](../src/op) for the accepted attributes and `op_case`. The case is a semantic variant,
-not a llama.cpp operation enum or an arbitrary tag. The generic builder forwards it without
-interpreting the operation. See [Tensor operations and shapes](#tensor-operations-and-shapes).
-
-Pay particular attention to layouts:
-
-- `ggml_permute` specifies the destination of each source axis, while OpenVINO's `perm` lists
- source axes in output order. With four GGML axes `axes[i]`, the corresponding mapping is
- `perm[3 - axes[i]] = 3 - i`. Derive it from axis meanings instead of copying four integers.
-- A ggml view's byte offset and strides describe a logical selection. For a simple contiguous
- subrange, VIEW case 3 accepts `view_slice = {ov_axis, start, length}` and optional
- `view_reshape`. More complex strided views need an appropriate converter or an explicit
- composition of layout operations; a slice alone is not a general replacement.
-- OpenVINO has no ggml contiguity requirement. CONT case 1 is a passthrough; a combined
- `ggml_cont_2d/3d/4d` call still has a reshape to preserve. Do not remove real transposes.
-- Preserve dynamic sequence/item dimensions. A successful one-token graph does not validate the
- layout: incorrect broadcasting can appear only with several tokens, heads or experts.
-
-### 4. Implement a whole-model builder
-
-The example below is a complete builder for an **illustrative** `example-encoder` file contract,
-not a claim of support for a named llama.cpp model. It shows the mechanics for a family with its
-own metadata and inputs, without using the decoder configuration or attention blocks.
-
-Assume the reference reads `example-encoder.block_count`, `example-encoder.embedding_length`
-and RMS epsilon (default `1e-5`), consumes feature vectors, and applies this per-layer computation:
-
-```cpp
-// Reference computation after resolving the layer's weights (optional biases omitted here).
-auto norm = ggml_rms_norm(ctx0, cur, eps);
-norm = ggml_mul(ctx0, norm, layer.norm);
-auto gate = ggml_silu(ctx0, ggml_mul_mat(ctx0, layer.gate, norm));
-auto up = ggml_mul_mat(ctx0, layer.up, norm);
-auto down = ggml_mul_mat(ctx0, layer.down, ggml_mul(ctx0, gate, up));
-cur = ggml_add(ctx0, cur, down);
-```
-
-Its GGUF tensors are `blk.N.norm.weight`, `blk.N.gate.weight`, `blk.N.up.weight`,
-`blk.N.down.weight`, optional projection `.bias` tensors, and `output_norm.weight`.
-Gate/up project the embedding width into the hidden width; down projects back. The output is the
-full feature sequence after final RMS normalization. The port, saved as `new_family.cpp`, is:
-
-```cpp
-#include "openvino/core/except.hpp"
-#include "openvino/frontend/gguf/builder/graph_context.hpp"
-#include "openvino/frontend/gguf/extension/architecture.hpp"
-
-namespace example {
-using namespace ov::frontend::gguf;
-
-class FeatureEncoder : public ModelBuilder {
-public:
- explicit FeatureEncoder(const BuildContext& context) : m_context(context) {}
-
- std::shared_ptr<GgufGraph> build() override {
- GgufGraphContext graph(m_context);
- const auto& metadata = graph.metadata();
- const auto count = metadata.get_int("example-encoder.block_count");
- const auto width = metadata.get_int("example-encoder.embedding_length");
- OPENVINO_ASSERT(count && *count > 0, "Missing or invalid block_count");
- OPENVINO_ASSERT(width && *width > 0, "Missing or invalid embedding_length");
- const auto eps = static_cast<float>(
- metadata.get_float("example-encoder.attention.layer_norm_rms_epsilon").value_or(1e-5));
- OPENVINO_ASSERT(eps > 0, "RMS epsilon must be positive");
- auto tensors = graph.tensors();
- auto cur = graph.add_input("features", ov::element::f32, {1, 1, -1, *width});
-
- const auto linear = [&](const std::string& base, const GgufValue& input) {
- auto out = graph.node("GGML_OP_MUL_MAT", {tensors.require(base + ".weight"), input});
- if (auto bias = tensors(base + ".bias")) {
- out = graph.node("GGML_OP_ADD", {out, bias});
- }
- return out;
- };
-
- for (int64_t layer = 0; layer < *count; ++layer) {
- const auto prefix = "blk." + std::to_string(layer) + ".";
- const auto residual = cur;
- auto norm = graph.build_norm(cur, tensors.require(prefix + "norm.weight"), eps);
- auto gate = linear(prefix + "gate", norm);
- gate = graph.node("GGML_UNARY_OP_SILU", {gate});
- auto up = linear(prefix + "up", norm);
- auto hidden = graph.node("GGML_OP_MUL", {gate, up});
- auto down = linear(prefix + "down", hidden);
- cur = graph.node("GGML_OP_ADD", {residual, down});
- }
-
- graph.set_output(graph.build_norm(cur, tensors.require("output_norm.weight"), eps));
- return graph.finish();
- }
-
-private:
- BuildContext m_context;
-};
-
-ArchitectureDefinition new_family_architecture() {
- return {"example.feature-encoder", "example-encoder", [](const BuildContext& context) {
- return std::make_shared<FeatureEncoder>(context);
- }};
-}
-} // namespace example
-```
-
-`BuildContext` is copied here only for the synchronous factory/build lifecycle. The built graph
-retains its weights, but the builder must not keep using the borrowed context after that call.
-The definition defaults to experimental maturity. Its id identifies the handler; its architecture
-string must match the file. Add a metadata predicate if multiple implementations share that string.
-
-For your target, replace this example's contract and layer body with the traced reference graph,
-including its embedding/patch frontend and output processing. Do not keep the example's names,
-activation, normalization or residual ordering merely because the dimensions match. The existing
-`VisionEncoderBuilder` in [`test_architecture_extension.cpp`](../tests/test_architecture_extension.cpp)
-shows a larger custom family with Q/K/V projections, non-causal attention, an FFN and a projector.
-
-### 5. Handle missing operations and state explicitly
-
-Inventory the operations in the **expanded** reference helpers against the converter table before
-iterating on the whole model. A new architecture built entirely from supported operations needs
-no new converters. If an operation is missing, either express its exact semantics using existing
-nodes or implement a converter:
-
-- An external plugin can register an `ov::frontend::ConversionExtension` along with its
- `ArchitectureExtension`. The converter receives a frontend `NodeContext` and returns OpenVINO
- outputs. Register it on the same frontend before `convert()`; the builder calls it through `node`.
- `ConverterRegisteredAfterLoadInfersBuilderValues` in the architecture tests is a working example.
-- For built-in support, follow [how_to_add_op.md](how_to_add_op.md): register the shared converter
- and add its tests and test-build source entry. Reuse an existing semantic case where applicable.
- If a legacy case requires cgraph output shapes, make its operation parameters explicit in the
- shared converter; do not add intermediate shape calculations to the builder.
-
-This is the only operation-support layer. Do not add a builder-specific enum, switch, shape rule,
-or `GgufGraphContext` method for the operation. OpenVINO shape inference happens when its converter
-constructs the output nodes. GGUF weight-format support is separate: an unsupported quantization
-format requires work in the weight loader, not a graph operation or architecture-name workaround.
-
-For stateful models, first make state flow explicit. Identify the previous-state inputs, the
-mathematical update and every output the consumer must retain. `add_recurrent_state` describes an
-overwritten state; it is not the declaration for an append-only attention KV cache. Reuse the
-shared decoder attention/cache blocks when they fit. A different cache algorithm needs its own
-correct graph and consumer contract. Declare RoPE, multimodal positions and sliding windows as
-explained in [Declare model contracts](#declare-model-contracts). Do not apply decoder-specific
-`AdaptToGenAI` conventions to encoder outputs automatically.
-
-### 6. Build and validate the port in increasing scope
-
-Wrap `new_family_architecture()` in the plugin entry point and build it against installed builder API
-headers using [Build and load an external plugin](#build-and-load-an-external-plugin). For this
-example, replace `projector.cpp` with `new_family.cpp` in the CMake target and declare the factory
-in a header included by the entry point. No llama.cpp objects or internal frontend headers are
-needed. If the plugin adds converters, include them in the same extension list.
-
-Validate more than graph construction:
-
-1. **File/interface:** load a small nonzero fixture through the actual plugin. Check required-field
- errors, optional/tied weights, inputs and outputs, then compile the converted model on CPU.
-2. **Fragments:** compare nontrivial layouts and new operations against real ggml CPU outputs.
- Use distinct dimensions and nonuniform values to expose swapped axes or misplaced scaling.
- llama.cpp's `cb` labels help locate corresponding intermediates when tracing the first mismatch.
-3. **Whole graph:** compare the same preprocessed inputs through llama.cpp and the native frontend.
- For encoders compare features, pooled outputs or projections directly. For decoders compare
- complete logits on identical token histories, then prefill and several cached decode steps.
- Test multiple sequence lengths, nonzero positions, state resets and relevant window boundaries.
-4. **Real checkpoint:** repeat with the actual model and quantization. Keep tokenizer, preprocessing,
- masks and precision settings aligned. Coherent text alone does not verify an encoder, pooling
- path or multimodal projector. Document any untested variants rather than marking them verified.
-5. **Regression:** retain a small reproducible numerical fixture. For decoder fixtures, reuse
- [`tests/gen_arch_accuracy.py`](../tests/gen_arch_accuracy.py) and the
- [reference-generation instructions](../tests/test_data/arch_accuracy/README.md). A new family's
- fixture needs an oracle for its own inputs/outputs rather than forcing it into a logits harness.
- Run the full frontend and external-library suites; changes to shared converters also need the
- existing architecture fingerprints and numerical regressions.
-
-See [debugging_accuracy.md](debugging_accuracy.md) for comparing intermediates. A static shape
-match or successful one-token run is a useful initial check, not evidence of numerical correctness.
-
-### 7. Integrate the verified implementation into the frontend
-
-Keep the architecture definition separate from the plugin entry point throughout development.
-Then follow [Promote the same implementation into OpenVINO](#promote-the-same-implementation-into-openvino):
-move the source, register the same definition and retain its tests. The `ModelBuilder` and its
-`node` calls do not change. If the plugin supplied converters, upstream those into the shared
-converter table as well. Update supported-model documentation with the actual validation scope.
-
-## Tensor operations and shapes
-
-`node` is the single operation API. It looks up the operation's registered converter, which
-constructs OpenVINO nodes immediately. `GgufValue` holds the resulting `ov::Output`;
-`value.shape()`, `value.type()` and `value.ne(i)` read OpenVINO's inferred result. There is no
-builder operation registry, per-operation method or separate shape implementation to maintain.
-
-```cpp
-auto sum = graph.node("GGML_OP_ADD", {a, b});
-auto projected = graph.node("GGML_OP_MUL_MAT", {weight, sum});
-auto experts = graph.node("GGML_OP_TOP_K", {scores}, 0, {{"k", int64_t{2}}});
-```
-
-Operands follow GGML order (weight before activation for matrix multiplication). Converters
-implement ggml's result-type rules: `MUL_MAT` and `MUL_MAT_ID` produce F32; `TOP_K` and `ARGSORT`
-produce I32 indices; type-preserving operations use their input type, and state writes use the
-destination tensor's type. Architecture code does not supply an output type. OpenVINO outputs
-carry the resulting types and shapes, including through custom `ConversionExtension` converters.
-
-`op_case` selects a converter's existing semantic variant. Attributes supply operation parameters,
-not inferred output metadata. Explicit types are needed only when the operation itself selects a
-destination precision, such as a cast or `IM2COL`:
-
-```cpp
-auto half = graph.node("GGML_OP_CPY", {input}, 0, {{"dst_type", ov::element::f16}});
-auto copied = graph.node("GGML_OP_CPY", {input, destination});
-```
-
-The first call is a cast; the second derives its type from `destination`. `IM2COL` likewise requires
-`dst_type` alongside its convolution parameters. Older cgraph decoders may expose these two
-operations' destination types through `output_type`; the shared converters accept that encoding
-for compatibility. New operation support requires only a converter, without builder changes.
-Missing converters report a conversion error.
-
-Value shapes use OpenVINO order; `value.ne(i)` accesses reversed GGML dimensions. Weight values
-preserve logical vector and expert axes. Missing optional weights return an empty value;
-`tensors.require(name)` reports missing mandatory weights.
-
-Input dimensions and operation-defining parameters remain explicit. For example, a reshape
-specifies an OpenVINO-order pattern; `-1` requests an inferred dimension and `special_zero` copies
-input dimensions at zero entries. Splitting attention heads while preserving a dynamic token
-axis and the leading batch is:
-
-```cpp
-auto heads = graph.node("GGML_OP_RESHAPE", {projected}, 6, {{"reshape_target", std::vector<int64_t>{0, -1, n_heads, head_size}},
- {"special_zero", true}});
-auto merged = graph.node("GGML_OP_RESHAPE", {heads}, 2, {{"merge_heads", true}});
-```
-
-`PERMUTE` case 1 takes `perm` in OpenVINO axis order. `CONCAT` takes `concat_axis` in GGML order;
-`REPEAT` takes integer `repeats`. Converters and OpenVINO validate these parameters. GGML
-view/stride semantics need explicit slice/layout parameters. No representative token count or
-intermediate output-shape metadata is supplied.
-
-The builder API is not a drop-in implementation of llama.cpp's `llm_graph_context`. Map sublayers onto
-shared blocks where applicable, then use `node` for new structure. Model-specific helpers may
-name repeated fragments without extending the builder API's operation vocabulary.
-
-`load()` parses the file and selects the architecture. `convert()` invokes the selected builder
-with the frontend's current converters, then normalizes the constructed OpenVINO graph. Operation
-extensions may therefore be registered between loading and conversion. Each conversion builds a
-fresh graph; external libraries implementing the selected builder stay alive with the loaded input.
-
-## Declare model contracts
-
-Graph nodes alone do not describe how consumers should maintain state or form masks:
-
-- `configure_decoder` records the resolved RoPE and sliding-window metadata automatically.
-- For custom RoPE, call `configure_rope(config)` before emitting nodes. Set `config.per_op`
- for per-node tables and `config.is_imrope` for the multimodal position contract, then emit
- `node("GGML_OP_ROPE", ...)` with the matching mode and per-node `rope_config` attribute.
-- `set_sliding_window(tokens)` records the window for a custom attention implementation.
-- `add_recurrent_state(input, update)` declares an overwritten state and marks the update as an
- output. `GGUFMakeStateful` consumes this relationship. Its existing batch/beam restrictions still
- apply.
-- `set_output(value)` appends an output. `set_primary_output(value)` puts the data output
- before auxiliary outputs already registered by decoder blocks (for example, logits before KV
- caches). `finish()` validates references and outputs and seals the context against further emission.
-
-These declarations are passed through the same `GgufGraph` and `TranslateSession` pipeline as the
-built-in decoder. A consumer selects `GGUFMakeStateful` and `AdaptToGenAI` through transformation
-extensions; an architecture definition does not select a device or force stateful execution.
-
-## Selection and replacement
-
-A definition has both a unique handler **id** and the file's **architecture**. Matching requires
-`general.architecture` to agree, followed by the optional metadata predicate. For example, two
-handlers may share `architecture = "clip"` but use ids `"clip.vision"` and `"clip.audio"`, with
-disjoint modality predicates. They coexist without overwriting each other.
-
-Two matching handlers are an error. Duplicate ids are also an error. To intentionally replace an
-existing handler, including a built-in, register with `RegistrationMode::Replace`:
-
-```cpp
-frontend.add_extension(std::make_shared<ArchitectureExtension>(
- my_architecture(), RegistrationMode::Replace));
-```
-
-Replacement requires the id to already exist. Registries belong to individual frontends, so a
-replacement never changes another frontend's catalog.
-
-## Build and load an external plugin
-
-The plugin entry point only wraps the definition:
-
-```cpp
-OPENVINO_CREATE_EXTENSIONS(std::vector<ov::Extension::Ptr>{
- std::make_shared<ov::frontend::gguf::ArchitectureExtension>(my_architecture())});
-```
-
-Link against `openvino::frontend::gguf`. The
-[standalone CMake example](../examples/architecture_extension/CMakeLists.txt) builds against the
-installed OpenVINO package:
-
-```sh
-cmake -S src/frontends/gguf/examples/architecture_extension -B /tmp/gguf-extension \
- -DOpenVINO_DIR=/path/to/openvino/runtime/cmake
-cmake --build /tmp/gguf-extension
-```
-
-Load by framework name: GGUF is currently hidden from automatic frontend selection.
-
-```cpp
-ov::frontend::FrontEndManager manager;
-auto frontend = manager.load_by_framework("gguf");
-frontend->add_extension("/path/to/libgguf_projector_extension.so");
-auto model = frontend->convert(frontend->load("model.gguf"));
-```
-
-A consumer integrating through `Core` must arrange for its extensions to reach the explicitly
-selected GGUF frontend. Registering on an unrelated frontend instance does not forward them.
-
-## Promote the same implementation into OpenVINO
-
-1. Move the architecture source/header (for example, `projector.cpp` / `projector.hpp`) into
- `src/builder/arch/`. Keep the definition factory and `ModelBuilder` unchanged. The frontend
- source collection includes files under this directory.
-2. Include its header in `src/builder/arch_registry.cpp` and add
- `definitions.push_back(my_architecture());` to `builtin_architectures()`.
-3. Add the source to the explicit frontend-source list in `tests/CMakeLists.txt`, and retain its
- conversion and accuracy tests. The plugin-only `OPENVINO_CREATE_EXTENSIONS` source is not needed.
-4. Update supported-model documentation and declare `Maturity::Verified` only after real-model
- accuracy validation. Synthetic conversion tests do not establish model support.
-
-For a plain decoder, add a row to the decoder catalog with name, RoPE mode, and maturity. For a
-decoder with options, add the unchanged definition factory instead. Do not also register a plain
-decoder row under the same id.
-
-No new family-dispatch branch, frontend registration method, or alternate graph implementation is
-needed. The tests compile the projector source both as a library and into a catalog test to exercise
-this migration path.
-
-## Validate
-
-- Compile an external plugin using installed headers and load the actual library.
-- Compare numerical results against a reference, including multiple token lengths and subsequent
- decoding with previously generated state. Check SWA beyond its window and non-default RoPE scaling.
-- Run `ov_gguf_frontend_tests` architecture fixtures to check built-in graph fingerprints.
-- For a real architecture, compare its outputs to llama.cpp on the same checkpoint before marking
- it verified: logits/generation for decoders, and features or pooled/projected outputs for encoders.
diff --git a/src/frontends/gguf/docs/quantization.md b/src/frontends/gguf/docs/quantization.md
new file mode 100644
index 00000000000..e49e72f9135
--- /dev/null
+++ b/src/frontends/gguf/docs/quantization.md
@@ -0,0 +1,63 @@
+# GGUF weights and execution precision
+
+File quantization, frontend storage, inference arithmetic, and KV-cache precision are separate
+choices. Support for a weight format does not establish model accuracy or device support.
+The native format mapping lives in [`weights.cpp`](../src/quant/weights.cpp); parsing and tensor
+extraction live in [`gguf.cpp`](../src/quant/gguf.cpp).
+
+## Native weight formats
+
+| GGUF weight type | OpenVINO weight representation |
+|---|---|
+| `F32`, `F16`, `BF16` | Floating-point constants; converter-facing values are F32 |
+| `Q1_0`, `Q3_K`, `Q4_0` | i4 codes with grouped scales |
+| `Q5_0`, `Q5_1`, `Q6_K`, `Q8_0`, `Q8_K` | i8 codes with scales and format-specific zero points |
+| `Q2_K`, `Q2_0` | u2 codes with grouped scales/zero points |
+| `Q4_1`, `Q4_K` | u4 codes; ordinary matmul weights use integer-zero-point requantization by default |
+| `Q5_K` | u8 requantization with integer zero points for ordinary matmul weights |
+| `MXFP4` | f4e2m1 codes and f8e8m0 per-32 scales |
+
+Widening codes to a supported storage type is different from requantizing values. Native Q6_K
+uses explicit F32 decompression arithmetic. Embedding/output tensors retain fractional zero
+points where applicable. Q4_K/Q4_1 and Q5_K requantization add error beyond that already present
+in the file; the frontend prints an accuracy notice once per process for each approximation.
+Mixed file labels such as `Q4_K_M` describe a checkpoint's tensor mix, not one tensor type.
+
+The supplied-cgraph/raw-byte weight path can have different representation choices, including
+channel-wise Q8_0_C requantization for embedding/output and selected formats. Record which
+path produced the model when comparing weights; native storage is not a claim about backend storage.
+
+## Accuracy controls
+
+For strict native CPU comparisons, use F32 inference, disable dynamic activation quantization,
+and select the reference's KV-cache precision (the decoder fixture suite uses F16):
+
+```python
+compiled = core.compile_model(model, "CPU", {
+ "INFERENCE_PRECISION_HINT": "f32",
+ "DYNAMIC_QUANTIZATION_GROUP_SIZE": 0,
+ "KV_CACHE_PRECISION": "f16",
+})
+```
+
+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
+environment later in a notebook does not switch an already initialized process. The option
+does not make every quantized format lossless. Fractional zero points can prevent compressed
+FullyConnected fusion, slow matmul, or be unsupported by a device implementation.
+
+llama.cpp's quantized kernels can quantize activations even when OpenVINO's dynamic activation
+quantization is disabled. Report comparisons against quantized CPU arithmetic separately from
+F32 arithmetic on the same represented weights. Improved greedy-token agreement can coexist
+with worse full-logit error; use both metrics and the [acceptance criteria](testing.md#acceptance).
+
+## Memory and packaging limits
+
+Frontend compressed storage does not guarantee compressed execution. In particular, CPU compressed
+expert matmul does not support u2 in this branch, so large Q2 MoE models can expand during
+compilation. Include weight reorders and temporary buffers in memory estimates; a smaller context
+does not remove those costs. Check [checkpoint-specific limits](supported_models.md#runtime-limitations).
+
+`Ternary-Bonsai-27B-Q2_0.gguf` uses g128 packing inconsistent with upstream Q2_0 g64. Use
+`Ternary-Bonsai-27B-Q2_g64.gguf`; the frontend rejects the mismatched packaging. Adding a builder
+or operation converter does not add a new quantization format.
diff --git a/src/frontends/gguf/docs/runtime.md b/src/frontends/gguf/docs/runtime.md
new file mode 100644
index 00000000000..e7b215be371
--- /dev/null
+++ b/src/frontends/gguf/docs/runtime.md
@@ -0,0 +1,98 @@
+# Running converted GGUF models
+
+`convert()` returns a stateless graph with llama.cpp-style inputs. A caller-registered `GenAIExtension`
+turns a language model into a stateful model with the OpenVINO GenAI interface. Multimodal projector
+files use their own [encoder contract](mmproj.md#graph-boundary).
+
+## Stateless contract
+
+The default decoder graph mirrors the llama.cpp backend interface:
+
+| Input | Meaning |
+|---|---|
+| `inp_tokens [1,1,1,T]` i32 | Token IDs of this step |
+| `inp_pos [1,1,1,T]` i32 | Positions; four sections per token for interleaved M-RoPE (`qwen35`, `qwen35moe`) |
+| `inp_out_ids [1,1,1,N]` i32 | Rows whose logits are produced |
+| `self_kq_mask [1,1,T,KV]` f32, `self_kq_mask_swa` | Additive causal mask; the second one for sliding-window layers |
+| `inp_kv_idx`, `token_len_per_seq` | KV write slots and per-sequence length, when the graph consumes them |
+| `cache_k_*`, `cache_v_*`, recurrent states | Previous cache/state, returned as matching outputs |
+
+The output is `logits`. [`run_gguf_model`](../../../../tests/model_hub_tests/gguf/utils.py) is a
+working Python driver for two steps. This is the only route available from Python: the GGUF passes
+below have no Python bindings, and `DecoderTransformationExtension` cannot be constructed from Python.
+
+## Stateful and GenAI conversion
+
+Register `GenAIExtension` before `convert()`. The frontend creates stateful caches before
+stateless cache lowering, completes normalization (including recurrent-operation fusion), then
+adapts the normalized graph to GenAI. Callers do not register or order individual passes.
+
+```cpp
+#include <openvino/frontend/gguf/extension/genai.hpp>
+#include <openvino/frontend/manager.hpp>
+
+using namespace ov::frontend::gguf;
+ov::frontend::FrontEndManager manager;
+auto frontend = manager.load_by_framework("gguf");
+frontend->add_extension(std::make_shared<GenAIExtension>());
+auto model = frontend->convert(frontend->load("model.gguf"));
+```
+
+Internally, [`GGUFMakeStateful`](../include/openvino/frontend/gguf/make_stateful.hpp) replaces each KV cache
+Parameter/Result pair with a Variable, adds `beam_idx` and reorders caches by it. Sliding-window
+caches can be left stateless with `skip_caches`. Recurrent states are declared through the
+`gguf_recurrent_states` rt_info key.
+
+[`AdaptToGenAI`](../include/openvino/frontend/gguf/adapt_to_genai.hpp) requires a stateful model and
+exposes GenAI's interface. Select the mode in the `GenAIExtension` constructor:
+
+| 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]` |
+
+- 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.
+- Sliding-window masks use the `gguf_swa_window_size` rt_info value when the file records a window length.
+- Gated-DeltaNet states (`qwen35`, `qwen35moe`) 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.
+ A consumer must reset, not trim, the states listed in `gguf_recurrent_states`.
+- The pass does not create a tokenizer, sampler or pipeline, and it does not adapt encoder models.
+
+`GGUFMakeStateful` remains independently available through `DecoderTransformationExtension`
+for consumers that keep GGUF IO. The llama.cpp backend uses its own stateful lowering for its
+cache-slot and fixed-mask semantics, without GenAI adaptation.
+
+## Tokenizer metadata
+
+Conversion attaches the file's `tokenizer.ggml.*` and `tokenizer.chat_template` values to the
+model's rt_info as [`GGUFTokenizerMetadata`](../include/openvino/frontend/gguf/tokenizer_metadata.hpp),
+under `gguf_tokenizer_metadata_key()`, when the decoder provides them. Values are strings, string vectors or tensors. A consumer such
+as GenAI can build the tokenizer from it without reopening the file. The attribute is intentionally
+in-memory only: it is dropped on `clone()` and not written to IR, so read it from the converted model.
+
+## Internal operations and serialization
+
+[`SetRows`](../include/openvino/frontend/gguf/set_rows_op.hpp) is a conversion placeholder for
+`GGML_OP_SET_ROWS`. `GGUFMakeStateful` consumes cache writes; `LowerSetRowsStateless` lowers the rest.
+It never survives into the converted model.
+
+These core `ov::op::internal` operations can remain in the converted model:
+
+| Operation | Emitted for | Alternative |
+|---|---|---|
+| `SelectiveSSM` | `SSM_SCAN`, Mamba 2 scalar decay | None |
+| `GatedDeltaNet` | `GATED_DELTA_NET`, scalar gate | `Loop` reference path for per-key gating or `force_ref`; not available with `split_outputs` |
+| `GatherMatmul` | `MUL_MAT_ID`, eligible constant expert weights | Generic Gather/MatMul for other weights |
+
+See [`ssm_scan.cpp`](../src/op/ssm_scan.cpp), [`gated_delta_net.cpp`](../src/op/gated_delta_net.cpp)
+and [`mul_mat_id.cpp`](../src/op/mul_mat_id.cpp) for exact selection conditions.
+
+Internal operations are outside the public IR opsets. Saving IR can succeed and still produce a file
+the IR frontend cannot read back, so test the save/read round trip. Compiled-model export, import
+and caching are plugin-specific; test them on the target device. In-process conversion needs no IR.
+
+A new internal-op path should keep a public-op reference path where practical, test both against
+the same oracle and update the table above. Frontend placeholders need a normalization lowering.
diff --git a/src/frontends/gguf/docs/supported_models.md b/src/frontends/gguf/docs/supported_models.md
index f7eca3d0c4f..ee50cb0f962 100644
--- a/src/frontends/gguf/docs/supported_models.md
+++ b/src/frontends/gguf/docs/supported_models.md
@@ -1,198 +1,116 @@
-# GGUF Frontend — Supported Models
+# GGUF frontend supported models
-The frontend accepts graphs from two paths:
+The frontend converts graphs from two paths that share operation converters but are validated
+separately:
-- **Native GGUF:** builds a graph directly from a `.gguf` file using the architecture catalog.
-- **llama.cpp cgraph:** converts a graph constructed by llama.cpp through its OpenVINO backend.
+- **Native GGUF:** builds the graph from a `.gguf` file through the architecture catalog.
+- **llama.cpp cgraph:** converts graphs built by llama.cpp's OpenVINO backend.
-The paths share operation converters, but architecture coverage is validated separately.
-Verification applies to a tested checkpoint and configuration; it does not guarantee support
-for every model, modality, context length or quantization using the same architecture name.
-
-## llama.cpp cgraph path
-
-Validated architectures and model examples:
-
-| Architecture | Verified model | Notes |
-|---|---|---|
-| `llama` | TinyLlama-1.1B-Chat v1.0 (Q4_K_M) | Dense; standard RoPE + GQA. |
-| `qwen2` | Qwen2.5-0.5B-Instruct (Q8_0) | Dense. |
-| `qwen3` | Qwen3-0.6B (Q8_0) | Dense; QK-norm. |
-| `qwen3moe`| Qwen3-0.9B-A0.6B (Q4_K_M), Qwen3-4B (Q4_K_M) | Mixture-of-experts (`mul_mat_id`). |
-| `olmoe` | OLMoE-1B-7B-0924-Instruct (Q4_0) | Mixture-of-experts. |
-| `gemma3` | gemma-3 family | Mixed sliding-window / global RoPE. |
-| `gemma4` | gemma-4-E4B-it (Q4_K_M) | Per-op RoPE (SWA vs global); f16 KV cache. |
-| `qwen35` | Qwen3.5-4B (Q4_K_M) | Hybrid GatedDeltaNet + full-attention layers; partial-rotary IMROPE; interleaved Q/gate joint projection; f16 KV cache. |
-
-Checkpoint validation for this path covers: `Q2_K`, `Q4_0`, `Q4_K_M`, `Q6_K`,
-`Q8_0`. The frontend weight path also handles `Q4_1`, `Q5_0`, `Q5_1` and the F16/F32
-paths; these are exercised by the unit tests but have not each been tied to a specific
-end-to-end real-model run.
-
-### Verification
-
-```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
-```
-
-A run counts as verification only when the output is coherent (e.g. completes
-"...is Paris") and consistent with the pure-ggml CPU backend on the same prompt. A model
-that loads but emits garbage is **not** counted as supported.
+Validation applies to the tested checkpoint and configuration, not to every model, modality,
+context length or quantization sharing an architecture name. Acceptance limits are defined in
+[testing.md](testing.md#acceptance). Projector files (`mmproj-*.gguf`) are covered in [mmproj.md](mmproj.md).
## Native GGUF path
-The native architecture catalog is defined in
-[`src/builder/arch_registry.cpp`](../src/builder/arch_registry.cpp):
-
-- **Verified** — conversion, compilation and decoding checked against a reference on a real
- checkpoint. Numerical regression coverage is described below.
-- **Experimental** — accepted by the registry, but end-to-end support is not established or
- known limitations remain. The frontend emits a warning; acceptance does not guarantee
- correct output.
-
-Without additional architecture registrations, names outside this catalog are rejected at load
-time. External definitions and custom-family catalog entries extend the same registry.
-
-### Verified — 25 architectures
-
-| Architecture | Notes |
-|---|---|
-| `bailingmoe2` | sigmoid routing, biased/grouped expert selection and shared experts |
-| `deepseek2-ocr` | language backbone: dense lead layers and shared/routed experts |
-| `ernie4_5-moe` | interleaved MoE, biased selection, normalized weights and shared experts |
-| `exaone4` | post-norm-only attention and FFN |
-| `gemma` | GeGLU and multi-query attention |
-| `gemma2` | post-norms, SWA, attention and final logit soft-caps |
-| `gemma3` | post-norms and final logit soft-cap |
-| `gemma4` | SWA, per-layer embeddings and shared KV |
-| `gpt-oss` | MoE, attention sinks, SWA and OAI gated activation |
-| `hunyuan-dense` | learned QK-norm after RoPE |
-| `llama` | llama-2 / llama-3 |
-| `maincoder` | NORMAL RoPE; learned QK-norm after RoPE |
-| `mamba2` | Mamba 2 mixer, tied or separate output embeddings; stateful greedy decoding with one sequence |
-| `mellum` | MoE with normalized expert weights |
-| `minicpm` | NORMAL RoPE; embedding/residual scales and inverse logit scale |
-| `mistral3` | dense decoder, NORMAL RoPE |
-| `muse-glimmer` | RoPE on SWA layers, attention output gate, pre/post norms |
-| `nemotron_h` | dense hybrid Mamba 2 / attention / ReLU-squared FFN; stateful greedy decoding with one sequence |
-| `olmoe` | full-width QK-norm and MoE |
-| `phi3` | fused QKV |
-| `qwen2` | qwen2 / qwen2.5 |
-| `qwen3` | QK-norm before RoPE; also covers Bonsai-8B (Q1_0) |
-| `qwen35` | hybrid GatedDeltaNet + full attention, interleaved M-RoPE; greedy / batch 1 only; also covers Bonsai-27B (Q1_0) and Ternary-Bonsai-27B (Q2_0) |
-| `qwen3moe` | NEOX RoPE, per-head QK-norm and normalized expert weights |
-| `smollm3` | NORMAL RoPE, skipped on every fourth layer |
-
-### Experimental — 7 architectures
-
-| Architecture | Status / limitation |
-|---|---|
-| `exaone-moe` | no real checkpoint validated |
-| `glm4moe` | no real checkpoint validated |
-| `hunyuan-moe` | small numerical fixture passes; no real checkpoint validated |
-| `jais2` | no real checkpoint validated |
-| `llama-embed` | needs embedding-specific numerical and pooling tests; completion is not a suitable test |
-| `minimax-m2` | no real checkpoint validated |
-| `plamo3` | native builder disagrees with the real checkpoint reference (0/13 matching choices); post-norm tensors without `.weight` are not recognized |
+[`arch_registry.cpp`](../src/builder/arch_registry.cpp) holds one catalog; other names are rejected at
+`load()` unless an [extension](extensions.md) registers them on that frontend. `clip` selects the
+[mmproj coordinator](mmproj.md).
+
+The checkpoint column counts matching greedy choices over prefill plus twelve reference-token decode
+steps for the prompt `The capital of France is`, through `GGUFMakeStateful`, `AdaptToGenAI` and CPU
+with the [strict accuracy settings](quantization.md#accuracy-controls) (`OV_GGUF_Q4_K_ZP_F16=1` for Q4_K).
+`—` means no recorded real-checkpoint comparison.
+
+| Architecture | Notes | Real checkpoint | Choices |
+|---|---|---|---|
+| `bailingmoe2` | Sigmoid routing, biased/grouped selection, shared experts | Ling-mini-2.0 Q2_K | 12/13 |
+| `deepseek2-ocr` | Language backbone: dense lead layers, shared/routed experts | DeepSeek-OCR-2 Q4_K_M | 13/13 |
+| `ernie4_5-moe` | Interleaved MoE, biased selection, normalized weights, shared experts | ERNIE-4.5-21B-A3B-PT Q4_K_M | 12/13 |
+| `exaone-moe` | Dense lead, shared/routed experts, RoPE on SWA layers only | K-EXAONE-236B-A23B Q2_K | 11/13 ¹ |
+| `exaone4` | Post-norm-only attention and FFN | EXAONE-4.0-1.2B Q4_K_M | 13/13 |
+| `gemma` | GeGLU, multi-query attention | gemma-2b Q4_K_M | 12/13 |
+| `gemma2` | Post-norms, SWA, attention and final soft-caps | gemma-2-2b-it Q4_K_M | 13/13 |
+| `gemma3` | Post-norms, final soft-cap, separate global/local RoPE scaling | — | |
+| `gemma4` | SWA, per-layer embeddings, shared KV, dense plus routed experts | — | |
+| `glm4moe` | Biased sigmoid selection, shared experts, optional QK-norm | GLM-4.5-Air REAP50 Q2_K | 12/13 |
+| `gpt-oss` | MoE, attention sinks, SWA, OAI gated activation; **no numerical fixture** | — | |
+| `hunyuan-dense` | Learned QK-norm after RoPE | Hunyuan-0.5B-Instruct Q8_0 | 13/13 |
+| `hunyuan-moe` | QK-norm after RoPE, routed and shared experts | Hunyuan-A13B-Instruct Q2_K | 13/13 |
+| `jais2` | Biased LayerNorm, ungated ReLU² FFN | Jais-2-8B-Chat Q4_K_M | 13/13 ² |
+| `llama` | llama-2 / llama-3, YaRN | Devstral Small 2507 24B Q4_K_M | 13/13 |
+| `llama-embed` | Per-token embeddings; mean/first/last pooling; causal or bidirectional | Llama-Nemotron-Embed-1B-v2 Q4_K_M | NMSE 3e-6 ² |
+| `maincoder` | NORMAL RoPE, QK-norm after RoPE | Maincoder-1B Q4_K_M | 13/13 |
+| `mamba2` | Mamba 2 mixer, tied or separate output; one-sequence greedy decoding | Mamba2-2.7B Q8_0 | 12/13 ³ |
+| `mellum` | MoE with normalized expert weights | Mellum2-12B-A2.5B-Instruct Q4_K_M | 12/13 |
+| `minicpm` | Embedding/residual scales, inverse logit scale | — | |
+| `minimax-m2` | Full-width QK-norm, partial RoPE, normalized experts | MiniMax-M2.1-REAP-50 Q2_K | 12/13 ⁴ |
+| `mistral3` | Dense, NORMAL RoPE, attention temperature | Devstral Small 2 24B; Ministral-3-3B-Instruct-2512 Q4_K_M | 13/13; 13/13 |
+| `muse-glimmer` | RoPE on SWA layers, attention output gate, pre/post norms | Muse-Glimmer-30B Q4_0 | 13/13 |
+| `nemotron_h` | Hybrid Mamba 2 / attention / ReLU² FFN; one-sequence greedy decoding | Nemotron-H-8B-Reasoning-128K Q4_K_M | 12/13 |
+| `olmoe` | Full-width QK-norm, MoE | — | |
+| `phi3` | Fused QKV | — | |
+| `plamo3` | Fused QKV and gate/up, bare post-norms, SWA | plamo-3-nict-2b-base Q4_K_M | 12/13 |
+| `qwen2` | qwen2 / qwen2.5 | — | |
+| `qwen3` | QK-norm before RoPE; also Bonsai-8B (Q1_0) | — | |
+| `qwen35` | Hybrid GatedDeltaNet + attention, interleaved M-RoPE; batching and beam search with SDPA and PA; also Bonsai-27B (Q1_0), Ternary-Bonsai-27B (Q2_0 g64) | — | |
+| `qwen35moe` | Hybrid GatedDeltaNet, separate or fused routed experts, shared expert | Qwen3.6-35B-A3B Q4_K_M / Q4_0 | 13/13 / 12/13 |
+| `qwen3moe` | NEOX RoPE, per-head QK-norm, normalized experts | Qwen3-0.9B-A0.6B Q4_K_M | 13/13 |
+| `smollm3` | NORMAL RoPE, skipped on every fourth layer | SmolLM3-3B Q4_K_M | 12/13 |
+
+1. Below the acceptance threshold (same first prediction, differences at steps 4–5). Its F32
+ fixtures, including NextN, pass. A staged CPU runner that compiles one layer at a time (u2 expert
+ weights expand) produced coherent chat answers; full-model compilation is not validated.
+2. Against llama.cpp F32 arithmetic on the represented weights. Against its quantized CPU kernels,
+ Jais gives 11/13 with the same first prediction; this remains a validation limitation.
+3. llama.cpp's Q8 path quantizes activations. Against F32 arithmetic on the same weights, Mamba2-130M
+ and 2.7B give 13/13; with OpenVINO dynamic quantization group size 32, both give 13/13 against Q8 CPU.
+4. Peaked at about 222 GiB RAM plus swap because u2 experts expand at CPU compilation; see
+ [memory limits](quantization.md#memory-and-packaging-limits).
### Numerical regression coverage
-[`GGUFArchitectureAccuracy`](../tests/test_arch_accuracy.cpp) contains 26 small, nonzero F32
-fixtures covering 21 verified architecture identifiers and experimental `hunyuan-moe`.
-Additional model variants exercise YaRN and position-dependent attention scaling under
-`llama` and `mistral3`. The suite does not cover `gemma3`, `gemma4`, `gpt-oss` or `qwen35`.
+[`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.
-Each fixture compares complete last-token logits with llama.cpp CPU through multi-token
-prefill, one-token decode and a two-token cache append. The normalized MSE limit is `1e-5`.
-F32 inference, F16 KV cache and disabled activation quantization isolate architecture behavior
-from optional CPU approximations.
-
-The fixtures include single-head KV for Gemma, nonuniform QK-norm weights, Gemma2/Muse
-sliding-window boundaries, SmolLM3's fourth NoPE layer, ERNIE shared experts without
-`expert_shared_count`, and Bailing's sigmoid/grouped routing. Configuration tests also
-cover Gemma2-27B's attention scale, EXAONE4's 64-layer SWA defaults and ERNIE's interleaved
-dense/MoE schedule. Zero-weight conversion fingerprints provide structural smoke coverage.
-
-### Mamba 2 execution
-
-`GGML_OP_SSM_SCAN` uses the existing `SelectiveSSM` operation. `GGUFMakeStateful` normalizes
-convolution caches for OpenVINO's recurrent fusions. Stateful execution supports greedy
-decoding with one sequence and resettable convolution/SSM caches.
-
-CPU tests cover prefill, decode and state reset through the stateful frontend path.
-GenAI paged integration is not included. Beam search and prefix-cache reuse are not verified.
-Mamba 1 and `nemotron_h_moe` are not supported.
+### Runtime limitations
-Regenerate the Mamba references with `gen_arch_accuracy.py --oracle <oracle>
---architectures mamba2 mamba2-tied nemotron_h`, using
-`architecture_oracle.cpp` built against llama.cpp `476c01efe88aad7880a8132d5d3a415f2ca75139`.
+- **Recurrent states:** Gated-DeltaNet states support batching and beams through `AdaptToGenAI`;
+ Mamba 2 and `nemotron_h` support one sequence with greedy decoding and resettable caches, without
+ GenAI paged integration; beam search and prefix-cache reuse are untested. Mamba 1 and
+ `nemotron_h_moe` are not supported. See [runtime.md](runtime.md#stateful-and-genai-conversion).
+- **Multimodal:** a tested language backbone does not cover its vision or audio encoders,
+ preprocessing or application pipeline.
+- **Quantization and memory:** see [quantization.md](quantization.md).
-### Reference-checked checkpoints
+## llama.cpp cgraph path
-The following checkpoint comparisons use the prompt `The capital of France is`, native
-conversion, `GGUFMakeStateful`, `AdaptToGenAI` and CPU compilation.
-The reference's next token is fed back for twelve decode steps, allowing comparison on
-identical histories after a token choice differs. The table counts matching greedy
-choices across prefill and those twelve steps. Q4_K checks use
-`OV_GGUF_Q4_K_ZP_F16=1`; inference uses the precision settings above.
+Manually validated with the backend's stateful execution:
-| Architecture | Real checkpoint | Matching choices |
+| Architecture | Tested model | Notes |
|---|---|---|
-| `bailingmoe2` | Ling-mini-2.0 Q2_K | 12/13 |
-| `deepseek2-ocr` | DeepSeek-OCR-2 Q4_K_M | 13/13 |
-| `ernie4_5-moe` | ERNIE-4.5-21B-A3B-PT Q4_K_M | 12/13 |
-| `exaone4` | EXAONE-4.0-1.2B Q4_K_M | 13/13 |
-| `gemma` | gemma-2b Q4_K_M | 12/13 |
-| `gemma2` | gemma-2-2b-it Q4_K_M | 13/13 |
-| `hunyuan-dense` | Hunyuan-0.5B-Instruct Q8_0 | 13/13 |
-| `llama` | Devstral Small 2507, 24B Q4_K_M | 13/13 |
-| `maincoder` | Maincoder-1B Q4_K_M | 13/13 |
-| `mamba2` | Mamba2-2.7B Q8_0 | 12/13 |
-| `mellum` | Mellum2-12B-A2.5B-Instruct Q4_K_M | 12/13 |
-| `mistral3` | Devstral Small 2, 24B Q4_K_M (text) | 13/13 |
-| `mistral3` | Ministral-3-3B-Instruct-2512 Q4_K_M | 13/13 |
-| `muse-glimmer` | Muse-Glimmer-30B Q4_0 | 13/13 |
-| `nemotron_h` | NVIDIA Nemotron-H-8B-Reasoning-128K Q4_K_M | 12/13 |
-| `qwen3moe` | Qwen3-0.9B-A0.6B Q4_K_M | 13/13 |
-| `smollm3` | SmolLM3-3B Q4_K_M | 12/13 |
-
-The real-model check requires the same first prediction and at least 90% matching
-choices. It records full-logit errors but does not apply the F32 fixture tolerance to
-lossy weight conversions. This is bounded decoder validation, not a quality benchmark
-or a guarantee for every checkpoint, context length, quantization or device. In particular,
-default integer-zero-point Q4_K and U8 KV-cache approximations can change output.
-
-Native Q8_0 preserves weight codes and scales. These comparisons disable OpenVINO's dynamic
-activation quantization (`DYNAMIC_QUANTIZATION_GROUP_SIZE=0`) and use F32 inference.
-llama.cpp's Q8 CPU path quantizes activations. Running llama.cpp with F32 arithmetic on
-the same decoded weights, while keeping OpenVINO's settings unchanged, gives 13/13 matching
-choices for Mamba2-130M and Mamba2-2.7B. The 130M checkpoint has model-hub smoke coverage but
-falls below the agreement threshold against Q8 CPU arithmetic with OpenVINO dynamic
-quantization disabled (11/13). Enabling it with group size 32 gives 13/13 matching choices
-for both checkpoints against llama.cpp Q8 CPU in stateful execution. Full logits still
-differ; their mean normalized error increases despite the improved token agreement.
-
-See [reference generation and reproduction instructions](../tests/test_data/arch_accuracy/README.md).
-These references are shipped with the frontend tests; no model download or llama.cpp
-build is needed in the regular test run. Real-model hub tests separately exercise
-additional checkpoint/quantization combinations in precommit/nightly jobs.
+| `llama` | TinyLlama-1.1B-Chat v1.0 Q4_K_M | Dense, GQA |
+| `qwen2` | Qwen2.5-0.5B-Instruct Q8_0 | Dense |
+| `qwen3` | Qwen3-0.6B Q8_0 | QK-norm |
+| `qwen3moe` | Qwen3-0.9B-A0.6B Q4_K_M, Qwen3-4B Q4_K_M | `mul_mat_id` |
+| `olmoe` | OLMoE-1B-7B-0924-Instruct Q4_0 | MoE |
+| `gemma3` | gemma-3 (checkpoint not recorded) | Mixed SWA/global RoPE |
+| `gemma4` | gemma-4-E4B-it Q4_K_M | Per-op RoPE, F16 KV cache |
+| `qwen35` | Qwen3.5-4B Q4_K_M | GatedDeltaNet, partial-rotary IMROPE, interleaved Q/gate; F16 KV cache |
+
+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:
-### Runtime limitations
+```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
+```
-- **`qwen35`: greedy decoding, batch size 1.** Recurrent states have no batch axis and are
- not reordered by `beam_idx`. Beam search, larger batches, prefix caching and PagedAttention
- are unsupported. Verified checkpoints include Qwen3.5-0.8B Q8_0 and
- Ternary-Bonsai-27B Q2_g64.
-- **Multimodal models:** a verified language backbone does not establish support for its
- vision or audio components, preprocessing or full application pipeline.
-- **Ternary Bonsai packaging:** `Ternary-Bonsai-27B-Q2_0.gguf` uses g128 packing that does
- not match upstream `Q2_0` (g64). Use `Ternary-Bonsai-27B-Q2_g64.gguf`. The frontend
- rejects the mismatched file.
-
-## Extending support
-
-See [adding an architecture](adding_an_architecture.md) for catalog entries and shared decoder
-features, and [porting a model from llama.cpp](porting_a_llama_cpp_model.md) for custom builders
-and runtime extensions. Verified status requires a real-checkpoint reference comparison;
-successful conversion alone is insufficient.
+Checkpoints used `Q2_K`, `Q4_0`, `Q4_K_M`, `Q6_K` and `Q8_0`; other formats are covered by unit tests only.
diff --git a/src/frontends/gguf/docs/testing.md b/src/frontends/gguf/docs/testing.md
new file mode 100644
index 00000000000..b77db4ad14c
--- /dev/null
+++ b/src/frontends/gguf/docs/testing.md
@@ -0,0 +1,119 @@
+# Building and validating the GGUF frontend
+
+Use the repository [build prerequisites](../../../../docs/dev/build.md). GGUF defaults to enabled
+(`ENABLE_OV_GGUF_FRONTEND=ON`); C++ tests require `ENABLE_TESTS=ON` and a shared-library build.
+This Linux single-configuration example puts binaries and libraries in an explicit directory:
+
+```sh
+cmake -S . -B build-gguf -DCMAKE_BUILD_TYPE=Release \
+ -DENABLE_OV_GGUF_FRONTEND=ON -DENABLE_TESTS=ON -DBUILD_SHARED_LIBS=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
+./build-gguf/bin/ov_gguf_frontend_tests
+./build-gguf/bin/ov_gguf_architecture_library_tests
+```
+
+For an existing build, use its configured output directory. OpenVINO normally writes under
+the source tree's `bin/<architecture>/<configuration>`, not necessarily under the CMake build tree.
+Multi-configuration generators can add a configuration subdirectory.
+
+## Select coverage
+
+| Change | Coverage |
+|---|---|
+| Converter or `op_case` | Relevant `GGUFOps` tests, then the full frontend binary for the operation-coverage gate |
+| Architecture/shared decoder blocks | `GGUFArchConversion`, `GGUFArchitectureAccuracy`, relevant adaptation/state tests |
+| mmproj | `GGUFMMProj`, `GGUFMMProjAccuracy`, `GGUFMMProjDynamicAccuracy`; relevant real-checkpoint tests |
+| Extension API or packaging | Builder/extension tests plus the separate architecture-library binary and actual shipped plugin |
+| Weight conversion | Weight/dequantization tests and checkpoint comparisons with recorded precision settings |
+
+Use `--gtest_list_tests` for exact parameterized names; filter while iterating, for example
+`--gtest_filter='GGUFOps.Scale*'`. A narrowed filter skips the operation-coverage gate. That gate
+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.
+
+## Fixtures and oracles
+
+Small NPZ/NPY numerical references are committed and work offline. Missing numerical references
+fail their tests. Architecture header fixtures are generated separately; if none are present,
+`GGUFArchConversion` skips, while a partially generated set fails. Generate them before claiming
+architecture fingerprint coverage.
+
+The generator requires NumPy and the `gguf` Python package (llama.cpp's `gguf-py`) in the active
+environment, plus Git, CMake, and a C/C++ compiler. `--fetch` does not install Python dependencies.
+
+```sh
+python3 src/frontends/gguf/tests/gen_arch_fixtures.py --fetch
+```
+
+This fetches/builds the pinned llama.cpp generator and writes headers plus the manifest under
+`tests/test_data/arch_fixtures`. Review manifest changes. `--llama-src /path/to/llama.cpp` uses an
+existing checkout; see the script's pinned revision and prerequisites. The optional Python
+fingerprint suite also skips unless `GGUF_FINGERPRINT_MODELS=name=path[=hash];...` is set.
+Fingerprints are structural checks, not proof of numerical equivalence.
+
+Regenerate numerical fixtures using their own contracts and reference revisions:
+
+- [Decoder/embedding references](../tests/test_data/arch_accuracy/README.md), including the
+ separately recorded Mamba 2/Nemotron-H oracle revision.
+- [mmproj references](../tests/test_data/mmproj_accuracy/README.md), including raw/adapted output
+ checks and multiple sizes on one compiled model.
+- [Single-operation oracles](debugging_accuracy.md#the-ggml-cpu-oracle) for layout-sensitive operations.
+
+## Real checkpoints
+
+Use a Python environment containing the matching OpenVINO build with the GGUF frontend.
+From the repository root, install the test dependencies and run the selected model-hub scope:
+
+```sh
+python3 -m pip install -r tests/requirements_gguf
+TEST_DEVICE=CPU PYTHONPATH="$PWD/tests/model_hub_tests${PYTHONPATH:+:$PYTHONPATH}" \
+ python3 -m pytest tests/model_hub_tests/gguf -m precommit -v
+```
+
+Use `-m nightly` for the larger list, or select `test_gguf.py` / `test_gguf_mmproj.py`.
+Decoder model-hub tests check finite, shaped outputs and state updates; they do not compare
+tokens/logits against a reference. The native reference-token replay instead uses
+`OV_GGUF_ACCURACY_DATA` (and `OV_GGUF_EMBEDDING_DATA` for `llama-embed`) as described in the
+[decoder fixture README](../tests/test_data/arch_accuracy/README.md). Run this separately: the
+variable replaces the selected synthetic fixture with a local checkpoint.
+
+mmproj model-hub tests compare real checkpoint encoders against llama.cpp on an F32 copy of the
+represented weights. They use generated test inputs, not a full media application. Downloads,
+a C/C++ compiler, Git, CMake, and Ninja are needed. Reference builds are cached under
+`GGUF_LLAMA_CPP_CACHE` (default `~/.cache/openvino_gguf_llama_cpp`). `GGUF_MMPROJ_ORACLE` selects a
+prebuilt oracle, but the pinned checkout is still needed for `gguf-py`. `HF_HUB_CACHE` controls
+checkpoint caching. To use local files, point `GGUF_MMPROJ_LIST` at a replacement precommit list:
+
+```text
+gemma3,,/absolute/path/mmproj-gemma3.gguf
+voxtral,,/absolute/path/mmproj-voxtral.gguf
+```
+
+The list format, skip reasons, and tolerance overrides live in
+[precommit](../../../../tests/model_hub_tests/gguf/gguf_mmproj_precommit) and
+[nightly](../../../../tests/model_hub_tests/gguf/gguf_mmproj_nightly).
+
+## Acceptance
+
+Keep registration, structural conversion, numerical agreement, and application functionality
+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 |
+|---|---|
+| Native decoder F32 fixture | Full-logit normalized MSE below `1e-5`; 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 |
+
+Use [quantization controls](quantization.md#accuracy-controls) consistently. Report checkpoint,
+revisions, device, precision, inputs, thresholds, skips, and failures. A represented-F32 reference
+does not erase a failed comparison against quantized CPU arithmetic, and coherent generated text
+does not establish encoder accuracy or broad answer quality.
+
+CI runs the two C++ binaries through [Smart CI's GGUF component gate](../../../../.github/workflows/job_cxx_unit_tests.yml).
+[Model-hub CI](../../../../.github/workflows/job_gguf_models_tests.yml) runs checkpoint lists;
+[llama.cpp compatibility CI](../../../../.github/workflows/job_gguf_llamacpp_validation.yml) records
+the backend revision, operator tests, state scenarios, and exclusions. These validate different contracts.
diff --git a/src/frontends/gguf/examples/architecture_extension/CMakeLists.txt b/src/frontends/gguf/examples/architecture_extension/CMakeLists.txt
index 7f95ab7f2e1..5f4de074bbf 100644
--- a/src/frontends/gguf/examples/architecture_extension/CMakeLists.txt
+++ b/src/frontends/gguf/examples/architecture_extension/CMakeLists.txt
@@ -2,8 +2,20 @@
# SPDX-License-Identifier: Apache-2.0
cmake_minimum_required(VERSION 3.16)
-project(gguf_projector_extension LANGUAGES CXX)
+project(gguf_extensions LANGUAGES CXX)
find_package(OpenVINO REQUIRED)
+if(NOT TARGET openvino::frontend::gguf)
+ message(FATAL_ERROR "The OpenVINO development package must include the GGUF frontend")
+endif()
+
add_library(gguf_projector_extension MODULE projector.cpp extension.cpp)
-target_compile_features(gguf_projector_extension PRIVATE cxx_std_17)
-target_link_libraries(gguf_projector_extension PRIVATE openvino::frontend::gguf)
+add_library(gguf_mmproj_extension MODULE mmproj_extension.cpp)
+add_library(gguf_decoder_extension MODULE decoder_extension.cpp)
+foreach(extension IN ITEMS gguf_projector_extension gguf_mmproj_extension gguf_decoder_extension)
+ target_compile_features(${extension} PRIVATE cxx_std_17)
+ target_link_libraries(${extension} PRIVATE openvino::frontend::gguf)
+endforeach()
+
+add_executable(gguf_extension_runner runner.cpp)
+target_compile_features(gguf_extension_runner PRIVATE cxx_std_17)
+target_link_libraries(gguf_extension_runner PRIVATE openvino::runtime openvino::frontend::gguf)
diff --git a/src/frontends/gguf/examples/architecture_extension/README.md b/src/frontends/gguf/examples/architecture_extension/README.md
new file mode 100644
index 00000000000..38521e1a72a
--- /dev/null
+++ b/src/frontends/gguf/examples/architecture_extension/README.md
@@ -0,0 +1,63 @@
+# GGUF extension examples
+
+This standalone project builds three plugins and a CPU runner against a matching
+OpenVINO development package containing the GGUF frontend. No OpenVINO rebuild is
+needed when building extensions against an already installed compatible package.
+
+| Target | Extension | File contract |
+|---|---|---|
+| `gguf_projector_extension` | Whole-model `ArchitectureExtension` | `general.architecture = example-projector`; F32 `projection.weight` with GGUF dimensions `[input_width, output_width]` |
+| `gguf_decoder_extension` | `ArchitectureExtension` reusing the decoder builder | `general.architecture = example-qwen3`; Qwen3-compatible decoder metadata and tensors |
+| `gguf_mmproj_extension` | Two `ProjectorExtension` registrations | `clip` mmproj: `vision / example-gemma3` reuses Gemma3; `audio / example-linear` builds a custom projection branch |
+
+The whole-model projection plugin builds and finishes its own graph. The mmproj
+plugin contributes a branch to the coordinator's shared graph. Its custom audio
+example takes caller-provided embeddings and applies
+`example.audio.projection.weight`; it does not implement waveform preprocessing or
+an audio encoder. The Gemma3 alias requires real Gemma3-compatible encoder metadata
+and weights. Changing a projector label alone does not make an unrelated model compatible.
+
+## Build
+
+```sh
+cmake -S src/frontends/gguf/examples/architecture_extension -B /tmp/gguf-extensions \
+ -DOpenVINO_DIR=/path/to/openvino/runtime/cmake
+cmake --build /tmp/gguf-extensions --parallel
+```
+
+Use the generated library and executable paths for your platform and build configuration.
+The commands below use Linux paths. If the dynamic loader cannot find OpenVINO libraries,
+source the installation's `setupvars.sh` first. Build against the release that will load
+these plugins; the GGUF developer API does not guarantee compatibility across releases.
+
+## Run small synthetic inputs
+
+The fixture generator uses Python's standard library and downloads nothing:
+
+```sh
+python3 src/frontends/gguf/examples/architecture_extension/generate_fixtures.py /tmp/gguf-inputs
+/tmp/gguf-extensions/gguf_extension_runner \
+ /tmp/gguf-extensions/libgguf_projector_extension.so /tmp/gguf-inputs/projection.gguf 3
+/tmp/gguf-extensions/gguf_extension_runner \
+ /tmp/gguf-extensions/libgguf_mmproj_extension.so /tmp/gguf-inputs/mmproj.gguf 3
+/tmp/gguf-extensions/gguf_extension_runner \
+ /tmp/gguf-extensions/libgguf_decoder_extension.so /tmp/gguf-inputs/decoder.gguf 3 --stateful
+```
+
+Both projection examples return `[1,1,3,3]` embeddings; with the runner's all-one
+inputs, each token's values are `[3,7,11]`. The decoder example returns `[1,1,16]` last-token logits and
+exercises `GenAIExtension`, which creates stateful caches and adapts IO after frontend normalization.
+
+The runner registers the library before loading the file, converts it, compiles on
+CPU, fills supported inputs, checks that F32 outputs are finite, and prints output names, shapes, types and first values.
+It supplies synthetic inputs for these fixtures, not tokenization, chat generation,
+media preprocessing, or a general multimodal input pipeline. `TOKENS` controls dynamic
+token dimensions. Use `--stateful` for the decoder fixture; explicit cache inputs in
+stateless decoders require a model-specific harness.
+
+To try the Gemma3 reuse entry, prepare a compatible mmproj GGUF with resolved vision
+projector type `example-gemma3` and use `libgguf_mmproj_extension.so`. For real media,
+provide the correct preprocessing and positional inputs described in [mmproj.md](../../docs/mmproj.md).
+
+See [extensions.md](../../docs/extensions.md) for whole-decoder builders, operation
+conversion extensions, normalization passes, component replacement, and registration timing.
diff --git a/src/frontends/gguf/examples/architecture_extension/decoder_extension.cpp b/src/frontends/gguf/examples/architecture_extension/decoder_extension.cpp
new file mode 100644
index 00000000000..2ea7d3af0d1
--- /dev/null
+++ b/src/frontends/gguf/examples/architecture_extension/decoder_extension.cpp
@@ -0,0 +1,8 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/frontend/gguf/extension/architecture.hpp"
+
+OPENVINO_CREATE_EXTENSIONS(std::vector<ov::Extension::Ptr>{
+ std::make_shared<ov::frontend::gguf::ArchitectureExtension>("example-qwen3", ov::frontend::gguf::RopeMode::Neox)});
diff --git a/src/frontends/gguf/examples/architecture_extension/generate_fixtures.py b/src/frontends/gguf/examples/architecture_extension/generate_fixtures.py
new file mode 100644
index 00000000000..ee23e5a7417
--- /dev/null
+++ b/src/frontends/gguf/examples/architecture_extension/generate_fixtures.py
@@ -0,0 +1,88 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+"""Write small synthetic GGUF inputs for the extension examples (standard library only)."""
+
+import argparse
+import math
+import struct
+from pathlib import Path
+
+
+def string(value):
+ data = value.encode("utf-8")
+ return struct.pack("<Q", len(data)) + data
+
+
+def write(path, metadata, tensors):
+ header = struct.pack("<IIQQ", 0x46554747, 3, len(tensors), len(metadata))
+ for key, value in metadata.items():
+ header += string(key)
+ if isinstance(value, bool):
+ header += struct.pack("<I?", 7, value)
+ elif isinstance(value, str):
+ header += struct.pack("<I", 8) + string(value)
+ elif isinstance(value, float):
+ header += struct.pack("<If", 6, value)
+ else:
+ header += struct.pack("<II", 4, value)
+ payload = bytearray()
+ for name, dimensions, values in tensors:
+ payload.extend(bytes((-len(payload)) % 32))
+ header += string(name) + struct.pack("<I", len(dimensions))
+ header += struct.pack("<" + "Q" * len(dimensions), *dimensions)
+ header += struct.pack("<IQ", 0, len(payload))
+ payload.extend(struct.pack("<" + "f" * len(values), *values))
+ path.write_bytes(header + bytes((-len(header)) % 32) + payload)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("output", type=Path)
+ args = parser.parse_args()
+ args.output.mkdir(parents=True, exist_ok=True)
+ weights = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
+ write(args.output / "projection.gguf", {"general.architecture": "example-projector"},
+ [("projection.weight", [2, 3], weights)])
+ write(args.output / "mmproj.gguf", {
+ "general.architecture": "clip",
+ "clip.has_audio_encoder": True,
+ "clip.audio.projector_type": "example-linear",
+ }, [("example.audio.projection.weight", [2, 3], weights)])
+
+ arch = "example-qwen3"
+ metadata = {
+ "general.architecture": arch,
+ f"{arch}.block_count": 1,
+ f"{arch}.embedding_length": 8,
+ f"{arch}.attention.head_count": 2,
+ f"{arch}.attention.head_count_kv": 1,
+ f"{arch}.rope.dimension_count": 4,
+ f"{arch}.context_length": 32,
+ f"{arch}.attention.layer_norm_rms_epsilon": 1e-5,
+ }
+ tensors = []
+
+ def weight(name, dimensions, norm=False):
+ count = math.prod(dimensions)
+ values = [1.0 + 0.01 * math.sin(i) if norm else 0.05 * math.sin(i + 1) for i in range(count)]
+ tensors.append((name, dimensions, values))
+
+ weight("token_embd.weight", [8, 16])
+ weight("output_norm.weight", [8], True)
+ weight("blk.0.attn_norm.weight", [8], True)
+ for name, dimensions in [("attn_q", [8, 8]), ("attn_k", [8, 4]), ("attn_v", [8, 4]),
+ ("attn_output", [8, 8])]:
+ weight(f"blk.0.{name}.weight", dimensions)
+ for name in ["attn_q_norm", "attn_k_norm"]:
+ weight(f"blk.0.{name}.weight", [4], True)
+ weight("blk.0.ffn_norm.weight", [8], True)
+ weight("blk.0.ffn_gate.weight", [8, 12])
+ weight("blk.0.ffn_up.weight", [8, 12])
+ weight("blk.0.ffn_down.weight", [12, 8])
+ write(args.output / "decoder.gguf", metadata, tensors)
+ print(f"Wrote projection.gguf, mmproj.gguf and decoder.gguf to {args.output}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/frontends/gguf/examples/architecture_extension/mmproj_extension.cpp b/src/frontends/gguf/examples/architecture_extension/mmproj_extension.cpp
new file mode 100644
index 00000000000..8c1212bc4ed
--- /dev/null
+++ b/src/frontends/gguf/examples/architecture_extension/mmproj_extension.cpp
@@ -0,0 +1,38 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/core/extension.hpp"
+#include "openvino/frontend/gguf/extension/projector.hpp"
+
+namespace {
+ov::frontend::gguf::ProjectorDefinition gemma3_alias() {
+ using namespace ov::frontend::gguf;
+ return {"clip.vision.example-gemma3",
+ "clip",
+ "vision",
+ "example-gemma3",
+ [](GgufGraphContext& graph) {
+ return build_builtin_projector(graph, "vision", "gemma3");
+ },
+ {}};
+}
+ov::frontend::gguf::ProjectorDefinition audio_projection() {
+ using namespace ov::frontend::gguf;
+ return {"clip.audio.example-linear",
+ "clip",
+ "audio",
+ "example-linear",
+ [](GgufGraphContext& graph) {
+ const auto weight = graph.tensors().require("example.audio.projection.weight");
+ const auto input =
+ graph.add_input("audio.example_embeddings", ov::element::f32, {1, 1, -1, weight.ne(0)});
+ return ProjectorResult{graph.node("GGML_OP_MUL_MAT", {weight, input}), {{"audio.merge", "1"}}};
+ },
+ {}};
+}
+} // namespace
+
+OPENVINO_CREATE_EXTENSIONS((std::vector<ov::Extension::Ptr>{
+ std::make_shared<ov::frontend::gguf::ProjectorExtension>(gemma3_alias()),
+ std::make_shared<ov::frontend::gguf::ProjectorExtension>(audio_projection())}))
diff --git a/src/frontends/gguf/examples/architecture_extension/runner.cpp b/src/frontends/gguf/examples/architecture_extension/runner.cpp
new file mode 100644
index 00000000000..24a2f63a70b
--- /dev/null
+++ b/src/frontends/gguf/examples/architecture_extension/runner.cpp
@@ -0,0 +1,82 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <algorithm>
+#include <cmath>
+#include <iostream>
+#include <stdexcept>
+
+#include "openvino/frontend/gguf/extension/genai.hpp"
+#include "openvino/frontend/gguf/frontend.hpp"
+#include "openvino/openvino.hpp"
+
+int main(int argc, char** argv) {
+ try {
+ if (argc < 3 || argc > 5) {
+ std::cerr << "Usage: gguf_extension_runner EXTENSION_LIBRARY MODEL.gguf [TOKENS] [--stateful]\n";
+ return 2;
+ }
+ const bool stateful = argc >= 4 && std::string(argv[argc - 1]) == "--stateful";
+ const auto argument_count = argc - (stateful ? 1 : 0);
+ if (argument_count > 4)
+ throw std::invalid_argument("Expected --stateful after TOKENS");
+ const auto tokens = argument_count == 4 ? std::stoul(argv[3]) : 3;
+ if (!tokens)
+ throw std::invalid_argument("TOKENS must be positive");
+ std::shared_ptr<ov::frontend::FrontEnd> frontend = std::make_shared<ov::frontend::gguf::FrontEnd>();
+ frontend->add_extension(std::string(argv[1]));
+ if (stateful) {
+ frontend->add_extension(std::make_shared<ov::frontend::gguf::GenAIExtension>());
+ }
+ auto model = frontend->convert(frontend->load(std::string(argv[2])));
+ auto compiled = ov::Core{}.compile_model(model, "CPU", ov::hint::inference_precision(ov::element::f32));
+ auto request = compiled.create_infer_request();
+ for (const auto& input : compiled.inputs()) {
+ const auto name = input.get_names().empty() ? input.get_node()->get_friendly_name() : input.get_any_name();
+ auto shape = input.get_partial_shape();
+ if (shape.rank().is_dynamic())
+ throw std::runtime_error("The example runner requires a known input rank");
+ ov::Shape concrete;
+ for (const auto& dimension : shape)
+ concrete.push_back(dimension.is_static() ? dimension.get_length() : tokens);
+ if (name == "input_ids" || name == "position_ids" || name == "attention_mask" || name == "beam_idx")
+ concrete[0] = 1;
+ ov::Tensor tensor(input.get_element_type(), concrete);
+ if (tensor.get_element_type() == ov::element::f32)
+ std::fill_n(tensor.data<float>(),
+ tensor.get_size(),
+ name.find("mask") != std::string::npos ? 0.f : 1.f);
+ else if (tensor.get_element_type() == ov::element::i32)
+ std::fill_n(tensor.data<int32_t>(), tensor.get_size(), 0);
+ else if (tensor.get_element_type() == ov::element::i64) {
+ const int64_t value = name == "token_len_per_seq" ? static_cast<int64_t>(tokens)
+ : name == "attention_mask" ? 1
+ : 0;
+ std::fill_n(tensor.data<int64_t>(), tensor.get_size(), value);
+ } else
+ throw std::runtime_error("Unsupported example input type for " + name);
+ if (name == "position_ids" && tensor.get_element_type() == ov::element::i64)
+ for (size_t i = 0; i < tensor.get_size(); ++i)
+ tensor.data<int64_t>()[i] = i;
+ request.set_tensor(input, tensor);
+ }
+ request.infer();
+ for (const auto& output : compiled.outputs()) {
+ auto tensor = request.get_tensor(output);
+ if (tensor.get_element_type() == ov::element::f32)
+ for (size_t i = 0; i < tensor.get_size(); ++i)
+ if (!std::isfinite(tensor.data<const float>()[i]))
+ throw std::runtime_error("Non-finite output");
+ std::cout << (output.get_names().empty() ? "output" : output.get_any_name()) << " " << tensor.get_shape()
+ << " " << tensor.get_element_type();
+ if (tensor.get_element_type() == ov::element::f32 && tensor.get_size())
+ std::cout << " first=" << tensor.data<const float>()[0];
+ std::cout << '\n';
+ }
+ return 0;
+ } catch (const std::exception& error) {
+ std::cerr << error.what() << '\n';
+ return 1;
+ }
+}
diff --git a/src/frontends/gguf/include/openvino/frontend/gguf/adapt_mmproj_to_genai.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/adapt_mmproj_to_genai.hpp
new file mode 100644
index 00000000000..64ed6ccdfb1
--- /dev/null
+++ b/src/frontends/gguf/include/openvino/frontend/gguf/adapt_mmproj_to_genai.hpp
@@ -0,0 +1,24 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/frontend/gguf/visibility.hpp"
+#include "openvino/pass/pass.hpp"
+
+namespace ov::frontend::gguf::pass {
+
+/// Select an encoder from a combined mmproj and expose its GenAI embedding layout [B,T,D].
+/// Run on independent clones to obtain both modalities. The source graph contains both encoders.
+class GGUF_FRONTEND_API AdaptMmprojToGenAI : public ov::pass::ModelPass {
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::frontend::gguf::pass::AdaptMmprojToGenAI");
+ enum class Modality { VISION, AUDIO };
+ explicit AdaptMmprojToGenAI(Modality modality) : m_modality(modality) {}
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+
+private:
+ Modality m_modality;
+};
+} // namespace ov::frontend::gguf::pass
diff --git a/src/frontends/gguf/include/openvino/frontend/gguf/adapt_to_genai.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/adapt_to_genai.hpp
index fe0b47781a3..918bc0fb0b3 100644
--- a/src/frontends/gguf/include/openvino/frontend/gguf/adapt_to_genai.hpp
+++ b/src/frontends/gguf/include/openvino/frontend/gguf/adapt_to_genai.hpp
@@ -28,6 +28,9 @@ namespace ov::frontend::gguf::pass {
/// the KV-cache sinks are preserved, and beam_idx (created by the make-stateful pass) passes
/// through unchanged since genai sets that tensor itself.
///
+/// Gated-DeltaNet recurrent states get a dynamic batch dimension and follow beam_idx; models with
+/// other recurrent states (Mamba 2) keep input_ids at one sequence.
+///
/// token_len_per_seq is optional when the source graph does not consume it.
/// If the required gguf inputs are absent (e.g. the model is already in genai form), the
/// pass is a no-op and returns false.
@@ -44,17 +47,36 @@ public:
OPENVINO_MODEL_PASS_RTTI("ov::frontend::gguf::pass::AdaptToGenAI");
/// \brief Which genai input contract to expose.
- /// IDS_TO_LOGITS : input_ids -> logits (text LLMPipeline). The only mode implemented today.
- /// EMBEDS_TO_LOGITS: inputs_embeds -> logits (reserved for the VLM language model, where
- /// image+text embeddings are merged outside the graph). Not yet implemented.
+ /// IDS_TO_LOGITS : input_ids -> logits (text LLMPipeline).
+ /// EMBEDS_TO_LOGITS: raw inputs_embeds -> logits, with scaling retained in the decoder.
+ /// Token-dependent auxiliary branches retain input_ids when required. Per-layer token
+ /// embeddings (Gemma4 E2B/E4B) move to a separate lookup model and become the
+ /// per_layer_inputs [B,T,layers,width] input; Gemma3 and other Gemma4 models take
+ /// token_type_ids [B,T] for bidirectional attention within each image. M-RoPE models
+ /// receive position_ids [4,B,T], containing GenAI's sequence/time/height/width sections;
+ /// callers supply all sections.
enum class InputMode { IDS_TO_LOGITS, EMBEDS_TO_LOGITS };
explicit AdaptToGenAI(InputMode mode = InputMode::IDS_TO_LOGITS) : m_mode(mode) {}
bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+ /// Raw token lookup extracted by EMBEDS_TO_LOGITS, sharing the original weight buffers.
+ /// Available after a successful run; inputs input_ids [B,T], output inputs_embeds [B,T,D].
+ const std::shared_ptr<ov::Model>& get_embedding_model() const {
+ return m_embedding_model;
+ }
+
+ /// Per-layer token lookup extracted by EMBEDS_TO_LOGITS (Gemma4 E2B/E4B), or null.
+ /// Inputs input_ids [B,T], output per_layer_inputs [B,T,layers,width].
+ const std::shared_ptr<ov::Model>& get_per_layer_embedding_model() const {
+ return m_per_layer_embedding_model;
+ }
+
private:
InputMode m_mode;
+ std::shared_ptr<ov::Model> m_embedding_model;
+ std::shared_ptr<ov::Model> m_per_layer_embedding_model;
};
} // namespace ov::frontend::gguf::pass
diff --git a/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hpp
index 6a02f187098..2ccb32ea88a 100644
--- a/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hpp
+++ b/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hpp
@@ -4,6 +4,7 @@
#pragma once
+#include <array>
#include <cstdint>
#include <functional>
#include <map>
@@ -41,6 +42,9 @@ struct RopeConfig {
// matches the per-op translate_rope path -- otherwise it builds a NEOX table whose token axis is
// 4x the data's and the rope Multiply fails the eltwise broadcast check.
bool is_imrope = false;
+ // Per-axis frequency counts for temporal, height, width and extra positions.
+ // An all-zero value retains the legacy interleaved three-axis assignment.
+ std::array<int32_t, 4> sections{};
};
// Decoder interface consumed by the gguf frontend translators.
@@ -134,6 +138,12 @@ public:
return empty;
}
+ // Full clip.* keys and resolved multimodal graph contracts. Values are serializable strings.
+ virtual const ov::AnyMap& get_mmproj_config() const {
+ static const ov::AnyMap empty;
+ return empty;
+ }
+
// Recurrent states, as {input name, output name} pairs: a linear-attention architecture
// (qwen35's Gated DeltaNet) carries a conv window and a delta matrix per recurrent layer,
// which the stateless graph exposes as a Parameter read at the start of a step and a Result
diff --git a/src/frontends/gguf/include/openvino/frontend/gguf/extension/genai.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/extension/genai.hpp
new file mode 100644
index 00000000000..3fefe3d8a79
--- /dev/null
+++ b/src/frontends/gguf/include/openvino/frontend/gguf/extension/genai.hpp
@@ -0,0 +1,36 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/core/extension.hpp"
+#include "openvino/frontend/gguf/adapt_to_genai.hpp"
+
+namespace ov::frontend::gguf {
+
+/// Prepare a decoder for GenAI during convert(): stateful caches, then normalized GenAI IO.
+/// Register before convert(), without separate GGUFMakeStateful or AdaptToGenAI passes.
+class GGUF_FRONTEND_API GenAIExtension : public ov::Extension {
+public:
+ OPENVINO_RTTI("gguf::GenAIExtension", "", ov::Extension);
+ using InputMode = pass::AdaptToGenAI::InputMode;
+
+ explicit GenAIExtension(InputMode mode = InputMode::IDS_TO_LOGITS) : m_mode(mode) {}
+
+ /// Extracted lookup models from the latest successful conversion in EMBEDS_TO_LOGITS mode.
+ const std::shared_ptr<ov::Model>& get_embedding_model() const {
+ return m_embedding_model;
+ }
+ const std::shared_ptr<ov::Model>& get_per_layer_embedding_model() const {
+ return m_per_layer_embedding_model;
+ }
+
+private:
+ friend class FrontEnd;
+ InputMode m_mode;
+ std::shared_ptr<ov::Model> m_embedding_model;
+ std::shared_ptr<ov::Model> m_per_layer_embedding_model;
+};
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/include/openvino/frontend/gguf/frontend.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/frontend.hpp
index 9accac4d44c..2387a66f8b4 100644
--- a/src/frontends/gguf/include/openvino/frontend/gguf/frontend.hpp
+++ b/src/frontends/gguf/include/openvino/frontend/gguf/frontend.hpp
@@ -39,11 +39,17 @@ public:
/// registers `ov::frontend::gguf::pass::GGUFMakeStateful` (or its own variant) here; without one
/// the frontend converts to a stateless graph.
/// - `ov::frontend::gguf::ArchitectureExtension` — registers decoder or custom-family builders
- /// without rebuilding the frontend. See docs/porting_a_llama_cpp_model.md.
- /// - `ov::frontend::TelemetryExtension` — receives error / event callbacks.
+ /// before load(), without rebuilding the frontend. See docs/extensions.md.
+ /// - `ov::frontend::gguf::ProjectorExtension` — registers one mmproj branch before load().
+ /// - `ov::frontend::gguf::GenAIExtension` — creates stateful decoder caches during normalization
+ /// and adapts the normalized model to GenAI IO before convert() returns.
+ /// - `ov::frontend::TelemetryExtension` — stored; callbacks are not currently invoked.
/// - `ov::detail::SOExtension` — shared-library extension; its inner extension is recursively registered.
/// - `ov::BaseOpExtension` — recursively registers attached op-level extensions.
///
+ /// Conversion and transformation extensions must be registered before convert().
+ /// Registrations affect only this frontend instance.
+ ///
/// \param extension Extension to register.
void add_extension(const std::shared_ptr<ov::Extension>& extension) override;
diff --git a/src/frontends/gguf/include/openvino/frontend/gguf/make_stateful.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/make_stateful.hpp
index 26fc1467f9c..c76e08ff806 100644
--- a/src/frontends/gguf/include/openvino/frontend/gguf/make_stateful.hpp
+++ b/src/frontends/gguf/include/openvino/frontend/gguf/make_stateful.hpp
@@ -36,6 +36,7 @@ namespace ov::frontend::gguf::pass {
/// it in a decoder would leave a consumer-less input on the stateless graph.
/// - the ReadValue init must be empty: CPU's stateful_sdpa_fusion folds the cache into
/// ScaledDotProductAttentionWithKVCache, whose MemoryInputSDPA aborts on zero parent edges.
+/// Caches fused into SDPA broadcast it to the beam_idx batch; plain states need a constant.
///
/// Scope: this grows the cache and deliberately does not touch the attention mask. The native
/// builder emits a dynamically sized mask, which needs no change; a graph that preallocates a
diff --git a/src/frontends/gguf/src/builder/api/graph_context.cpp b/src/frontends/gguf/src/builder/api/graph_context.cpp
index 71e31ebe525..328cc390ba7 100644
--- a/src/frontends/gguf/src/builder/api/graph_context.cpp
+++ b/src/frontends/gguf/src/builder/api/graph_context.cpp
@@ -204,6 +204,18 @@ void GgufGraphContext::set_primary_output(const GgufValue& value) {
outputs.insert(outputs.begin(), m_impl->value_name(value));
}
+void GgufGraphContext::set_output(const GgufValue& value, const std::string& name) {
+ m_impl->check_open();
+ auto& emitter = m_impl->emitter;
+ OPENVINO_ASSERT(!name.empty() && !emitter.graph()->values->count(name) && !emitter.has_weight(name),
+ "[GGUF] output name is already used: ",
+ name);
+ emitter.add_op("GGML_OP_CONT", name, {m_impl->value_name(value)}, 1, {{"op_case", 1}});
+ // The copy may be the source tensor itself; keep the names it already exposes.
+ emitter.value(name).get_tensor().add_names({name});
+ emitter.graph()->model_output_names.push_back(name);
+}
+
void GgufGraphContext::set_sliding_window(int64_t tokens) {
m_impl->check_open();
OPENVINO_ASSERT(tokens > 0 && tokens <= std::numeric_limits<int>::max(),
@@ -244,6 +256,7 @@ std::shared_ptr<GgufGraph> GgufGraphContext::finish() {
OPENVINO_ASSERT(available.count(input), "[GGUF] node '", node.name, "' uses unknown value '", input, "'");
}
available.insert(node.output_name);
+ available.insert(node.extra_output_names.begin(), node.extra_output_names.end());
}
std::set<std::string> outputs;
for (const auto& output : graph->model_output_names) {
diff --git a/src/frontends/gguf/src/builder/arch/decoder_builder.cpp b/src/frontends/gguf/src/builder/arch/decoder_builder.cpp
index e664f6c9ce1..b88e68f37ed 100644
--- a/src/frontends/gguf/src/builder/arch/decoder_builder.cpp
+++ b/src/frontends/gguf/src/builder/arch/decoder_builder.cpp
@@ -20,7 +20,13 @@
#include "builder/blocks/common.hpp"
#include "builder/blocks/ffn.hpp"
#include "builder/blocks/gated_delta_net.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/gather.hpp"
#include "openvino/op/parameter.hpp"
+#include "openvino/op/reduce_mean.hpp"
+#include "openvino/op/shape_of.hpp"
+#include "openvino/op/squeeze.hpp"
+#include "openvino/op/subtract.hpp"
namespace ov::frontend::gguf {
@@ -54,7 +60,8 @@ void DecoderBuilder::build_inputs() {
// index inputs.
m_emit.add_input("inp_tokens", i32, ps({1, 1, 1, D}));
m_emit.add_input("inp_pos", i32, ps({1, 1, 1, D}));
- m_emit.add_input("inp_out_ids", i32, ps({1, 1, 1, D}));
+ if (!m_cfg.embedding_model)
+ m_emit.add_input("inp_out_ids", i32, ps({1, 1, 1, D}));
m_emit.add_input("self_kq_mask", f32, ps({1, 1, D, D}));
// gpt-oss alternates sliding-window / full attention; the windowed mask is a separate
// input. Only added when the model uses SWA.
@@ -68,7 +75,8 @@ void DecoderBuilder::build_inputs() {
// Gather on the past, is emitted.
// KV-cache update index (consumed by SET_ROWS; unused in the stateful Concat branch).
- m_emit.add_input("inp_kv_idx", i32, ps({1, 1, 1, D}));
+ if (!m_cfg.embedding_model)
+ m_emit.add_input("inp_kv_idx", i32, ps({1, 1, 1, D}));
// token_len_per_seq: number of new tokens per sequence; used by TranslateSession's mask
// slicing (add_sliced_mask) to build KQ_mask_sliced. An extra (Parameter) input.
@@ -82,10 +90,18 @@ std::string DecoderBuilder::build_embeddings() {
// 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"});
- // MiniCPM scales the embeddings by a constant.
+ // The tagged node ends the lookup that AdaptToGenAI moves into the embedding model.
+ const auto mark_token_embedding = [&](const std::string& name) {
+ m_emit.value(name).get_node_shared_ptr()->get_rt_info()["gguf.token_embedding"] = true;
+ };
+ if (!m_cfg.embedding_scale_tokens_only)
+ mark_token_embedding(cur);
+ // Gemma and MiniCPM scale the embeddings by a constant.
if (m_cfg.embedding_scale != 1.0f) {
cur = blocks::scale(m_emit, cur, m_cfg.embedding_scale, "embd_scaled");
}
+ if (m_cfg.embedding_scale_tokens_only)
+ mark_token_embedding(cur);
// muse-glimmer normalizes the token embeddings with a WEIGHTLESS RMSNorm before layer 0
// (build_norm with a null weight -> plain ggml_rms_norm, no multiplicative term).
if (m_cfg.scaleless_embd_norm) {
@@ -138,6 +154,9 @@ void DecoderBuilder::build_per_layer_embeddings(const std::string& embd) {
auto pe_flat = m_emit.add_op("GGML_OP_GET_ROWS", "pe_tok_flat", {"per_layer_token_embd.weight", "inp_tokens"});
const float pe_scale = std::sqrt(static_cast<float>(pe));
pe_flat = blocks::scale(m_emit, pe_flat, pe_scale, "pe_tok_flat_scaled");
+ // Moved to the embedding model as per_layer_inputs in AdaptToGenAI's embedding mode.
+ m_emit.value(pe_flat).get_node_shared_ptr()->get_rt_info()["gguf.per_layer_token_embedding"] =
+ static_cast<int64_t>(n_layer);
auto pe_tok = reshape_to_layer_major(pe_flat, "pe_tok");
// Model projection: MUL_MAT(per_layer_model_proj, embd) -> [1,1,T, pe_total]
@@ -188,7 +207,7 @@ std::string DecoderBuilder::inject_per_layer_embedding(int il, const std::string
// gemma4.cpp:347-349: also filter pl_slice so the MUL doesn't broadcast it back to the full
// sequence length.
std::string pl_slice_used = pl_slice;
- if (il == m_cfg.n_layer - 1) {
+ if (selects_output_rows(il)) {
pl_slice_used = p + "per_layer_slice_sel";
m_emit.add_op("GGML_OP_GET_ROWS", pl_slice_used, {pl_slice, "inp_out_ids"});
}
@@ -217,11 +236,11 @@ std::string DecoderBuilder::build_layer(int il, const std::string& layer_in) {
// eps for the post-attention / post-FFN norms; 0 in the config means "reuse rms_eps"
// (muse-glimmer's post-norms use a tighter 1e-8 than its pre-norms).
+ const auto norm = m_cfg.layer_norm ? blocks::layer_norm : blocks::rms_norm;
const float post_eps = m_cfg.post_norm_eps > 0.0f ? m_cfg.post_norm_eps : m_cfg.rms_eps;
const std::string attn_norm =
- m_cfg.post_norm_only ? cur
- : blocks::rms_norm(m_emit, cur, p + m_cfg.attn_norm_key, p + "attn_norm", m_cfg.rms_eps);
+ m_cfg.post_norm_only ? cur : norm(m_emit, cur, p + m_cfg.attn_norm_key, p + "attn_norm", m_cfg.rms_eps);
if (m_cfg.is_qwen35 && m_cfg.is_recurrent_layer(il)) {
// Hybrid stack: 3 of every 4 layers replace attention with a Gated DeltaNet block.
@@ -230,7 +249,7 @@ std::string DecoderBuilder::build_layer(int il, const std::string& layer_in) {
const std::string gdn_out = blocks::gated_delta_net(m_emit, m_cfg, il, attn_norm);
std::string sa = inpSA;
std::string ao = gdn_out;
- if (il == m_cfg.n_layer - 1) {
+ if (selects_output_rows(il)) {
ao = m_emit.add_op("GGML_OP_GET_ROWS", p + "attn_out_g", {gdn_out, "inp_out_ids"});
sa = m_emit.add_op("GGML_OP_GET_ROWS", p + "inpSA_g", {inpSA, "inp_out_ids"});
}
@@ -255,26 +274,27 @@ std::string DecoderBuilder::build_layer(int il, const std::string& layer_in) {
}
std::string sa = inpSA;
std::string ao = attn_out;
- if (il == m_cfg.n_layer - 1) {
+ if (selects_output_rows(il)) {
ao = m_emit.add_op("GGML_OP_GET_ROWS", p + "attn_out_g", {attn_out, "inp_out_ids"});
sa = m_emit.add_op("GGML_OP_GET_ROWS", p + "inpSA_g", {inpSA, "inp_out_ids"});
}
// Gemma2: post-attention RMSNorm applied to the sublayer output before residual add.
// Applied after GET_ROWS so the selected-token path matches gemma2.cpp's order.
if (m_cfg.has_attn_post_norm) {
- ao = blocks::rms_norm(m_emit, ao, p + "post_attention_norm.weight", p + "attn_post_norm", post_eps);
+ ao = blocks::rms_norm(m_emit, ao, p + m_cfg.attn_post_norm_key, p + "attn_post_norm", post_eps);
}
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
- : blocks::rms_norm(m_emit, ffn_inp, p + m_cfg.ffn_norm_key, p + "ffn_norm", m_cfg.rms_eps);
+ 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);
// 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);
- std::string down = is_moe_layer ? blocks::moe_ffn(m_emit, m_cfg, p, ffn_norm)
+ std::string down = is_moe_layer && m_emit.has_weight(p + "pre_ffw_norm_2.weight")
+ ? blocks::gemma4_moe_ffn(m_emit, m_cfg, p, ffn_inp, ffn_norm)
+ : is_moe_layer ? blocks::moe_ffn(m_emit, m_cfg, p, ffn_norm)
: m_cfg.is_geglu ? blocks::geglu_ffn(m_emit, m_cfg, p, ffn_norm)
: blocks::dense_ffn(m_emit, m_cfg, p, ffn_norm);
// MiniCPM scales the FFN sublayer output before the residual add.
@@ -283,7 +303,7 @@ std::string DecoderBuilder::build_layer(int il, const std::string& layer_in) {
}
// Gemma2: post-FFN RMSNorm applied to the FFN output before residual add.
if (m_cfg.has_ffn_post_norm) {
- down = blocks::rms_norm(m_emit, down, p + "post_ffw_norm.weight", p + "ffn_post_norm", post_eps);
+ down = blocks::rms_norm(m_emit, down, p + m_cfg.ffn_post_norm_key, p + "ffn_post_norm", post_eps);
}
cur = m_emit.add_op("GGML_OP_ADD", p + "l_out", {down, ffn_inp});
@@ -302,7 +322,30 @@ std::string DecoderBuilder::build_layer(int il, const std::string& layer_in) {
std::string DecoderBuilder::build_head(const std::string& in) {
// final norm + lm_head
- std::string cur = blocks::rms_norm(m_emit, in, "output_norm.weight", "result_norm", m_cfg.rms_eps);
+ 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.embedding_model) {
+ using namespace ov::op;
+ auto embeddings = m_emit.value(cur);
+ ov::Output<ov::Node> output = embeddings;
+ auto token_axis = v0::Constant::create(i64, {1}, {2});
+ if (m_cfg.pooling_type == 1) {
+ output = std::make_shared<v1::ReduceMean>(embeddings, token_axis, true);
+ } else if (m_cfg.pooling_type == 2 || m_cfg.pooling_type == 3) {
+ ov::Output<ov::Node> index = v0::Constant::create(i64, {1}, {0});
+ if (m_cfg.pooling_type == 3) {
+ auto shape = std::make_shared<v3::ShapeOf>(embeddings);
+ auto axis = v0::Constant::create(i64, {}, {0});
+ auto count = std::make_shared<v8::Gather>(shape, token_axis, axis);
+ index = std::make_shared<v1::Subtract>(count, v0::Constant::create(i64, {1}, {1}));
+ }
+ output = std::make_shared<v8::Gather>(embeddings, index, token_axis);
+ }
+ output = std::make_shared<v0::Squeeze>(output, v0::Constant::create(i64, {2}, {0, 1}));
+ output.set_names({"embeddings"});
+ (*m_emit.graph()->values)["embeddings"] = output;
+ 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);
diff --git a/src/frontends/gguf/src/builder/arch/decoder_builder.hpp b/src/frontends/gguf/src/builder/arch/decoder_builder.hpp
index ce3bc5ae9ae..af5a250c515 100644
--- a/src/frontends/gguf/src/builder/arch/decoder_builder.hpp
+++ b/src/frontends/gguf/src/builder/arch/decoder_builder.hpp
@@ -60,6 +60,9 @@ private:
// Final norm, lm_head, and the optional logit scale / soft-cap.
std::string build_head(const std::string& cur);
+ bool selects_output_rows(int il) const {
+ return il == m_cfg.n_layer - 1 && !m_cfg.embedding_model;
+ }
DecoderConfig m_cfg;
GraphEmitter m_emit;
diff --git a/src/frontends/gguf/src/builder/arch/mamba_builder.cpp b/src/frontends/gguf/src/builder/arch/mamba_builder.cpp
index 3b43e187d71..c212d0e318d 100644
--- a/src/frontends/gguf/src/builder/arch/mamba_builder.cpp
+++ b/src/frontends/gguf/src/builder/arch/mamba_builder.cpp
@@ -145,14 +145,8 @@ private:
} // namespace
-ArchitectureDefinition mamba2_architecture(const std::string& architecture) {
- return {architecture,
- architecture,
- [](const BuildContext& context) {
- return std::make_shared<Mamba2Builder>(context);
- },
- {},
- Maturity::Verified};
+std::shared_ptr<ModelBuilder> make_mamba2_builder(const BuildContext& context) {
+ return std::make_shared<Mamba2Builder>(context);
}
} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/arch/mamba_builder.hpp b/src/frontends/gguf/src/builder/arch/mamba_builder.hpp
index b196e2eb16c..eff0f411a62 100644
--- a/src/frontends/gguf/src/builder/arch/mamba_builder.hpp
+++ b/src/frontends/gguf/src/builder/arch/mamba_builder.hpp
@@ -3,8 +3,8 @@
//
#pragma once
-#include "openvino/frontend/gguf/extension/architecture.hpp"
+#include "openvino/frontend/gguf/builder/model_builder.hpp"
namespace ov::frontend::gguf {
-ArchitectureDefinition mamba2_architecture(const std::string& architecture);
+std::shared_ptr<ModelBuilder> make_mamba2_builder(const BuildContext& context);
} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp b/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp
new file mode 100644
index 00000000000..897213b49c1
--- /dev/null
+++ b/src/frontends/gguf/src/builder/arch/mmproj_builder.cpp
@@ -0,0 +1,1202 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "mmproj_builder.hpp"
+
+#include <algorithm>
+#include <array>
+#include <cmath>
+#include <limits>
+#include <optional>
+#include <sstream>
+
+#include "builder/api/metadata_store.hpp"
+#include "builder/gguf_graph.hpp"
+#include "builder/projector_registry.hpp"
+#include "openvino/frontend/gguf/builder/graph_context.hpp"
+
+namespace ov::frontend::gguf {
+namespace {
+
+// Power-of-two shrink that keeps Gemma 4 unified-vision activations within F16.
+constexpr float kUnifiedShrink = 1.f / 16;
+
+enum class EncoderTopology {
+ SIGLIP,
+ CLIP,
+ WHISPER,
+ QWEN,
+ INTERNVL,
+ RESAMPLER,
+ PIXTRAL,
+ GEMMA4,
+ UNIFIED_VISION,
+ UNIFIED_AUDIO,
+ MINICPM46,
+ MUSE_GLIMMER,
+ PHI4,
+ GEMMA4_AUDIO,
+ OCR,
+ OCR2
+};
+
+// ggml rope mode bits, as passed in the op_case.
+constexpr int ROPE_NEOX = 1 << 16;
+constexpr int ROPE_VISION = 3 << 16;
+
+// Per-projector traits follow llama.cpp's clip.cpp choices.
+enum ProjectorTraits : unsigned {
+ RMS_NORM = 1, // encoder norms are RMS rather than layer norms
+ SWAPPED_FFN = 2, // legacy exports name ffn_up/ffn_down after each other's roles
+ POOL_2 = 4, // average-pool encoder tokens by 2 before the projector
+};
+
+struct ProjectorTopology {
+ const char* modality;
+ const char* name;
+ EncoderTopology topology;
+ unsigned traits = 0;
+};
+
+// Entries describe implemented graph topologies, independently of language DecoderConfig.
+constexpr ProjectorTopology projector_catalog[] = {
+ {"vision", "deepseekocr", EncoderTopology::OCR},
+ {"vision", "deepseekocr2", EncoderTopology::OCR2, RMS_NORM},
+ {"vision", "pixtral", EncoderTopology::PIXTRAL, RMS_NORM},
+ {"vision", "phi4", EncoderTopology::PHI4},
+ {"vision", "muse-glimmer", EncoderTopology::MUSE_GLIMMER},
+ {"vision", "gemma4v", EncoderTopology::GEMMA4, RMS_NORM},
+ {"vision", "gemma4uv", EncoderTopology::UNIFIED_VISION},
+ {"audio", "gemma4a", EncoderTopology::GEMMA4_AUDIO},
+ {"audio", "gemma4ua", EncoderTopology::UNIFIED_AUDIO},
+ {"vision", "minicpmv4_6", EncoderTopology::MINICPM46},
+ {"vision", "gemma3", EncoderTopology::SIGLIP, SWAPPED_FFN},
+ {"vision", "idefics3", EncoderTopology::SIGLIP, SWAPPED_FFN},
+ {"vision", "janus_pro", EncoderTopology::SIGLIP},
+ {"vision", "mlp", EncoderTopology::CLIP, SWAPPED_FFN},
+ {"vision", "internvl", EncoderTopology::INTERNVL},
+ {"vision", "resampler", EncoderTopology::RESAMPLER},
+ {"vision", "qwen2vl_merger", EncoderTopology::QWEN, SWAPPED_FFN},
+ {"vision", "qwen2.5vl_merger", EncoderTopology::QWEN, RMS_NORM | SWAPPED_FFN},
+ {"vision", "qwen3vl_merger", EncoderTopology::QWEN},
+ {"audio", "qwen2a", EncoderTopology::WHISPER, POOL_2},
+ {"audio", "ultravox", EncoderTopology::WHISPER},
+ {"audio", "voxtral", EncoderTopology::WHISPER, POOL_2},
+ {"audio", "musicflamingo", EncoderTopology::WHISPER, POOL_2},
+ {"audio", "meralion", EncoderTopology::WHISPER},
+ {"audio", "glma", EncoderTopology::WHISPER},
+};
+
+struct EncoderConfig {
+ std::string projector, prefix, activation;
+ int64_t width, heads, layers, image_size = 0, patch = 0, merge = 1;
+ EncoderTopology topology;
+ int64_t window_pattern = 0;
+ int64_t version = 0, queries = 0, kv_heads = 0;
+ std::vector<int64_t> feature_layers;
+ float eps;
+ unsigned traits = 0;
+ bool rms = false; // encoder norms are RMS rather than layer norms
+};
+
+bool rms_encoder(const EncoderConfig& c) {
+ // As in llama.cpp, InternViT-6B is recognized by its geometry.
+ return (c.traits & RMS_NORM) || (c.topology == EncoderTopology::INTERNVL && c.width == 3200 && c.layers == 45);
+}
+
+int64_t positive(const GgufMetadata& meta, const std::string& key) {
+ const auto value = meta.get_int(key);
+ OPENVINO_ASSERT(value && *value > 0 && *value <= std::numeric_limits<int>::max(),
+ "[GGUF] mmproj requires a positive integer '",
+ key,
+ "'");
+ return *value;
+}
+
+EncoderConfig config(const GgufMetadata& meta, const std::string& modality, const std::string& projector) {
+ EncoderConfig c;
+ c.prefix = modality == "vision" ? "v." : "a.";
+ const auto key = "clip." + modality + ".";
+ c.projector = projector;
+ const auto entry =
+ std::find_if(std::begin(projector_catalog), std::end(projector_catalog), [&](const auto& candidate) {
+ return modality == candidate.modality && c.projector == candidate.name;
+ });
+ OPENVINO_ASSERT(entry != std::end(projector_catalog),
+ "[GGUF] unsupported ",
+ modality,
+ " mmproj projector '",
+ c.projector,
+ "'");
+ c.topology = entry->topology;
+ c.traits = entry->traits;
+ if (c.topology == EncoderTopology::UNIFIED_AUDIO) {
+ c.width = 640;
+ c.heads = 1;
+ c.layers = 0;
+ c.eps = 1e-6f;
+ return c;
+ }
+ c.width = positive(meta, key + "embedding_length");
+ c.heads = c.topology == EncoderTopology::UNIFIED_VISION ? 1 : positive(meta, key + "attention.head_count");
+ c.kv_heads = c.topology == EncoderTopology::OCR2 ? positive(meta, key + "attention.head_count_kv") : c.heads;
+ // GQA head expansion is done by the FLASH_ATTN_EXT translator.
+ OPENVINO_ASSERT(c.heads % c.kv_heads == 0, "[GGUF] encoder GQA head count mismatch");
+ c.layers = c.topology == EncoderTopology::UNIFIED_VISION ? 0 : positive(meta, key + "block_count");
+ if (c.topology == EncoderTopology::CLIP) {
+ c.feature_layers = meta.get_int_array(key + "feature_layer");
+ for (auto layer : c.feature_layers)
+ OPENVINO_ASSERT(layer >= 0 && layer <= c.layers, "[GGUF] invalid CLIP feature layer ", layer);
+ c.layers = c.feature_layers.empty() ? c.layers - 1
+ : *std::max_element(c.feature_layers.begin(), c.feature_layers.end());
+ }
+ OPENVINO_ASSERT(c.width % c.heads == 0, "[GGUF] mmproj embedding width must be divisible by head count");
+ const auto eps = meta.get_float(key + "attention.layer_norm_epsilon");
+ OPENVINO_ASSERT(eps && std::isfinite(*eps) && *eps > 0, "[GGUF] invalid ", key, "attention.layer_norm_epsilon");
+ c.eps = c.topology == EncoderTopology::GEMMA4_AUDIO ? 1e-6f : static_cast<float>(*eps);
+ const bool gelu = meta.get_bool("clip.use_gelu").value_or(false);
+ const bool silu = meta.get_bool("clip.use_silu").value_or(false);
+ OPENVINO_ASSERT(!(gelu && silu), "[GGUF] mmproj cannot enable both GELU and SiLU");
+ c.activation = modality == "audio" ? "GGML_UNARY_OP_GELU_ERF"
+ : gelu ? "GGML_UNARY_OP_GELU"
+ : "GGML_UNARY_OP_GELU_QUICK";
+ if (modality == "vision" && silu)
+ c.activation = "GGML_UNARY_OP_SILU";
+ if (modality == "vision") {
+ c.patch = positive(meta, key + "patch_size");
+ if (c.topology == EncoderTopology::OCR || c.topology == EncoderTopology::OCR2) {
+ c.patch = 16;
+ c.merge = 4;
+ if (c.topology == EncoderTopology::OCR) {
+ c.eps = 1e-5f;
+ c.activation = "GGML_UNARY_OP_GELU_QUICK";
+ } else {
+ c.activation = "GGML_UNARY_OP_SILU";
+ }
+ return c;
+ }
+ if (c.topology == EncoderTopology::PIXTRAL || c.topology == EncoderTopology::GEMMA4 ||
+ c.topology == EncoderTopology::UNIFIED_VISION || c.topology == EncoderTopology::MINICPM46 ||
+ c.topology == EncoderTopology::PHI4) {
+ if (c.topology == EncoderTopology::PIXTRAL)
+ c.merge = meta.get_int(key + "spatial_merge_size").value_or(1);
+ else if (c.topology != EncoderTopology::PHI4)
+ c.merge = meta.get_int(key + "projector.scale_factor")
+ .value_or(c.topology == EncoderTopology::MINICPM46 ? 4 : 3);
+ OPENVINO_ASSERT(c.merge > 0, "[GGUF] invalid vision merge size");
+ if (c.topology == EncoderTopology::UNIFIED_VISION) {
+ c.patch *= c.merge;
+ c.merge = 1;
+ }
+ if (c.topology == EncoderTopology::MINICPM46) {
+ auto layers = meta.get_int_array(key + "wa_layer_indexes");
+ c.window_pattern = layers.empty() ? 0 : layers.front();
+ OPENVINO_ASSERT(c.merge == 4 && c.window_pattern >= 0 && c.window_pattern < c.layers,
+ "[GGUF] invalid minicpmv4_6 merger configuration");
+ }
+ return c;
+ }
+ if (c.topology == EncoderTopology::MUSE_GLIMMER) {
+ c.merge = meta.get_int(key + "spatial_merge_size").value_or(2);
+ c.window_pattern = 4;
+ c.activation = "GGML_UNARY_OP_GELU_ERF";
+ OPENVINO_ASSERT(c.merge > 0 && c.width / c.heads % 4 == 0,
+ "[GGUF] invalid Muse Glimmer merge or rotary head dimensions");
+ return c;
+ }
+ if (c.topology == EncoderTopology::RESAMPLER) {
+ c.version = meta.get_int("clip.minicpmv_version").value_or(2);
+ if (c.version == 0)
+ c.version = 2;
+ OPENVINO_ASSERT(c.version == 2 || c.version == 3 || c.version == 4 || c.version == 5 || c.version == 6 ||
+ c.version == 100045,
+ "[GGUF] unsupported vision mmproj projector 'resampler' version ",
+ c.version);
+ c.queries = meta.get_int("clip.minicpmv_query_num").value_or(0);
+ OPENVINO_ASSERT(c.queries >= 0, "[GGUF] vision resampler query count must be nonnegative");
+ if (c.queries == 0)
+ c.queries = c.version == 2 ? 96 : 64;
+ return c;
+ }
+ if (c.topology == EncoderTopology::QWEN) {
+ c.merge = meta.get_int(key + "spatial_merge_size").value_or(2);
+ c.window_pattern = c.projector == "qwen2.5vl_merger" ? positive(meta, key + "n_wa_pattern") : 0;
+ OPENVINO_ASSERT(c.merge == 2 && c.width / c.heads % 4 == 0,
+ "[GGUF] Qwen vision requires merge size two and head width divisible by four");
+ return c;
+ }
+ c.image_size = positive(meta, key + "image_size");
+ c.merge = c.projector == "janus_pro" || c.topology == EncoderTopology::CLIP
+ ? 1
+ : meta.get_int(key + "projector.scale_factor").value_or(c.projector == "gemma3" ? 4 : 2);
+ OPENVINO_ASSERT(c.merge > 0 && c.image_size % c.patch == 0 && (c.image_size / c.patch) % c.merge == 0,
+ "[GGUF] incompatible mmproj patch/merge dimensions");
+ }
+ return c;
+}
+
+class BuiltinProjectorBuilder {
+public:
+ explicit BuiltinProjectorBuilder(GgufGraphContext& graph) : g(graph) {}
+
+ ProjectorResult build(const std::string& modality, const std::string& projector) {
+ auto c = config(g.metadata(), modality, projector);
+ c.rms = rms_encoder(c);
+ clippable = c.topology == EncoderTopology::GEMMA4 || c.topology == EncoderTopology::GEMMA4_AUDIO;
+ ProjectorResult result;
+ result.output = modality == "vision" ? vision(c) : audio(c);
+ result.config[modality + ".merge"] = std::to_string(c.merge);
+ if (c.topology == EncoderTopology::MUSE_GLIMMER)
+ result.config["vision.window_size"] = std::to_string(muse_window);
+ if (c.topology == EncoderTopology::RESAMPLER) {
+ result.config["vision.minicpmv_version"] = std::to_string(c.version);
+ result.config["vision.query_count"] = std::to_string(c.queries);
+ }
+ if (modality == "vision")
+ result.config["vision.auxiliary_count"] = std::to_string(auxiliary.size());
+ return result;
+ }
+
+private:
+ GgufGraphContext& g;
+ std::vector<GgufValue> auxiliary;
+ GgufValue default_clip_min, default_clip_max;
+ // Set once per encoder in build(); the Gemma4 families clamp every linear's input and output.
+ bool clippable = false;
+ // Muse Glimmer window side, which matches its square learned position grid.
+ int64_t muse_window = 0;
+
+ GgufValue reshape(const GgufValue& x, std::vector<int64_t> shape, bool special_zero = false) {
+ return g.node("GGML_OP_RESHAPE",
+ {x},
+ 0,
+ {{"reshape_target", std::move(shape)}, {"special_zero", special_zero}});
+ }
+ GgufValue transpose(const GgufValue& x, std::vector<int64_t> perm = {0, 1, 3, 2}) {
+ return g.node("GGML_OP_TRANSPOSE", {x}, 0, {{"perm", std::move(perm)}});
+ }
+ GgufValue add(const GgufValue& x, const GgufValue& y) {
+ return g.node("GGML_OP_ADD", {x, y});
+ }
+ GgufValue mul(const GgufValue& x, const GgufValue& y) {
+ return g.node("GGML_OP_MUL", {x, y});
+ }
+ GgufValue scale(const GgufValue& x, float value, float bias = 0.f) {
+ return g.node("GGML_OP_SCALE", {x}, 0, {{"scale", value}, {"bias", bias}});
+ }
+ 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 concat(const GgufValue& a, const GgufValue& b, int64_t axis = 0) {
+ return g.node("GGML_OP_CONCAT", {a, b}, 0, {{"concat_axis", axis}});
+ }
+ GgufValue grid(const GgufValue& x, const GgufValue& reference, int64_t width) {
+ return reshape_like(x, reference, {1, width, 0, 0}, {-1, -1, 2, 3});
+ }
+ GgufValue clip_linear(const GgufValue& x, const std::string& base, const std::string& side) {
+ auto lo = g.tensors()(base + "." + side + "_min"), hi = g.tensors()(base + "." + side + "_max");
+ if (!lo && !hi)
+ return x;
+ const auto bound = [&](GgufValue& slot, const char* name, float value) {
+ if (!slot) {
+ ov::Tensor t(ov::element::f32, {1});
+ t.data<float>()[0] = value;
+ slot = g.add_constant(name, t);
+ }
+ return slot;
+ };
+ const auto limit = std::numeric_limits<float>::max();
+ return g.node("GGML_OP_CLAMP",
+ {x,
+ lo ? lo : bound(default_clip_min, "mmproj.clip_min", -limit),
+ hi ? hi : bound(default_clip_max, "mmproj.clip_max", limit)});
+ }
+ GgufValue linear(const GgufValue& x, const std::string& base, bool with_bias = true) {
+ auto y = g.node("GGML_OP_MUL_MAT",
+ {g.tensors().require(base + ".weight"), clippable ? clip_linear(x, base, "input") : x});
+ if (clippable)
+ y = clip_linear(y, base, "output");
+ if (auto bias = with_bias ? g.tensors()(base + ".bias") : GgufValue{})
+ y = add(y, bias);
+ return y;
+ }
+ GgufValue norm(const GgufValue& x, const std::string& base, float eps) {
+ return g.build_norm_ln(x, g.tensors()(base + ".weight"), g.tensors()(base + ".bias"), eps);
+ }
+ GgufValue encoder_norm(const GgufValue& x, const std::string& base, const EncoderConfig& c, bool with_bias = true) {
+ const auto weight = g.tensors()(base + ".weight");
+ const auto bias = with_bias ? g.tensors()(base + ".bias") : GgufValue{};
+ if (!c.rms)
+ return g.build_norm_ln(x, weight, bias, c.eps);
+ auto y = g.build_norm(x, weight, c.eps);
+ return bias ? add(y, bias) : y;
+ }
+ GgufValue attention(const GgufValue& q,
+ const GgufValue& k,
+ const GgufValue& v,
+ float factor,
+ const GgufValue& mask = {}) {
+ std::vector<GgufValue> inputs{q, k, v};
+ if (mask)
+ inputs.push_back(mask);
+ return g.node("GGML_OP_FLASH_ATTN_EXT", inputs, 100, {{"f32_attention", true}, {"scale", factor}});
+ }
+ GgufValue patch_embeddings(const GgufValue& spatial, int64_t width, bool with_bias = true) {
+ auto x = transpose(reshape(spatial, {1, 1, width, -1}));
+ if (auto bias = with_bias ? g.tensors()("v.patch_embd.bias") : GgufValue{})
+ x = add(x, bias);
+ return x;
+ }
+ GgufValue ffn(const GgufValue& x,
+ const std::string& up,
+ const std::string& down,
+ const std::string& activation,
+ const std::string& gate = "",
+ bool with_bias = true) {
+ auto y = linear(x, up, with_bias);
+ if (!gate.empty() && g.tensors().has(gate + ".weight"))
+ y = mul(y, g.node(activation, {linear(x, gate)}));
+ else
+ y = g.node(activation, {y});
+ return linear(y, down, with_bias);
+ }
+ GgufValue pool(const GgufValue& x, int64_t kx, int64_t ky) {
+ // op_case 2: average pooling; params are kx, ky, sx, sy, px, py.
+ return g.node(
+ "GGML_OP_POOL_2D",
+ {x},
+ 2,
+ {{"pool_params", std::vector<int32_t>{int32_t(kx), int32_t(ky), int32_t(kx), int32_t(ky), 0, 0}}});
+ }
+ GgufValue vit(GgufValue x,
+ const EncoderConfig& c,
+ const GgufValue& positions,
+ const GgufValue& rope_positions = {},
+ const GgufValue& window_mask = {},
+ const GgufValue& rope_positions_b = {},
+ int64_t first = 0,
+ int64_t end = -1,
+ bool post_norm = true) {
+ if (end < 0)
+ end = c.layers;
+ if (positions)
+ x = add(x, positions);
+ if (first == 0 && g.tensors().has(c.prefix + "pre_ln.weight"))
+ x = encoder_norm(x, c.prefix + "pre_ln", c);
+ // The per-layer width check below confirms a legacy ffn_up/ffn_down name swap.
+ const bool swappable = c.traits & SWAPPED_FFN;
+ std::vector<GgufValue> features;
+ const auto save_feature = [&](int64_t layer, const GgufValue& value) {
+ if (std::find(c.feature_layers.begin(), c.feature_layers.end(), layer) != c.feature_layers.end())
+ features.push_back(value);
+ };
+ for (int64_t i = first; i < end; ++i) {
+ save_feature(i, x);
+ const auto p = c.prefix + "blk." + std::to_string(i) + ".";
+ auto z = encoder_norm(x, p + "ln1", c);
+ const bool fused = g.tensors().has(p + "attn_qkv.weight");
+ auto qkv = fused ? linear(z, p + "attn_qkv") : GgufValue{};
+ // Whether QK norm weights are per head or whole-tensor is a property of the layer.
+ const bool per_head = fused || (g.tensors().has(p + "attn_q_norm.weight") &&
+ g.tensors().require(p + "attn_q_norm.weight").ne(0) == c.width / c.heads);
+ const auto projection = [&](const std::string& name, int64_t offset) {
+ auto value = fused ? slice(qkv, 3, offset * c.width, c.width) : linear(z, p + name);
+ const auto weight = g.tensors()(p + name + "_norm.weight");
+ if (weight && !per_head)
+ value = encoder_norm(value, p + name + "_norm", c, false);
+ value = reshape(value, {0, -1, name == "attn_q" ? c.heads : c.kv_heads, c.width / c.heads}, true);
+ if (weight && per_head)
+ value = encoder_norm(value, p + name + "_norm", c, false);
+ return value;
+ };
+ auto q = projection("attn_q", 0);
+ auto k = projection("attn_k", 1);
+ auto v = projection("attn_v", 2);
+ if (rope_positions) {
+ q = encoder_rope(q, c, rope_positions, rope_positions_b);
+ k = encoder_rope(k, c, rope_positions, rope_positions_b);
+ }
+ if (c.topology == EncoderTopology::GEMMA4)
+ v = g.build_norm(v, {}, c.eps);
+ const bool muse = c.topology == EncoderTopology::MUSE_GLIMMER;
+ const bool windowed = window_mask && (c.window_pattern == 0 || (i + 1) % c.window_pattern != 0) &&
+ !(muse && i == c.layers - 1);
+ auto mask = windowed ? window_mask : GgufValue{};
+ // Muse Glimmer windows are padded to equal size and attend as a batch; its global
+ // layer still ignores the padding.
+ const int64_t window_tokens = muse && windowed ? muse_window * muse_window : 0;
+ if (window_tokens) {
+ const auto head = c.width / c.heads;
+ q = reshape(q, {-1, window_tokens, c.heads, head});
+ k = reshape(k, {-1, window_tokens, c.kv_heads, head});
+ v = reshape(v, {-1, window_tokens, c.kv_heads, head});
+ } else if (muse && window_mask) {
+ mask = reshape(window_mask, {1, 1, 1, -1});
+ }
+ z = attention(q,
+ k,
+ v,
+ c.topology == EncoderTopology::GEMMA4 ? 1.f : 1.f / std::sqrt(float(c.width / c.heads)),
+ mask);
+ z = window_tokens ? reshape(z, {1, 1, -1, c.width}) : reshape(z, {0, 1, -1, c.width}, true);
+ z = linear(z, p + "attn_out");
+ if (auto scale = g.tensors()(p + "ls1.weight"))
+ z = mul(z, scale);
+ if (g.tensors().has(p + "attn_post_norm.weight"))
+ z = encoder_norm(z, p + "attn_post_norm", c, false);
+ x = add(x, z);
+ const bool legacy_swap = swappable && g.tensors().require(p + "ffn_down.weight").ne(0) == c.width;
+ z = ffn(encoder_norm(x, p + "ln2", c),
+ p + (legacy_swap ? "ffn_down" : "ffn_up"),
+ p + (legacy_swap ? "ffn_up" : "ffn_down"),
+ c.activation,
+ p + "ffn_gate");
+ if (g.tensors().has(p + "ffn_post_norm.weight"))
+ z = encoder_norm(z, p + "ffn_post_norm", c, false);
+ if (auto scale = g.tensors()(p + "ls2.weight"))
+ z = mul(z, scale);
+ x = add(x, z);
+ if (auto scale = g.tensors()(p + "out_scale.weight"))
+ x = mul(x, scale);
+ const auto deep = "v.deepstack." + std::to_string(i);
+ if (c.projector == "qwen3vl_merger" && g.tensors().has(deep + ".norm.weight")) {
+ auto feature = norm(reshape(x, {1, 1, -1, 4 * c.width}), deep + ".norm", c.eps);
+ auxiliary.push_back(ffn(feature, deep + ".fc1", deep + ".fc2", "GGML_UNARY_OP_GELU"));
+ }
+ }
+ if (c.traits & POOL_2)
+ x = transpose(pool(transpose(x), 2, 1));
+ if (post_norm && end == c.layers && g.tensors().has(c.prefix + "post_ln.weight"))
+ x = encoder_norm(x, c.prefix + "post_ln", c);
+ save_feature(end, x);
+ if (!features.empty()) {
+ x = features.front();
+ for (size_t i = 1; i < features.size(); ++i)
+ x = concat(x, features[i]);
+ }
+ return x;
+ }
+ GgufValue encoder_rope(const GgufValue& x,
+ const EncoderConfig& c,
+ const GgufValue& positions,
+ const GgufValue& positions_b) {
+ const auto head = int(c.width / c.heads);
+ RopeConfig r;
+ r.freq_scale = r.attn_factor = 1.f;
+ const auto rope = [&](const GgufValue& value, const GgufValue& pos, int mode) {
+ return g.node("GGML_OP_ROPE", {value, pos}, mode, {{"rope_config", r}});
+ };
+ if (c.topology == EncoderTopology::OCR2) {
+ r.n_dims = head;
+ r.freq_base = 1000000.f;
+ return rope(x, positions, ROPE_NEOX);
+ }
+ r.n_dims = head / 2;
+ if (!positions_b) {
+ r.freq_base = 10000.f;
+ r.sections.fill(int32_t(head / 4));
+ return rope(x, positions, ROPE_VISION);
+ }
+ // Two position axes, each rotating one half of the head.
+ const bool gemma4 = c.topology == EncoderTopology::GEMMA4;
+ const int mode = gemma4 ? ROPE_NEOX : 0;
+ r.freq_base = gemma4 ? 100.f : 10000.f;
+ auto a = rope(slice(x, 3, 0, r.n_dims), positions, mode);
+ if (c.topology == EncoderTopology::PIXTRAL)
+ r.freq_scale = std::pow(r.freq_base, -2.f / float(head));
+ auto b = rope(slice(x, 3, r.n_dims, r.n_dims), positions_b, mode);
+ return concat(a, b);
+ }
+ // Resizes a square [side*side, width] learned position table to the grid of `like`; NCHW result.
+ GgufValue resize_square_table(const GgufValue& table,
+ const GgufValue& like,
+ int64_t width,
+ int interpolation_mode,
+ const char* family) {
+ const int64_t side = int64_t(std::sqrt(double(table.ne(1))));
+ OPENVINO_ASSERT(side * side == table.ne(1), "[GGUF] ", family, " position table must be square");
+ return g.node("GGML_OP_UPSCALE",
+ {transpose(reshape(table, {1, side, side, width}), {0, 3, 1, 2}), like},
+ 0,
+ {{"resize_like", true}, {"interpolation_mode", interpolation_mode}});
+ }
+ GgufValue index_input(const std::string& name) {
+ return g.add_input("vision." + name, ov::element::i32, {1, 1, 1, -1});
+ }
+ GgufValue gather_rows(const GgufValue& x, const std::string& index_name) {
+ return g.node("GGML_OP_GET_ROWS", {x, index_input(index_name)});
+ }
+ GgufValue vision(const EncoderConfig& c) {
+ if (c.topology == EncoderTopology::OCR || c.topology == EncoderTopology::OCR2)
+ return ocr_vision(c);
+ if (c.topology == EncoderTopology::PIXTRAL || c.topology == EncoderTopology::GEMMA4 ||
+ c.topology == EncoderTopology::UNIFIED_VISION || c.topology == EncoderTopology::PHI4)
+ return dynamic_vision(c);
+ if (c.topology == EncoderTopology::MINICPM46)
+ return minicpm46(c);
+ if (c.topology == EncoderTopology::QWEN)
+ return qwen_vision(c);
+ if (c.topology == EncoderTopology::MUSE_GLIMMER)
+ return muse_glimmer_vision(c);
+ if (c.topology == EncoderTopology::RESAMPLER)
+ return resampler_vision(c);
+ auto x = g.add_input("vision.pixel_values", ov::element::f32, {1, 3, c.image_size, c.image_size});
+ x = patch_embeddings(convolution(x, "v.patch_embd.weight", c.patch), c.width);
+ if ((c.topology == EncoderTopology::CLIP || c.topology == EncoderTopology::INTERNVL) &&
+ g.tensors().has("v.class_embd"))
+ x = concat(x, reshape(g.tensors().require("v.class_embd"), {1, 1, 1, c.width}), 1);
+ x = vit(x, c, g.tensors().require("v.position_embd.weight"));
+ const auto side = c.image_size / c.patch;
+ if (c.topology == EncoderTopology::INTERNVL) {
+ OPENVINO_ASSERT(g.tensors().has("v.class_embd"), "[GGUF] InternVL requires a class embedding");
+ x = slice(x, 2, 0, side * side);
+ x = reshape(x, {1, side, side / c.merge, c.width * c.merge});
+ x = transpose(x, {0, 2, 1, 3});
+ x = reshape(x, {1, side / c.merge, side / c.merge, c.width * c.merge * c.merge});
+ x = transpose(x, {0, 2, 1, 3});
+ x = reshape(x, {1, 1, -1, c.width * c.merge * c.merge});
+ return ffn(norm(x, "mm.model.mlp.0", 1e-5f), "mm.model.mlp.1", "mm.model.mlp.3", "GGML_UNARY_OP_GELU");
+ }
+ if (c.topology == EncoderTopology::CLIP) {
+ const int64_t offset = g.tensors().has("v.class_embd") ? 1 : 0;
+ x = slice(x, 2, offset, side * side);
+ x = linear(x, "mm.0");
+ const bool normalized = g.tensors().has("mm.3.weight");
+ if (normalized)
+ x = norm(x, "mm.1", c.eps);
+ x = g.node("GGML_UNARY_OP_GELU", {x});
+ if (normalized)
+ return norm(linear(x, "mm.3"), "mm.4", c.eps);
+ return g.tensors().has("mm.2.weight") ? linear(x, "mm.2") : x;
+ }
+ if (c.projector == "gemma3") {
+ x = reshape(transpose(x), {1, c.width, side, side});
+ x = transpose(reshape(pool(x, c.merge, c.merge), {1, 1, c.width, -1}));
+ x = g.build_norm(x, g.tensors().require("mm.soft_emb_norm.weight"), c.eps);
+ return g.node("GGML_OP_MUL_MAT", {transpose(g.tensors().require("mm.input_projection.weight"), {1, 0}), x});
+ }
+ if (c.projector == "idefics3") {
+ // Gather each spatial merge window in row-major pixel order, then project it.
+ std::vector<int32_t> order;
+ for (int64_t y = 0; y < side; y += c.merge)
+ for (int64_t xx = 0; xx < side; xx += c.merge)
+ for (int64_t dy = 0; dy < c.merge; ++dy)
+ for (int64_t dx = 0; dx < c.merge; ++dx)
+ order.push_back(int32_t((y + dy) * side + xx + dx));
+ ov::Tensor indices(ov::element::i32, {1, 1, 1, order.size()});
+ std::copy(order.begin(), order.end(), indices.data<int32_t>());
+ x = g.node("GGML_OP_GET_ROWS", {x, g.add_constant("vision.merge_indices", indices)});
+ return linear(reshape(x, {1, 1, -1, c.width * c.merge * c.merge}), "mm.model.fc");
+ }
+ return ffn(x, "mm.0", "mm.1", c.activation);
+ }
+ GgufValue convolution(const GgufValue& pixels, const GgufValue& weight, int64_t stride, int64_t padding = 0) {
+ return g.node("GGML_OP_CONV_2D",
+ {weight, pixels},
+ 0,
+ {{"conv_params", std::vector<int64_t>{stride, stride, padding, padding, 1, 1}}});
+ }
+ GgufValue convolution(const GgufValue& pixels, const std::string& weight, int64_t stride, int64_t padding = 0) {
+ return convolution(pixels, g.tensors().require(weight), stride, padding);
+ }
+ GgufValue unfold(const GgufValue& x, int64_t channels, int64_t kernel) {
+ return g.node("GGML_OP_IM2COL",
+ {x},
+ 0,
+ {{"im2col_params", std::vector<int32_t>{int32_t(kernel), int32_t(kernel), 0, 0, 1, 1, 1}},
+ {"kernel_shape", ov::Shape{1, size_t(channels), size_t(kernel), size_t(kernel)}},
+ {"dst_type", ov::element::f32}});
+ }
+ GgufValue dynamic_vision(const EncoderConfig& c) {
+ auto pixels = g.add_input("vision.pixel_values", ov::element::f32, {1, 3, -1, -1});
+ GgufValue spatial, x;
+ if (c.topology == EncoderTopology::UNIFIED_VISION) {
+ for (int i = 1; i <= 3; ++i) {
+ g.tensors().require("v.patch_norm." + std::to_string(i) + ".weight");
+ g.tensors().require("v.patch_norm." + std::to_string(i) + ".bias");
+ }
+ spatial = pool(pixels, c.patch, c.patch);
+ x = reshape(unfold(pixels, 3, c.patch), {1, 1, -1, 3 * c.patch * c.patch});
+ // LayerNorm is invariant to a uniform shift. Recenter low-contrast pixel patches
+ // before the mean reduction, whose F32 accumulation otherwise loses precision.
+ x = g.node("GGML_OP_SUB", {x, slice(x, 3, 0, 1)});
+ x = norm(x, "v.patch_norm.1", 1e-5f);
+ // The patch projection reaches 1.5e5 on real images, beyond F16. LayerNorm is invariant
+ // to a uniform scale once its eps shrinks by the square, so compute it shrunk.
+ x = linear(scale(x, kUnifiedShrink), "v.patch_embd", /*with_bias=*/false);
+ x = add(x, scale(g.tensors().require("v.patch_embd.bias"), kUnifiedShrink));
+ x = norm(x, "v.patch_norm.2", 1e-5f * kUnifiedShrink * kUnifiedShrink);
+ } else {
+ spatial = convolution(c.topology == EncoderTopology::GEMMA4 ? scale(pixels, 2.f, -1.f) : pixels,
+ "v.patch_embd.weight",
+ c.patch);
+ x = patch_embeddings(spatial, c.width, c.topology != EncoderTopology::GEMMA4);
+ }
+ GgufValue pos_a, pos_b, learned;
+ if (c.topology == EncoderTopology::PHI4) {
+ auto table =
+ resize_square_table(g.tensors().require("v.position_embd.weight"), spatial, c.width, 0x201, "phi4");
+ learned = reshape(transpose(table, {0, 2, 3, 1}), {1, 1, -1, c.width});
+ } else {
+ pos_a = index_input("position_x");
+ pos_b = index_input("position_y");
+ if (c.topology != EncoderTopology::PIXTRAL) {
+ auto table = g.tensors().require("v.position_embd.weight");
+ OPENVINO_ASSERT(table.ne(2) == 2, "[GGUF] Gemma4 position table requires x/y axes");
+ table = reshape(table, {1, 2, table.ne(1), c.width});
+ learned = add(g.node("GGML_OP_GET_ROWS", {slice(table, 1, 0, 1), pos_a}),
+ g.node("GGML_OP_GET_ROWS", {slice(table, 1, 1, 1), pos_b}));
+ }
+ }
+ if (c.topology == EncoderTopology::UNIFIED_VISION) {
+ // The RMSNorm input squared exceeds F16 (x up to ~800); RMSNorm is scale-invariant as well.
+ auto normed = scale(norm(add(x, learned), "v.patch_norm.3", 1e-5f), kUnifiedShrink);
+ return linear(g.build_norm(normed, {}, c.eps * kUnifiedShrink * kUnifiedShrink), "mm.input_projection");
+ }
+ // Pixtral uses height then width, with alternating frequencies; Gemma4 uses x then y, NEOX halves.
+ x = vit(x,
+ c,
+ learned,
+ c.topology == EncoderTopology::PIXTRAL ? pos_b : pos_a,
+ {},
+ c.topology == EncoderTopology::PIXTRAL ? pos_a : pos_b);
+ if (c.topology == EncoderTopology::PHI4) {
+ g.tensors().require("mm.0.bias");
+ g.tensors().require("mm.2.bias");
+ return ffn(x, "mm.0", "mm.2", "GGML_UNARY_OP_GELU");
+ }
+ if (c.topology == EncoderTopology::GEMMA4) {
+ x = pool(grid(transpose(x), spatial, c.width), c.merge, c.merge);
+ x = scale(transpose(reshape(x, {1, 1, c.width, -1})), std::sqrt(float(c.width)));
+ if (g.tensors().has("v.std_bias") && g.tensors().has("v.std_scale"))
+ x = mul(g.node("GGML_OP_SUB", {x, g.tensors().require("v.std_bias")}),
+ g.tensors().require("v.std_scale"));
+ return linear(g.build_norm(x, {}, c.eps), "mm.input_projection");
+ }
+ if (g.tensors().has("mm.patch_merger.weight")) {
+ x = g.build_norm(x, g.tensors().require("mm.input_norm.weight"), c.eps);
+ x = unfold(grid(transpose(x), spatial, c.width), c.width, c.merge);
+ x = linear(reshape(x, {1, 1, -1, c.width * c.merge * c.merge}), "mm.patch_merger");
+ spatial = pool(spatial, c.merge, c.merge);
+ } else {
+ OPENVINO_ASSERT(c.merge == 1, "[GGUF] pixtral merge requires patch merger weights");
+ }
+ x = ffn(x, "mm.1", "mm.2", "GGML_UNARY_OP_GELU");
+ if (auto token = g.tensors()("v.token_embd.img_break")) {
+ const auto width = token.ne(0);
+ x = transpose(grid(transpose(x), spatial, width), {0, 2, 3, 1});
+ auto row_break = add(scale(slice(x, 2, 0, 1), 0.f), token);
+ x = reshape(concat(x, row_break, 1), {1, 1, -1, width});
+ x = slice(x, 2, 0, -1); // no break after the final row
+ }
+ return x;
+ }
+ GgufValue minicpm46(const EncoderConfig& c) {
+ auto pixels = g.add_input("vision.pixel_values", ov::element::f32, {1, 3, -1, -1});
+ auto x = patch_embeddings(convolution(pixels, "v.patch_embd.weight", c.patch), c.width);
+ auto learned = gather_rows(g.tensors().require("v.position_embd.weight"), "position_ids");
+ x = vit(x, c, learned, {}, {}, {}, 0, c.window_pattern + 1, false);
+ const std::string p = "v.vit_merger.";
+ auto z = gather_rows(norm(x, p + "ln1", c.eps), "window_indices");
+ auto q = reshape(linear(z, p + "attn_q"), {1, -1, c.heads, c.width / c.heads});
+ auto k = reshape(linear(z, p + "attn_k"), {1, -1, c.heads, c.width / c.heads});
+ auto v = reshape(linear(z, p + "attn_v"), {1, -1, c.heads, c.width / c.heads});
+ auto mask = g.add_input("vision.attention_mask", ov::element::f32, {1, 1, -1, -1});
+ z = attention(q, k, v, 1.f / std::sqrt(float(c.width / c.heads)), mask);
+ z = linear(reshape(z, {1, 1, -1, c.width}), p + "attn_out");
+ x = add(x, gather_rows(z, "inverse_window_indices"));
+ // Gather the four cells of each 2x2 merge window, in index order.
+ const auto gather4 = [&](const GgufValue& value, const std::string& name) {
+ std::array<GgufValue, 4> parts;
+ for (int i = 0; i < 4; ++i)
+ parts[i] = gather_rows(value, name + ".indices." + std::to_string(i));
+ return parts;
+ };
+ const auto concat4 = [&](const std::array<GgufValue, 4>& parts) {
+ return concat(concat(concat(parts[0], parts[1]), parts[2]), parts[3]);
+ };
+ auto parts = gather4(x, "vit_merger");
+ auto cat = concat4(parts);
+ x = add(ffn(norm(cat, p + "ds_ln", c.eps), p + "ds_ffn_up", p + "ds_ffn_down", "GGML_UNARY_OP_GELU"),
+ scale(add(add(add(parts[0], parts[1]), parts[2]), parts[3]), .25f));
+ x = vit(x, c, {}, {}, {}, {}, c.window_pattern + 1);
+ parts = gather4(x, "merger");
+ cat = concat4(parts);
+ return ffn(norm(cat, "mm.input_norm", c.eps), "mm.up", "mm.down", "GGML_UNARY_OP_GELU_ERF");
+ }
+ GgufValue resampler_vision(const EncoderConfig& c) {
+ auto pixels = g.add_input("vision.pixel_values", ov::element::f32, {1, 3, -1, -1});
+ auto x = patch_embeddings(convolution(pixels, "v.patch_embd.weight", c.patch), c.width);
+ x = vit(x, c, gather_rows(g.tensors().require("v.position_embd.weight"), "position_ids"));
+
+ const auto query = g.tensors().require("resampler.query");
+ const auto width = query.ne(0);
+ OPENVINO_ASSERT(width > 0 && width % 128 == 0 && query.ne(1) == c.queries,
+ "[GGUF] vision resampler requires 128-wide heads and a query tensor matching query_count");
+ for (const auto* name : {"q", "kv", "post"}) {
+ g.tensors().require(std::string("resampler.ln_") + name + ".weight");
+ g.tensors().require(std::string("resampler.ln_") + name + ".bias");
+ }
+ for (const auto* name : {"q", "k", "v", "out"})
+ g.tensors().require(std::string("resampler.attn.") + name + ".bias");
+ auto q = norm(reshape(query, {1, 1, c.queries, width}), "resampler.ln_q", c.eps);
+ auto v = norm(linear(x, "resampler.kv"), "resampler.ln_kv", c.eps);
+ auto pos_h = g.add_input("vision.position_h", ov::element::f32, {1, 1, -1, 1});
+ auto pos_w = g.add_input("vision.position_w", ov::element::f32, {1, 1, -1, 1});
+ ov::Tensor omega(ov::element::f32, {1, 1, 1, size_t(width / 4)});
+ for (int64_t i = 0; i < width / 4; ++i)
+ omega.data<float>()[i] = 1.f / std::pow(10000.f, float(i) / float(width / 4));
+ auto frequency = g.add_constant("vision.resampler_omega", omega);
+ const auto sinusoid = [&](const GgufValue& pos) {
+ auto theta = mul(pos, frequency);
+ return concat(g.node("GGML_OP_SIN", {theta}), g.node("GGML_OP_COS", {theta}));
+ };
+ auto positional = concat(sinusoid(pos_w), sinusoid(pos_h));
+ auto k = add(v, positional);
+ q = reshape(linear(q, "resampler.attn.q"), {1, c.queries, width / 128, 128});
+ k = reshape(linear(k, "resampler.attn.k"), {1, -1, width / 128, 128});
+ v = reshape(linear(v, "resampler.attn.v"), {1, -1, width / 128, 128});
+ x = attention(q, k, v, 1.f / std::sqrt(128.f));
+ x = linear(reshape(x, {1, 1, c.queries, width}), "resampler.attn.out");
+ return linear(norm(x, "resampler.ln_post", c.eps), "resampler.proj");
+ }
+ GgufValue muse_glimmer_vision(const EncoderConfig& c) {
+ auto pixels = g.add_input("vision.pixel_values", ov::element::f32, {1, 3, -1, -1});
+ auto spatial = convolution(pixels, "v.patch_embd.weight", c.patch);
+ auto x = patch_embeddings(spatial, c.width);
+ auto table = g.tensors().require("v.position_embd.weight");
+ table = resize_square_table(table, spatial, c.width, 1, "Muse Glimmer");
+ x = add(x, reshape(transpose(table, {0, 2, 3, 1}), {1, 1, -1, c.width}));
+ x = gather_rows(x, "patch_indices");
+ auto pos_x = index_input("position_x"), pos_y = index_input("position_y");
+ muse_window = int64_t(std::sqrt(double(g.tensors().require("v.position_embd.weight").ne(1))));
+ // Additive key mask of every window padded to muse_window^2 patches.
+ auto mask = g.add_input("vision.window_mask", ov::element::f32, {-1, 1, 1, muse_window * muse_window});
+ x = vit(x, c, {}, pos_x, mask, pos_y);
+ x = gather_rows(x, "output_indices");
+ x = gather_rows(x, "merge_indices");
+ // Channel-outer pixel shuffle: each channel's spatial neighbours stay together.
+ x = reshape(x, {1, -1, c.merge * c.merge, c.width});
+ x = reshape(transpose(x, {0, 1, 3, 2}), {1, 1, -1, c.width * c.merge * c.merge});
+ x = g.node("GGML_UNARY_OP_GELU_ERF", {linear(x, "mm.0", false)});
+ x = g.node("GGML_UNARY_OP_GELU_ERF", {linear(x, "mm.1", false)});
+ return linear(x, "mm.2", false);
+ }
+ GgufValue qwen_vision(const EncoderConfig& c) {
+ // A temporal pair; still-image callers duplicate the image. Index inputs specify
+ // spatial 2x2 grouping and, for Qwen2.5, the reference's window permutation.
+ auto pixels = g.add_input("vision.pixel_values", ov::element::f32, {2, 3, -1, -1});
+ // One convolution over both frames stacked on the channel axis.
+ auto weight =
+ concat(g.tensors().require("v.patch_embd.weight"), g.tensors().require("v.patch_embd.weight.1"), 2);
+ auto patches = convolution(reshape(pixels, {1, -1, 0, 0}, true), weight, c.patch);
+ auto indices = index_input("patch_indices");
+ auto group = [&](const GgufValue& value) {
+ return g.node("GGML_OP_GET_ROWS", {transpose(reshape(value, {1, 1, c.width, -1})), indices});
+ };
+ auto x = group(patches);
+ if (auto bias = g.tensors()("v.patch_embd.bias"))
+ x = add(x, bias);
+ GgufValue learned_positions;
+ if (c.projector == "qwen3vl_merger") {
+ learned_positions = group(resize_square_table(g.tensors().require("v.position_embd.weight"),
+ patches,
+ c.width,
+ 1 | 0x100,
+ "Qwen"));
+ }
+ auto positions = index_input("position_ids");
+ GgufValue window_mask;
+ if (c.window_pattern)
+ window_mask = g.add_input("vision.attention_mask", ov::element::f32, {1, 1, -1, -1});
+ x = vit(x, c, learned_positions, positions, window_mask);
+ x = ffn(reshape(x, {1, 1, -1, 4 * c.width}), "mm.0", "mm.2", "GGML_UNARY_OP_GELU");
+ for (const auto& feature : auxiliary)
+ x = concat(x, feature);
+ if (c.window_pattern)
+ x = gather_rows(x, "output_indices");
+ return x;
+ }
+ GgufValue reshape_like(const GgufValue& x,
+ const GgufValue& reference,
+ std::vector<int64_t> pattern,
+ std::vector<int64_t> axes) {
+ return g.node("GGML_OP_RESHAPE",
+ {x, reference},
+ 0,
+ {{"reshape_target", std::move(pattern)}, {"shape_axes", std::move(axes)}});
+ }
+ GgufValue sam(const GgufValue& pixels) {
+ const auto width = positive(g.metadata(), "clip.vision.sam.embedding_length");
+ const auto heads = positive(g.metadata(), "clip.vision.sam.head_count");
+ const auto layers = positive(g.metadata(), "clip.vision.sam.block_count");
+ const auto window = positive(g.metadata(), "clip.vision.window_size");
+ OPENVINO_ASSERT(width % heads == 0, "[GGUF] invalid SAM head count");
+ const auto head = width / heads;
+ auto x = convolution(pixels, "v.sam.patch_embd.weight", g.tensors().require("v.sam.patch_embd.weight").ne(0));
+ x = transpose(x, {0, 2, 3, 1});
+ x = add(x, g.tensors().require("v.sam.patch_embd.bias"));
+ auto pos = g.tensors().require("v.sam.pos_embd.weight");
+ pos = reshape(pos, {1, pos.ne(2), pos.ne(1), width});
+ pos = g.node("GGML_OP_UPSCALE",
+ {transpose(pos, {0, 3, 1, 2}), transpose(x, {0, 3, 1, 2})},
+ 0,
+ {{"resize_like", true}, {"interpolation_mode", 2}});
+ x = add(x, transpose(pos, {0, 2, 3, 1}));
+ auto local = g.add_input("vision.relative_indices_local", ov::element::i32, {1, 1, window, window});
+ auto global = g.add_input("vision.relative_indices_global", ov::element::i32, {1, 1, -1, -1});
+ for (int64_t i = 0; i < layers; ++i) {
+ const auto p = "v.sam.blk." + std::to_string(i) + ".";
+ const bool global_layer = i == 2 || i == 5 || i == 8 || i == 11;
+ auto z = norm(x, p + "pre_ln", 1e-6f);
+ if (!global_layer)
+ z = g.node("GGML_OP_WIN_PART", {z}, 0, {{"window", window}});
+ auto geometry = z;
+ auto qkv = linear(z, p + "attn.qkv");
+ const auto project = [&](int part) {
+ return reshape(slice(qkv, 3, part * width, width), {0, -1, heads, head}, true);
+ };
+ auto q = project(0), k = project(1), v = project(2);
+ auto qr = reshape_like(transpose(q, {0, 2, 1, 3}), geometry, {-1, 0, 0, head}, {-1, 1, 2, -1});
+ const auto rel_pos = [&](const std::string& axis) {
+ return g.node("GGML_OP_GET_REL_POS",
+ {g.tensors().require(p + "attn.pos_" + axis + ".weight"), global_layer ? global : local},
+ 1);
+ };
+ auto rw = rel_pos("w");
+ auto rh = rel_pos("h");
+ rw = transpose(g.node("GGML_OP_MUL_MAT", {rw, transpose(qr, {0, 2, 1, 3})}), {0, 2, 1, 3});
+ rh = g.node("GGML_OP_MUL_MAT", {rh, qr});
+ rw = reshape_like(rw, rw, {0, 0, 0, 1, 0}, {0, 1, 2, -1, 3});
+ rh = reshape_like(rh, rh, {0, 0, 0, 0, 1}, {0, 1, 2, 3, -1});
+ auto mask = reshape_like(add(rw, rh), q, {0, heads, 0, 0}, {0, -1, 1, 1});
+ z = attention(q, k, v, 1.f / std::sqrt(float(head)), mask);
+ z = linear(reshape_like(z, geometry, {0, 0, 0, 0}, {0, 1, 2, 3}), p + "attn.out");
+ if (!global_layer)
+ z = g.node("GGML_OP_WIN_UNPART", {z, x}, 0, {{"window", window}});
+ x = add(x, z);
+ x = add(x, ffn(norm(x, p + "post_ln", 1e-6f), p + "mlp.lin1", p + "mlp.lin2", "GGML_UNARY_OP_GELU"));
+ }
+ x = convolution(transpose(x, {0, 3, 1, 2}), "v.sam.neck.0.weight", 1);
+ x = norm(transpose(x, {0, 2, 3, 1}), "v.sam.neck.1", 1e-6f);
+ x = convolution(transpose(x, {0, 3, 1, 2}), "v.sam.neck.2.weight", 1, 1);
+ x = norm(transpose(x, {0, 2, 3, 1}), "v.sam.neck.3", 1e-6f);
+ x = convolution(transpose(x, {0, 3, 1, 2}), "v.sam.net_2.weight", 2, 1);
+ return convolution(x, "v.sam.net_3.weight", 2, 1);
+ }
+ GgufValue ocr_vision(const EncoderConfig& c) {
+ auto pixels = g.add_input("vision.pixel_values", ov::element::f32, {-1, 3, -1, -1});
+ auto spatial = sam(pixels);
+ const auto sam_features = reshape(transpose(spatial, {0, 2, 3, 1}), {0, 1, -1, c.width}, true);
+ auto x = sam_features;
+ if (c.topology == EncoderTopology::OCR2) {
+ auto queries = concat(reshape(g.tensors().require("v.resample_query_768.weight"), {1, 1, 144, c.width}),
+ reshape(g.tensors().require("v.resample_query_1024.weight"), {1, 1, 256, c.width}),
+ 1);
+ x = concat(x, gather_rows(queries, "query_indices"), 1);
+ auto positions = index_input("position_ids");
+ auto mask = g.add_input("vision.attention_mask", ov::element::f32, {1, 1, -1, -1});
+ x = vit(x, c, {}, positions, mask);
+ x = g.node("GGML_OP_GET_ROWS", {x, index_input("query_output_indices")}, 4);
+ } else {
+ auto cls = reshape(g.tensors().require("v.class_embd"), {1, 1, 1, c.width});
+ // Repeat the class token once per independently encoded tile.
+ cls = add(scale(slice(x, 2, 0, 1), 0.f), cls);
+ x = concat(cls, x, 1);
+ auto pos = g.tensors().require("v.position_embd.weight");
+ // Preserve the pinned loader's legacy CLIP table layout, including the
+ // byte offset of its trailing class position. The caller selects the
+ // original table for an unchanged grid, or the resized table otherwise.
+ const auto side = int64_t(std::sqrt(double(pos.ne(1) - 1)));
+ auto original = reshape(pos, {1, 1, -1, c.width});
+ auto old = slice(original, 2, 0, side * side);
+ auto resized = g.node("GGML_OP_UPSCALE",
+ {old, slice(spatial, 0, 0, 1)},
+ 0,
+ {{"resize_like", true}, {"interpolation_mode", 2}});
+ resized = g.node("GGML_OP_REPEAT", {resized}, 0, {{"repeats", std::vector<int64_t>{1, c.width, 1, 1}}});
+ resized = reshape(resized, {1, 1, -1, c.width});
+ auto cls_pos = slice(reshape(pos, {1, 1, 1, -1}), 3, side * side / int64_t(pos.type().size()), c.width);
+ auto tables = concat(original, concat(resized, cls_pos, 1), 1);
+ pos = gather_rows(tables, "position_indices");
+ x = vit(x, c, pos);
+ x = slice(x, 2, 1, std::numeric_limits<int32_t>::max() - 1);
+ x = concat(x, sam_features);
+ }
+ x = linear(x, "mm.model.fc");
+ const auto width = g.tensors().require("mm.model.fc.weight").ne(1);
+ x = reshape(x, {1, 1, -1, width});
+ // Indexing describes overview/tile row assembly, including learned separators.
+ if (c.topology == EncoderTopology::OCR)
+ x = concat(x, reshape(g.tensors().require("v.image_newline"), {1, 1, 1, width}), 1);
+ x = concat(x, reshape(g.tensors().require("v.view_seperator"), {1, 1, 1, width}), 1);
+ return gather_rows(x, "output_indices");
+ }
+ GgufValue gemma4_audio(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, 1, mel, -1});
+ x = transpose(x); // [1, 1, time, frequency]
+ for (int i = 0; i < 2; ++i) {
+ const auto p = "a.conv1d." + std::to_string(i);
+ x = convolution(x, p + ".weight", 2, 1);
+ if (auto bias = g.tensors()(p + ".bias"))
+ x = add(x, bias);
+ x = transpose(x, {0, 2, 3, 1});
+ if (auto weight = g.tensors()(p + ".norm.weight"))
+ x = g.build_norm_ln(x, weight, {}, c.eps);
+ x = transpose(g.node("GGML_UNARY_OP_RELU", {x}), {0, 3, 1, 2});
+ }
+ // Reference flatten order is frequency-major with channels innermost.
+ const auto flattened = g.tensors().require("a.input_projection.weight").ne(0);
+ x = reshape(transpose(x, {0, 2, 3, 1}), {1, 1, -1, flattened});
+ x = linear(x, "a.input_projection");
+ // Each token attends to itself and the 11 before it, with relative positions 12..0.
+ constexpr int64_t horizon = 12;
+ ov::Tensor table(ov::element::f32, {1, 1, horizon + 1, static_cast<size_t>(c.width)});
+ const int64_t half = c.width / 2;
+ const float increment = std::log(10000.f) / std::max<int64_t>(half - 1, 1);
+ for (int64_t p = 0; p <= horizon; ++p)
+ for (int64_t i = 0; i < half; ++i) {
+ const float angle = float(horizon - p) * std::exp(-float(i) * increment);
+ table.data<float>()[p * c.width + i] = std::sin(angle);
+ table.data<float>()[p * c.width + half + i] = std::cos(angle);
+ }
+ auto positions = g.add_constant("mmproj.audio.relative_positions", table);
+ const auto clamp = [&](const GgufValue& value, float lo, float hi) {
+ return g.node("GGML_OP_CLAMP", {value}, 0, {{"clamp_min", lo}, {"clamp_max", hi}});
+ };
+ auto index = scale(g.node("GGML_OP_CUMSUM", {transpose(scale(slice(x, 3, 0, 1), 0.f, 1.f))}), 1.f, -1.f);
+ auto distance = g.node("GGML_OP_SUB", {transpose(index), index}); // query - key
+ const auto ahead = scale(distance, -1.f, float(horizon));
+ auto relative = g.node("GGML_OP_CPY", {clamp(ahead, 0.f, float(horizon))}, 0, {{"dst_type", ov::element::i32}});
+ auto inside = mul(clamp(scale(distance, 1.f, 1.f), 0.f, 1.f), clamp(ahead, 0.f, 1.f));
+ auto mask = scale(inside, 1e9f, -1e9f);
+ const auto rms = [&](const GgufValue& value, const std::string& name) {
+ return g.build_norm(value, g.tensors().require(name + ".weight"), c.eps);
+ };
+ const auto maybe_rms = [&](const GgufValue& value, const std::string& name) {
+ auto w = g.tensors()(name + ".weight");
+ return w ? g.build_norm(value, w, c.eps) : value;
+ };
+ // Both FFN sublayers are post-normed and added back at half weight.
+ const auto half_ffn = [&](const GgufValue& value, const std::string& p, const std::string& suffix) {
+ auto z = ffn(rms(value, p + "ffn_norm" + suffix),
+ p + "ffn_up" + suffix,
+ p + "ffn_down" + suffix,
+ "GGML_UNARY_OP_SILU",
+ "",
+ false);
+ return add(value, scale(maybe_rms(z, p + "ffn_post_norm" + suffix), .5f));
+ };
+ for (int64_t i = 0; i < c.layers; ++i) {
+ const auto p = "a.blk." + std::to_string(i) + ".";
+ x = half_ffn(x, p, "");
+ auto z = rms(x, p + (g.tensors().has(p + "attn_pre_norm.weight") ? "attn_pre_norm" : "ln1"));
+ auto q = linear(z, p + "attn_q", false);
+ auto k = linear(z, p + "attn_k", false);
+ auto v = linear(z, p + "attn_v", false);
+ const auto head = c.width / c.heads;
+ q = scale(reshape(q, {1, -1, c.heads, head}), 1.f / std::sqrt(float(head)) / std::log(2.f));
+ k = scale(reshape(k, {1, -1, c.heads, head}), std::log1p(std::exp(1.f)) / std::log(2.f));
+ if (auto w = g.tensors()(p + "per_dim_scale.weight"))
+ q = mul(q, reshape(w, {1, 1, 1, head}));
+ if (auto w = g.tensors()(p + "per_dim_k_scale.weight"))
+ k = mul(k, reshape(w, {1, 1, 1, head}));
+ q = transpose(q, {0, 2, 1, 3});
+ k = transpose(k, {0, 2, 1, 3});
+ v = transpose(reshape(v, {1, -1, c.heads, head}), {0, 2, 3, 1});
+ auto scores = g.node("GGML_OP_MUL_MAT", {k, q});
+ if (g.tensors().has(p + "attn_k_rel.weight")) {
+ // The reference projects RPE without clamping, unlike its content projections.
+ auto pos = g.node("GGML_OP_MUL_MAT", {g.tensors().require(p + "attn_k_rel.weight"), positions});
+ pos = transpose(reshape(pos, {1, 13, c.heads, head}), {0, 2, 1, 3});
+ auto bias = g.node("GGML_OP_MUL_MAT", {pos, q});
+ bias = g.node("GGML_OP_GET_ROWS", {bias, relative}, 0, {{"gather_elements", true}});
+ scores = add(scores, bias);
+ }
+ scores = add(scale(g.node("GGML_UNARY_OP_TANH", {scale(scores, 1.f / 50.f)}), 50.f), mask);
+ auto probability = g.node("GGML_OP_SOFT_MAX", {scores}, 0, {{"scale", 1.f}});
+ z = g.node("GGML_OP_MUL_MAT", {v, probability});
+ z = linear(reshape(transpose(z, {0, 2, 1, 3}), {1, 1, -1, c.width}), p + "attn_out");
+ x = add(x, maybe_rms(z, p + "attn_post_norm"));
+ z = linear(rms(x, p + "conv_norm"), p + "conv_pw1", false);
+ z = mul(slice(z, 3, 0, c.width), g.node("GGML_UNARY_OP_SIGMOID", {slice(z, 3, c.width, c.width)}));
+ z = transpose(z);
+ z = g.node("GGML_OP_PAD", {z}, 0, {{"pad_params", std::vector<int32_t>{4, 0, 0, 0, 0, 0, 0, 0}}});
+ z = g.node("GGML_OP_SSM_CONV", {z, g.tensors().require(p + "conv_dw.weight")});
+ if (auto bias = g.tensors()(p + "conv_dw.bias"))
+ z = add(z, bias);
+ z = maybe_rms(z, p + "norm_conv");
+ x = add(x, linear(g.node("GGML_UNARY_OP_SILU", {z}), p + "conv_pw2", false));
+ x = half_ffn(x, p, "_1");
+ x = maybe_rms(x, p + "ln2");
+ }
+ if (g.tensors().has("a.pre_encode.out.weight"))
+ x = linear(x, "a.pre_encode.out");
+ x = g.build_norm(x, g.tensors()("mm.a.soft_emb_norm.weight"), c.eps);
+ return linear(x, "mm.a.input_projection", false);
+ }
+ GgufValue audio(const EncoderConfig& c) {
+ if (c.topology == EncoderTopology::GEMMA4_AUDIO)
+ return gemma4_audio(c);
+ if (c.topology == EncoderTopology::UNIFIED_AUDIO) {
+ auto x = g.add_input("audio.waveform_frames", ov::element::f32, {1, 1, -1, 640});
+ return linear(g.build_norm(x, {}, c.eps), "mm.a.input_projection");
+ }
+ 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});
+ for (int i = 1; i <= 2; ++i) {
+ const auto base = "a.conv1d." + std::to_string(i);
+ auto w = g.tensors().require(base + ".weight");
+ const auto kernel = w.ne(0), in = w.ne(1), out = w.ne(2);
+ w = reshape(w, {out, in, 1, kernel});
+ x = g.node("GGML_OP_CONV_2D",
+ {w, x},
+ 0,
+ {{"conv_params", std::vector<int64_t>{i, 1, kernel / 2, 0, 1, 1}}});
+ x = add(x, reshape(g.tensors().require(base + ".bias"), {1, out, 1, 1}));
+ x = g.node("GGML_UNARY_OP_GELU_ERF", {x});
+ }
+ x = transpose(reshape(x, {1, 1, c.width, -1}));
+ auto ids = g.add_input("audio.position_ids", ov::element::i32, {1, 1, 1, -1});
+ auto pos = g.node("GGML_OP_GET_ROWS", {g.tensors().require("a.position_embd.weight"), ids});
+ x = vit(x, c, pos);
+ if (c.projector == "qwen2a")
+ return linear(x, "mm.a.fc");
+ if (c.projector == "glma")
+ x = norm(x, "mm.a.norm_pre", c.eps);
+ if (c.projector == "ultravox" || c.projector == "voxtral" || c.projector == "meralion" ||
+ c.projector == "glma") {
+ const auto stack = positive(g.metadata(), "clip.audio.projector.stack_factor");
+ x = g.node("GGML_OP_PAD", {x}, 0, {{"pad_tokens_to_multiple", stack}});
+ x = reshape(x, {1, 1, -1, c.width * stack});
+ }
+ if (c.projector == "ultravox") {
+ x = g.build_norm(x, g.tensors().require("mm.a.norm_pre.weight"), 1e-6f);
+ x = linear(x, "mm.a.mlp.1");
+ x = g.node("GGML_GLU_OP_SWIGLU", {x}, 0, {{"swapped", true}});
+ x = g.build_norm(x, g.tensors().require("mm.a.norm_mid.weight"), 1e-6f);
+ return linear(x, "mm.a.mlp.2");
+ }
+ if (c.projector == "meralion") {
+ x = g.node("GGML_UNARY_OP_SILU", {linear(norm(x, "mm.a.norm_pre", c.eps), "mm.a.mlp.0")});
+ x = mul(g.node("GGML_UNARY_OP_SILU", {linear(x, "mm.a.mlp.1")}), linear(x, "mm.a.mlp.2"));
+ return linear(x, "mm.a.mlp.3");
+ }
+ if (c.projector == "glma") {
+ x = ffn(x, "mm.a.mlp.1", "mm.a.mlp.2", c.activation);
+ const auto width = x.ne(0);
+ x = concat(reshape(g.tensors().require("v.boi"), {1, 1, 1, width}), x, 1);
+ return concat(x, reshape(g.tensors().require("v.eoi"), {1, 1, 1, width}), 1);
+ }
+ return ffn(x, "mm.a.mlp.1", "mm.a.mlp.2", "GGML_UNARY_OP_GELU_ERF");
+ }
+};
+
+class MmprojBuilder : public ModelBuilder {
+public:
+ explicit MmprojBuilder(const BuildContext& context) : ctx(context), g(context) {}
+
+ std::shared_ptr<GgufGraph> build() override {
+ std::optional<ProjectorRegistry> defaults;
+ const auto& registry = ctx.projectors ? *ctx.projectors : defaults.emplace();
+ std::vector<std::shared_ptr<const ProjectorDefinition>> encoders;
+ for (const auto* modality : {"vision", "audio"}) {
+ if (!ctx.metadata.get_bool(std::string("clip.has_") + modality + "_encoder").value_or(false))
+ continue;
+ const auto type = resolve_projector_type(ctx.metadata, modality);
+ const auto definition = registry.find(ctx.metadata, modality, type);
+ OPENVINO_ASSERT(definition, "[GGUF] unsupported ", modality, " mmproj projector '", type, "'");
+ encoders.push_back(definition);
+ }
+ OPENVINO_ASSERT(!encoders.empty(), "[GGUF] mmproj has no encoder");
+ std::map<std::string, std::string> branch_config;
+ branch_config["vision.auxiliary_count"] = "0";
+ for (const auto& definition : encoders) {
+ auto result = definition->build(g);
+ OPENVINO_ASSERT(result.output, "[GGUF] projector handler '", definition->id, "' returned no output");
+ g.set_output(result.output, definition->modality + ".embeddings");
+ for (const auto& entry : result.config) {
+ OPENVINO_ASSERT(entry.first.rfind(definition->modality + ".", 0) == 0,
+ "[GGUF] projector metadata must use its modality prefix");
+ branch_config[entry.first] = entry.second;
+ }
+ branch_config[definition->modality + ".projector"] = definition->projector_type;
+ }
+ auto graph = g.finish();
+ const auto number = [](auto value) {
+ std::ostringstream stream;
+ stream.precision(std::numeric_limits<double>::max_digits10);
+ stream << value;
+ return stream.str();
+ };
+ const auto join = [&](const auto& values) {
+ std::string text;
+ for (size_t i = 0; i < values.size(); ++i)
+ text += (i ? "," : "") + number(values[i]);
+ return text;
+ };
+ // Preserve full metadata names. Strings serialize through the standard IR rt_info path.
+ for (const auto& [key, value] : detail::MetadataAccess::get(ctx.metadata).map) {
+ if (key.rfind("clip.", 0) != 0)
+ continue;
+ if (const auto s = ctx.metadata.get_str(key)) {
+ graph->mmproj_config[key] = *s;
+ } else if (const auto n = ctx.metadata.get_int(key)) {
+ graph->mmproj_config[key] = std::to_string(*n);
+ } else if (const auto f = ctx.metadata.get_float(key)) {
+ graph->mmproj_config[key] = number(*f);
+ } else if (std::holds_alternative<std::vector<std::string>>(value)) {
+ // Length-prefixed strings preserve commas, quotes and empty entries.
+ std::ostringstream stream;
+ for (const auto& item : ctx.metadata.get_str_array(key))
+ stream << item.size() << ':' << item;
+ graph->mmproj_config[key] = stream.str();
+ graph->mmproj_config[key + ".encoding"] = std::string("length-prefixed-strings");
+ } else if (const auto integers = ctx.metadata.get_int_array(key); !integers.empty()) {
+ graph->mmproj_config[key] = join(integers);
+ } else {
+ graph->mmproj_config[key] = join(ctx.metadata.get_float_array(key));
+ }
+ }
+ for (const auto& entry : branch_config)
+ graph->mmproj_config[entry.first] = entry.second;
+ return graph;
+ }
+
+private:
+ BuildContext ctx;
+ GgufGraphContext g;
+};
+
+} // namespace
+
+ProjectorResult build_builtin_projector(GgufGraphContext& graph,
+ const std::string& modality,
+ const std::string& projector_type) {
+ return BuiltinProjectorBuilder(graph).build(modality, projector_type);
+}
+
+std::vector<ProjectorDefinition> builtin_projectors() {
+ std::vector<ProjectorDefinition> definitions;
+ for (const auto& entry : projector_catalog) {
+ const std::string modality = entry.modality;
+ const std::string type = entry.name;
+ definitions.push_back({"clip." + modality + "." + type,
+ "clip",
+ modality,
+ type,
+ [modality, type](GgufGraphContext& graph) {
+ return build_builtin_projector(graph, modality, type);
+ },
+ {}});
+ }
+ return definitions;
+}
+
+std::shared_ptr<ModelBuilder> make_mmproj_builder(const BuildContext& context) {
+ return std::make_shared<MmprojBuilder>(context);
+}
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/arch/mmproj_builder.hpp b/src/frontends/gguf/src/builder/arch/mmproj_builder.hpp
new file mode 100644
index 00000000000..ed5fbe9e1b1
--- /dev/null
+++ b/src/frontends/gguf/src/builder/arch/mmproj_builder.hpp
@@ -0,0 +1,11 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/frontend/gguf/builder/model_builder.hpp"
+
+namespace ov::frontend::gguf {
+std::shared_ptr<ModelBuilder> make_mmproj_builder(const BuildContext& context);
+} // 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 129e75b3a5a..6a1d70462f0 100644
--- a/src/frontends/gguf/src/builder/arch_registry.cpp
+++ b/src/frontends/gguf/src/builder/arch_registry.cpp
@@ -4,85 +4,98 @@
#include "arch_registry.hpp"
+#include <optional>
+#include <utility>
+
#include "builder/arch/mamba_builder.hpp"
+#include "builder/arch/mmproj_builder.hpp"
#include "openvino/core/except.hpp"
namespace ov::frontend::gguf {
namespace {
-struct DecoderEntry {
+struct ArchitectureEntry {
+ ArchitectureEntry(const char* name, RopeMode rope) : name(name), rope(rope) {}
+
+ ArchitectureEntry(const char* name,
+ ArchitectureDefinition::BuilderFactory factory,
+ ArchitectureDefinition::MatchFn match = {},
+ const char* id = nullptr)
+ : name(name),
+ factory(std::move(factory)),
+ match(std::move(match)),
+ id(id) {}
+
const char* name;
- RopeMode rope;
- Maturity maturity;
+ std::optional<RopeMode> rope;
+ ArchitectureDefinition::BuilderFactory factory = {};
+ ArchitectureDefinition::MatchFn match = {};
+ const char* id = nullptr;
};
-const DecoderEntry decoders[] = {
- {"bailingmoe2", RopeMode::Neox, Maturity::Verified}, {"deepseek2-ocr", RopeMode::Neox, Maturity::Verified},
- {"ernie4_5-moe", RopeMode::Normal, Maturity::Verified}, {"exaone-moe", RopeMode::Neox, Maturity::Experimental},
- {"exaone4", RopeMode::Neox, Maturity::Verified}, {"gemma", RopeMode::Neox, Maturity::Verified},
- {"gemma2", RopeMode::Neox, Maturity::Verified}, {"gemma3", RopeMode::Neox, Maturity::Verified},
- {"gemma4", RopeMode::Neox, Maturity::Verified}, {"glm4moe", RopeMode::Neox, Maturity::Experimental},
- {"gpt-oss", RopeMode::Neox, Maturity::Verified}, {"hunyuan-dense", RopeMode::Neox, Maturity::Verified},
- {"hunyuan-moe", RopeMode::Neox, Maturity::Experimental}, {"jais2", RopeMode::Neox, Maturity::Experimental},
- {"llama", RopeMode::Normal, Maturity::Verified}, {"llama-embed", RopeMode::Normal, Maturity::Experimental},
- {"maincoder", RopeMode::Normal, Maturity::Verified}, {"mellum", RopeMode::Neox, Maturity::Verified},
- {"minicpm", RopeMode::Normal, Maturity::Verified}, {"minimax-m2", RopeMode::Neox, Maturity::Experimental},
- {"mistral3", RopeMode::Normal, Maturity::Verified}, {"muse-glimmer", RopeMode::Normal, Maturity::Verified},
- {"olmoe", RopeMode::Neox, Maturity::Verified}, {"phi3", RopeMode::Neox, Maturity::Verified},
- {"plamo3", RopeMode::Neox, Maturity::Experimental}, {"qwen2", RopeMode::Neox, Maturity::Verified},
- {"qwen3", RopeMode::Neox, Maturity::Verified}, {"qwen35", RopeMode::Interleaved, Maturity::Verified},
- {"qwen3moe", RopeMode::Neox, Maturity::Verified}, {"smollm3", RopeMode::Normal, Maturity::Verified},
+const ArchitectureEntry architectures[] = {
+ {"bailingmoe2", RopeMode::Neox},
+ {"clip",
+ make_mmproj_builder,
+ [](const GgufMetadata& meta) {
+ return meta.has("clip.projector_type") || meta.has("clip.vision.projector_type") ||
+ meta.has("clip.audio.projector_type");
+ },
+ "clip.mmproj"},
+ {"deepseek2-ocr", RopeMode::Neox},
+ {"ernie4_5-moe", RopeMode::Normal},
+ {"exaone-moe", RopeMode::Neox},
+ {"exaone4", RopeMode::Neox},
+ {"gemma", RopeMode::Neox},
+ {"gemma2", RopeMode::Neox},
+ {"gemma3", RopeMode::Neox},
+ {"gemma4", RopeMode::Neox},
+ {"glm4moe", RopeMode::Neox},
+ {"gpt-oss", RopeMode::Neox},
+ {"hunyuan-dense", RopeMode::Neox},
+ {"hunyuan-moe", RopeMode::Neox},
+ {"jais2", RopeMode::Neox},
+ {"llama", RopeMode::Normal},
+ {"llama-embed", RopeMode::Normal},
+ {"maincoder", RopeMode::Normal},
+ {"mamba2", make_mamba2_builder},
+ {"mellum", RopeMode::Neox},
+ {"minicpm", RopeMode::Normal},
+ {"minimax-m2", RopeMode::Neox},
+ {"mistral3", RopeMode::Normal},
+ {"muse-glimmer", RopeMode::Normal},
+ {"nemotron_h", make_mamba2_builder},
+ {"olmoe", RopeMode::Neox},
+ {"phi3", RopeMode::Neox},
+ {"plamo3", RopeMode::Neox},
+ {"qwen2", RopeMode::Neox},
+ {"qwen3", RopeMode::Neox},
+ {"qwen35", RopeMode::Interleaved},
+ {"qwen35moe", RopeMode::Interleaved},
+ {"qwen3moe", RopeMode::Neox},
+ {"smollm3", RopeMode::Normal},
};
} // namespace
std::vector<ArchitectureDefinition> builtin_architectures() {
std::vector<ArchitectureDefinition> definitions;
- for (const auto& entry : decoders) {
- definitions.push_back(make_decoder_architecture(entry.name, entry.rope, {}, entry.maturity));
+ 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()));
+ }
}
- definitions.push_back(mamba2_architecture("mamba2"));
- definitions.push_back(mamba2_architecture("nemotron_h"));
return definitions;
}
bool arch_uses_neox_rope(const std::string& arch) {
- for (const auto& entry : decoders) {
+ for (const auto& entry : architectures) {
if (arch == entry.name)
return entry.rope == RopeMode::Neox;
}
return false;
}
-const std::set<std::string>& verified_archs() {
- static const auto names = [] {
- std::set<std::string> result;
- for (const auto& definition : builtin_architectures())
- if (definition.maturity == Maturity::Verified)
- result.insert(definition.architecture);
- return result;
- }();
- return names;
-}
-
-const std::set<std::string>& experimental_archs() {
- static const auto names = [] {
- std::set<std::string> result;
- for (const auto& definition : builtin_architectures())
- if (definition.maturity == Maturity::Experimental)
- result.insert(definition.architecture);
- return result;
- }();
- return names;
-}
-
-const std::set<std::string>& supported_archs() {
- static const auto names = [] {
- auto result = verified_archs();
- result.insert(experimental_archs().begin(), experimental_archs().end());
- return result;
- }();
- return names;
-}
-
ArchRegistry::ArchRegistry(std::vector<ArchitectureDefinition> definitions) {
for (auto& definition : definitions)
add(std::move(definition), RegistrationMode::Add);
@@ -110,7 +123,10 @@ void ArchRegistry::add(ArchitectureDefinition definition, RegistrationMode mode)
void ArchRegistry::add_extension(const ArchitectureExtension::Ptr& ext) {
OPENVINO_ASSERT(ext, "[GGUF] null ArchitectureExtension");
- add(ext->definition(), ext->registration_mode());
+ if (const auto projector = std::dynamic_pointer_cast<ProjectorExtension>(ext))
+ m_projectors.add(projector->projector_definition(), projector->registration_mode());
+ else
+ add(ext->definition(), ext->registration_mode());
}
std::shared_ptr<const ArchitectureDefinition> ArchRegistry::find(const GgufMetadata& meta) const {
@@ -124,11 +140,17 @@ std::shared_ptr<const ArchitectureDefinition> ArchRegistry::find(const GgufMetad
return found;
}
+std::set<std::string> ArchRegistry::supported_archs() const {
+ std::set<std::string> names;
+ for (const auto& entry : m_definitions)
+ names.insert(entry.second->architecture);
+ return names;
+}
+
std::string ArchRegistry::describe_supported() const {
std::string out;
- for (const auto& [id, definition] : m_definitions) {
- out += (out.empty() ? "" : ", ") + id;
- }
+ for (const auto& architecture : supported_archs())
+ out += (out.empty() ? "" : ", ") + architecture;
return out;
}
diff --git a/src/frontends/gguf/src/builder/arch_registry.hpp b/src/frontends/gguf/src/builder/arch_registry.hpp
index bb80a95d91a..bda2d1403cf 100644
--- a/src/frontends/gguf/src/builder/arch_registry.hpp
+++ b/src/frontends/gguf/src/builder/arch_registry.hpp
@@ -9,6 +9,7 @@
#include <vector>
#include "openvino/frontend/gguf/extension/architecture.hpp"
+#include "projector_registry.hpp"
namespace ov::frontend::gguf {
@@ -16,9 +17,6 @@ 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);
-const std::set<std::string>& verified_archs();
-const std::set<std::string>& experimental_archs();
-const std::set<std::string>& supported_archs();
// Single catalog for built-in decoder and custom-family definitions.
std::vector<ArchitectureDefinition> builtin_architectures();
@@ -29,9 +27,14 @@ public:
void add(ArchitectureDefinition definition, RegistrationMode mode = RegistrationMode::Add);
void add_extension(const ArchitectureExtension::Ptr& ext);
std::shared_ptr<const ArchitectureDefinition> find(const GgufMetadata& meta) const;
+ std::set<std::string> supported_archs() const;
std::string describe_supported() const;
+ const ProjectorRegistry& projectors() const {
+ return m_projectors;
+ }
private:
+ ProjectorRegistry m_projectors;
std::map<std::string, std::shared_ptr<const ArchitectureDefinition>> m_definitions;
};
diff --git a/src/frontends/gguf/src/builder/blocks/attention.cpp b/src/frontends/gguf/src/builder/blocks/attention.cpp
index 64aff831cc2..152a61bf4e2 100644
--- a/src/frontends/gguf/src/builder/blocks/attention.cpp
+++ b/src/frontends/gguf/src/builder/blocks/attention.cpp
@@ -181,7 +181,7 @@ std::string attention(GraphEmitter& e,
const std::string kc = "cache_k_l" + std::to_string(anchor_il);
const std::string vc = "cache_v_l" + std::to_string(anchor_il);
- if (has_own_kv) {
+ if (!cfg.embedding_model && has_own_kv) {
// Per-layer f16 KV cache Parameters. The K/V read back out of a cache are f16, and so is
// Q after its convert in the translator, so the FLASH_ATTN inputs agree.
const ov::PartialShape cache_shape = ps({1, D, n_head_kv_l, head_size_l});
@@ -200,7 +200,7 @@ std::string attention(GraphEmitter& e,
// sink paired with the cache's ReadValue).
graph.model_output_names.push_back(kc);
graph.model_output_names.push_back(vc);
- } else {
+ } else if (!cfg.embedding_model) {
// Shared-KV layer: K/V have already been set in the anchor layer's SET_ROWS.
// Use the anchor's combined cache. If the current layer has a smaller head size
// (SWA shared layer vs a global anchor), slice K/V to the layer's head_size along
@@ -229,12 +229,16 @@ std::string attention(GraphEmitter& e,
// FLASH_ATTN_EXT(q, k, v, mask[, sinks]) -> [1, n_tokens, n_head, head_size].
// gpt-oss: SWA layers use the sliding-window mask; plus a per-head sink logit.
const std::string mask_name = is_swa_layer ? "self_kq_mask_swa" : "self_kq_mask";
- std::vector<std::string> attn_in = {q, k, v, mask_name};
+ std::vector<std::string> attn_in = {q, k, v};
+ if (!cfg.embedding_model || cfg.causal_attention)
+ attn_in.push_back(mask_name);
if (cfg.has_sinks) {
e.add_named_weight(p + "attn_sinks.weight");
attn_in.push_back(p + "attn_sinks.weight");
}
std::map<std::string, ov::Any> attn_attrs = {{"scale", kq_scale}};
+ if (cfg.embedding_model)
+ attn_attrs["f32_attention"] = true;
if (cfg.attn_soft_cap != 0.0f) {
attn_attrs["kq_soft_cap"] = cfg.attn_soft_cap;
}
diff --git a/src/frontends/gguf/src/builder/blocks/common.cpp b/src/frontends/gguf/src/builder/blocks/common.cpp
index 8806d542c79..fddf9d628ec 100644
--- a/src/frontends/gguf/src/builder/blocks/common.cpp
+++ b/src/frontends/gguf/src/builder/blocks/common.cpp
@@ -4,6 +4,10 @@
#include "builder/blocks/common.hpp"
+#include <cstring>
+#include <tuple>
+#include <vector>
+
namespace ov::frontend::gguf::blocks {
std::string rms_norm(GraphEmitter& e,
@@ -11,11 +15,29 @@ std::string rms_norm(GraphEmitter& e,
const std::string& weight,
const std::string& out_prefix,
float eps) {
- e.add_weight(weight);
+ if (strip_weight_suffix(weight) == weight)
+ e.add_named_weight(weight);
+ else
+ e.add_weight(weight);
auto norm = e.add_op("GGML_OP_RMS_NORM", out_prefix + ".rms", {in}, 0, {{"eps", eps}});
return e.add_op("GGML_OP_MUL", out_prefix, {norm, weight});
}
+std::string layer_norm(GraphEmitter& e,
+ const std::string& in,
+ const std::string& weight,
+ const std::string& out_prefix,
+ float eps) {
+ 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);
+}
+
+std::string bias_weight_name(const std::string& weight_name) {
+ return strip_weight_suffix(weight_name) + ".bias";
+}
+
std::string scale(GraphEmitter& e, const std::string& x, float factor, const std::string& name) {
return e.add_op("GGML_OP_SCALE", name, {x}, 0, {{"scale", factor}, {"bias", 0.0f}});
}
@@ -25,4 +47,49 @@ std::string add_bias(GraphEmitter& e, const std::string& x, const std::string& b
return e.add_op("GGML_OP_ADD", name, {x, bias_weight});
}
+void store_parts(GraphEmitter& e, const std::string& base, const WeightTensors& t, GgufTensorType qtype) {
+ auto& w = e.weights();
+ w[base + ".weight"] = t.weight;
+ if (t.scales) {
+ w[base + ".scales"] = t.scales;
+ }
+ if (t.zero_point) {
+ w[base + ".zp"] = t.zero_point;
+ }
+ e.qtypes()[base + ".qtype"] = qtype;
+}
+
+// Concatenate the rows of two weights with the same quantization layout into one; empty on mismatch.
+std::optional<WeightTensors> concat_rows(const WeightTensors& a,
+ const WeightTensors& b,
+ GgufTensorType qa,
+ GgufTensorType qb) {
+ if (qa != qb || !a.weight || !b.weight) {
+ return std::nullopt;
+ }
+ WeightTensors out;
+ const std::vector<std::tuple<const ov::Tensor*, const ov::Tensor*, ov::Tensor*>> parts{
+ {&a.weight, &b.weight, &out.weight},
+ {&a.scales, &b.scales, &out.scales},
+ {&a.zero_point, &b.zero_point, &out.zero_point}};
+ for (const auto& [x, y, dst] : parts) {
+ if (static_cast<bool>(*x) != static_cast<bool>(*y)) {
+ return std::nullopt;
+ }
+ if (!*x) {
+ continue;
+ }
+ auto sx = x->get_shape(), sy = y->get_shape();
+ if (x->get_element_type() != y->get_element_type() || sx.empty() || sx.size() != sy.size() ||
+ !std::equal(sx.begin() + 1, sx.end(), sy.begin() + 1)) {
+ return std::nullopt;
+ }
+ sx[0] += sy[0];
+ *dst = ov::Tensor(x->get_element_type(), sx);
+ std::memcpy(dst->data(), x->data(), x->get_byte_size());
+ std::memcpy(static_cast<uint8_t*>(dst->data()) + x->get_byte_size(), y->data(), y->get_byte_size());
+ }
+ return out;
+}
+
} // namespace ov::frontend::gguf::blocks
diff --git a/src/frontends/gguf/src/builder/blocks/common.hpp b/src/frontends/gguf/src/builder/blocks/common.hpp
index 3cb2cc99f26..e69769a7f85 100644
--- a/src/frontends/gguf/src/builder/blocks/common.hpp
+++ b/src/frontends/gguf/src/builder/blocks/common.hpp
@@ -4,7 +4,9 @@
#pragma once
+#include <optional>
#include <string>
+#include <utility>
#include "builder/graph_emitter.hpp"
@@ -25,10 +27,29 @@ std::string rms_norm(GraphEmitter& e,
const std::string& out_prefix,
float eps);
+// NORM -> MUL(weight) -> ADD(bias).
+std::string layer_norm(GraphEmitter& e,
+ const std::string& in,
+ const std::string& weight,
+ const std::string& out_prefix,
+ float eps);
+
// Scale a tensor by a constant: GGML_OP_SCALE with attr "scale" (and bias 0).
std::string scale(GraphEmitter& e, const std::string& x, float factor, const std::string& name);
+// "<name>.weight" -> "<name>.bias".
+std::string bias_weight_name(const std::string& weight_name);
+
// Elementwise add of a (broadcast) bias weight: GGML_OP_ADD(x, bias_weight).
std::string add_bias(GraphEmitter& e, const std::string& x, const std::string& bias_weight, const std::string& name);
+// Register the tensors of a derived weight `base` with quant type `qtype`.
+void store_parts(GraphEmitter& e, const std::string& base, const WeightTensors& t, GgufTensorType qtype);
+
+// Concatenate the rows of two weights with the same quantization layout into one; empty on mismatch.
+std::optional<WeightTensors> concat_rows(const WeightTensors& a,
+ const WeightTensors& b,
+ GgufTensorType qa,
+ GgufTensorType qb);
+
} // namespace ov::frontend::gguf::blocks
diff --git a/src/frontends/gguf/src/builder/blocks/ffn.cpp b/src/frontends/gguf/src/builder/blocks/ffn.cpp
index a59b218258d..fc6df11cef8 100644
--- a/src/frontends/gguf/src/builder/blocks/ffn.cpp
+++ b/src/frontends/gguf/src/builder/blocks/ffn.cpp
@@ -4,6 +4,7 @@
#include "builder/blocks/ffn.hpp"
+#include <cmath>
#include <limits>
#include "builder/blocks/common.hpp"
@@ -12,11 +13,27 @@ namespace ov::frontend::gguf::blocks {
namespace {
-// "<name>.weight" -> "<name>.bias": every weight tensor in this file follows that naming
-// convention, so a projection's bias weight name can always be derived from its own.
-std::string bias_weight_name(const std::string& weight_name) {
- static const std::string suffix = ".weight";
- return weight_name.substr(0, weight_name.size() - suffix.size()) + ".bias";
+std::string gated_gate_up(GraphEmitter& e,
+ const std::string& glu_op,
+ const std::string& gate_w,
+ const std::string& up_w,
+ const std::string& ffn_norm,
+ const std::string& gate_name,
+ const std::string& up_name,
+ const std::string& glu_name,
+ bool has_bias) {
+ // Separate gate and up matmuls: a merged weight would copy both and keep the originals alive.
+ e.add_weight(gate_w);
+ auto gate = e.add_op("GGML_OP_MUL_MAT", gate_name, {gate_w, ffn_norm});
+ if (has_bias) {
+ gate = add_bias(e, gate, bias_weight_name(gate_w), gate_name + "_b");
+ }
+ e.add_weight(up_w);
+ auto up = e.add_op("GGML_OP_MUL_MAT", up_name, {up_w, ffn_norm});
+ if (has_bias) {
+ up = add_bias(e, up, bias_weight_name(up_w), up_name + "_b");
+ }
+ return e.add_op(glu_op, glu_name, {gate, up}, 0, {{"swapped", false}});
}
} // namespace
@@ -36,26 +53,20 @@ std::string swiglu_gate_up(GraphEmitter& e,
const std::string& up_name,
const std::string& glu_name,
bool has_bias) {
- e.add_weight(gate_w);
- auto gate = e.add_op("GGML_OP_MUL_MAT", gate_name, {gate_w, ffn_norm});
- if (has_bias) {
- gate = add_bias(e, gate, bias_weight_name(gate_w), gate_name + "_b");
- }
- e.add_weight(up_w);
- auto up = e.add_op("GGML_OP_MUL_MAT", up_name, {up_w, ffn_norm});
- if (has_bias) {
- up = add_bias(e, up, bias_weight_name(up_w), up_name + "_b");
- }
- return e.add_op("GGML_GLU_OP_SWIGLU", glu_name, {gate, up}, 0, {{"swapped", false}});
+ return gated_gate_up(e, "GGML_GLU_OP_SWIGLU", gate_w, up_w, ffn_norm, gate_name, up_name, glu_name, has_bias);
}
std::string geglu_ffn(GraphEmitter& e, const DecoderConfig& cfg, const std::string& p, const std::string& ffn_norm) {
- e.add_weight(p + "ffn_gate.weight");
- e.add_weight(p + "ffn_up.weight");
e.add_weight(p + "ffn_down.weight");
- auto gate = e.add_op("GGML_OP_MUL_MAT", p + "ffn_gate", {p + "ffn_gate.weight", ffn_norm});
- auto up = e.add_op("GGML_OP_MUL_MAT", p + "ffn_up", {p + "ffn_up.weight", ffn_norm});
- auto glu = e.add_op("GGML_GLU_OP_GEGLU", p + "ffn_geglu", {gate, up}, 0, {{"swapped", false}});
+ const auto glu = gated_gate_up(e,
+ "GGML_GLU_OP_GEGLU",
+ p + "ffn_gate.weight",
+ p + "ffn_up.weight",
+ ffn_norm,
+ p + "ffn_gate",
+ p + "ffn_up",
+ p + "ffn_geglu",
+ false);
return e.add_op("GGML_OP_MUL_MAT", p + "ffn_out", {p + "ffn_down.weight", glu});
}
@@ -65,7 +76,13 @@ std::string dense_ffn(GraphEmitter& e, const DecoderConfig& cfg, const std::stri
const bool fused_ffn = !e.has_weight(p + "ffn_gate.weight"); // phi-3: fused gate+up
const bool has_ffn_bias = e.has_weight(p + "ffn_up.bias");
std::string glu;
- if (fused_ffn) {
+ if (cfg.relu_squared_ffn) {
+ auto up = e.add_op("GGML_OP_MUL_MAT", p + "ffn_up", {p + "ffn_up.weight", ffn_norm});
+ if (has_ffn_bias)
+ up = add_bias(e, up, p + "ffn_up.bias", p + "ffn_up_b");
+ auto relu = e.add_op("GGML_UNARY_OP_RELU", p + "ffn_relu", {up});
+ glu = e.add_op("GGML_OP_SQR", p + "ffn_relu_squared", {relu});
+ } else if (fused_ffn) {
auto up = e.add_op("GGML_OP_MUL_MAT", p + "ffn_up", {p + "ffn_up.weight", ffn_norm});
glu = e.add_op("GGML_GLU_OP_SWIGLU", p + "ffn_swiglu", {up}, 0, {{"swapped", false}});
} else {
@@ -85,10 +102,24 @@ std::string dense_ffn(GraphEmitter& e, const DecoderConfig& cfg, const std::stri
return out;
}
-std::string moe_ffn(GraphEmitter& e, const DecoderConfig& cfg, const std::string& p, const std::string& ffn_norm) {
+std::string moe_ffn(GraphEmitter& e,
+ const DecoderConfig& cfg,
+ const std::string& p,
+ const std::string& input,
+ const std::string& router_input) {
+ // Routing uses one flat token axis for both SDPA and PA layouts.
+ const auto flatten = [&](const std::string& name, const std::string& x) {
+ return e.add_op("GGML_OP_RESHAPE",
+ name,
+ {x},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{1, 1, -1, cfg.n_embd}}, {"special_zero", false}});
+ };
+ const auto ffn_norm = flatten(p + "moe_input", input);
// --- router: logits [1,1,T,E] = gate_inp · x ---
e.add_weight(p + "ffn_gate_inp.weight");
- auto logits = e.add_op("GGML_OP_MUL_MAT", p + "moe_logits", {p + "ffn_gate_inp.weight", ffn_norm});
+ auto router = router_input.empty() ? ffn_norm : flatten(p + "moe_router_input", router_input);
+ auto logits = e.add_op("GGML_OP_MUL_MAT", p + "moe_logits", {p + "ffn_gate_inp.weight", router});
if (cfg.has_moe_gate_bias) {
logits = add_bias(e, logits, p + "ffn_gate_inp.bias", p + "moe_logits_b");
}
@@ -146,17 +177,34 @@ std::string moe_ffn(GraphEmitter& e, const DecoderConfig& cfg, const std::string
// expert FFN via MUL_MAT_ID. The routed input x is broadcast to K slots; the
// translator gathers each token's selected expert matrices. gpt-oss adds per-expert
// biases (ADD_ID gathers the selected experts' bias rows).
- e.add_weight(p + "ffn_gate_exps.weight");
- e.add_weight(p + "ffn_up_exps.weight");
e.add_weight(p + "ffn_down_exps.weight");
const bool eb = cfg.has_moe_expert_bias;
- auto up = e.add_op("GGML_OP_MUL_MAT_ID", p + "moe_up", {p + "ffn_up_exps.weight", ffn_norm, selected});
+ std::string gate, up;
+ if (e.has_weight(p + "ffn_gate_up_exps.weight")) {
+ e.add_weight(p + "ffn_gate_up_exps.weight");
+ auto joint =
+ e.add_op("GGML_OP_MUL_MAT_ID", p + "moe_gate_up", {p + "ffn_gate_up_exps.weight", ffn_norm, selected});
+ const auto width = e.value(joint).get_partial_shape()[3].get_length();
+ OPENVINO_ASSERT(width % 2 == 0, "[GGUF] fused expert projection must contain equal gate and up halves");
+ gate = e.add_op("GGML_OP_VIEW",
+ p + "moe_gate",
+ {joint},
+ 3,
+ {{"view_slice", std::vector<int64_t>{3, 0, width / 2}}});
+ up = e.add_op("GGML_OP_VIEW",
+ p + "moe_up",
+ {joint},
+ 3,
+ {{"view_slice", std::vector<int64_t>{3, width / 2, width / 2}}});
+ } else {
+ e.add_weight(p + "ffn_gate_exps.weight");
+ e.add_weight(p + "ffn_up_exps.weight");
+ gate = e.add_op("GGML_OP_MUL_MAT_ID", p + "moe_gate", {p + "ffn_gate_exps.weight", ffn_norm, selected});
+ up = e.add_op("GGML_OP_MUL_MAT_ID", p + "moe_up", {p + "ffn_up_exps.weight", ffn_norm, selected});
+ }
if (eb) {
e.add_named_weight(p + "ffn_up_exps.bias");
up = e.add_op("GGML_OP_ADD_ID", p + "moe_up_b", {up, p + "ffn_up_exps.bias", selected});
- }
- auto gate = e.add_op("GGML_OP_MUL_MAT_ID", p + "moe_gate", {p + "ffn_gate_exps.weight", ffn_norm, selected});
- if (eb) {
e.add_named_weight(p + "ffn_gate_exps.bias");
gate = e.add_op("GGML_OP_ADD_ID", p + "moe_gate_b", {gate, p + "ffn_gate_exps.bias", selected});
}
@@ -169,7 +217,11 @@ std::string moe_ffn(GraphEmitter& e, const DecoderConfig& cfg, const std::string
// is the external contract the shared translators read: glu_alpha/glu_limit.
{{"swapped", false}, {"glu_alpha", 1.702f}, {"glu_limit", 7.0f}});
} else {
- act = e.add_op("GGML_GLU_OP_SWIGLU", p + "moe_act", {gate, up}, 0, {{"swapped", false}});
+ act = e.add_op(cfg.is_geglu ? "GGML_GLU_OP_GEGLU" : "GGML_GLU_OP_SWIGLU",
+ p + "moe_act",
+ {gate, up},
+ 0,
+ {{"swapped", false}});
}
auto experts = e.add_op("GGML_OP_MUL_MAT_ID", p + "moe_down", {p + "ffn_down_exps.weight", act, selected});
if (eb) {
@@ -177,6 +229,19 @@ std::string moe_ffn(GraphEmitter& e, const DecoderConfig& cfg, const std::string
experts = e.add_op("GGML_OP_ADD_ID", p + "moe_down_b", {experts, p + "ffn_down_exps.bias", selected});
}
+ if (e.has_weight(p + "ffn_down_exps.scale")) {
+ e.add_named_weight(p + "ffn_down_exps.scale");
+ auto scales =
+ e.add_op("GGML_OP_RESHAPE",
+ p + "moe_scale_row",
+ {p + "ffn_down_exps.scale"},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{1, 1, 1, cfg.n_expert}}, {"special_zero", false}});
+ scales =
+ e.add_op("GGML_OP_GET_ROWS", p + "moe_selected_scales", {scales, selected}, 10, {{"shared_row", true}});
+ weights = e.add_op("GGML_OP_MUL", p + "moe_scaled_weights", {weights, scales});
+ }
+
// Weighted sum over the K selected experts. weights is [1,T,K,1] (per-expert col).
// experts [1,T,K,n_embd] * weights -> [1,T,K,n_embd]
// TRANSPOSE last two axes -> [1,T,n_embd,K]; SUM_ROWS over K -> [1,T,n_embd,1]
@@ -202,9 +267,43 @@ std::string moe_ffn(GraphEmitter& e, const DecoderConfig& cfg, const std::string
/*has_bias=*/false);
e.add_weight(p + "ffn_down_shexp.weight");
auto s_down = e.add_op("GGML_OP_MUL_MAT", p + "shexp_out", {p + "ffn_down_shexp.weight", s_act});
+ if (e.has_weight(p + "ffn_gate_inp_shexp.weight")) {
+ e.add_weight(p + "ffn_gate_inp_shexp.weight");
+ auto gate_weight =
+ e.add_op("GGML_OP_RESHAPE",
+ p + "shexp_router_weight",
+ {p + "ffn_gate_inp_shexp.weight"},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{1, 1, 1, cfg.n_embd}}, {"special_zero", false}});
+ auto gate = e.add_op("GGML_OP_MUL_MAT", p + "shexp_router", {gate_weight, ffn_norm});
+ gate = e.add_op("GGML_UNARY_OP_SIGMOID", p + "shexp_router_sigmoid", {gate});
+ s_down = e.add_op("GGML_OP_MUL", p + "shexp_gated", {s_down, gate});
+ }
moe_out = e.add_op("GGML_OP_ADD", p + "moe_shared_out", {moe_out, s_down});
}
- return moe_out;
+ return e.add_op("GGML_OP_RESHAPE",
+ p + "moe_output_layout",
+ {moe_out, input},
+ 0,
+ {{"reshape_target", std::vector<int64_t>{1, 1, -1, cfg.n_embd}},
+ {"shape_axes", std::vector<int64_t>{0, 1, 2, -1}}});
+}
+
+std::string gemma4_moe_ffn(GraphEmitter& e,
+ const DecoderConfig& cfg,
+ const std::string& p,
+ const std::string& input,
+ const std::string& dense_norm) {
+ auto dense = geglu_ffn(e, cfg, p, dense_norm);
+ dense = rms_norm(e, dense, p + "post_ffw_norm_1.weight", p + "dense_post_norm", cfg.rms_eps);
+ auto routed_input = rms_norm(e, input, p + "pre_ffw_norm_2.weight", p + "expert_pre_norm", cfg.rms_eps);
+ auto router = e.add_op("GGML_OP_RMS_NORM", p + "router_norm", {input}, 0, {{"eps", cfg.rms_eps}});
+ router = scale(e, router, 1.f / std::sqrt(float(cfg.n_embd)), p + "router_scale");
+ e.add_named_weight(p + "ffn_gate_inp.scale");
+ router = e.add_op("GGML_OP_MUL", p + "router_weighted", {router, p + "ffn_gate_inp.scale"});
+ auto routed = moe_ffn(e, cfg, p, routed_input, router);
+ routed = rms_norm(e, routed, p + "post_ffw_norm_2.weight", p + "expert_post_norm", cfg.rms_eps);
+ return e.add_op("GGML_OP_ADD", p + "combined_experts", {dense, routed});
}
} // namespace ov::frontend::gguf::blocks
diff --git a/src/frontends/gguf/src/builder/blocks/ffn.hpp b/src/frontends/gguf/src/builder/blocks/ffn.hpp
index f2dbdd3ed3f..75335777023 100644
--- a/src/frontends/gguf/src/builder/blocks/ffn.hpp
+++ b/src/frontends/gguf/src/builder/blocks/ffn.hpp
@@ -34,6 +34,17 @@ std::string geglu_ffn(GraphEmitter& e,
// Routing: logits = gate_inp·x; probs = softmax/identity; pick top-k experts; per-token expert
// matmuls via MUL_MAT_ID; gated activation; weighted sum over the used experts; plus the optional
// always-active shared experts.
-std::string moe_ffn(GraphEmitter& e, const DecoderConfig& cfg, const std::string& prefix, const std::string& ffn_norm);
+std::string moe_ffn(GraphEmitter& e,
+ const DecoderConfig& cfg,
+ const std::string& prefix,
+ const std::string& input,
+ const std::string& router_input = "");
+
+// Gemma4 uses separately normalized dense and routed experts and a scaled router.
+std::string gemma4_moe_ffn(GraphEmitter& e,
+ const DecoderConfig& cfg,
+ const std::string& prefix,
+ const std::string& input,
+ const std::string& dense_norm);
} // namespace ov::frontend::gguf::blocks
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 37e9844fdab..9f86190568e 100644
--- a/src/frontends/gguf/src/builder/blocks/gated_delta_net.cpp
+++ b/src/frontends/gguf/src/builder/blocks/gated_delta_net.cpp
@@ -4,6 +4,11 @@
#include "builder/blocks/gated_delta_net.hpp"
+#include <algorithm>
+#include <array>
+#include <cstring>
+#include <functional>
+#include <optional>
#include <vector>
#include "builder/blocks/common.hpp"
@@ -11,6 +16,94 @@
namespace ov::frontend::gguf::blocks {
+namespace {
+
+// Copy of `t` viewed as `outer` rows of bytes, where the chunks [first, first + src.size())
+// of `chunk_bytes` in every row are reordered so that new chunk n holds old chunk src[n].
+// Returns an empty tensor when the byte layout does not split evenly.
+ov::Tensor permute_chunks(const ov::Tensor& t,
+ size_t outer,
+ size_t chunk_bytes,
+ size_t first,
+ const std::vector<int64_t>& src) {
+ const size_t bytes = t.get_byte_size();
+ if (outer == 0 || bytes % outer != 0 || chunk_bytes == 0 || (first + src.size()) * chunk_bytes > bytes / outer) {
+ return {};
+ }
+ const size_t row_bytes = bytes / outer;
+ ov::Tensor out(t.get_element_type(), t.get_shape());
+ const auto* in_data = static_cast<const uint8_t*>(t.data());
+ auto* out_data = static_cast<uint8_t*>(out.data());
+ const size_t head = first * chunk_bytes, tail = (first + src.size()) * chunk_bytes;
+ for (size_t r = 0; r < outer; ++r) {
+ const auto* in_row = in_data + r * row_bytes;
+ auto* out_row = out_data + r * row_bytes;
+ std::memcpy(out_row, in_row, head);
+ std::memcpy(out_row + tail, in_row + tail, row_bytes - tail);
+ for (size_t n = 0; n < src.size(); ++n) {
+ std::memcpy(out_row + (first + n) * chunk_bytes,
+ in_row + (first + static_cast<size_t>(src[n])) * chunk_bytes,
+ chunk_bytes);
+ }
+ }
+ return out;
+}
+
+// Reorder `src.size()` blocks of `rows_per_block` rows (dim 0) starting at row `first_row`.
+ov::Tensor permute_row_blocks(const ov::Tensor& t,
+ size_t first_row,
+ size_t rows_per_block,
+ const std::vector<int64_t>& src) {
+ const auto& shape = t.get_shape();
+ if (shape.empty() || shape[0] == 0 || rows_per_block == 0 || t.get_byte_size() % shape[0] != 0) {
+ return {};
+ }
+ const size_t chunk = t.get_byte_size() / shape[0] * rows_per_block;
+ if (first_row % rows_per_block != 0) {
+ return {};
+ }
+ return permute_chunks(t, 1, chunk, first_row / rows_per_block, src);
+}
+
+// Reorder `src.size()` column blocks of `block_cols` of a [rows, logical_cols] weight part.
+// Per-row tensors with a single column (channel-wise scales) are left as they are.
+ov::Tensor permute_col_blocks(const ov::Tensor& t,
+ size_t logical_cols,
+ size_t block_cols,
+ const std::vector<int64_t>& src) {
+ const auto& shape = t.get_shape();
+ if (shape.size() == 2 && shape[1] == 1) {
+ return t;
+ }
+ if (shape.size() != 2 || shape[0] == 0 || logical_cols == 0 || t.get_byte_size() % shape[0] != 0) {
+ return {};
+ }
+ const size_t row_bytes = t.get_byte_size() / shape[0];
+ if ((row_bytes * block_cols) % logical_cols != 0) {
+ return {};
+ }
+ return permute_chunks(t, shape[0], row_bytes * block_cols / logical_cols, 0, src);
+}
+
+// Apply `fn` to every present part; fails (returns false) if any present part cannot be transformed.
+template <typename Fn>
+bool transform_parts(const WeightTensors& in, WeightTensors& out, Fn&& fn) {
+ const std::vector<std::pair<const ov::Tensor*, ov::Tensor*>> parts{{&in.weight, &out.weight},
+ {&in.scales, &out.scales},
+ {&in.zero_point, &out.zero_point}};
+ for (const auto& [src, dst] : parts) {
+ if (*src) {
+ *dst = fn(*src);
+ if (!*dst) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+} // namespace
+
std::string gated_delta_net(GraphEmitter& e, const DecoderConfig& cfg, int il, const std::string& attn_norm) {
using ov::element::f32;
const std::string p = "blk." + std::to_string(il) + ".";
@@ -20,6 +113,7 @@ std::string gated_delta_net(GraphEmitter& e, const DecoderConfig& cfg, int il, c
const int64_t S = cfg.ssm_state_size; // head_k_dim == head_v_dim
const int64_t H_k = cfg.ssm_group_count; // num_k_heads
const int64_t H_v = cfg.ssm_dt_rank; // num_v_heads
+ OPENVINO_ASSERT(H_k > 0, "[GGUF] Gated-DeltaNet requires a positive ssm.group_count, got ", H_k);
OPENVINO_ASSERT(H_v > 0 && cfg.ssm_inner_size % H_v == 0,
"[GGUF] Gated-DeltaNet: ssm_inner_size (",
cfg.ssm_inner_size,
@@ -31,15 +125,108 @@ std::string gated_delta_net(GraphEmitter& e, const DecoderConfig& cfg, int il, c
const int64_t value_dim = head_v * H_v;
const int64_t conv_dim = 2 * key_dim + value_dim;
+ // ggml pairs V head j with K head j % H_k (tiled order); the fused OV op pairs it with
+ // K head j / (H_v / H_k) (grouped order). Storing the V heads in grouped order in every
+ // per-V-head weight lets the op run without a runtime Tile of q and k.
+ 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_w = p + "ssm_conv1d.weight", a_w = p + "ssm_a", dt_w = p + "ssm_dt.bias";
+ bool gqa_grouped = false;
+ if (H_v != H_k && H_v % H_k == 0) {
+ const int64_t rep = H_v / H_k;
+ std::vector<int64_t> src(H_v);
+ for (int64_t n = 0; n < H_v; ++n) {
+ src[n] = (n % rep) * H_k + n / rep;
+ }
+ const auto rows = [&](size_t first, size_t per_block) {
+ return [&, first, per_block](const ov::Tensor& t) {
+ return permute_row_blocks(t, first, per_block, src);
+ };
+ };
+ const auto cols = [&](const ov::Tensor& t) {
+ return permute_col_blocks(t, value_dim, head_v, src);
+ };
+ struct Grouped {
+ std::string& base;
+ std::function<ov::Tensor(const ov::Tensor&)> permute;
+ WeightTensors parts;
+ };
+ std::array<Grouped, 5> grouped{{{qkv_base, rows(2 * key_dim, head_v), {}},
+ {gate_base, rows(0, head_v), {}},
+ {alpha_base, rows(0, 1), {}},
+ {beta_base, rows(0, 1), {}},
+ {out_base, cols, {}}}};
+ bool ok = std::all_of(grouped.begin(), grouped.end(), [&](Grouped& w) {
+ return transform_parts(e.weight_parts(w.base), w.parts, w.permute);
+ });
+ ov::Tensor conv, a, dt;
+ if (ok) {
+ conv = permute_row_blocks(e.weight_tensor(conv_w), 2 * key_dim, head_v, src);
+ a = permute_row_blocks(e.weight_tensor(a_w), 0, 1, src);
+ dt = permute_row_blocks(e.weight_tensor(dt_w), 0, 1, src);
+ ok = conv && a && dt;
+ }
+ if (ok) {
+ const std::string g = "_grouped";
+ for (auto& w : grouped) {
+ store_parts(e, w.base + g, w.parts, e.weight_qtype(w.base));
+ w.base += g;
+ }
+ conv_w = p + "ssm_conv1d" + g + ".weight", a_w = p + "ssm_a" + g, dt_w = p + "ssm_dt" + g + ".bias";
+ e.weights()[conv_w] = conv;
+ e.weights()[a_w] = a;
+ e.weights()[dt_w] = dt;
+ gqa_grouped = true;
+ }
+ }
+
// ---- input projections ----
- e.add_weight(p + "attn_qkv.weight");
- auto qkv = e.add_op("GGML_OP_MUL_MAT", p + "qkv_mixed", {p + "attn_qkv.weight", attn_norm});
- e.add_weight(p + "attn_gate.weight");
- auto z = e.add_op("GGML_OP_MUL_MAT", p + "z", {p + "attn_gate.weight", attn_norm});
+ e.add_weight(qkv_base + ".weight");
+ auto qkv = e.add_op("GGML_OP_MUL_MAT", p + "qkv_mixed", {qkv_base + ".weight", attn_norm});
+
+ // z, ssm_beta and ssm_alpha share the input. beta/alpha produce one scalar per v-head, and
+ // such a narrow matmul costs about as much as a wide one, so all three run as one matmul when
+ // they share a quantization layout. Widening z to merge would cost more weight bandwidth.
+ std::string z, beta, alpha;
+ auto ba = concat_rows(e.weight_parts(beta_base),
+ e.weight_parts(alpha_base),
+ e.weight_qtype(beta_base),
+ e.weight_qtype(alpha_base));
+ auto zba = ba ? concat_rows(e.weight_parts(gate_base), *ba, e.weight_qtype(gate_base), e.weight_qtype(beta_base))
+ : std::nullopt;
+ if (zba) {
+ store_parts(e, p + "ssm_z_beta_alpha", *zba, e.weight_qtype(gate_base));
+ e.add_weight(p + "ssm_z_beta_alpha.weight");
+ auto zba_out = e.add_op("GGML_OP_MUL_MAT", p + "z_beta_alpha", {p + "ssm_z_beta_alpha.weight", attn_norm});
+ z = e.add_op("GGML_OP_VIEW", p + "z", {zba_out}, 3, {{"view_slice", std::vector<int64_t>{3, 0, value_dim}}});
+ beta = e.add_op("GGML_OP_VIEW",
+ p + "beta",
+ {zba_out},
+ 3,
+ {{"view_slice", std::vector<int64_t>{3, value_dim, H_v}}});
+ alpha = e.add_op("GGML_OP_VIEW",
+ p + "alpha",
+ {zba_out},
+ 3,
+ {{"view_slice", std::vector<int64_t>{3, value_dim + H_v, H_v}}});
+ } else if (ba) {
+ e.add_weight(gate_base + ".weight");
+ z = e.add_op("GGML_OP_MUL_MAT", p + "z", {gate_base + ".weight", attn_norm});
+ store_parts(e, p + "ssm_beta_alpha", *ba, e.weight_qtype(beta_base));
+ e.add_weight(p + "ssm_beta_alpha.weight");
+ auto ba_out = e.add_op("GGML_OP_MUL_MAT", p + "beta_alpha", {p + "ssm_beta_alpha.weight", attn_norm});
+ beta = e.add_op("GGML_OP_VIEW", p + "beta", {ba_out}, 3, {{"view_slice", std::vector<int64_t>{3, 0, H_v}}});
+ alpha = e.add_op("GGML_OP_VIEW", p + "alpha", {ba_out}, 3, {{"view_slice", std::vector<int64_t>{3, H_v, H_v}}});
+ } else {
+ e.add_weight(gate_base + ".weight");
+ z = e.add_op("GGML_OP_MUL_MAT", p + "z", {gate_base + ".weight", attn_norm});
+ e.add_weight(beta_base + ".weight");
+ beta = e.add_op("GGML_OP_MUL_MAT", p + "beta", {beta_base + ".weight", attn_norm});
+ e.add_weight(alpha_base + ".weight");
+ alpha = e.add_op("GGML_OP_MUL_MAT", p + "alpha", {alpha_base + ".weight", attn_norm});
+ }
// beta = sigmoid(ssm_beta @ x), one scalar per v-head
- e.add_weight(p + "ssm_beta.weight");
- auto beta = e.add_op("GGML_OP_MUL_MAT", p + "beta", {p + "ssm_beta.weight", attn_norm});
beta = e.add_op("GGML_UNARY_OP_SIGMOID", p + "beta_sig", {beta});
beta = e.add_op("GGML_OP_RESHAPE",
p + "beta_4d",
@@ -48,13 +235,11 @@ std::string gated_delta_net(GraphEmitter& e, const DecoderConfig& cfg, int il, c
{{"reshape_target", std::vector<int64_t>{0, -1, H_v, 1}}, {"special_zero", true}});
// g = softplus(ssm_alpha @ x + ssm_dt.bias) * ssm_a (ggml: -A_log.exp() * softplus)
- e.add_weight(p + "ssm_alpha.weight");
- auto alpha = e.add_op("GGML_OP_MUL_MAT", p + "alpha", {p + "ssm_alpha.weight", attn_norm});
- e.add_named_weight(p + "ssm_dt.bias");
- alpha = e.add_op("GGML_OP_ADD", p + "alpha_biased", {alpha, p + "ssm_dt.bias"});
+ e.add_named_weight(dt_w);
+ alpha = e.add_op("GGML_OP_ADD", p + "alpha_biased", {alpha, dt_w});
alpha = e.add_op("GGML_UNARY_OP_SOFTPLUS", p + "alpha_sp", {alpha});
- e.add_named_weight(p + "ssm_a");
- auto g = e.add_op("GGML_OP_MUL", p + "gate", {alpha, p + "ssm_a"});
+ e.add_named_weight(a_w);
+ auto g = e.add_op("GGML_OP_MUL", p + "gate", {alpha, a_w});
g = e.add_op("GGML_OP_RESHAPE",
p + "gate_4d",
{g},
@@ -78,11 +263,11 @@ std::string gated_delta_net(GraphEmitter& e, const DecoderConfig& cfg, int il, c
graph.model_output_names.push_back(cs_out);
graph.recurrent_states.emplace_back(cs, cs_out);
- e.add_named_weight(p + "ssm_conv1d.weight");
- auto conv = e.add_op("GGML_OP_SSM_CONV", p + "conv_out", {conv_in, p + "ssm_conv1d.weight"});
+ e.add_named_weight(conv_w);
+ auto conv = e.add_op("GGML_OP_SSM_CONV", p + "conv_out", {conv_in, conv_w}, 0, {{"batch_major", true}});
conv = e.add_op("GGML_UNARY_OP_SILU", p + "conv_silu", {conv});
- // ---- split the conv output into q | k | v and normalize q/k ----
+ // ---- split the conv output into q | k | v; the fused op L2-normalizes q/k ----
auto slice_heads = [&](const std::string& name, int64_t off, int64_t width, int64_t heads, int64_t dim) {
const std::vector<int64_t> sl{3, off, width};
auto s = e.add_op("GGML_OP_VIEW", p + name + "_s", {conv}, 3, {{"view_slice", sl}});
@@ -95,33 +280,26 @@ std::string gated_delta_net(GraphEmitter& e, const DecoderConfig& cfg, int il, c
auto q = slice_heads("q_conv", 0, key_dim, H_k, S);
auto k = slice_heads("k_conv", key_dim, key_dim, H_k, S);
auto v = slice_heads("v_conv", 2 * key_dim, value_dim, H_v, head_v);
- q = e.add_op("GGML_OP_L2_NORM", p + "q_l2", {q}, 0, {{"eps", cfg.rms_eps}});
- k = e.add_op("GGML_OP_L2_NORM", p + "k_l2", {k}, 0, {{"eps", cfg.rms_eps}});
// ---- recurrent delta rule ----
- // ggml state layout is [B, H_v, value_dim, key_dim]; the translator transposes it for
- // the fused op and transposes the new state back, so the Parameter keeps ggml's layout.
+ // The state keeps the fused op's [B, H_v, key_dim, value_dim] layout, and the op returns the
+ // attention and the new state as separate outputs.
const std::string ss = "ssm_state_l" + std::to_string(il);
if (!e.has_model_input(ss)) {
- e.add_input(ss, f32, ps({1, H_v, head_v, S}));
+ e.add_input(ss, f32, ps({1, H_v, S, head_v}));
}
- auto gdn =
- e.add_op("GGML_OP_GATED_DELTA_NET", p + "gdn", {q, k, v, g, beta, ss}, 0, {{"gdn_state_slots", int64_t{1}}});
-
- // Split the packed attention rows and recurrent state; only the token axis is inferred.
- const std::vector<int64_t> attn_view{0, head_v};
- const std::vector<int64_t> state_view{1, head_v};
- auto attn = e.add_op("GGML_OP_VIEW",
- p + "gdn_attn",
- {gdn},
- 4,
- {{"gdn_view", attn_view}, {"view_reshape", std::vector<int64_t>{1, -1, H_v, head_v}}});
- auto new_state = e.add_op("GGML_OP_VIEW",
- ss + "_out",
- {gdn},
- 4,
- {{"gdn_view", state_view}, {"view_reshape", std::vector<int64_t>{1, H_v, head_v, S}}});
+ const auto new_state = ss + "_out";
+ auto attn = e.add_op("GGML_OP_GATED_DELTA_NET",
+ p + "gdn",
+ {q, k, v, g, beta, ss},
+ 0,
+ {{"gdn_state_slots", int64_t{1}},
+ {"fuse_qk_l2norm", true},
+ {"qk_l2_norm_eps", cfg.rms_eps},
+ {"gqa_grouped", gqa_grouped},
+ {"split_outputs", true}},
+ {new_state});
graph.model_output_names.push_back(new_state);
graph.recurrent_states.emplace_back(ss, new_state);
@@ -137,12 +315,13 @@ std::string gated_delta_net(GraphEmitter& e, const DecoderConfig& cfg, int il, c
out = e.add_op("GGML_OP_MUL", p + "gdn_gated", {out, z_silu});
out = e.add_op("GGML_OP_RESHAPE",
p + "gdn_merged",
- {out},
- 6,
- {{"reshape_target", std::vector<int64_t>{0, 1, -1, value_dim}}, {"special_zero", true}});
+ {out, attn_norm},
+ 0,
+ {{"reshape_target", std::vector<int64_t>{1, 1, -1, value_dim}},
+ {"shape_axes", std::vector<int64_t>{0, 1, 2, -1}}});
- e.add_weight(p + "ssm_out.weight");
- return e.add_op("GGML_OP_MUL_MAT", p + "linear_attn_out", {p + "ssm_out.weight", out});
+ e.add_weight(out_base + ".weight");
+ return e.add_op("GGML_OP_MUL_MAT", p + "linear_attn_out", {out_base + ".weight", out});
}
} // namespace ov::frontend::gguf::blocks
diff --git a/src/frontends/gguf/src/builder/decoder_config.cpp b/src/frontends/gguf/src/builder/decoder_config.cpp
index 45b751eea30..5ae387f5270 100644
--- a/src/frontends/gguf/src/builder/decoder_config.cpp
+++ b/src/frontends/gguf/src/builder/decoder_config.cpp
@@ -66,6 +66,16 @@ DecoderConfig::DecoderConfig(const std::map<std::string, GGUFMetaData>& config,
}
arch = std::get<std::string>(config.at("architecture"));
+ embedding_model = arch == "llama-embed";
+ if (embedding_model) {
+ pooling_type = cfg_i("pooling_type");
+ causal_attention = cfg_i("causal_attention") != 0;
+ OPENVINO_ASSERT(pooling_type >= 0 && pooling_type <= 3,
+ "[GGUF] unsupported embedding pooling type: ",
+ pooling_type);
+ }
+ layer_norm = arch == "jais2";
+ relu_squared_ffn = arch == "jais2";
// Per-architecture structure, auto-detected from the GGUF tensor table (layer 0).
has_qk_norm = has("blk.0.attn_q_norm.weight");
@@ -84,7 +94,7 @@ DecoderConfig::DecoderConfig(const std::map<std::string, GGUFMetaData>& config,
{
const int probe = (std::max(0, n_dense_lead) / moe_layer_step + 1) * moe_layer_step - 1;
const std::string pp = "blk." + std::to_string(probe) + ".";
- is_moe = has(pp + "ffn_gate_exps.weight");
+ is_moe = has(pp + "ffn_gate_exps.weight") || has(pp + "ffn_gate_up_exps.weight");
}
// Gemma/Gemma2 use GeGLU (GELU-gated FFN). Detected by arch name since other archs
// in the supported set (llama, qwen2, qwen3, phi3) all use SwiGLU.
@@ -104,9 +114,13 @@ DecoderConfig::DecoderConfig(const std::map<std::string, GGUFMetaData>& config,
options.qk_norm_after_rope.value_or(arch == "hunyuan-dense" || arch == "hunyuan-moe" || arch == "maincoder");
post_norm_only = options.post_norm_only.value_or(arch == "exaone4");
// EXAONE4 has only post-norms; GPT-OSS names its pre-FFN norm post_attention_norm.
- has_attn_post_norm = has("blk.0.post_attention_norm.weight") &&
+ if (!has("blk.0." + attn_post_norm_key) && has("blk.0.post_attention_norm"))
+ attn_post_norm_key = "post_attention_norm";
+ if (!has("blk.0." + ffn_post_norm_key) && has("blk.0.post_ffw_norm"))
+ ffn_post_norm_key = "post_ffw_norm";
+ has_attn_post_norm = has("blk.0." + attn_post_norm_key) &&
(post_norm_only || (has("blk.0.attn_norm.weight") && has("blk.0.ffn_norm.weight")));
- has_ffn_post_norm = has("blk.0.post_ffw_norm.weight") && (post_norm_only || has("blk.0.ffn_norm.weight"));
+ has_ffn_post_norm = has("blk.0." + ffn_post_norm_key) && (post_norm_only || has("blk.0.ffn_norm.weight"));
if (!post_norm_only && !has("blk.0.ffn_norm.weight") && has("blk.0.post_attention_norm.weight"))
ffn_norm_key = "post_attention_norm.weight";
moe_sigmoid_gating = cfg_i("expert_gating_func") == 2;
@@ -133,7 +147,7 @@ DecoderConfig::DecoderConfig(const std::map<std::string, GGUFMetaData>& config,
// tighter eps (post_norm_eps = 1e-8) than the pre-norms use.
const bool is_muse_glimmer = arch == "muse-glimmer";
scaleless_embd_norm = is_muse_glimmer;
- rope_on_swa_only = is_muse_glimmer || (arch == "exaone4" && n_layer == 64);
+ rope_on_swa_only = is_muse_glimmer || arch == "exaone-moe" || (arch == "exaone4" && n_layer == 64);
rope_skip_period = options.rope_skip_period.value_or(arch == "smollm3" ? 4 : 0);
OPENVINO_ASSERT(rope_skip_period >= 0, "[GGUF] RoPE skip period must be nonnegative");
post_norm_eps = is_muse_glimmer ? 1e-8f : 0.0f; // 0 -> reuse rms_eps
@@ -141,7 +155,7 @@ DecoderConfig::DecoderConfig(const std::map<std::string, GGUFMetaData>& config,
// ---- qwen35 (Qwen3.5/3.6): hybrid Gated-DeltaNet + full attention ----
// Layers alternate: every full_attention_interval-th layer is full attention, the rest
// run a linear-attention (GDN) block. llama.cpp src/models/qwen35.cpp.
- is_qwen35 = arch == "qwen35";
+ is_qwen35 = arch == "qwen35" || arch == "qwen35moe";
ssm_conv_kernel = cfg_i("ssm_conv_kernel");
ssm_state_size = cfg_i("ssm_state_size");
ssm_group_count = cfg_i("ssm_group_count");
@@ -180,21 +194,24 @@ DecoderConfig::DecoderConfig(const std::map<std::string, GGUFMetaData>& config,
// qwen35's pre-FFN norm key ("post_attention_norm.weight", HF's
// post_attention_layernorm) already falls out of the generic rule above: attn_norm
// exists, ffn_norm does not, which is the gpt-oss pattern.
- // MTP/NextN blocks are stored past the main stack and are not part of a normal
- // forward pass, so the layer loop must not walk into them.
- n_layer -= n_layer_nextn;
- OPENVINO_ASSERT(n_layer > 0, "[GGUF] qwen35: no trunk layers left after excluding NextN blocks");
}
+ // Trailing MTP/NextN blocks are excluded from the decoder trunk.
+ OPENVINO_ASSERT(n_layer_nextn >= 0 && n_layer_nextn < n_layer,
+ "[GGUF] invalid number of NextN blocks: ",
+ n_layer_nextn);
+ n_layer -= n_layer_nextn;
// Per-architecture scalars from metadata (1.0 / 0.0 when absent -> no-op).
embedding_scale = cfg_f("embedding_scale");
+ embedding_scale_tokens_only = arch == "gemma3" || arch == "gemma4";
residual_scale = cfg_f("residual_scale");
logit_scale = cfg_f("logit_scale");
attention_scale = cfg_f("attention_scale"); // 0 -> 1/sqrt(head_size)
expert_weights_scale = cfg_f("expert_weights_scale"); // 0 -> 1.0 no-op
// These llama.cpp builders require normalization independently of optional GGUF metadata.
expert_weights_norm = options.normalize_expert_weights.value_or(
- arch == "qwen3moe" || arch == "ernie4_5-moe" || arch == "mellum" || cfg_i("expert_weights_norm") != 0);
+ arch == "hunyuan-moe" || arch == "minimax-m2" || arch == "qwen3moe" || arch == "qwen35moe" ||
+ arch == "ernie4_5-moe" || arch == "mellum" || arch == "gemma4" || cfg_i("expert_weights_norm") != 0);
rope_freq_base_swa = cfg_f("rope_freq_base_swa");
swa_layer_pattern = cfg_i("swa_layer_pattern");
// Gemma4: per-layer SWA boolean flags (non-empty when swa_layer_pattern==0).
@@ -236,6 +253,10 @@ DecoderConfig::DecoderConfig(const std::map<std::string, GGUFMetaData>& config,
rope_config_swa = rope_config;
rope_config_swa.freq_base = cfg_f("rope_freq_base_swa");
rope_config_swa.n_dims = cfg_i("rope_dimension_count_swa");
+ // Gemma local attention uses the training default, independently of global
+ // linear RoPE scaling (for example 1/8 in Gemma3 4B).
+ if (arch == "gemma3" || arch == "gemma4")
+ rope_config_swa.freq_scale = 1.0f;
if (options.geglu)
is_geglu = *options.geglu;
if (options.value_norm)
@@ -276,7 +297,8 @@ DecoderConfig::DecoderConfig(const std::map<std::string, GGUFMetaData>& config,
// share the global table and SWA layers would be roped wrong.
const bool swa_dims_differ = rope_dim_swa > 0 && rope_dim_swa != rope_config.n_dims;
const bool swa_freq_differs = rope_config_swa.freq_base != rope_config.freq_base;
- if (has_swa && (swa_dims_differ || swa_freq_differs)) {
+ const bool swa_scale_differs = rope_config_swa.freq_scale != rope_config.freq_scale;
+ if (has_swa && (swa_dims_differ || swa_freq_differs || swa_scale_differs)) {
use_per_op_rope = true;
}
// M-RoPE: inp_pos carries 4 sections per token and only the first n_dims of each head
@@ -285,6 +307,8 @@ DecoderConfig::DecoderConfig(const std::map<std::string, GGUFMetaData>& config,
// case (see RopeConfig::is_imrope / use_per_op_rope).
if (rope_op_case == ROPE_OP_CASE_IMROPE) {
rope_config.is_imrope = true;
+ OPENVINO_ASSERT(rope_sections.size() <= rope_config.sections.size(), "[GGUF] too many M-RoPE sections");
+ std::copy(rope_sections.begin(), rope_sections.end(), rope_config.sections.begin());
use_per_op_rope = true;
}
}
diff --git a/src/frontends/gguf/src/builder/decoder_config.hpp b/src/frontends/gguf/src/builder/decoder_config.hpp
index 2865558cf15..cc25af93533 100644
--- a/src/frontends/gguf/src/builder/decoder_config.hpp
+++ b/src/frontends/gguf/src/builder/decoder_config.hpp
@@ -34,6 +34,11 @@ struct DecoderConfig {
int head_size = 0;
int n_embd = 0;
float rms_eps = 0.0f;
+ bool embedding_model = false;
+ int pooling_type = 0;
+ bool causal_attention = true;
+ bool layer_norm = false;
+ bool relu_squared_ffn = false;
std::vector<uint32_t> n_head_kv_per_layer; // non-empty when head_count_kv varies by layer
// ---- auto-detected per-architecture structure ----
@@ -54,6 +59,8 @@ struct DecoderConfig {
bool has_swa = false;
bool has_attn_post_norm = false;
bool has_ffn_post_norm = false;
+ std::string attn_post_norm_key{"post_attention_norm.weight"};
+ std::string ffn_post_norm_key{"post_ffw_norm.weight"};
bool is_geglu = false;
bool has_v_norm = false; // gemma4: V is also RMSNorm'd like K
@@ -89,6 +96,8 @@ struct DecoderConfig {
int expert_groups = 1;
int expert_groups_used = 1;
float embedding_scale = 1.0f;
+ // Like llama.cpp's Gemma3/Gemma4, scale token lookups only; injected embeddings stay raw.
+ bool embedding_scale_tokens_only = false;
float residual_scale = 1.0f;
float logit_scale = 1.0f;
float attention_scale = 0.0f; // 0 -> 1/sqrt(head_size)
diff --git a/src/frontends/gguf/src/builder/gguf_builder.cpp b/src/frontends/gguf/src/builder/gguf_builder.cpp
index 8aed121bd94..49a9f8db9b1 100644
--- a/src/frontends/gguf/src/builder/gguf_builder.cpp
+++ b/src/frontends/gguf/src/builder/gguf_builder.cpp
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
//
// Parse GGUF, select an architecture definition, and build a graph for the shared op translators.
-// See docs/adding_an_architecture.md for the builder layers and registration paths.
+// See docs/architectures.md for the builder layers and registration paths.
#include "gguf_builder.hpp"
@@ -16,7 +16,6 @@
#include "gguf_graph.hpp"
#include "openvino/core/except.hpp"
#include "openvino/frontend/gguf/builder/model_builder.hpp"
-#include "openvino/util/log.hpp"
#include "quant/gguf.hpp"
namespace ov::frontend::gguf {
@@ -53,7 +52,7 @@ ov::AnyMap extract_tokenizer_config(const std::unordered_map<std::string, GGUFMe
GraphBuilder load_gguf_builder(const std::string& file, const ArchRegistry& registry) {
auto data = std::make_shared<decltype(get_gguf_data(file))>(get_gguf_data(file));
- auto& [metadata, weights, qtypes, mmap, quant_buf] = *data;
+ auto& [metadata, weights, qtypes, mmap] = *data;
const detail::MetadataStore meta_store{metadata};
const GgufMetadata meta_view(meta_store);
@@ -73,24 +72,21 @@ GraphBuilder load_gguf_builder(const std::string& file, const ArchRegistry& regi
registry.describe_supported(),
". Register an ArchitectureExtension.");
}
- if (definition->maturity == Maturity::Experimental) {
- OPENVINO_WARN("[GGUF] architecture handler '",
- definition->id,
- "' is experimental; validate accuracy before relying on it.");
- }
- return [data, definition = *definition](const std::unordered_map<std::string, CreatorFunction>& translators) {
- const auto& [metadata, source_weights, source_qtypes, mmap, quant_buf] = *data;
+ return [data, definition = *definition, projectors = registry.projectors()](
+ const std::unordered_map<std::string, CreatorFunction>& translators) {
+ const auto& [metadata, source_weights, source_qtypes, mmap] = *data;
auto weights = source_weights;
auto qtypes = source_qtypes;
const detail::MetadataStore meta_store{metadata};
const GgufMetadata meta_view(meta_store);
detail::WeightStore weight_store{weights, qtypes, &translators};
- BuildContext ctx{meta_view, meta_view.architecture(), &weight_store};
+ BuildContext ctx{meta_view, meta_view.architecture(), &weight_store, &projectors};
auto builder = definition.factory(ctx);
OPENVINO_ASSERT(builder, "[GGUF] architecture handler '", definition.id, "' returned no builder");
auto graph = builder->build();
OPENVINO_ASSERT(graph, "[GGUF] architecture handler '", definition.id, "' returned no graph");
graph->tokenizer_config = extract_tokenizer_config(metadata);
+ graph->architecture = meta_view.architecture();
return graph;
};
}
diff --git a/src/frontends/gguf/src/builder/gguf_builder_decoder.cpp b/src/frontends/gguf/src/builder/gguf_builder_decoder.cpp
index 00977437a2a..e713d27b27b 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 == "architecture" && m_node_idx < 0)
+ return m_graph->architecture;
// RoPE config is queried at model scope (prepare_graph_inputs, to build the shared
// sin/cos table) and at node scope (each ROPE op's own config). At MODEL scope (no bound node)
// expose the graph's config with per_op / n_dims==0 encoding "no shared table". At NODE scope
@@ -86,7 +88,9 @@ PartialShape GgufBuilderDecoder::get_output_shape() const {
}
std::vector<std::string> GgufBuilderDecoder::get_output_names() const {
- return {node().output_name};
+ auto names = node().extra_output_names;
+ names.insert(names.begin(), node().output_name);
+ return names;
}
// ---- Op type / name ----
@@ -129,4 +133,8 @@ const ov::AnyMap& GgufBuilderDecoder::get_tokenizer_config() const {
return m_graph->tokenizer_config;
}
+const ov::AnyMap& GgufBuilderDecoder::get_mmproj_config() const {
+ return m_graph->mmproj_config;
+}
+
} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/gguf_builder_decoder.hpp b/src/frontends/gguf/src/builder/gguf_builder_decoder.hpp
index 288f96102d8..770a0608206 100644
--- a/src/frontends/gguf/src/builder/gguf_builder_decoder.hpp
+++ b/src/frontends/gguf/src/builder/gguf_builder_decoder.hpp
@@ -46,6 +46,7 @@ public:
std::vector<std::string> get_model_output_names() const override;
const std::vector<std::pair<std::string, std::string>>& get_recurrent_states() const override;
const ov::AnyMap& get_tokenizer_config() const override;
+ const ov::AnyMap& get_mmproj_config() const override;
private:
std::shared_ptr<GgufGraph> m_graph;
diff --git a/src/frontends/gguf/src/builder/gguf_graph.hpp b/src/frontends/gguf/src/builder/gguf_graph.hpp
index 5cd59340186..df14cf7ef99 100644
--- a/src/frontends/gguf/src/builder/gguf_graph.hpp
+++ b/src/frontends/gguf/src/builder/gguf_graph.hpp
@@ -24,10 +24,11 @@ namespace ov::frontend::gguf {
// builder fills these by construction, so all per-op parameters are typed attributes (no
// raw gguf op_params layout).
struct GgufOp {
- std::string op_type; // e.g. "GGML_OP_MUL_MAT"
- std::string name; // unique node/op name
- std::vector<std::string> input_names; // producer tensor names (weights / inputs / other nodes)
- std::string output_name; // this node's output tensor name
+ std::string op_type; // e.g. "GGML_OP_MUL_MAT"
+ std::string name; // unique node/op name
+ std::vector<std::string> input_names; // producer tensor names (weights / inputs / other nodes)
+ std::string output_name; // this node's output tensor name
+ std::vector<std::string> extra_output_names; // further outputs of multi-output ops
int op_case = 0;
// Typed scalar/struct op attributes consumed by translators via get_attribute<T>
@@ -39,6 +40,7 @@ struct GgufOp {
// model-level I/O the decoder reports. Built by an architecture builder (e.g. qwen3) from
// a parsed GGUF file; consumed by GgufBuilderDecoder.
struct GgufGraph {
+ std::string architecture;
std::vector<GgufOp> nodes;
std::shared_ptr<TensorMap> values = std::make_shared<TensorMap>();
@@ -75,6 +77,8 @@ struct GgufGraph {
// by TranslateSession so a downstream consumer can build the tokenizer without re-reading
// the .gguf. Empty if the file carries no tokenizer metadata.
ov::AnyMap tokenizer_config;
+ // Serializable strings containing the full clip.* keys and resolved graph contracts.
+ ov::AnyMap mmproj_config;
};
} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/graph_emitter.cpp b/src/frontends/gguf/src/builder/graph_emitter.cpp
index 2e6c1e46b38..7d2878ac115 100644
--- a/src/frontends/gguf/src/builder/graph_emitter.cpp
+++ b/src/frontends/gguf/src/builder/graph_emitter.cpp
@@ -14,15 +14,6 @@ namespace ov::frontend::gguf {
namespace {
-// Split "<something>.weight" into "<something>"; return the name unchanged when it does not end
-// in ".weight" (biases and other plain tensors keep their full name as the base).
-std::string strip_weight_suffix(const std::string& name) {
- static const std::string suffix = ".weight";
- const bool ends_with_weight =
- name.size() > suffix.size() && name.compare(name.size() - suffix.size(), suffix.size(), suffix) == 0;
- return ends_with_weight ? name.substr(0, name.size() - suffix.size()) : name;
-}
-
WeightTensors find_weight_tensors(const std::unordered_map<std::string, ov::Tensor>& weights, const std::string& base) {
WeightTensors tensors;
if (auto it = weights.find(base + ".weight"); it != weights.end()) {
@@ -39,6 +30,13 @@ WeightTensors find_weight_tensors(const std::unordered_map<std::string, ov::Tens
} // namespace
+std::string strip_weight_suffix(const std::string& name) {
+ static const std::string suffix = ".weight";
+ const bool ends_with_weight =
+ name.size() > suffix.size() && name.compare(name.size() - suffix.size(), suffix.size(), suffix) == 0;
+ return ends_with_weight ? name.substr(0, name.size() - suffix.size()) : name;
+}
+
GraphEmitter::GraphEmitter(std::unordered_map<std::string, ov::Tensor>& weights,
std::unordered_map<std::string, GgufTensorType>& qtypes,
std::string arch,
@@ -79,12 +77,14 @@ std::string GraphEmitter::add_op(const std::string& op_type,
const std::string& name,
const std::vector<std::string>& inputs,
int op_case,
- std::map<std::string, ov::Any> attrs) {
+ std::map<std::string, ov::Any> attrs,
+ std::vector<std::string> extra_outputs) {
GgufOp op;
op.op_type = op_type;
op.name = name;
op.input_names = inputs;
op.output_name = name;
+ op.extra_output_names = std::move(extra_outputs);
op.op_case = op_case;
op.attributes = std::move(attrs);
m_graph->nodes.push_back(std::move(op));
@@ -137,31 +137,27 @@ void GraphEmitter::emit_weight_op(const std::string& node_name, const WeightTens
add_op("GGML_OP_NONE", node_name, {}, 0, std::move(attrs));
}
+WeightTensors GraphEmitter::weight_parts(const std::string& base) const {
+ return find_weight_tensors(m_weights, base);
+}
+
+GgufTensorType GraphEmitter::weight_qtype(const std::string& base) const {
+ return lookup_qtype(base, m_qtypes);
+}
+
void GraphEmitter::add_weight(const std::string& ggml_name) {
if (m_emitted_weights.count(ggml_name)) {
return;
}
const std::string base = strip_weight_suffix(ggml_name);
-
- auto tensors = find_weight_tensors(m_weights, base);
- GgufTensorType qtype = GGUF_TYPE_F16;
- if (auto it = m_qtypes.find(base + ".qtype"); it != m_qtypes.end()) {
- qtype = it->second;
- }
-
- emit_weight_op(ggml_name, tensors, qtype);
+ emit_weight_op(ggml_name, weight_parts(base), weight_qtype(base));
}
void GraphEmitter::add_weight_from(const std::string& node_name, const std::string& src_base) {
if (m_emitted_weights.count(node_name)) {
return;
}
- auto tensors = find_weight_tensors(m_weights, src_base);
- GgufTensorType qtype = GGUF_TYPE_F16;
- if (auto it = m_qtypes.find(src_base + ".qtype"); it != m_qtypes.end()) {
- qtype = it->second;
- }
- emit_weight_op(node_name, tensors, qtype);
+ emit_weight_op(node_name, weight_parts(src_base), weight_qtype(src_base));
}
void GraphEmitter::add_named_weight(const std::string& ggml_name) {
diff --git a/src/frontends/gguf/src/builder/graph_emitter.hpp b/src/frontends/gguf/src/builder/graph_emitter.hpp
index 446ecded080..75680710f03 100644
--- a/src/frontends/gguf/src/builder/graph_emitter.hpp
+++ b/src/frontends/gguf/src/builder/graph_emitter.hpp
@@ -22,6 +22,10 @@
namespace ov::frontend::gguf {
+// Split "<something>.weight" into "<something>"; return the name unchanged when it does not end
+// in ".weight" (biases and other plain tensors keep their full name as the base).
+std::string strip_weight_suffix(const std::string& name);
+
// Builds OpenVINO values through the shared GGML converters.
class GraphEmitter {
public:
@@ -51,6 +55,11 @@ public:
// First extent of a weight's OV shape (its row count), 1 when the weight is absent/scalar.
int64_t weight_rows(const std::string& name) const;
+ // The "<base>.weight" / ".scales" / ".zp" tensors present for a weight, and its quant type
+ // ("<base>.qtype", F16 when absent).
+ WeightTensors weight_parts(const std::string& base) const;
+ GgufTensorType weight_qtype(const std::string& base) const;
+
std::unordered_map<std::string, ov::Tensor>& weights() {
return m_weights;
}
@@ -72,7 +81,8 @@ public:
const std::string& name,
const std::vector<std::string>& inputs,
int op_case = 0,
- std::map<std::string, ov::Any> attrs = {});
+ std::map<std::string, ov::Any> attrs = {},
+ std::vector<std::string> extra_outputs = {});
std::shared_ptr<ov::op::v0::Parameter> add_input(const std::string& name,
ov::element::Type type,
diff --git a/src/frontends/gguf/src/builder/projector_registry.cpp b/src/frontends/gguf/src/builder/projector_registry.cpp
new file mode 100644
index 00000000000..c10f1d174be
--- /dev/null
+++ b/src/frontends/gguf/src/builder/projector_registry.cpp
@@ -0,0 +1,69 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "projector_registry.hpp"
+
+#include "openvino/core/except.hpp"
+
+namespace ov::frontend::gguf {
+
+std::string resolve_projector_type(const GgufMetadata& metadata, const std::string& modality) {
+ auto type = metadata.get_str("clip.projector_type").value_or("");
+ if (type.empty())
+ type = metadata.get_str("clip." + modality + ".projector_type").value_or("");
+ if (type == "qwen2.5o")
+ type = modality == "vision" ? "qwen2.5vl_merger" : "qwen2a";
+ return type;
+}
+
+ProjectorRegistry::ProjectorRegistry(std::vector<ProjectorDefinition> definitions) {
+ for (auto& definition : definitions)
+ add(std::move(definition));
+}
+
+void ProjectorRegistry::add(ProjectorDefinition definition, RegistrationMode mode) {
+ OPENVINO_ASSERT(!definition.id.empty() && !definition.architecture.empty() &&
+ (definition.modality == "vision" || definition.modality == "audio") &&
+ !definition.projector_type.empty() && definition.build,
+ "[GGUF] invalid projector definition");
+ const auto existing = m_definitions.find(definition.id);
+ OPENVINO_ASSERT(mode == RegistrationMode::Add ? existing == m_definitions.end() : existing != m_definitions.end(),
+ "[GGUF] cannot ",
+ mode == RegistrationMode::Add ? "add duplicate" : "replace unknown",
+ " projector handler '",
+ definition.id,
+ "'");
+ const auto id = definition.id;
+ m_definitions[id] = std::make_shared<const ProjectorDefinition>(std::move(definition));
+}
+
+std::shared_ptr<const ProjectorDefinition> ProjectorRegistry::find(const GgufMetadata& metadata,
+ const std::string& modality,
+ const std::string& projector_type) const {
+ std::shared_ptr<const ProjectorDefinition> found;
+ const auto architecture = metadata.architecture();
+ for (const auto& entry : m_definitions) {
+ const auto& definition = entry.second;
+ if (definition->architecture != architecture || definition->modality != modality ||
+ definition->projector_type != projector_type || (definition->match && !definition->match(metadata)))
+ continue;
+ OPENVINO_ASSERT(!found,
+ "[GGUF] multiple projector handlers claim ",
+ modality,
+ " projector '",
+ projector_type,
+ "'");
+ found = definition;
+ }
+ return found;
+}
+
+std::vector<ProjectorDefinition> ProjectorRegistry::supported_projectors() const {
+ std::vector<ProjectorDefinition> definitions;
+ for (const auto& entry : m_definitions)
+ definitions.push_back(*entry.second);
+ return definitions;
+}
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/projector_registry.hpp b/src/frontends/gguf/src/builder/projector_registry.hpp
new file mode 100644
index 00000000000..45b63509b25
--- /dev/null
+++ b/src/frontends/gguf/src/builder/projector_registry.hpp
@@ -0,0 +1,27 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/frontend/gguf/extension/projector.hpp"
+
+namespace ov::frontend::gguf {
+
+std::vector<ProjectorDefinition> builtin_projectors();
+std::string resolve_projector_type(const GgufMetadata& metadata, const std::string& modality);
+
+class ProjectorRegistry {
+public:
+ explicit ProjectorRegistry(std::vector<ProjectorDefinition> definitions = builtin_projectors());
+ void add(ProjectorDefinition definition, RegistrationMode mode = RegistrationMode::Add);
+ std::shared_ptr<const ProjectorDefinition> find(const GgufMetadata& metadata,
+ const std::string& modality,
+ const std::string& projector_type) const;
+ std::vector<ProjectorDefinition> supported_projectors() const;
+
+private:
+ std::map<std::string, std::shared_ptr<const ProjectorDefinition>> m_definitions;
+};
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/extension/architecture.cpp b/src/frontends/gguf/src/extension/architecture.cpp
index 679acd5a2d5..cfd046c950f 100644
--- a/src/frontends/gguf/src/extension/architecture.cpp
+++ b/src/frontends/gguf/src/extension/architecture.cpp
@@ -14,13 +14,9 @@ bool ArchitectureDefinition::matches(const GgufMetadata& metadata) const {
return metadata.architecture() == architecture && (!match || match(metadata));
}
-ArchitectureDefinition make_decoder_architecture(std::string architecture,
- RopeMode rope,
- DecoderOptionsFn options,
- Maturity maturity) {
+ArchitectureDefinition make_decoder_architecture(std::string architecture, RopeMode rope, DecoderOptionsFn options) {
ArchitectureDefinition definition;
definition.id = definition.architecture = std::move(architecture);
- definition.maturity = maturity;
definition.factory = [rope, options = std::move(options)](const BuildContext& ctx) {
OPENVINO_ASSERT(ctx.weights, "[GGUF] decoder builder requires a weight table");
const auto overrides = options ? options(ctx.metadata) : DecoderOptions{};
@@ -39,8 +35,10 @@ ArchitectureExtension::ArchitectureExtension(ArchitectureDefinition definition,
: m_definition(std::move(definition)),
m_mode(mode) {}
-ArchitectureExtension::ArchitectureExtension(std::string architecture, RopeMode rope, Maturity maturity)
- : ArchitectureExtension(make_decoder_architecture(std::move(architecture), rope, {}, maturity)) {}
+ArchitectureExtension::ArchitectureExtension(std::string architecture, RopeMode rope)
+ : ArchitectureExtension(make_decoder_architecture(std::move(architecture), rope)) {}
+
+ArchitectureExtension::ArchitectureExtension(RegistrationMode mode) : m_mode(mode) {}
ArchitectureExtension::~ArchitectureExtension() = default;
diff --git a/src/frontends/gguf/src/extension/projector.cpp b/src/frontends/gguf/src/extension/projector.cpp
new file mode 100644
index 00000000000..e00837c21a5
--- /dev/null
+++ b/src/frontends/gguf/src/extension/projector.cpp
@@ -0,0 +1,15 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/frontend/gguf/extension/projector.hpp"
+
+namespace ov::frontend::gguf {
+
+ProjectorExtension::ProjectorExtension(ProjectorDefinition definition, RegistrationMode mode)
+ : ArchitectureExtension(mode),
+ m_projector(std::move(definition)) {}
+
+ProjectorExtension::~ProjectorExtension() = default;
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/frontend.cpp b/src/frontends/gguf/src/frontend.cpp
index 9b3059be023..ff6f99aa134 100644
--- a/src/frontends/gguf/src/frontend.cpp
+++ b/src/frontends/gguf/src/frontend.cpp
@@ -19,6 +19,8 @@
#include "openvino/frontend/extension/telemetry.hpp"
#include "openvino/frontend/gguf/decoder.hpp"
#include "openvino/frontend/gguf/extension/architecture.hpp"
+#include "openvino/frontend/gguf/extension/genai.hpp"
+#include "openvino/frontend/gguf/make_stateful.hpp"
#include "openvino/frontend/manager.hpp"
#include "translate_session.hpp"
@@ -44,6 +46,7 @@ struct FrontEnd::Impl {
// Transformation extensions run in the normalization stage. A caller uses these to swap the
// default (stateless) SetRows lowering for an alternative (e.g. a backend stateful lowering).
std::vector<DecoderTransformationExtension::Ptr> transformation_extensions;
+ std::shared_ptr<GenAIExtension> genai_extension;
TelemetryExtension::Ptr telemetry;
// Per-instance catalog: runtime registrations do not affect other frontends.
ArchRegistry arch_registry;
@@ -89,9 +92,20 @@ std::shared_ptr<Model> FrontEnd::convert(const InputModel::Ptr& model) const {
auto graph = gguf_model->m_builder(ops);
conversion_input = std::make_shared<gguf::InputModel>(std::make_shared<GgufBuilderDecoder>(graph));
}
- TranslateSession translate_session(conversion_input, ops, m_impl->transformation_extensions);
+ auto transformations = m_impl->transformation_extensions;
+ if (m_impl->genai_extension) {
+ transformations.push_back(std::make_shared<DecoderTransformationExtension>(pass::GGUFMakeStateful()));
+ }
+ TranslateSession translate_session(conversion_input, ops, transformations);
converted_model = translate_session.get_converted_model();
}
+ if (m_impl->genai_extension) {
+ pass::AdaptToGenAI adapter(m_impl->genai_extension->m_mode);
+ FRONT_END_GENERAL_CHECK(adapter.run_on_model(converted_model),
+ "GenAIExtension requires a GGUF decoder with adaptable inputs");
+ m_impl->genai_extension->m_embedding_model = adapter.get_embedding_model();
+ m_impl->genai_extension->m_per_layer_embedding_model = adapter.get_per_layer_embedding_model();
+ }
return converted_model;
}
@@ -111,6 +125,9 @@ void FrontEnd::add_extension(const std::shared_ptr<ov::Extension>& extension) {
} else if (const auto& so_ext = std::dynamic_pointer_cast<ov::detail::SOExtension>(extension)) {
add_extension(so_ext->extension());
m_extensions.push_back(so_ext);
+ } else if (const auto& genai = std::dynamic_pointer_cast<GenAIExtension>(extension)) {
+ FRONT_END_GENERAL_CHECK(!m_impl->genai_extension, "GenAIExtension is already registered");
+ m_impl->genai_extension = genai;
} else if (const auto& transformation = std::dynamic_pointer_cast<DecoderTransformationExtension>(extension)) {
m_impl->transformation_extensions.push_back(transformation);
} else if (const auto& arch_ext = std::dynamic_pointer_cast<ArchitectureExtension>(extension)) {
diff --git a/src/frontends/gguf/src/op/add_id.cpp b/src/frontends/gguf/src/op/add_id.cpp
index 309cf53e910..23864934180 100644
--- a/src/frontends/gguf/src/op/add_id.cpp
+++ b/src/frontends/gguf/src/op/add_id.cpp
@@ -32,7 +32,7 @@ ov::Output<ov::Node> reshape_add_id_input_to_2d(const ov::Output<ov::Node>& inpu
return input;
}
auto shape = std::make_shared<ov::op::v3::ShapeOf>(input, ov::element::i64);
- return std::make_shared<ov::op::v1::Reshape>(input, get_dimensions(shape, dims), false);
+ return std::make_shared<ov::op::v1::Reshape>(input, gather_dims(shape, dims), false);
}
} // namespace
diff --git a/src/frontends/gguf/src/op/clamp.cpp b/src/frontends/gguf/src/op/clamp.cpp
index a6a1955570e..d103e192c03 100644
--- a/src/frontends/gguf/src/op/clamp.cpp
+++ b/src/frontends/gguf/src/op/clamp.cpp
@@ -8,6 +8,8 @@
#include "node_context.hpp"
#include "op_table.hpp"
+#include "openvino/op/maximum.hpp"
+#include "openvino/op/minimum.hpp"
#include "utils.hpp"
namespace ov::frontend::gguf::op {
@@ -15,7 +17,13 @@ namespace ov::frontend::gguf::op {
// GGML_OP_CLAMP: elementwise clamp to [min, max]. The decoder exposes the bounds as typed
// float attributes ("clamp_min"/"clamp_max"), so the translator never reads ggml op_params.
OutputVector translate_clamp(const NodeContext& context) {
- num_inputs_check(context, 1, 1);
+ num_inputs_check(context, 1, 3);
+ if (context.get_input_size() == 3) {
+ auto bounded = std::make_shared<ov::op::v1::Maximum>(context.get_input(0), context.get_input(1));
+ return rename_outputs_with_suffix({std::make_shared<ov::op::v1::Minimum>(bounded, context.get_input(2))},
+ context.get_name());
+ }
+ FRONT_END_OP_CONVERSION_CHECK(context.get_input_size() == 1, "CLAMP requires both bounds");
auto input = context.get_input(0);
float min = context.get_attribute<float>("clamp_min");
diff --git a/src/frontends/gguf/src/op/div.cpp b/src/frontends/gguf/src/op/div.cpp
index bc843d3a8a1..5f9cf854e8b 100644
--- a/src/frontends/gguf/src/op/div.cpp
+++ b/src/frontends/gguf/src/op/div.cpp
@@ -17,7 +17,7 @@
#include "openvino/op/sigmoid.hpp"
#include "openvino/op/swish.hpp"
#include "openvino/op/tile.hpp"
-#include "openvino/op/util/precision_sensitive_attribute.hpp"
+#include "transformations/rt_info/disable_precision_conversion.hpp"
#include "utils.hpp"
namespace ov::frontend::gguf::op {
@@ -137,13 +137,11 @@ OutputVector translate_div(const NodeContext& context) {
ov::Output<ov::Node> res = std::make_shared<ov::op::v1::Divide>(input_0, input_1);
// Keep the divide in FP32: the GPU plugin would otherwise compress it back to FP16 and overflow
- // on small gate values (e.g. silu(x) / x in qwen2moe).
- ov::mark_as_precision_sensitive(res.get_node_shared_ptr()->input(0));
- ov::mark_as_precision_sensitive(res.get_node_shared_ptr()->input(1));
+ // on small gate values (e.g. silu(x) / x in qwen2moe). Precision-sensitive inputs would instead
+ // mark the whole producing subgraph as a shape computation and keep it in FP32.
+ ov::disable_conversion(res.get_node_shared_ptr(), ov::element::f16);
if (res.get_element_type() != output_type) {
- auto output_convert = std::make_shared<ov::op::v0::Convert>(res, output_type);
- ov::mark_as_precision_sensitive(output_convert->input(0));
- res = output_convert;
+ res = std::make_shared<ov::op::v0::Convert>(res, output_type);
}
return rename_outputs_with_suffix({std::move(res)}, context.get_name());
}
diff --git a/src/frontends/gguf/src/op/flash_attn_ext.cpp b/src/frontends/gguf/src/op/flash_attn_ext.cpp
index 2d34b395ba6..8728570f35b 100644
--- a/src/frontends/gguf/src/op/flash_attn_ext.cpp
+++ b/src/frontends/gguf/src/op/flash_attn_ext.cpp
@@ -70,6 +70,33 @@ ov::Output<ov::Node> reshape_flat_kv(const NodeContext& context,
ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3}));
}
+// Expand K/V from n_head_kv to n_head (GQA): insert a repeat axis after the head axis, broadcast it
+// to `factor`, then fold it back in. `ggml_natural` selects [B, L, H, S] (head axis 2) over the
+// canonical SDPA [B, H, L, S] (head axis 1).
+ov::Output<Node> tile_kv(int64_t num_heads,
+ int64_t num_heads_kv,
+ int64_t head_size,
+ ov::Output<Node> kv,
+ bool ggml_natural) {
+ const size_t head_axis = ggml_natural ? 2 : 1;
+ const int64_t factor = num_heads / num_heads_kv;
+ if (factor <= 1 || num_heads_kv <= 1) {
+ return kv;
+ }
+ auto unsqueeze_axes = ov::op::v0::Constant::create(ov::element::i64, Shape{}, {(int64_t)head_axis + 1});
+ auto kv_unsqueezed = std::make_shared<ov::op::v0::Unsqueeze>(kv, unsqueeze_axes);
+ std::vector<int64_t> bcast(5, 1);
+ bcast[head_axis + 1] = factor;
+ auto kv_broadcast_shape = ov::op::v0::Constant::create(ov::element::i64, {5}, bcast);
+ // special_zero keeps the leading dims (incl. the dynamic token axis) as-is.
+ std::vector<int64_t> new_shape = ggml_natural ? std::vector<int64_t>{0, 0, num_heads, head_size}
+ : std::vector<int64_t>{0, num_heads, -1, head_size};
+ auto new_kv_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, new_shape);
+ kv = std::make_shared<ov::op::v3::Broadcast>(kv_unsqueezed,
+ kv_broadcast_shape,
+ ov::op::BroadcastType::BIDIRECTIONAL);
+ return std::make_shared<ov::op::v1::Reshape>(kv, new_kv_shape, true);
+}
} // namespace
OutputVector translate_flash_attn_ext(const NodeContext& context) {
@@ -105,7 +132,8 @@ OutputVector translate_flash_attn_ext(const NodeContext& context) {
FRONT_END_OP_CONVERSION_CHECK(has_mask || kq_soft_cap == 0.0f,
"Maskless FLASH_ATTN_EXT does not support a non-zero soft cap");
- const auto sdpa_type = ov::element::f16;
+ // 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);
auto scale_node = std::make_shared<ov::op::v0::Constant>(sdpa_type, ov::Shape{}, std::vector<float>{scale});
@@ -123,7 +151,7 @@ OutputVector translate_flash_attn_ext(const NodeContext& context) {
auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});
auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
auto two = ov::op::v0::Constant::create(ov::element::i64, {1}, {2});
- auto token_len = get_dimensions(q, {2});
+ auto token_len = get_dimensions(q, {op_case == 100 ? 1 : 2});
mask_sliced = std::make_shared<ov::op::v8::Slice>(mask, zero, token_len, one, two);
}
@@ -144,35 +172,14 @@ OutputVector translate_flash_attn_ext(const NodeContext& context) {
const bool ggml_natural = op_case == 100;
const size_t head_axis = ggml_natural ? 2 : 1;
- auto tile_kv = [&](int64_t num_heads, int64_t num_heads_kv, int64_t head_size, ov::Output<Node> kv) {
- int64_t factor = num_heads / num_heads_kv;
- if (factor > 1 && num_heads_kv > 1) {
- // Insert the repeat axis right after the head axis, broadcast it to `factor`, then fold
- // it back into the head axis: [.., n_head_kv, ..] -> [.., n_head_kv * factor, ..].
- auto unsqueeze_axes = ov::op::v0::Constant::create(ov::element::i64, Shape{}, {(int64_t)head_axis + 1});
- auto kv_unsqueezed = std::make_shared<ov::op::v0::Unsqueeze>(kv, unsqueeze_axes);
- std::vector<int64_t> bcast(5, 1);
- bcast[head_axis + 1] = factor;
- auto kv_broadcast_shape = ov::op::v0::Constant::create(ov::element::i64, {5}, bcast);
- // special_zero keeps the leading dims (incl. the dynamic token axis) as-is.
- std::vector<int64_t> new_shape = ggml_natural ? std::vector<int64_t>{0, 0, num_heads, head_size}
- : std::vector<int64_t>{0, num_heads, -1, head_size};
- auto new_kv_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, new_shape);
- kv = std::make_shared<ov::op::v3::Broadcast>(kv_unsqueezed,
- kv_broadcast_shape,
- ov::op::BroadcastType::BIDIRECTIONAL);
- kv = std::make_shared<ov::op::v1::Reshape>(kv, new_kv_shape, true);
- }
- return kv;
- };
-
auto q_shape = context.get_input_shape(0);
+ const auto heads = q_shape[head_axis].get_length();
const auto k_heads = flat_kv ? context.get_attribute<std::vector<int64_t>>("flat_kv_shape_k")[1]
: context.get_input_shape(1)[head_axis].get_length();
const auto v_heads = flat_kv ? context.get_attribute<std::vector<int64_t>>("flat_kv_shape_v")[1]
: context.get_input_shape(2)[head_axis].get_length();
- k = tile_kv(q_shape[head_axis].get_length(), k_heads, q_shape[3].get_length(), k);
- v = tile_kv(q_shape[head_axis].get_length(), v_heads, q_shape[3].get_length(), v);
+ k = tile_kv(heads, k_heads, q_shape[3].get_length(), k, ggml_natural);
+ v = tile_kv(heads, v_heads, q_shape[3].get_length(), v, ggml_natural);
// SDPA requires q/k/v to share an element type; match k/v to q (ConvertConvertLike lowers these).
k = std::make_shared<ov::op::v1::ConvertLike>(k, q);
@@ -244,13 +251,12 @@ OutputVector translate_flash_attn_ext(const NodeContext& context) {
// over [B, n_head, q, 1] (rank must equal the query rank, last dim 1).
using namespace ov::op;
auto sink = context.get_input(4);
- auto sink_f16 = sink.get_element_type() != element::f16
- ? std::make_shared<v0::Convert>(sink, element::f16)->output(0)
- : sink;
+ auto sink_typed =
+ sink.get_element_type() != sdpa_type ? std::make_shared<v0::Convert>(sink, sdpa_type)->output(0) : sink;
auto sink_shape = v0::Constant::create(element::i64,
{4},
std::vector<int64_t>{1, (int64_t)q_shape[head_axis].get_length(), 1, 1});
- auto sink_r = std::make_shared<v1::Reshape>(sink_f16, sink_shape, false);
+ auto sink_r = std::make_shared<v1::Reshape>(sink_typed, sink_shape, false);
sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(q_t,
k_t,
v_t,
@@ -262,8 +268,8 @@ OutputVector translate_flash_attn_ext(const NodeContext& context) {
// [B, H, L, S] -> [B, L, H, S] (ggml-natural layout expected by caller).
res = std::make_shared<ov::op::v1::Transpose>(sdpa,
ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3}));
- // SDPA paths produce f16; the soft-cap path produces f32 directly.
- if (kq_soft_cap == 0.0f) {
+ // SDPA paths produce sdpa_type; the soft-cap path produces f32 directly.
+ if (kq_soft_cap == 0.0f && sdpa_type != ov::element::f32) {
res = std::make_shared<ov::op::v0::Convert>(res, ov::element::f32);
}
return rename_outputs_with_suffix({std::move(res)}, context.get_name());
diff --git a/src/frontends/gguf/src/op/gated_delta_net.cpp b/src/frontends/gguf/src/op/gated_delta_net.cpp
index ab77c2575ae..1d93b5519e8 100644
--- a/src/frontends/gguf/src/op/gated_delta_net.cpp
+++ b/src/frontends/gguf/src/op/gated_delta_net.cpp
@@ -38,7 +38,7 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext& context);
// GGML_OP_GATED_DELTA_NET (qwen3next linear-attention block). Emits the internal (non-opset) op
// ov::op::internal::GatedDeltaNet for the device's fused kernel; a model using it is not
-// IR-serializable (see docs/internal_ops.md). The fused op only supports scalar gating, so the
+// IR-serializable (see docs/runtime.md). The fused op only supports scalar gating, so the
// per-key-dimension gating case (kda) uses the serializable Loop reference path below.
OutputVector translate_gated_delta_net(const NodeContext& context) {
num_inputs_check(context, 6, 6);
@@ -60,9 +60,14 @@ OutputVector translate_gated_delta_net(const NodeContext& context) {
"GATED_DELTA_NET supports a single recurrent-state snapshot, got K = ",
snapshot_slots);
+ // Builder graphs take attention and the state as separate outputs, the state in the op's
+ // [B, H_v, key_dim, value_dim] layout; ggml graphs pack both in ggml's state layout.
+ const bool split_outputs = context.get_attribute<bool>("split_outputs", false);
+
// kda needs the Loop path; "force_ref" lets tests exercise the Loop path's multi-head packing
// against the ggml-CPU oracle for the scalar-gate case too.
if (kda || context.get_attribute<bool>("force_ref", false)) {
+ FRONT_END_OP_CONVERSION_CHECK(!split_outputs, "GATED_DELTA_NET split outputs require the fused path");
return translate_gated_delta_net_ref(context);
}
@@ -73,9 +78,18 @@ OutputVector translate_gated_delta_net(const NodeContext& context) {
auto beta = context.get_input(4);
auto state = context.get_input(5);
+ // ggml normalizes with x / max(||x||, eps); the op's fused normalization adds eps under the
+ // square root instead, which differs for small vectors, so normalize here.
+ if (context.get_attribute<bool>("fuse_qk_l2norm", false)) {
+ const float eps = context.get_attribute<float>("qk_l2_norm_eps", 1e-6f);
+ q = make_l2_norm(q, eps);
+ k = make_l2_norm(k, eps);
+ }
+
// ggml maps GQA heads in tiled order, while the OV op maps repeated heads in grouped order:
- // tile Q/K along the head axis so their head count matches V.
- if (H_v != H_k) {
+ // tile Q/K along the head axis so their head count matches V. A builder that already stored
+ // the V heads in grouped order sets "gqa_grouped" and needs no Tile.
+ if (H_v != H_k && !context.get_attribute<bool>("gqa_grouped", false)) {
const int64_t repeat = H_v / H_k;
auto repeats = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 1, repeat, 1});
q = std::make_shared<ov::op::v0::Tile>(q, repeats);
@@ -85,7 +99,8 @@ OutputVector translate_gated_delta_net(const NodeContext& context) {
// ggml state layout (OV notation) is [B, H_v, value_dim, key_dim]; the op expects
// [B, H_v, key_dim, value_dim].
auto state_perm = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{0, 1, 3, 2});
- state = std::make_shared<ov::op::v1::Transpose>(state, state_perm);
+ if (!split_outputs)
+ state = std::make_shared<ov::op::v1::Transpose>(state, state_perm);
// Gate/beta carry a trailing singleton in the scalar-gate case; the op takes them rank-3.
auto sq_axis_3 = ov::op::v0::Constant::create(ov::element::i64, {1}, {3});
@@ -110,9 +125,13 @@ OutputVector translate_gated_delta_net(const NodeContext& context) {
beta = std::make_shared<ov::op::v1::Multiply>(beta, mask);
}
- auto gdn = std::make_shared<ov::op::internal::GatedDeltaNet>(q, k, v, state, g, beta);
+ auto gdn = std::make_shared<ov::op::internal::GatedDeltaNet>(q, k, v, state, g, beta, false);
auto attn_4d = gdn->output(0);
auto state_4d = gdn->output(1); // [B, H_v, key_dim, value_dim]
+ if (split_outputs) {
+ rename_outputs_with_suffix({attn_4d}, context.get_name());
+ return {attn_4d, state_4d};
+ }
// Transpose state back to ggml's [B, H_v, value_dim, key_dim] and pack [attn | state] flat,
// matching the reference path.
@@ -152,6 +171,14 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext& context) {
const int64_t rq1 = H_v / H_k; // GQA head repeat factor
const float scale = 1.0f / std::sqrt((float)S_v);
+ const bool gqa_grouped = context.get_attribute<bool>("gqa_grouped", false);
+
+ // ggml's l2_norm (x / max(||x||, eps)) when the builder asked the fused op to normalize q/k.
+ if (context.get_attribute<bool>("fuse_qk_l2norm", false)) {
+ const float eps = context.get_attribute<float>("qk_l2_norm_eps", 1e-6f);
+ q = make_l2_norm(q, eps);
+ k = make_l2_norm(k, eps);
+ }
if (context.has_input("chunk_valid_len")) {
FRONT_END_OP_CONVERSION_CHECK(v_shape[1].is_static(),
@@ -193,7 +220,10 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext& context) {
std::make_shared<ov::op::v3::Broadcast>(q_unsq, bcast_shape, ov::op::BroadcastType::BIDIRECTIONAL);
auto k_bcast =
std::make_shared<ov::op::v3::Broadcast>(k_unsq, bcast_shape, ov::op::BroadcastType::BIDIRECTIONAL);
- auto perm_5d = ov::op::v0::Constant::create(ov::element::i64, {5}, std::vector<int64_t>{0, 2, 1, 3, 4});
+ auto perm_5d = ov::op::v0::Constant::create(
+ ov::element::i64,
+ {5},
+ gqa_grouped ? std::vector<int64_t>{0, 1, 2, 3, 4} : std::vector<int64_t>{0, 2, 1, 3, 4});
auto q_transposed = std::make_shared<ov::op::v1::Transpose>(q_bcast, perm_5d);
auto k_transposed = std::make_shared<ov::op::v1::Transpose>(k_bcast, perm_5d);
// [B, H_v, T, S_v] with T dynamic (-1).
diff --git a/src/frontends/gguf/src/op/get_rows.cpp b/src/frontends/gguf/src/op/get_rows.cpp
index fffffb6630d..6c9a2a03627 100644
--- a/src/frontends/gguf/src/op/get_rows.cpp
+++ b/src/frontends/gguf/src/op/get_rows.cpp
@@ -6,6 +6,8 @@
#include "op_table.hpp"
#include "openvino/core/node.hpp"
#include "openvino/core/node_output.hpp"
+#include "openvino/op/broadcast.hpp"
+#include "openvino/op/concat.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/convert.hpp"
#include "openvino/op/gather.hpp"
@@ -34,6 +36,16 @@ OutputVector translate_get_rows(const NodeContext& context) {
return rows;
};
+ if (context.get_attribute<bool>("gather_elements", false)) {
+ // Select a column independently in each row; singleton index batches broadcast.
+ auto shape = std::make_shared<ov::op::v0::Concat>(
+ ov::OutputVector{get_dimensions(data, {0, 1, 2}), get_dimensions(indices, {3})},
+ 0);
+ indices = std::make_shared<ov::op::v3::Broadcast>(indices, shape);
+ return rename_outputs_with_suffix(
+ {convert_rows(std::make_shared<ov::op::v6::GatherElements>(data, indices, 3))},
+ context.get_name());
+ }
if (op_case == 3) {
return {convert_rows(data)};
}
@@ -58,7 +70,17 @@ OutputVector translate_get_rows(const NodeContext& context) {
const auto ids_shape = indices.get_partial_shape();
const int64_t K = ids_shape[ids_shape.size() - 1].get_length();
auto idx = std::make_shared<ov::op::v0::Convert>(indices, ov::element::i32);
- auto ge = std::make_shared<ov::op::v6::GatherElements>(data, idx, -1); // [1,1,T,K]
+ // A single shared row (per-expert scales [1,1,1,E]) is gathered directly instead of per token.
+ ov::Output<Node> ge;
+ if (context.get_attribute<bool>("shared_row", false)) {
+ auto row = std::make_shared<ov::op::v1::Reshape>(data,
+ ov::op::v0::Constant::create(ov::element::i64, {1}, {-1}),
+ false);
+ ge =
+ std::make_shared<ov::op::v8::Gather>(row, idx, ov::op::v0::Constant::create(ov::element::i32, {}, {0}));
+ } else {
+ ge = std::make_shared<ov::op::v6::GatherElements>(data, idx, -1); // [1,1,T,K]
+ }
auto col = std::make_shared<ov::op::v1::Reshape>(
ge,
ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, -1, K, 1}),
diff --git a/src/frontends/gguf/src/op/im2col.cpp b/src/frontends/gguf/src/op/im2col.cpp
index d3a522c7491..c268c7ddebc 100644
--- a/src/frontends/gguf/src/op/im2col.cpp
+++ b/src/frontends/gguf/src/op/im2col.cpp
@@ -11,21 +11,63 @@
#include "op_table.hpp"
#include "openvino/core/shape.hpp"
#include "openvino/core/strides.hpp"
+#include "openvino/op/concat.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/convert.hpp"
+#include "openvino/op/divide.hpp"
#include "openvino/op/extractimagepatches.hpp"
+#include "openvino/op/multiply.hpp"
#include "openvino/op/pad.hpp"
#include "openvino/op/reshape.hpp"
+#include "openvino/op/shape_of.hpp"
+#include "openvino/op/slice.hpp"
#include "openvino/op/transpose.hpp"
#include "openvino/op/util/attr_types.hpp"
#include "utils.hpp"
namespace ov::frontend::gguf::op {
+namespace {
+
+// Non-overlapping patches (a ViT patch embedding) are a pure reshape: crop to whole patches like
+// ExtractImagePatches VALID, split H and W into (patches, patch), and move each patch's (C, KH, KW)
+// to the last axis. ExtractImagePatches has no dynamic-shape GPU implementation.
+ov::Output<Node> non_overlapping_patches(const ov::Output<Node>& image, size_t IC, size_t KH, size_t KW) {
+ using ov::op::v0::Constant;
+ const auto shape = std::make_shared<ov::op::v3::ShapeOf>(image, ov::element::i64);
+ const auto kernel = Constant::create(ov::element::i64,
+ {2},
+ std::vector<int64_t>{static_cast<int64_t>(KH), static_cast<int64_t>(KW)});
+ const auto patches = std::make_shared<ov::op::v1::Divide>(gather_dims(shape, {2, 3}), kernel);
+ const auto cropped = std::make_shared<ov::op::v8::Slice>(image,
+ Constant::create(ov::element::i64, {2}, {0, 0}),
+ std::make_shared<ov::op::v1::Multiply>(patches, kernel),
+ Constant::create(ov::element::i64, {2}, {1, 1}),
+ Constant::create(ov::element::i64, {2}, {2, 3}));
+ const auto split_shape = std::make_shared<ov::op::v0::Concat>(
+ ov::OutputVector{gather_dims(shape, {0, 1}),
+ gather_dims(patches, {0}),
+ Constant::create(ov::element::i64, {1}, {static_cast<int64_t>(KH)}),
+ gather_dims(patches, {1}),
+ Constant::create(ov::element::i64, {1}, {static_cast<int64_t>(KW)})},
+ 0);
+ const auto split = std::make_shared<ov::op::v1::Reshape>(cropped, split_shape, false);
+ const auto grouped =
+ std::make_shared<ov::op::v1::Transpose>(split, Constant::create(ov::element::i64, {6}, {0, 2, 4, 1, 3, 5}));
+ return std::make_shared<ov::op::v1::Reshape>(
+ grouped,
+ Constant::create(ov::element::i64, {4}, std::vector<int64_t>{0, 0, 0, static_cast<int64_t>(IC * KH * KW)}),
+ true);
+}
+
+} // namespace
+
// GGML_OP_IM2COL: unfold a 1D/2D convolution input into column patches (conv / vision models).
// The decoder exposes the conv params (strides/pads/dilations + is_2D) as a typed int vector.
OutputVector translate_im2col(const NodeContext& context) {
- num_inputs_check(context, 2, 2);
+ // Builder graphs pass the kernel shape as an attribute instead of a placeholder kernel tensor.
+ num_inputs_check(context, 1, 2);
+ const bool kernel_input = context.get_input_size() == 2;
auto params = context.get_attribute<std::vector<int32_t>>("im2col_params");
FRONT_END_OP_CONVERSION_CHECK(params.size() >= 7, "IM2COL requires 7 params");
@@ -38,8 +80,9 @@ OutputVector translate_im2col(const NodeContext& context) {
bool is_2D = params[6] == 1;
ov::Output<Node> res;
- ov::Output<Node> image = context.get_input(1);
- const ov::Shape kernel_shape = context.get_input(0).get_shape();
+ ov::Output<Node> image = context.get_input(kernel_input ? 1 : 0);
+ const ov::Shape kernel_shape =
+ kernel_input ? context.get_input(0).get_shape() : context.get_attribute<ov::Shape>("kernel_shape");
const size_t IC = is_2D ? kernel_shape[1] : kernel_shape[2];
const size_t KH = is_2D ? kernel_shape[2] : 1;
@@ -53,69 +96,65 @@ OutputVector translate_im2col(const NodeContext& context) {
int32_t dil_h = is_2D ? d1 : 1;
if (!is_2D) {
- const ov::Shape image_shape = image.get_shape();
- const size_t N = image_shape[1];
- const size_t IW = image_shape[3];
- auto image_reshape_shape = ov::op::v0::Constant::create(
- ov::element::i64,
- ov::Shape{4},
- std::vector<int64_t>{static_cast<int64_t>(N), static_cast<int64_t>(IC), 1, static_cast<int64_t>(IW)});
+ const auto image_shape = std::make_shared<ov::op::v3::ShapeOf>(image, ov::element::i64);
+ auto image_reshape_shape = std::make_shared<ov::op::v0::Concat>(
+ ov::OutputVector{
+ gather_dims(image_shape, {1}),
+ ov::op::v0::Constant::create(ov::element::i64, {2}, std::vector<int64_t>{static_cast<int64_t>(IC), 1}),
+ gather_dims(image_shape, {3})},
+ 0);
image = std::make_shared<ov::op::v1::Reshape>(image, image_reshape_shape, false);
}
- const ov::Shape patch_sizes = {KH, KW};
- const ov::Strides strides = {static_cast<size_t>(stride_h), static_cast<size_t>(stride_w)};
- const ov::Shape rates = {static_cast<size_t>(dil_h), static_cast<size_t>(dil_w)};
-
- auto pads_begin =
- ov::op::v0::Constant::create(ov::element::i64, ov::Shape{4}, std::vector<int64_t>{0, 0, pad_h, pad_w});
- auto pads_end =
- ov::op::v0::Constant::create(ov::element::i64, ov::Shape{4}, std::vector<int64_t>{0, 0, pad_h, pad_w});
-
- auto pad = std::make_shared<ov::op::v1::Pad>(image, pads_begin, pads_end, ov::op::PadMode::CONSTANT);
- auto patches =
- std::make_shared<ov::op::v3::ExtractImagePatches>(pad, patch_sizes, strides, rates, ov::op::PadType::VALID);
-
- auto perm1 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{4}, std::vector<int64_t>{0, 2, 3, 1});
- auto t1 = std::make_shared<ov::op::v1::Transpose>(patches, perm1);
-
- const ov::Shape out_shape = t1->get_output_shape(0);
- const size_t N = out_shape[0];
- const size_t OH = out_shape[1];
- const size_t OW = out_shape[2];
- auto reshape1_shape = ov::op::v0::Constant::create(ov::element::i64,
- ov::Shape{5},
- std::vector<int64_t>{static_cast<int64_t>(N),
- static_cast<int64_t>(OH),
- static_cast<int64_t>(OW),
- static_cast<int64_t>(KH * KW),
- static_cast<int64_t>(IC)});
- auto r1 = std::make_shared<ov::op::v1::Reshape>(t1, reshape1_shape, false);
-
- auto perm2 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{5}, std::vector<int64_t>{0, 1, 2, 4, 3});
- auto t2 = std::make_shared<ov::op::v1::Transpose>(r1, perm2);
-
- auto r2_shape = ov::op::v0::Constant::create(ov::element::i64,
- ov::Shape{4},
- std::vector<int64_t>{static_cast<int64_t>(N),
- static_cast<int64_t>(OH),
- static_cast<int64_t>(OW),
- static_cast<int64_t>(IC * KH * KW)});
- res = std::make_shared<ov::op::v1::Reshape>(t2, r2_shape, false);
-
- if (!is_2D) {
- auto final_reshape_shape = ov::op::v0::Constant::create(
- ov::element::i64,
- ov::Shape{4},
- std::vector<int64_t>{1, static_cast<int64_t>(N), static_cast<int64_t>(OW), static_cast<int64_t>(IC * KW)});
- res = std::make_shared<ov::op::v1::Reshape>(res, final_reshape_shape, false);
- }
-
// Older cgraph decoders expose ggml_im2col's dst_type as output_type.
const auto output_type = context.get_attribute<ov::element::Type>(
"dst_type",
context.get_attribute<ov::element::Type>("output_type", ov::element::dynamic));
FRONT_END_OP_CONVERSION_CHECK(output_type.is_static(), "IM2COL requires 'dst_type'");
+
+ if (is_2D && stride_h == static_cast<int32_t>(KH) && stride_w == static_cast<int32_t>(KW) && pad_h == 0 &&
+ pad_w == 0 && dil_h == 1 && dil_w == 1) {
+ res = non_overlapping_patches(image, IC, KH, KW);
+ } else {
+ const ov::Shape patch_sizes = {KH, KW};
+ const ov::Strides strides = {static_cast<size_t>(stride_h), static_cast<size_t>(stride_w)};
+ const ov::Shape rates = {static_cast<size_t>(dil_h), static_cast<size_t>(dil_w)};
+
+ auto pads_begin =
+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{4}, std::vector<int64_t>{0, 0, pad_h, pad_w});
+ auto pad = std::make_shared<ov::op::v1::Pad>(image, pads_begin, pads_begin, ov::op::PadMode::CONSTANT);
+ auto patches =
+ std::make_shared<ov::op::v3::ExtractImagePatches>(pad, patch_sizes, strides, rates, ov::op::PadType::VALID);
+
+ auto perm1 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{4}, std::vector<int64_t>{0, 2, 3, 1});
+ auto t1 = std::make_shared<ov::op::v1::Transpose>(patches, perm1);
+
+ auto reshape1_shape = ov::op::v0::Constant::create(
+ ov::element::i64,
+ {5},
+ std::vector<int64_t>{0, 0, 0, static_cast<int64_t>(KH * KW), static_cast<int64_t>(IC)});
+ auto r1 = std::make_shared<ov::op::v1::Reshape>(t1, reshape1_shape, true);
+
+ auto perm2 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{5}, std::vector<int64_t>{0, 1, 2, 4, 3});
+ auto t2 = std::make_shared<ov::op::v1::Transpose>(r1, perm2);
+
+ auto r2_shape = ov::op::v0::Constant::create(ov::element::i64,
+ {4},
+ std::vector<int64_t>{0, 0, 0, static_cast<int64_t>(IC * KH * KW)});
+ res = std::make_shared<ov::op::v1::Reshape>(t2, r2_shape, true);
+
+ if (!is_2D) {
+ auto final_reshape_shape = std::make_shared<ov::op::v0::Concat>(
+ ov::OutputVector{ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),
+ get_dimensions(t1, {0, 2}),
+ ov::op::v0::Constant::create(ov::element::i64,
+ {1},
+ std::vector<int64_t>{static_cast<int64_t>(IC * KW)})},
+ 0);
+ res = std::make_shared<ov::op::v1::Reshape>(res, final_reshape_shape, false);
+ }
+ }
+
if (res.get_element_type() != output_type) {
res = std::make_shared<ov::op::v0::Convert>(res, output_type);
}
diff --git a/src/frontends/gguf/src/op/l2_norm.cpp b/src/frontends/gguf/src/op/l2_norm.cpp
index 456faa2be3e..f0b0d73c707 100644
--- a/src/frontends/gguf/src/op/l2_norm.cpp
+++ b/src/frontends/gguf/src/op/l2_norm.cpp
@@ -6,12 +6,6 @@
#include "node_context.hpp"
#include "op_table.hpp"
-#include "openvino/op/constant.hpp"
-#include "openvino/op/divide.hpp"
-#include "openvino/op/maximum.hpp"
-#include "openvino/op/multiply.hpp"
-#include "openvino/op/reduce_sum.hpp"
-#include "openvino/op/sqrt.hpp"
#include "utils.hpp"
namespace ov::frontend::gguf::op {
@@ -20,20 +14,8 @@ namespace ov::frontend::gguf::op {
OutputVector translate_l2_norm(const NodeContext& context) {
num_inputs_check(context, 1, 1);
- auto input_node = context.get_input(0);
- float eps = context.get_attribute<float>("eps");
-
- auto squared = std::make_shared<ov::op::v1::Multiply>(input_node, input_node);
- auto sum_squared =
- std::make_shared<ov::op::v1::ReduceSum>(squared,
- ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {-1}),
- true);
- auto l2_norm = std::make_shared<ov::op::v0::Sqrt>(sum_squared);
- auto eps_const = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1}, {eps});
- auto clamped_norm = std::make_shared<ov::op::v1::Maximum>(l2_norm, eps_const);
- auto res = std::make_shared<ov::op::v1::Divide>(input_node, clamped_norm);
-
- return rename_outputs_with_suffix({std::move(res)}, context.get_name());
+ return rename_outputs_with_suffix({make_l2_norm(context.get_input(0), context.get_attribute<float>("eps"))},
+ context.get_name());
}
} // namespace ov::frontend::gguf::op
diff --git a/src/frontends/gguf/src/op/mul_mat_id.cpp b/src/frontends/gguf/src/op/mul_mat_id.cpp
index 1bb2d575443..a73e0192956 100644
--- a/src/frontends/gguf/src/op/mul_mat_id.cpp
+++ b/src/frontends/gguf/src/op/mul_mat_id.cpp
@@ -84,14 +84,13 @@ ov::Output<ov::Node> activations_per_expert(const ov::Output<ov::Node>& activati
if (!already_per_expert) {
rows = std::make_shared<ov::op::v1::Reshape>(
activations,
- std::make_shared<ov::op::v0::Concat>(ov::OutputVector{get_dimensions(ids_shape, {0}),
- const_i64({1}),
- get_dimensions(activations_shape, {2})},
- 0),
+ std::make_shared<ov::op::v0::Concat>(
+ ov::OutputVector{gather_dims(ids_shape, {0}), const_i64({1}), gather_dims(activations_shape, {2})},
+ 0),
false);
}
auto target = std::make_shared<ov::op::v0::Concat>(
- ov::OutputVector{get_dimensions(ids_shape, {0, 1}), get_dimensions(activations_shape, {2})},
+ ov::OutputVector{gather_dims(ids_shape, {0, 1}), gather_dims(activations_shape, {2})},
0);
return std::make_shared<ov::op::v3::Broadcast>(rows, target, ov::op::BroadcastType::BIDIRECTIONAL);
}
@@ -117,8 +116,8 @@ ov::Output<ov::Node> translate_mul_mat_id_mxfp4_packed(ov::Output<ov::Node> expe
auto activations_shape_4d = std::make_shared<ov::op::v3::ShapeOf>(activations, ov::element::i64);
auto ids_shape_4d = std::make_shared<ov::op::v3::ShapeOf>(ids, ov::element::i64);
- auto activations_shape_3d = get_dimensions(activations_shape_4d, {1, 2, 3});
- auto ids_shape_2d = get_dimensions(ids_shape_4d, {2, 3});
+ auto activations_shape_3d = gather_dims(activations_shape_4d, {1, 2, 3});
+ auto ids_shape_2d = gather_dims(ids_shape_4d, {2, 3});
activations = std::make_shared<ov::op::v1::Reshape>(activations, activations_shape_3d, false);
ids = std::make_shared<ov::op::v1::Reshape>(ids, ids_shape_2d, false);
@@ -166,9 +165,9 @@ ov::Output<ov::Node> translate_mul_mat_id_mxfp4_packed(ov::Output<ov::Node> expe
std::make_shared<ov::op::v1::Multiply>(weights_f32, scales_f32, ov::op::AutoBroadcastType::NUMPY);
auto ids_shape = std::make_shared<ov::op::v3::ShapeOf>(ids, ov::element::i64);
- auto selected_weights_target_dims = std::make_shared<ov::op::v0::Concat>(
- ov::OutputVector{get_dimensions(ids_shape, {0, 1}), const_i64({rows, cols})},
- 0);
+ auto selected_weights_target_dims =
+ std::make_shared<ov::op::v0::Concat>(ov::OutputVector{gather_dims(ids_shape, {0, 1}), const_i64({rows, cols})},
+ 0);
selected_weights = std::make_shared<ov::op::v1::Reshape>(selected_weights, selected_weights_target_dims, false);
auto activations_shape = std::make_shared<ov::op::v3::ShapeOf>(activations, ov::element::i64);
@@ -181,8 +180,7 @@ ov::Output<ov::Node> translate_mul_mat_id_mxfp4_packed(ov::Output<ov::Node> expe
auto batch_dim = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
auto row_dim = ov::op::v0::Constant::create(ov::element::i64, {1}, {rows});
auto result_target_dims =
- std::make_shared<ov::op::v0::Concat>(ov::OutputVector{batch_dim, get_dimensions(ids_shape, {0, 1}), row_dim},
- 0);
+ std::make_shared<ov::op::v0::Concat>(ov::OutputVector{batch_dim, gather_dims(ids_shape, {0, 1}), row_dim}, 0);
result = std::make_shared<ov::op::v1::Reshape>(result, result_target_dims, false);
return result;
@@ -214,7 +212,7 @@ ov::Output<ov::Node> translate_mul_mat_id_gathermatmul(ov::Output<ov::Node> expe
ov::Output<ov::Node> as = expert_weights;
if (as.get_partial_shape().rank().is_static() && as.get_partial_shape().rank().get_length() == 4) {
auto as_shape = std::make_shared<ov::op::v3::ShapeOf>(as, ov::element::i64);
- as = std::make_shared<ov::op::v1::Reshape>(as, get_dimensions(as_shape, {1, 2, 3}), false);
+ as = std::make_shared<ov::op::v1::Reshape>(as, gather_dims(as_shape, {1, 2, 3}), false);
}
auto b = activations;
@@ -282,12 +280,11 @@ ov::Output<ov::Node> translate_mul_mat_id_generic(ov::Output<ov::Node> expert_we
auto activations_shape_4d = std::make_shared<ov::op::v3::ShapeOf>(activations, ov::element::i64);
auto ids_shape_4d = std::make_shared<ov::op::v3::ShapeOf>(ids, ov::element::i64);
- expert_weights = std::make_shared<ov::op::v1::Reshape>(expert_weights,
- get_dimensions(expert_weights_shape_4d, {1, 2, 3}),
- false);
+ expert_weights =
+ std::make_shared<ov::op::v1::Reshape>(expert_weights, gather_dims(expert_weights_shape_4d, {1, 2, 3}), false);
activations =
- std::make_shared<ov::op::v1::Reshape>(activations, get_dimensions(activations_shape_4d, {1, 2, 3}), false);
- ids = std::make_shared<ov::op::v1::Reshape>(ids, get_dimensions(ids_shape_4d, {2, 3}), false);
+ std::make_shared<ov::op::v1::Reshape>(activations, gather_dims(activations_shape_4d, {1, 2, 3}), false);
+ ids = std::make_shared<ov::op::v1::Reshape>(ids, gather_dims(ids_shape_4d, {2, 3}), false);
if (ids.get_element_type() != ov::element::i32 && ids.get_element_type() != ov::element::i64) {
ids = std::make_shared<ov::op::v0::Convert>(ids, ov::element::i32);
@@ -321,8 +318,7 @@ ov::Output<ov::Node> translate_mul_mat_id_generic(ov::Output<ov::Node> expert_we
ov::Output<ov::Node> result =
std::make_shared<ov::op::v0::MatMul>(activations_expanded, selected_weights, false, true);
auto result_target_dims =
- std::make_shared<ov::op::v0::Concat>(ov::OutputVector{batch_dim, get_dimensions(ids_shape, {0, 1}), row_dim},
- 0);
+ std::make_shared<ov::op::v0::Concat>(ov::OutputVector{batch_dim, gather_dims(ids_shape, {0, 1}), row_dim}, 0);
result = std::make_shared<ov::op::v1::Reshape>(result, result_target_dims, false);
return result;
}
diff --git a/src/frontends/gguf/src/op/mulmat.cpp b/src/frontends/gguf/src/op/mulmat.cpp
index e2597c43869..c123e14747d 100644
--- a/src/frontends/gguf/src/op/mulmat.cpp
+++ b/src/frontends/gguf/src/op/mulmat.cpp
@@ -52,6 +52,12 @@ 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()) {
+ // Variable encoder grids use equal or singleton batch axes. MatMul validates
+ // their broadcast compatibility at runtime; do not freeze a grid dimension.
+ return rename_outputs_with_suffix({std::make_shared<ov::op::v0::MatMul>(A, B, false, transpose_b)},
+ context.get_name());
+ }
int64_t A_batch = A_shape[1].get_length();
int64_t B_batch = B_shape[1].get_length();
diff --git a/src/frontends/gguf/src/op/multimodal.cpp b/src/frontends/gguf/src/op/multimodal.cpp
new file mode 100644
index 00000000000..8f8a220ac0d
--- /dev/null
+++ b/src/frontends/gguf/src/op/multimodal.cpp
@@ -0,0 +1,244 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "op_table.hpp"
+#include "openvino/op/abs.hpp"
+#include "openvino/op/add.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/convolution.hpp"
+#include "openvino/op/divide.hpp"
+#include "openvino/op/floor_mod.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/greater.hpp"
+#include "openvino/op/interpolate.hpp"
+#include "openvino/op/less.hpp"
+#include "openvino/op/logical_and.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/maximum.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/pad.hpp"
+#include "openvino/op/range.hpp"
+#include "openvino/op/reduce_sum.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/select.hpp"
+#include "openvino/op/shape_of.hpp"
+#include "openvino/op/slice.hpp"
+#include "openvino/op/squeeze.hpp"
+#include "openvino/op/subtract.hpp"
+#include "openvino/op/transpose.hpp"
+#include "openvino/op/unsqueeze.hpp"
+#include "utils.hpp"
+
+namespace ov::frontend::gguf::op {
+
+namespace {
+std::shared_ptr<ov::op::v0::Constant> i64_const(std::vector<int64_t> v) {
+ return ov::op::v0::Constant::create(ov::element::i64, {v.size()}, v);
+}
+// ggml discards out-of-bounds taps and renormalizes the remaining triangle weights.
+// Interpolate's edge extension differs when downsampling, so use separable filters.
+ov::Output<ov::Node> antialiased_bilinear(const ov::Output<ov::Node>& input,
+ const ov::Output<ov::Node>& sizes,
+ bool align_corners) {
+ using namespace ov::op;
+ const auto zero = v0::Constant::create(ov::element::f32, {}, {0});
+ const auto one = v0::Constant::create(ov::element::f32, {}, {1});
+ const auto offset = v0::Constant::create(ov::element::f32, {}, {align_corners ? 0.f : .5f});
+ const auto shape = std::make_shared<v3::ShapeOf>(input);
+ const auto dimension = [&](const ov::Output<ov::Node>& value, int64_t axis) {
+ return std::make_shared<v0::Convert>(
+ std::make_shared<v8::Gather>(value, v0::Constant::create(ov::element::i64, {}, {axis}), i64_const({0})),
+ ov::element::f32);
+ };
+ const auto filter = [&](int64_t axis) -> ov::Output<ov::Node> {
+ const auto in_size = dimension(shape, axis);
+ const auto out_size = dimension(sizes, axis - 2);
+ ov::Output<ov::Node> scale = std::make_shared<v1::Divide>(out_size, in_size);
+ if (align_corners) {
+ auto valid = std::make_shared<v1::LogicalAnd>(std::make_shared<v1::Greater>(in_size, one),
+ std::make_shared<v1::Greater>(out_size, one));
+ auto corners = std::make_shared<v1::Divide>(
+ std::make_shared<v1::Subtract>(out_size, one),
+ std::make_shared<v1::Maximum>(std::make_shared<v1::Subtract>(in_size, one), one));
+ scale = std::make_shared<v1::Select>(valid, corners, scale);
+ }
+ auto support = std::make_shared<v1::Maximum>(one, std::make_shared<v1::Divide>(one, scale));
+ auto src = std::make_shared<v4::Range>(zero, in_size, one, ov::element::f32);
+ auto dst = std::make_shared<v4::Range>(zero, out_size, one, ov::element::f32);
+ auto center = std::make_shared<v1::Divide>(std::make_shared<v1::Add>(dst, offset), scale);
+ auto distance = std::make_shared<v1::Subtract>(
+ std::make_shared<v0::Unsqueeze>(std::make_shared<v1::Add>(src, offset), i64_const({0})),
+ std::make_shared<v0::Unsqueeze>(center, i64_const({1})));
+ auto weights = std::make_shared<v1::Maximum>(
+ zero,
+ std::make_shared<v1::Subtract>(one,
+ std::make_shared<v1::Divide>(std::make_shared<v0::Abs>(distance), support)));
+ // ggml truncates the exclusive upper bound to an integer, including with
+ // align_corners (zero pixel offset), where the omitted tap can be nonzero.
+ auto end = std::make_shared<v0::Convert>(
+ std::make_shared<v0::Convert>(std::make_shared<v1::Add>(std::make_shared<v1::Add>(center, support), offset),
+ ov::element::i64),
+ ov::element::f32);
+ auto valid_taps = std::make_shared<v1::Less>(std::make_shared<v0::Unsqueeze>(src, i64_const({0})),
+ std::make_shared<v0::Unsqueeze>(end, i64_const({1})));
+ auto clipped = std::make_shared<v1::Select>(valid_taps, weights, zero);
+ return std::make_shared<v1::Divide>(clipped, std::make_shared<v1::ReduceSum>(clipped, i64_const({1}), true));
+ };
+ auto width = std::make_shared<v0::MatMul>(input, filter(3), false, true);
+ auto transposed = std::make_shared<v1::Transpose>(width, i64_const({0, 1, 3, 2}));
+ auto height = std::make_shared<v0::MatMul>(transposed, filter(2), false, true);
+ return std::make_shared<v1::Transpose>(height, i64_const({0, 1, 3, 2}));
+}
+} // namespace
+
+OutputVector translate_upscale(const NodeContext& context) {
+ num_inputs_check(context, 2, 2);
+ const int flags = context.get_attribute<int>("interpolation_mode", 1);
+ FRONT_END_OP_CONVERSION_CHECK((flags & ~0x303) == 0 && (flags & 0xff) <= 2, "Unsupported interpolation mode");
+ using Interpolate = ov::op::v4::Interpolate;
+ Interpolate::InterpolateAttrs attrs;
+ attrs.mode = (flags & 0xff) == 0 ? Interpolate::InterpolateMode::NEAREST
+ : (flags & 0xff) == 1 ? Interpolate::InterpolateMode::LINEAR
+ : Interpolate::InterpolateMode::CUBIC;
+ attrs.shape_calculation_mode = Interpolate::ShapeCalcMode::SIZES;
+ attrs.coordinate_transformation_mode = (flags & 0x100) ? Interpolate::CoordinateTransformMode::ALIGN_CORNERS
+ : (flags & 0xff) == 0 ? Interpolate::CoordinateTransformMode::ASYMMETRIC
+ : Interpolate::CoordinateTransformMode::HALF_PIXEL;
+ attrs.nearest_mode = Interpolate::NearestMode::FLOOR;
+ attrs.antialias = (flags & 0x200) != 0;
+ attrs.pads_begin = attrs.pads_end = {0, 0, 0, 0};
+ const std::vector<int> axes{2, 3};
+ auto sizes = context.get_attribute<bool>("resize_like", false)
+ ? get_dimensions(context.get_input(1), axes)->output(0)
+ : context.get_input(1);
+ if ((flags & 0xff) == 1 && attrs.antialias) {
+ return rename_outputs_with_suffix({antialiased_bilinear(context.get_input(0), sizes, (flags & 0x100) != 0)},
+ context.get_name());
+ }
+ auto result = std::make_shared<Interpolate>(
+ context.get_input(0),
+ sizes,
+ ov::op::v0::Constant::create(ov::element::f32, {axes.size()}, std::vector<float>(axes.size(), 1.f)),
+ ov::op::v0::Constant::create(ov::element::i64, {axes.size()}, axes),
+ attrs);
+ return rename_outputs_with_suffix({result}, context.get_name());
+}
+
+OutputVector translate_conv_2d(const NodeContext& context) {
+ num_inputs_check(context, 2, 2);
+ const auto p = context.get_attribute<std::vector<int64_t>>("conv_params");
+ FRONT_END_OP_CONVERSION_CHECK(p.size() == 6, "CONV_2D requires sx,sy,px,py,dx,dy");
+ FRONT_END_OP_CONVERSION_CHECK(p[0] > 0 && p[1] > 0 && p[2] >= 0 && p[3] >= 0 && p[4] > 0 && p[5] > 0,
+ "Invalid CONV_2D parameters");
+ auto w = context.get_input(0), x = context.get_input(1);
+ if (w.get_element_type() != ov::element::f32)
+ 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);
+ 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])})},
+ context.get_name());
+}
+
+OutputVector translate_win_part(const NodeContext& context) {
+ num_inputs_check(context, 1, 1);
+ using namespace ov::op;
+ auto x = context.get_input(0);
+ const auto window = context.get_attribute<int64_t>("window");
+ FRONT_END_OP_CONVERSION_CHECK(window > 0 && x.get_partial_shape().rank() == 4, "Invalid window partition");
+ const auto& c = i64_const;
+ const auto x_shape = std::make_shared<v3::ShapeOf>(x, ov::element::i64);
+ auto spatial = gather_dims(x_shape, {1, 2});
+ auto padding = std::make_shared<v1::FloorMod>(std::make_shared<v1::Subtract>(c({window, window}), spatial),
+ c({window, window}));
+ auto padded = std::make_shared<v1::Pad>(x,
+ c({0, 0, 0, 0}),
+ std::make_shared<v0::Concat>(OutputVector{c({0}), padding, c({0})}, 0),
+ PadMode::CONSTANT);
+ auto size = std::make_shared<v1::Divide>(get_dimensions(padded, {1, 2}), c({window, window}), true);
+ auto split = gather_dims(size, {0});
+ auto split_w = gather_dims(size, {1});
+ auto pattern = std::make_shared<v0::Concat>(
+ OutputVector{gather_dims(x_shape, {0}), split, c({window}), split_w, c({window}), gather_dims(x_shape, {3})},
+ 0);
+ auto reshaped = std::make_shared<v1::Reshape>(padded, pattern, false);
+ auto ordered = std::make_shared<v1::Transpose>(reshaped, c({0, 1, 3, 2, 4, 5}));
+ auto output = std::make_shared<v1::Reshape>(
+ ordered,
+ std::make_shared<v0::Concat>(OutputVector{c({-1, window, window}), gather_dims(x_shape, {3})}, 0),
+ false);
+ return rename_outputs_with_suffix({output}, context.get_name());
+}
+
+OutputVector translate_win_unpart(const NodeContext& context) {
+ num_inputs_check(context, 2, 2);
+ using namespace ov::op;
+ auto x = context.get_input(0), reference = context.get_input(1);
+ const auto window = context.get_attribute<int64_t>("window");
+ FRONT_END_OP_CONVERSION_CHECK(window > 0, "Invalid window unpartition");
+ const auto& c = i64_const;
+ const auto x_shape = std::make_shared<v3::ShapeOf>(x, ov::element::i64);
+ const auto reference_shape = std::make_shared<v3::ShapeOf>(reference, ov::element::i64);
+ auto spatial = gather_dims(reference_shape, {1, 2});
+ auto blocks = std::make_shared<v1::Divide>(std::make_shared<v1::Add>(spatial, c({window - 1, window - 1})),
+ c({window, window}),
+ true);
+ auto h = gather_dims(blocks, {0});
+ auto w = gather_dims(blocks, {1});
+ auto pattern = std::make_shared<v0::Concat>(
+ OutputVector{gather_dims(reference_shape, {0}), h, w, c({window, window}), gather_dims(x_shape, {3})},
+ 0);
+ auto ordered =
+ std::make_shared<v1::Transpose>(std::make_shared<v1::Reshape>(x, pattern, false), c({0, 1, 3, 2, 4, 5}));
+ auto padded_shape =
+ std::make_shared<v0::Concat>(OutputVector{gather_dims(reference_shape, {0}),
+ std::make_shared<v1::Multiply>(blocks, c({window, window})),
+ gather_dims(x_shape, {3})},
+ 0);
+ auto padded = std::make_shared<v1::Reshape>(ordered, padded_shape, false);
+ return rename_outputs_with_suffix({std::make_shared<v8::Slice>(padded, c({0, 0}), spatial, c({1, 1}), c({1, 2}))},
+ context.get_name());
+}
+
+OutputVector translate_get_rel_pos(const NodeContext& context) {
+ num_inputs_check(context, 2, 2);
+ FRONT_END_OP_CONVERSION_CHECK(context.get_op_case() == 1, "Indexed relative positions require case 1");
+ using namespace ov::op;
+ auto table = context.get_input(0), indices = context.get_input(1);
+ const auto& c = i64_const;
+ // The table is a weight, so its width is known at conversion time.
+ const auto& table_shape = table.get_partial_shape();
+ FRONT_END_OP_CONVERSION_CHECK(table_shape.rank() == 2 && table_shape[1].is_static(),
+ "Relative position table must have a static width");
+ const auto table_width = c({table_shape[1].get_length()});
+ // SAM decomposed relative positions: resize the distance table before gathering.
+ auto length =
+ std::make_shared<v1::Subtract>(std::make_shared<v1::Multiply>(get_dimensions(indices, {2}), c({2})), c({1}));
+ auto data =
+ std::make_shared<v1::Reshape>(std::make_shared<v1::Transpose>(table, c({1, 0})),
+ std::make_shared<v0::Concat>(OutputVector{c({1}), table_width, c({1, -1})}, 0),
+ false);
+ v4::Interpolate::InterpolateAttrs attrs;
+ attrs.mode = v4::Interpolate::InterpolateMode::LINEAR;
+ attrs.shape_calculation_mode = v4::Interpolate::ShapeCalcMode::SIZES;
+ attrs.coordinate_transformation_mode = v4::Interpolate::CoordinateTransformMode::HALF_PIXEL;
+ auto resized = std::make_shared<v4::Interpolate>(data,
+ length,
+ v0::Constant::create(ov::element::f32, {1}, {1}),
+ c({3}),
+ attrs);
+ auto rows = std::make_shared<v1::Reshape>(std::make_shared<v1::Transpose>(resized, c({0, 2, 3, 1})),
+ std::make_shared<v0::Concat>(OutputVector{c({-1}), table_width}, 0),
+ false);
+ auto ids = std::make_shared<v0::Squeeze>(indices, c({0}));
+ return rename_outputs_with_suffix({std::make_shared<v8::Gather>(rows, ids, c({0}))}, context.get_name());
+}
+
+} // namespace ov::frontend::gguf::op
diff --git a/src/frontends/gguf/src/op/pad.cpp b/src/frontends/gguf/src/op/pad.cpp
index b2ca2a332a1..8698586582d 100644
--- a/src/frontends/gguf/src/op/pad.cpp
+++ b/src/frontends/gguf/src/op/pad.cpp
@@ -11,10 +11,13 @@
#include "node_context.hpp"
#include "op_table.hpp"
#include "openvino/frontend/exception.hpp"
+#include "openvino/op/concat.hpp"
#include "openvino/op/constant.hpp"
+#include "openvino/op/floor_mod.hpp"
#include "openvino/op/gather.hpp"
#include "openvino/op/reshape.hpp"
#include "openvino/op/shape_of.hpp"
+#include "openvino/op/subtract.hpp"
#include "utils.hpp"
namespace ov::frontend::gguf::op {
@@ -58,6 +61,27 @@ OutputVector translate_pad(const NodeContext& context) {
num_inputs_check(context, 1, 1);
auto input = context.get_input(0);
+ 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,
+ "Token padding requires rank four and a positive multiple");
+ auto length = get_dimensions(input, {2});
+ auto divisor = ov::op::v0::Constant::create(ov::element::i64, {1}, {multiple});
+ auto remainder = std::make_shared<ov::op::v1::FloorMod>(length, divisor);
+ auto count =
+ std::make_shared<ov::op::v1::FloorMod>(std::make_shared<ov::op::v1::Subtract>(divisor, remainder), divisor);
+ auto pads = std::make_shared<ov::op::v0::Concat>(
+ ov::OutputVector{ov::op::v0::Constant::create(ov::element::i64, {2}, {0, 0}),
+ count,
+ ov::op::v0::Constant::create(ov::element::i64, {1}, {0})},
+ 0);
+ auto result =
+ std::make_shared<ov::op::v1::Pad>(input,
+ ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 0, 0, 0}),
+ pads,
+ ov::op::PadMode::CONSTANT);
+ return rename_outputs_with_suffix({result}, context.get_name());
+ }
if (context.get_input_shape(0) == context.get_output_shape()) {
auto input_shape = std::make_shared<ov::op::v3::ShapeOf>(input);
auto res = std::make_shared<ov::op::v1::Reshape>(input, input_shape, false);
diff --git a/src/frontends/gguf/src/op/reshape.cpp b/src/frontends/gguf/src/op/reshape.cpp
index 46a2f8cedb3..519e29da69a 100644
--- a/src/frontends/gguf/src/op/reshape.cpp
+++ b/src/frontends/gguf/src/op/reshape.cpp
@@ -25,7 +25,32 @@
namespace ov::frontend::gguf::op {
OutputVector translate_reshape(const NodeContext& context) {
- num_inputs_check(context, 1, 1);
+ num_inputs_check(context, 1, 2);
+ if (context.get_input_size() == 2) {
+ // Copy selected dimensions from a reference tensor, preserving variable grids.
+ const auto target = context.get_attribute<std::vector<int64_t>>("reshape_target");
+ const auto axes = context.get_attribute<std::vector<int64_t>>("shape_axes");
+ FRONT_END_OP_CONVERSION_CHECK(target.size() == axes.size(), "Invalid reference reshape pattern");
+ // One ShapeOf for the whole pattern, and one Gather per run of copied axes.
+ const auto reference_shape = std::make_shared<ov::op::v3::ShapeOf>(context.get_input(1), ov::element::i64);
+ ov::OutputVector dimensions;
+ for (size_t i = 0; i < target.size();) {
+ if (axes[i] < 0) {
+ dimensions.push_back(ov::op::v0::Constant::create(ov::element::i64, {1}, {target[i]}));
+ ++i;
+ continue;
+ }
+ std::vector<int> copied;
+ for (; i < target.size() && axes[i] >= 0; ++i)
+ copied.push_back(static_cast<int>(axes[i]));
+ dimensions.push_back(gather_dims(reference_shape, copied));
+ }
+ return rename_outputs_with_suffix(
+ {std::make_shared<ov::op::v1::Reshape>(context.get_input(0),
+ std::make_shared<ov::op::v0::Concat>(dimensions, 0),
+ false)},
+ context.get_name());
+ }
const auto target = context.get_attribute<std::vector<int64_t>>("reshape_target", {});
if (!target.empty() && (context.get_op_case() == 0 || context.get_op_case() == 6)) {
auto pattern = ov::op::v0::Constant::create(ov::element::i64, {target.size()}, target);
diff --git a/src/frontends/gguf/src/op/rope.cpp b/src/frontends/gguf/src/op/rope.cpp
index e329aab7357..f530210d6b5 100644
--- a/src/frontends/gguf/src/op/rope.cpp
+++ b/src/frontends/gguf/src/op/rope.cpp
@@ -4,6 +4,7 @@
#include "openvino/decompositions/rope.hpp"
+#include <cmath>
#include <cstdint>
#include <memory>
#include <vector>
@@ -53,6 +54,66 @@ OutputVector translate_rope(const NodeContext& context) {
constexpr int TYPE_NORMAL = 0;
constexpr int TYPE_NEOX = 1;
constexpr int TYPE_IMROPE = 2;
+ constexpr int TYPE_VISION = 3;
+
+ if (mode == TYPE_VISION) {
+ // ggml vision RoPE rotates the full head in two halves; n_dims is half the
+ // head width, and each position section restarts its frequency progression.
+ using namespace ov::op;
+ const auto shape = data.get_partial_shape();
+ FRONT_END_OP_CONVERSION_CHECK(shape.rank() == 4 && shape[3].is_static(),
+ "Vision RoPE requires rank four and a static head width");
+ const int64_t half = shape[3].get_length() / 2;
+ FRONT_END_OP_CONVERSION_CHECK(2 * half == shape[3].get_length() && rope_config.n_dims == half,
+ "Vision RoPE n_dims must equal half the head width");
+ FRONT_END_OP_CONVERSION_CHECK(rope_config.ext_factor == 0.f && context.get_input_size() == 2,
+ "Vision RoPE with YaRN or frequency-factor weights is not supported");
+ auto sections = rope_config.sections;
+ int64_t total = 0; // four int32 counts always fit in 64 bits
+ for (auto section : sections) {
+ FRONT_END_OP_CONVERSION_CHECK(section >= 0, "Negative vision RoPE section");
+ total += section;
+ }
+ FRONT_END_OP_CONVERSION_CHECK(total > 0 && total <= 2 * half && rope_config.freq_base > 0.f,
+ "Invalid vision RoPE sections or frequency base");
+ std::vector<int64_t> axes(half);
+ std::vector<float> factors(half);
+ for (int64_t i = 0; i < half; ++i) {
+ int offset = int(i % total), section = 0;
+ while (section < 3 && offset >= sections[section]) {
+ offset -= sections[section];
+ ++section;
+ }
+ axes[i] = section;
+ factors[i] = std::pow(rope_config.freq_base, -2.f * offset / half) * rope_config.freq_scale;
+ }
+ auto positions = std::make_shared<v1::Reshape>(context.get_input(1),
+ v0::Constant::create(ov::element::i64, {2}, {4, -1}),
+ false);
+ auto transposed =
+ std::make_shared<v1::Transpose>(positions, v0::Constant::create(ov::element::i64, {2}, {1, 0}));
+ auto selected = std::make_shared<v8::Gather>(transposed,
+ v0::Constant::create(ov::element::i64, {size_t(half)}, axes),
+ v0::Constant::create(ov::element::i64, {}, {1}));
+ auto theta = std::make_shared<v1::Multiply>(std::make_shared<v0::Convert>(selected, ov::element::f32),
+ v0::Constant::create(ov::element::f32, {size_t(half)}, factors));
+ auto expand = v0::Constant::create(ov::element::i64, {2}, {0, 2});
+ auto scale = v0::Constant::create(ov::element::f32, {}, {rope_config.attn_factor});
+ auto cos =
+ std::make_shared<v1::Multiply>(std::make_shared<v0::Unsqueeze>(std::make_shared<v0::Cos>(theta), expand),
+ scale);
+ auto sin =
+ std::make_shared<v1::Multiply>(std::make_shared<v0::Unsqueeze>(std::make_shared<v0::Sin>(theta), expand),
+ scale);
+ const auto type = data.get_element_type();
+ if (type != ov::element::f32)
+ data = std::make_shared<v0::Convert>(data, ov::element::f32);
+ ov::pass::NodeRegistry reg;
+ res = ov::decomposition::rope(reg, data, cos, sin, half);
+ if (type != ov::element::f32)
+ res = std::make_shared<v0::Convert>(res, type);
+ return rename_outputs_with_suffix({res}, context.get_name());
+ }
Output<Node> cos_theta_node;
Output<Node> sin_theta_node;
@@ -276,7 +337,7 @@ OutputVector translate_rope(const NodeContext& context) {
auto cos_sin_shape = std::make_shared<ov::op::v0::Constant>(ov::element::i64,
ov::Shape{4},
- std::vector<int64_t>{1, -1, 1, (n_rot >> 1)});
+ std::vector<int64_t>{0, -1, 1, (n_rot >> 1)});
auto cos_reshaped = std::make_shared<ov::op::v1::Reshape>(cos_theta_node, cos_sin_shape, true);
auto sin_reshaped = std::make_shared<ov::op::v1::Reshape>(sin_theta_node, cos_sin_shape, true);
diff --git a/src/frontends/gguf/src/op/ssm_conv.cpp b/src/frontends/gguf/src/op/ssm_conv.cpp
index 1c20b0b4ba3..8beddc9c736 100644
--- a/src/frontends/gguf/src/op/ssm_conv.cpp
+++ b/src/frontends/gguf/src/op/ssm_conv.cpp
@@ -10,6 +10,7 @@
#include "openvino/op/group_conv.hpp"
#include "openvino/op/reshape.hpp"
#include "openvino/op/transpose.hpp"
+#include "openvino/op/unsqueeze.hpp"
#include "utils.hpp"
namespace ov::frontend::gguf::op {
@@ -51,6 +52,13 @@ OutputVector translate_ssm_conv(const NodeContext& context) {
auto perm = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{0, 2, 1});
auto transposed = std::make_shared<ov::op::v1::Transpose>(conv, perm);
+ if (context.get_attribute<bool>("batch_major", false)) {
+ return rename_outputs_with_suffix(
+ {std::make_shared<ov::op::v0::Unsqueeze>(transposed,
+ ov::op::v0::Constant::create(ov::element::i64, {1}, {1}))},
+ context.get_name());
+ }
+
// [1, n_s, n_t, d_inner] with the token axis n_t dynamic (-1).
auto out_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, n_s, -1, d_inner});
auto res = std::make_shared<ov::op::v1::Reshape>(transposed, out_shape, false);
diff --git a/src/frontends/gguf/src/op_table.cpp b/src/frontends/gguf/src/op_table.cpp
index 759f6c73e76..90e54a4caa4 100644
--- a/src/frontends/gguf/src/op_table.cpp
+++ b/src/frontends/gguf/src/op_table.cpp
@@ -10,6 +10,7 @@
#include "openvino/op/divide.hpp"
#include "openvino/op/exp.hpp"
#include "openvino/op/gather.hpp"
+#include "openvino/op/gelu.hpp"
#include "openvino/op/log.hpp"
#include "openvino/op/matmul.hpp"
#include "openvino/op/multiply.hpp"
@@ -39,6 +40,7 @@ std::unordered_map<std::string, CreatorFunction> get_supported_ops() {
{"GGML_OP_CLAMP", op::translate_clamp},
{"GGML_OP_CONCAT", op::translate_concat},
{"GGML_OP_CONT", op::translate_cont},
+ {"GGML_OP_CONV_2D", op::translate_conv_2d},
{"GGML_OP_COS", op::translate_1to1_match_1_input<v0::Cos>},
{"GGML_OP_CPY", op::translate_cpy},
{"GGML_OP_CUMSUM", op::translate_cumsum},
@@ -47,6 +49,7 @@ std::unordered_map<std::string, CreatorFunction> get_supported_ops() {
{"GGML_OP_FILL", op::translate_fill},
{"GGML_OP_FLASH_ATTN_EXT", op::translate_flash_attn_ext},
{"GGML_OP_GATED_DELTA_NET", op::translate_gated_delta_net},
+ {"GGML_OP_GET_REL_POS", op::translate_get_rel_pos},
{"GGML_OP_GET_ROWS", op::translate_get_rows},
{"GGML_OP_IM2COL", op::translate_im2col},
{"GGML_OP_L2_NORM", op::translate_l2_norm},
@@ -79,10 +82,14 @@ std::unordered_map<std::string, CreatorFunction> get_supported_ops() {
{"GGML_OP_TOP_K", op::translate_top_k},
{"GGML_OP_TRANSPOSE", op::translate_transpose},
{"GGML_OP_TRI", op::translate_tri},
+ {"GGML_OP_UPSCALE", op::translate_upscale},
{"GGML_OP_VIEW", op::translate_view},
+ {"GGML_OP_WIN_PART", op::translate_win_part},
+ {"GGML_OP_WIN_UNPART", op::translate_win_unpart},
{"GGML_UNARY_OP_ELU", op::translate_unary_elu},
{"GGML_UNARY_OP_EXP", op::translate_1to1_match_1_input<v0::Exp>},
{"GGML_UNARY_OP_GELU", op::translate_unary_gelu},
+ {"GGML_UNARY_OP_GELU_ERF", op::translate_1to1_match_1_input<v7::Gelu>},
{"GGML_UNARY_OP_GELU_QUICK", op::translate_unary_gelu_quick},
{"GGML_UNARY_OP_NEG", op::translate_1to1_match_1_input<v0::Negative>},
{"GGML_UNARY_OP_RELU", op::translate_1to1_match_1_input<v0::Relu>},
diff --git a/src/frontends/gguf/src/op_table.hpp b/src/frontends/gguf/src/op_table.hpp
index 45cd4dce075..a9981cfb35f 100644
--- a/src/frontends/gguf/src/op_table.hpp
+++ b/src/frontends/gguf/src/op_table.hpp
@@ -19,6 +19,9 @@ GGUF_OP_CONVERTER(translate_concat);
GGUF_OP_CONVERTER(translate_cont);
GGUF_OP_CONVERTER(translate_cpy);
GGUF_OP_CONVERTER(translate_get_rows);
+GGUF_OP_CONVERTER(translate_get_rel_pos);
+GGUF_OP_CONVERTER(translate_win_part);
+GGUF_OP_CONVERTER(translate_win_unpart);
GGUF_OP_CONVERTER(translate_permute);
GGUF_OP_CONVERTER(translate_repeat);
GGUF_OP_CONVERTER(translate_reshape);
@@ -81,8 +84,10 @@ GGUF_OP_CONVERTER(translate_fill);
// Convolution-family / sequence ops.
GGUF_OP_CONVERTER(translate_im2col);
-GGUF_OP_CONVERTER(translate_pad);
GGUF_OP_CONVERTER(translate_pool_2d);
+GGUF_OP_CONVERTER(translate_conv_2d);
+GGUF_OP_CONVERTER(translate_upscale);
+GGUF_OP_CONVERTER(translate_pad);
GGUF_OP_CONVERTER(translate_roll);
GGUF_OP_CONVERTER(translate_solve_tri);
GGUF_OP_CONVERTER(translate_ssm_conv);
diff --git a/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp b/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp
new file mode 100644
index 00000000000..1d3c7e97c42
--- /dev/null
+++ b/src/frontends/gguf/src/pass/adapt_mmproj_to_genai.cpp
@@ -0,0 +1,58 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/frontend/gguf/adapt_mmproj_to_genai.hpp"
+
+#include <unordered_set>
+
+#include "openvino/op/constant.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/split.hpp"
+#include "openvino/op/squeeze.hpp"
+#include "pass/prune_orphaned_parameters.hpp"
+#include "utils.hpp"
+
+namespace ov::frontend::gguf::pass {
+bool AdaptMmprojToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ const std::string prefix = m_modality == Modality::VISION ? "vision." : "audio.";
+ std::shared_ptr<ov::op::v0::Result> selected;
+ for (const auto& result : model->get_results()) {
+ if (result->input_value(0).get_names().count(prefix + "embeddings"))
+ selected = result;
+ }
+ OPENVINO_ASSERT(selected, "[GGUF] mmproj has no ", prefix, "embeddings output");
+ auto live_before = std::make_shared<std::unordered_set<const ov::Node*>>();
+ SnapshotLiveParameters(live_before).run_on_model(model);
+ const auto results = model->get_results();
+ for (const auto& result : results)
+ model->remove_result(result);
+ auto embeddings = std::make_shared<ov::op::v0::Squeeze>(selected->input_value(0),
+ ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
+ size_t auxiliary_count = 0;
+ if (m_modality == Modality::VISION && model->has_rt_info({"gguf_mmproj", "vision.auxiliary_count"}))
+ auxiliary_count = std::stoull(model->get_rt_info<std::string>({"gguf_mmproj", "vision.auxiliary_count"}));
+ if (auxiliary_count) {
+ 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)});
+ model->add_results({std::make_shared<ov::op::v0::Result>(split->output(i))});
+ }
+ } else {
+ // Only the tensor that becomes a Result is named; the Split path names output 0 instead.
+ embeddings->output(0).set_names({m_modality == Modality::VISION ? "image_features" : "audio_features"});
+ model->add_results({std::make_shared<ov::op::v0::Result>(embeddings)});
+ }
+ PruneParametersOrphanedSince(live_before).run_on_model(model);
+ for (const auto& p : model->get_parameters()) {
+ const auto& name = p->get_friendly_name();
+ if (name.rfind(prefix, 0) == 0)
+ name_output(p, name.substr(prefix.size()));
+ }
+ model->validate_nodes_and_infer_types();
+ return true;
+}
+} // namespace ov::frontend::gguf::pass
diff --git a/src/frontends/gguf/src/pass/adapt_to_genai.cpp b/src/frontends/gguf/src/pass/adapt_to_genai.cpp
index 6b9d3eb1d39..597154b711a 100644
--- a/src/frontends/gguf/src/pass/adapt_to_genai.cpp
+++ b/src/frontends/gguf/src/pass/adapt_to_genai.cpp
@@ -4,19 +4,31 @@
#include "openvino/frontend/gguf/adapt_to_genai.hpp"
+#include <algorithm>
#include <memory>
+#include <vector>
+#include "openvino/core/graph_util.hpp"
#include "openvino/core/rt_info.hpp"
#include "openvino/frontend/gguf/make_stateful.hpp"
#include "openvino/op/add.hpp"
+#include "openvino/op/broadcast.hpp"
#include "openvino/op/concat.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/convert.hpp"
+#include "openvino/op/cum_sum.hpp"
+#include "openvino/op/divide.hpp"
+#include "openvino/op/equal.hpp"
+#include "openvino/op/gated_delta_net.hpp"
#include "openvino/op/gather.hpp"
#include "openvino/op/greater_eq.hpp"
+#include "openvino/op/group_conv.hpp"
#include "openvino/op/less_eq.hpp"
#include "openvino/op/logical_and.hpp"
+#include "openvino/op/logical_or.hpp"
+#include "openvino/op/matmul.hpp"
#include "openvino/op/multiply.hpp"
+#include "openvino/op/not_equal.hpp"
#include "openvino/op/parameter.hpp"
#include "openvino/op/range.hpp"
#include "openvino/op/read_value.hpp"
@@ -26,9 +38,12 @@
#include "openvino/op/scaled_dot_product_attention.hpp"
#include "openvino/op/select.hpp"
#include "openvino/op/shape_of.hpp"
+#include "openvino/op/slice.hpp"
#include "openvino/op/squeeze.hpp"
#include "openvino/op/subtract.hpp"
+#include "openvino/op/tanh.hpp"
#include "openvino/op/tile.hpp"
+#include "openvino/op/transpose.hpp"
#include "openvino/op/unsqueeze.hpp"
#include "openvino/pass/manager.hpp"
#include "openvino/pass/matcher_pass.hpp"
@@ -154,11 +169,6 @@ public:
}
};
-void name_output(const ov::Output<ov::Node>& out, const std::string& name) {
- out.get_node_shared_ptr()->set_friendly_name(name);
- out.get_node_shared_ptr()->output(0).set_names({name});
-}
-
// Largest attention head size across the stateful KV caches (the ReadValue last dim). The
// frontend emits f16 KV caches mirroring llama.cpp, but the CPU plugin defaults
// KV_CACHE_PRECISION to u8 (dynamic-quantized) -- faster and accurate enough for the common
@@ -183,9 +193,11 @@ int64_t max_kv_cache_head_size(const std::shared_ptr<ov::Model>& model) {
bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
using namespace ov::op;
- OPENVINO_ASSERT(m_mode == InputMode::IDS_TO_LOGITS,
- "[gguf] AdaptToGenAI: only InputMode::IDS_TO_LOGITS is implemented; "
- "EMBEDS_TO_LOGITS (VLM language model) is reserved for future work.");
+
+ for (const auto& output : model->outputs()) {
+ if (output.get_names().count("embeddings"))
+ 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.
@@ -194,11 +206,35 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
auto self_kq_mask = find_parameter(model, "self_kq_mask");
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();
+ const bool batchable_recurrent =
+ has_recurrent_states && std::any_of(operations.begin(), operations.end(), [](const auto& node) {
+ return ov::is_type<internal::GatedDeltaNet>(node);
+ });
const bool recurrent_only = !inp_pos && !self_kq_mask && has_recurrent_states;
if (!inp_tokens || (!recurrent_only && !self_kq_mask)) {
return false;
}
+ // 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;
+ if (m_mode == InputMode::EMBEDS_TO_LOGITS) {
+ for (const auto& node : operations) {
+ const auto& rt_info = node->get_rt_info();
+ if (rt_info.count("gguf.token_embedding")) {
+ OPENVINO_ASSERT(embedding_name.empty(), "[GGUF] ambiguous token embedding boundary");
+ embedding_name = node->get_friendly_name();
+ }
+ if (const auto it = rt_info.find("gguf.per_layer_token_embedding"); it != rt_info.end()) {
+ OPENVINO_ASSERT(per_layer_name.empty(), "[GGUF] ambiguous per-layer token embedding boundary");
+ per_layer_name = node->get_friendly_name();
+ per_layer_count = it->second.as<int64_t>();
+ }
+ }
+ OPENVINO_ASSERT(!embedding_name.empty(), "[GGUF] missing native token embedding boundary");
+ }
+
// Must run before inp_out_ids's value is replaced below, while these patterns can still
// structurally identify "embd" and the inp_out_ids-rooted row-selection call sites.
ov::pass::Manager self_correcting_axis_manager;
@@ -206,16 +242,95 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
self_correcting_axis_manager.register_pass<FixEmbdAxis>();
self_correcting_axis_manager.run_passes(model);
+ std::shared_ptr<v0::Parameter> inputs_embeds, per_layer_inputs;
+ 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) {
+ std::shared_ptr<ov::Node> found;
+ for (const auto& node : model->get_ops()) {
+ if (node->get_friendly_name() == name) {
+ OPENVINO_ASSERT(!found, "[GGUF] ambiguous embedding boundary ", name);
+ found = node;
+ }
+ }
+ OPENVINO_ASSERT(found, "[GGUF] missing embedding boundary ", name);
+ return found;
+ };
+ // Both lookups are [batch, 1, tokens, width].
+ auto axis_1 = v0::Constant::create(ov::element::i64, {1}, {1});
+ auto embedding = find_boundary(embedding_name);
+ 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) {
+ auto extracted = make_shared<ov::Model>(ov::OutputVector{lookup}, ov::ParameterVector{inp_tokens})->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 ids4 = make_shared<v0::Unsqueeze>(make_shared<v0::Convert>(ids, ov::element::i32),
+ v0::Constant::create(ov::element::i64, {2}, {0, 1}));
+ auto old_ids = extracted->get_parameters().front();
+ old_ids->output(0).replace(ids4->output(0));
+ extracted->remove_parameter(old_ids);
+ extracted->add_parameters({ids});
+ extracted->output(0).get_tensor().set_names({name});
+ extracted->validate_nodes_and_infer_types();
+ return extracted;
+ };
+ m_embedding_model = extract(make_shared<v0::Squeeze>(embedding, axis_1), "inputs_embeds");
+ auto per_layer = per_layer_name.empty() ? nullptr : find_boundary(per_layer_name);
+ int64_t per_layer_width = 0;
+ if (per_layer) {
+ const auto total = per_layer->get_output_partial_shape(0)[3].get_length();
+ OPENVINO_ASSERT(per_layer_count > 0 && total % per_layer_count == 0,
+ "[GGUF] per-layer token embedding width does not match its layer count");
+ per_layer_width = total / per_layer_count;
+ // [batch, tokens, layers, width], as in optimum-intel.
+ m_per_layer_embedding_model =
+ extract(make_shared<v1::Reshape>(
+ make_shared<v0::Squeeze>(per_layer, axis_1),
+ v0::Constant::create(ov::element::i64,
+ {4},
+ {int64_t{0}, int64_t{0}, per_layer_count, per_layer_width}),
+ true),
+ "per_layer_inputs");
+ }
+ inputs_embeds = make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{-1, -1, width});
+ name_output(inputs_embeds, "inputs_embeds");
+ auto lifted = make_shared<v0::Unsqueeze>(inputs_embeds, v0::Constant::create(ov::element::i64, {1}, {1}));
+ embedding->output(0).replace(lifted->output(0));
+ if (per_layer) {
+ per_layer_inputs = make_shared<v0::Parameter>(per_layer->get_output_element_type(0),
+ ov::PartialShape{-1, -1, per_layer_count, per_layer_width});
+ name_output(per_layer_inputs, "per_layer_inputs");
+ // Lift like inputs_embeds; PA feeds [tokens, 1, layers, width].
+ auto flat = make_shared<v1::Reshape>(per_layer_inputs,
+ v0::Constant::create(ov::element::i64, {3}, {0, 0, -1}),
+ true);
+ per_layer->output(0).replace(make_shared<v0::Unsqueeze>(flat, axis_1)->output(0));
+ }
+ }
+
// ---- new genai inputs: input_ids / attention_mask / position_ids [b, seq] i64 ----
// Recurrent state buffers currently hold one sequence. Keep that constraint explicit.
- auto input_ids =
- make_shared<v0::Parameter>(ov::element::i64,
- has_recurrent_states ? ov::PartialShape{1, -1} : ov::PartialShape{-1, -1});
+ auto input_ids = make_shared<v0::Parameter>(
+ ov::element::i64,
+ (has_recurrent_states && !batchable_recurrent) ? ov::PartialShape{1, -1} : ov::PartialShape{-1, -1});
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");
- auto position_ids = make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});
+ 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});
name_output(position_ids, "position_ids");
+ std::shared_ptr<v0::Parameter> token_type_ids;
+ const auto arch_it = model->get_rt_info().find("gguf_architecture");
+ const auto arch = arch_it != model->get_rt_info().end() ? arch_it->second.as<std::string>() : std::string{};
+ // Gemma4 E2B/E4B, the variants with per-layer token embeddings, keep image attention causal.
+ if (inputs_embeds && (arch == "gemma3" || (arch == "gemma4" && !per_layer_inputs))) {
+ token_type_ids = make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});
+ name_output(token_type_ids, "token_type_ids");
+ }
// beam_idx (i32 [D]) is added by the make-stateful pass, next to the Gather that reads it; genai
// sets it via set_tensor("beam_idx"). Keep that Parameter so its wiring is preserved. Its absence
@@ -239,7 +354,8 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
// and splices an Unsqueeze(axis=1) in front of its consumers, making it [tokens, 1]. Reading
// dim 1 would then yield 1 for every prompt, collapsing the causal mask and the logits to a
// single token; reading dim 0 breaks the un-rewritten case. ReduceProd is correct under both.
- auto ids_shape = make_shared<v3::ShapeOf>(input_ids, ov::element::i64);
+ ov::Output<ov::Node> ids_shape = inputs_embeds ? get_dimensions(inputs_embeds, {0, 1})
+ : 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);
if (token_len_per_seq)
@@ -270,12 +386,24 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
inp_tokens->output(0).replace(tokens_4d->output(0));
ov::Output<ov::Node> pos_i32 = make_shared<v0::Convert>(position_ids, ov::element::i32);
- // 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).
- if (model->get_rt_info().count(gguf_imrope_key())) {
+ 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}));
+ // 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 =
+ make_shared<v0::Concat>(ov::OutputVector{v0::Constant::create(ov::element::i64, {1}, {4}), ids_shape}, 0);
+ 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);
}
@@ -283,46 +411,68 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
if (inp_pos)
inp_pos->output(0).replace(pos_4d->output(0));
- // ---- self_kq_mask [1,1,seq,kv_len] f32: 0 where attended, -inf above causal ----
- // kv_len = attention_mask length (= past + seq). query absolute positions = position_ids[0].
+ // Build one mask per sequence. Token positions exclude left padding, so keys
+ // use cumulative non-padding positions rather than their physical column index.
auto am_shape = make_shared<v3::ShapeOf>(attention_mask, ov::element::i64);
- ov::Output<ov::Node> kv_len = get_dimensions(am_shape, {1}); // [1]
-
- // Flatten position_ids to [seq] via a shape-independent Reshape({-1}) rather than Squeeze(axis=0):
- // PA also rewrites position_ids to rank-1 and Unsqueezes it to [seq,1], where squeezing axis 0
- // would fail (or drop the wrong axis).
- auto flat_shape = v0::Constant::create(ov::element::i64, {1}, {-1});
- auto q_pos = make_shared<v0::Convert>(make_shared<v1::Reshape>(position_ids, flat_shape, false),
- ov::element::i32); // [seq]
+ auto kv_len = gather_dims(am_shape, {1});
+ auto batch_len = gather_dims(ids_shape, {0});
+ auto query_len = gather_dims(ids_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});
- auto q_pos_col = make_shared<v1::Reshape>(q_pos,
- make_shared<v0::Concat>(ov::OutputVector{seq_len, one_1}, 0),
- false); // [seq, 1]
-
- auto zero_i32 = v0::Constant::create(ov::element::i32, ov::Shape{}, {0});
- auto one_i32 = v0::Constant::create(ov::element::i32, ov::Shape{}, {1});
auto squeeze_axis_0 = v0::Constant::create(ov::element::i64, {1}, {0});
- auto kv_len_i32 = make_shared<v0::Squeeze>(make_shared<v0::Convert>(kv_len, ov::element::i32),
- squeeze_axis_0); // scalar
- auto k_range = make_shared<v4::Range>(zero_i32, kv_len_i32, one_i32, ov::element::i32); // [kv_len]
- auto k_row = make_shared<v1::Reshape>(k_range,
- make_shared<v0::Concat>(ov::OutputVector{one_1, kv_len}, 0),
- false); // [1, kv_len]
-
- auto zero_f = v0::Constant::create(ov::element::f32, ov::Shape{}, {0.0f});
- auto neg_f = v0::Constant::create(ov::element::f32, ov::Shape{}, {NEG_INF});
- // [seq, kv_len] boolean predicate -> [1, 1, seq, kv_len] f32 mask (0 where attended, -inf elsewhere).
- auto to_mask_4d = [&](const ov::Output<ov::Node>& allowed_pred) {
- auto mask2d = make_shared<v1::Select>(allowed_pred, zero_f, neg_f); // [seq, kv_len] f32
- return make_shared<v1::Reshape>(mask2d,
- make_shared<v0::Concat>(ov::OutputVector{ones_1_1, seq_len, kv_len}, 0),
- false); // [1, 1, seq, kv_len]
+ auto axis_1 = v0::Constant::create(ov::element::i64, {}, {1});
+ auto one_i32 = v0::Constant::create(ov::element::i32, {}, {1});
+ auto zero_i32 = v0::Constant::create(ov::element::i32, {}, {0});
+ auto zero_f = v0::Constant::create(ov::element::f32, {}, {0.f});
+ auto neg_f = v0::Constant::create(ov::element::f32, {}, {NEG_INF});
+ const auto query_shape = make_shared<v0::Concat>(ov::OutputVector{batch_len, query_len, one_1}, 0);
+ const auto key_shape = make_shared<v0::Concat>(ov::OutputVector{batch_len, one_1, kv_len}, 0);
+ auto as_query_col = [&](const ov::Output<ov::Node>& value) {
+ return make_shared<v1::Reshape>(value, query_shape, false);
};
-
- auto allowed = make_shared<v1::LessEqual>(k_row, q_pos_col); // [seq, kv_len] bool
+ auto as_key_row = [&](const ov::Output<ov::Node>& value) {
+ return make_shared<v1::Reshape>(value, key_shape, false);
+ };
+ auto key_positions = make_shared<v1::Subtract>(
+ 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) {
+ // 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);
+ }
+ auto q_pos_col = as_query_col(q_pos);
+ auto k_row = as_key_row(key_positions);
+ auto to_mask_4d = [&](const ov::Output<ov::Node>& predicate) {
+ 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;
+ if (token_type_ids) {
+ // Only patches within the same current image can attend bidirectionally.
+ auto zeros = make_shared<v3::Broadcast>(v0::Constant::create(ov::element::i64, {}, {0}),
+ make_shared<v0::Concat>(ov::OutputVector{batch_len, past_len}, 0));
+ auto key_types = make_shared<v0::Concat>(ov::OutputVector{zeros, token_type_ids}, 1);
+ auto non_image = make_shared<v1::Equal>(key_types, v0::Constant::create(ov::element::i64, {}, {0}));
+ auto groups = make_shared<v0::CumSum>(make_shared<v0::Convert>(non_image, ov::element::i64), axis_1);
+ auto query_groups = make_shared<v8::Slice>(groups, past_len, kv_len, one_1, one_1);
+ auto same_group = make_shared<v1::Equal>(as_query_col(query_groups), as_key_row(groups));
+ auto one = v0::Constant::create(ov::element::i64, {}, {1});
+ auto images = make_shared<v1::LogicalAnd>(make_shared<v1::Equal>(as_query_col(token_type_ids), one),
+ make_shared<v1::Equal>(as_key_row(key_types), one));
+ allowed = make_shared<v1::LogicalOr>(allowed, make_shared<v1::LogicalAnd>(same_group, images));
+ }
+ auto valid_keys =
+ make_shared<v1::NotEqual>(as_key_row(attention_mask), v0::Constant::create(ov::element::i64, {}, {0}));
+ allowed = make_shared<v1::LogicalAnd>(allowed, valid_keys);
auto mask_4d = to_mask_4d(allowed);
- if (self_kq_mask)
- self_kq_mask->output(0).replace(mask_4d->output(0));
+ if (self_kq_mask) {
+ // Gemma4 permits bidirectional image attention only in sliding-window layers.
+ const bool causal_global = token_type_ids && arch == "gemma4";
+ auto global_mask = causal_global ? to_mask_4d(make_shared<v1::LogicalAnd>(causal, valid_keys)) : mask_4d;
+ self_kq_mask->output(0).replace(global_mask->output(0));
+ }
// Sliding-window mask: for prompts within the window this equals the full causal mask, but
// once the context (prompt + generated tokens) exceeds it, reusing the causal mask would
@@ -347,6 +497,47 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
self_kq_mask_swa->output(0).replace(swa_mask_4d);
}
+ if (batchable_recurrent) {
+ const auto& states = model->get_rt_info().at(gguf_recurrent_states_key()).as<std::vector<std::string>>();
+ // Left-padding must not seed the causal convolution with padding embeddings. The
+ // Slice -> Unsqueeze -> Convert order matches the gate EliminateConvPaddingMaskGating
+ // removes for packed PagedAttention sequences.
+ auto current_mask = make_shared<v8::Slice>(attention_mask, past_len, kv_len, one_1, one_1);
+ auto recurrent_mask =
+ make_shared<v0::Convert>(make_shared<v0::Unsqueeze>(current_mask, one_1), ov::element::f32);
+ const auto feeds_convolution = [](const ov::Node& node) {
+ const auto targets = node.output(0).get_target_inputs();
+ return std::any_of(targets.begin(), targets.end(), [](const ov::Input<ov::Node>& target) {
+ return ov::is_type<v1::GroupConvolution>(target.get_node()) && target.get_index() == 0;
+ });
+ };
+ for (const auto& node : model->get_ops()) {
+ const auto read = ov::as_type_ptr<v6::ReadValue>(node);
+ if (!read || std::find(states.begin(), states.end(), read->get_variable_id()) == states.end())
+ continue;
+ auto info = read->get_variable()->get_info();
+ auto tail = info.data_shape.to_shape();
+ tail.erase(tail.begin());
+ auto initializer_shape = make_shared<v0::Concat>(
+ ov::OutputVector{batch_len, v0::Constant::create(ov::element::i64, {tail.size()}, tail)},
+ 0);
+ read->input(0).replace_source_output(
+ make_shared<v3::Broadcast>(v0::Constant::create(info.data_type, {}, {0}), initializer_shape));
+ info.data_shape[0] = ov::Dimension::dynamic();
+ read->get_variable()->update(info);
+ const auto consumers = read->output(0).get_target_inputs();
+ auto reordered = make_shared<v8::Gather>(read, beam_idx, v0::Constant::create(ov::element::i64, {}, {0}));
+ for (auto consumer : consumers) {
+ consumer.replace_source_output(reordered);
+ // A causal convolution window: [reordered state | current tokens].
+ auto* window = ov::as_type<v0::Concat>(consumer.get_node());
+ if (window && consumer.get_index() == 0 && window->get_input_size() == 2 && feeds_convolution(*window))
+ window->input(1).replace_source_output(
+ make_shared<v1::Multiply>(window->input_value(1), recurrent_mask));
+ }
+ }
+ }
+
// inp_out_ids selects which rows the output head runs on. Emit the LAST row only: genai reads
// just the final token's logits, so projecting every prompt position to vocab costs an extra
// (tokens - 1) x hidden x vocab matmul per prefill.
@@ -358,8 +549,8 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
// [tokens, 1] (batch_dim=tokens, seq_dim=1), giving indices [0, 1, .., tokens - 1] -- the
// identity that layout needs, since it already carries one token per row.
if (auto inp_out_ids = find_parameter(model, "inp_out_ids")) {
- ov::Output<ov::Node> batch_dim = get_dimensions(ids_shape, {0}); // [1]: ids_shape[0]
- auto seq_dim = get_dimensions(ids_shape, {1}); // [1]: ids_shape[1]
+ auto batch_dim = gather_dims(ids_shape, {0});
+ auto seq_dim = gather_dims(ids_shape, {1});
auto seq_dim_i32 = make_shared<v0::Convert>(seq_dim, ov::element::i32);
auto last_index =
make_shared<v1::Subtract>(seq_dim_i32,
@@ -383,20 +574,78 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
}
// ---- logits: rank-4 [.., .., .., vocab] -> [b, seq, vocab] ----
- // genai always wants [batch, seq, vocab] regardless of which axis the body kept the tokens on,
- // and both layouts hold seq*vocab contiguous values, so collapse everything ahead of vocab into
- // the sequence axis with a fixed batch of 1. (batch > 1 is not part of the genai stateful
- // contract this pass targets; token_len_per_seq above is likewise a whole-input token count.)
+ // Keep the input's batch dimension, including when beam search expands it.
// Keep ownership while add_results() may reallocate the model's ResultVector below.
const std::shared_ptr<ov::op::v0::Result> old_result = model->get_results()[0];
auto logits_src = old_result->input_value(0);
- auto vocab = get_dimensions(logits_src, {-1}); // [1]
- auto batch_seq_flat = v0::Constant::create(ov::element::i64, {2}, {1, -1});
- auto logits_3d = make_shared<v1::Reshape>(logits_src,
- make_shared<v0::Concat>(ov::OutputVector{batch_seq_flat, vocab}, 0),
- false); // [1, seq, vocab]
- name_output(logits_3d, "logits");
- auto new_result = make_shared<v0::Result>(logits_3d);
+
+ // genai's gather/slice-before-matmul only finds the LM head as Result <- MatMul (optionally
+ // behind Add / Transpose / Divide -> Tanh -> Multiply) with a rank-3 input. Without it, PA
+ // prefill projects every prompt token to vocab, which exhausts GPU memory at long context.
+ std::shared_ptr<v0::MatMul> lm_head;
+ std::vector<std::shared_ptr<ov::Node>> head_chain; // ops between the head and the Result
+ for (auto out = logits_src; head_chain.size() < 4;) {
+ const auto node = out.get_node_shared_ptr();
+ if ((lm_head = ov::as_type_ptr<v0::MatMul>(node))) {
+ break;
+ }
+ if (!ov::is_type<v1::Multiply>(node) && !ov::is_type<v0::Tanh>(node)) {
+ break;
+ }
+ head_chain.push_back(node);
+ out = node->input_value(0);
+ }
+ const auto& hidden_ps = lm_head ? lm_head->get_input_partial_shape(0) : ov::PartialShape::dynamic();
+ if (lm_head && hidden_ps.rank().is_static() && hidden_ps.size() == 4 && hidden_ps[3].is_static() &&
+ lm_head->get_input_partial_shape(1).size() == 2) {
+ auto hidden_3d = make_shared<v1::Reshape>(
+ lm_head->input_value(0),
+ make_shared<v0::Concat>(
+ ov::OutputVector{batch_len,
+ v0::Constant::create(ov::element::i64, {2}, {int64_t{-1}, hidden_ps[3].get_length()})},
+ 0),
+ false); // [batch, seq, hidden]
+ lm_head->input(0).replace_source_output(hidden_3d);
+ lm_head->revalidate_and_infer_types();
+ // Softcap (x * (1/cap) -> tanh -> * cap): scalar constants keep the chain rank-3, and the
+ // first scale becomes x / cap, the form genai matches (MatMul -> Divide -> Tanh).
+ for (auto it = head_chain.rbegin(); it != head_chain.rend(); ++it) {
+ auto node = *it;
+ if (ov::is_type<v1::Multiply>(node)) {
+ const auto c = ov::as_type_ptr<v0::Constant>(node->get_input_node_shared_ptr(1));
+ if (c && ov::shape_size(c->get_shape()) == 1) {
+ const float value = c->cast_vector<float>()[0];
+ const bool first_scale = it == head_chain.rbegin() && head_chain.size() == 3;
+ const auto scalar =
+ v0::Constant::create(c->get_element_type(), {}, {first_scale ? 1.0f / value : value});
+ if (first_scale) {
+ auto div = make_shared<v1::Divide>(node->input_value(0), scalar);
+ ov::copy_runtime_info(node, div);
+ ov::replace_node(node, div);
+ continue;
+ }
+ node->input(1).replace_source_output(scalar);
+ }
+ }
+ node->revalidate_and_infer_types();
+ }
+ logits_src = old_result->input_value(0);
+ }
+
+ ov::Output<ov::Node> logits = logits_src;
+ if (logits_src.get_partial_shape().rank() != 3) {
+ const auto vocab_dim = logits_src.get_partial_shape()[logits_src.get_partial_shape().rank().get_length() - 1];
+ ov::Output<ov::Node> vocab =
+ vocab_dim.is_static() ? v0::Constant::create(ov::element::i64, {1}, {vocab_dim.get_length()})->output(0)
+ : get_dimensions(logits_src, {-1});
+ auto batch_seq_flat =
+ make_shared<v0::Concat>(ov::OutputVector{batch_len, v0::Constant::create(ov::element::i64, {1}, {-1})}, 0);
+ logits = make_shared<v1::Reshape>(logits_src,
+ make_shared<v0::Concat>(ov::OutputVector{batch_seq_flat, vocab}, 0),
+ false); // [batch, seq, vocab]
+ }
+ name_output(logits, "logits");
+ auto new_result = make_shared<v0::Result>(logits);
new_result->set_friendly_name("logits");
model->add_results({new_result});
@@ -405,13 +654,15 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
// Swap the input list to the genai contract. beam_idx is kept as-is; every other old
// gguf Parameter has had its output rewired (consumers now read the derived subgraph),
// so removing it is safe.
- model->add_parameters({input_ids, attention_mask, position_ids});
+ ov::ParameterVector kept{input_ids, attention_mask, position_ids};
+ for (const auto& p : {inputs_embeds, per_layer_inputs, token_type_ids})
+ 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 (p == input_ids || p == attention_mask || p == position_ids || p == beam_idx) {
- continue;
- }
- model->remove_parameter(p);
+ if (p != beam_idx && std::find(kept.begin(), kept.end(), p) == kept.end())
+ model->remove_parameter(p);
}
// Pin the runtime KV-cache precision to f16 for large-head models so decode matches both
@@ -423,6 +674,17 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
}
model->validate_nodes_and_infer_types();
+ if (inputs_embeds) {
+ // Detached nodes can still consume input_ids. Only reachable auxiliary branches
+ // require it in the model's input contract; get_ops() excludes detached consumers.
+ bool uses_ids = false;
+ for (const auto& node : model->get_ops()) {
+ for (const auto& input : node->input_values())
+ uses_ids |= input.get_node() == input_ids.get();
+ }
+ if (!uses_ids)
+ model->remove_parameter(input_ids);
+ }
return true;
}
diff --git a/src/frontends/gguf/src/pass/make_stateful.cpp b/src/frontends/gguf/src/pass/make_stateful.cpp
index 8b2ac5c938c..b820754f0df 100644
--- a/src/frontends/gguf/src/pass/make_stateful.cpp
+++ b/src/frontends/gguf/src/pass/make_stateful.cpp
@@ -4,26 +4,41 @@
#include "openvino/frontend/gguf/make_stateful.hpp"
+#include <algorithm>
#include <limits>
#include <memory>
+#include <optional>
#include <string>
+#include <unordered_set>
#include <vector>
#include "openvino/core/graph_util.hpp"
#include "openvino/core/rt_info.hpp"
#include "openvino/frontend/gguf/set_rows_op.hpp"
#include "openvino/op/assign.hpp"
+#include "openvino/op/broadcast.hpp"
#include "openvino/op/concat.hpp"
#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/convert_like.hpp"
#include "openvino/op/gather.hpp"
#include "openvino/op/group_conv.hpp"
#include "openvino/op/parameter.hpp"
#include "openvino/op/read_value.hpp"
#include "openvino/op/reshape.hpp"
#include "openvino/op/result.hpp"
+#include "openvino/op/scaled_dot_product_attention.hpp"
+#include "openvino/op/shape_of.hpp"
#include "openvino/op/slice.hpp"
#include "openvino/op/transpose.hpp"
#include "openvino/op/util/variable.hpp"
+#include "openvino/pass/pattern/matcher.hpp"
+#include "openvino/pass/pattern/op/label.hpp"
+#include "openvino/pass/pattern/op/optional.hpp"
+#include "openvino/pass/pattern/op/or.hpp"
+#include "openvino/pass/pattern/op/pattern.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "transformations/utils/utils.hpp"
#include "utils.hpp"
namespace ov::frontend::gguf::pass {
@@ -127,10 +142,9 @@ void normalize_causal_conv_state(const std::shared_ptr<ov::op::v0::Parameter>& s
// Restore token-major order before collapsing axes, then expose [B, C, T].
const auto token_major = std::make_shared<v1::Transpose>(window->input_value(1),
v0::Constant::create(ov::element::i64, {4}, {0, 1, 3, 2}));
- const auto pattern = v0::Constant::create(ov::element::i64,
- {3},
- std::vector<int64_t>{shape[1].get_length(), -1, shape[2].get_length()});
- const auto token_rows = std::make_shared<v1::Reshape>(token_major, pattern, false);
+ const auto pattern =
+ v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{0, -1, shape[2].get_length()});
+ const auto token_rows = std::make_shared<v1::Reshape>(token_major, pattern, true);
const auto tokens =
std::make_shared<v1::Transpose>(token_rows, v0::Constant::create(ov::element::i64, {3}, {0, 2, 1}));
state->set_partial_shape(ov::PartialShape{shape[1], shape[2], kernel});
@@ -151,6 +165,85 @@ void normalize_causal_conv_state(const std::shared_ptr<ov::op::v0::Parameter>& s
state_result->input(0).replace_source_output(new_state);
}
+// A KV read feeding SDPA: Concat -> [grouped-query broadcast] -> [type alignment] -> [Transpose].
+struct KvRead {
+ const ov::Node* concat = nullptr;
+ std::vector<int64_t> order; // empty without a Transpose
+};
+
+std::optional<KvRead> match_kv_read(const ov::Output<ov::Node>& value, const ov::ResultVector& results) {
+ using namespace ov::pass::pattern;
+ using ov::pass::operator|;
+ auto kv = wrap_type<ov::op::v0::Concat>();
+ auto present = kv | std::get<0>(ov::op::util::match_multi_query_bcst(kv));
+ // The CPU drops this type alignment before fusing.
+ auto like = any_input();
+ auto aligned = optional<ov::op::v1::ConvertLike, ov::op::v0::Convert>({present, like}) |
+ optional<ov::op::v0::Convert>({present});
+ auto order = wrap_type<ov::op::v0::Constant>();
+ Matcher matcher(aligned | wrap_type<ov::op::v1::Transpose>({aligned, order}));
+ if (!matcher.match(value))
+ return std::nullopt;
+ const auto& map = matcher.get_pattern_value_map();
+ KvRead read{map.at(kv).get_node(), {}};
+ if (map.count(order))
+ read.order = ov::as_type_ptr<ov::op::v0::Constant>(map.at(order).get_node_shared_ptr())->cast_vector<int64_t>();
+ // Nodes between the cache and SDPA must have no other readers. Walk the matched branch: the
+ // grouped-query Multiply accepts either operand order.
+ std::unordered_set<const ov::Node*> branch;
+ for (const auto& [pattern, bound] : map) {
+ if (pattern != like && !ov::is_type<ov::op::v0::Constant>(bound.get_node()))
+ branch.insert(bound.get_node());
+ }
+ for (auto node = value.get_node(); node != read.concat;) {
+ if (node->get_output_target_inputs(0).size() != 1)
+ return std::nullopt;
+ const auto inputs = node->input_values();
+ const auto next = std::find_if(inputs.begin(), inputs.end(), [&](const ov::Output<ov::Node>& input) {
+ return branch.count(input.get_node());
+ });
+ if (next == inputs.end())
+ return std::nullopt;
+ node = next->get_node();
+ }
+ // The cache feeds SDPA and Assign, plus at most a ShapeOf. Removed Results still hold inputs.
+ auto readers = read.concat->get_output_target_inputs(0);
+ for (auto it = readers.begin(); it != readers.end();) {
+ const auto* result = ov::as_type<ov::op::v0::Result>(it->get_node());
+ const bool detached = result && std::none_of(results.begin(), results.end(), [&](const auto& live) {
+ return live.get() == result;
+ });
+ it = detached ? readers.erase(it) : std::next(it);
+ }
+ const bool shape_of = std::any_of(readers.begin(), readers.end(), [](const ov::Input<ov::Node>& reader) {
+ return ov::is_type_any_of<ov::op::v0::ShapeOf, ov::op::v3::ShapeOf>(reader.get_node());
+ });
+ if (readers.size() != 2 && !(readers.size() == 3 && shape_of))
+ return std::nullopt;
+ return read;
+}
+
+// KV-cache Concats that the CPU StatefulSDPAFusion folds into a stateful SDPA.
+std::unordered_set<const ov::Node*> kv_concats_read_by_sdpa(const std::shared_ptr<ov::Model>& model) {
+ std::unordered_set<const ov::Node*> concats;
+ for (const auto& node : model->get_ops()) {
+ if (!ov::is_type<ov::op::v13::ScaledDotProductAttention>(node))
+ continue;
+ const auto key = match_kv_read(node->input_value(1), model->get_results());
+ const auto value = match_kv_read(node->input_value(2), model->get_results());
+ if (!key || !value || key->order != value->order)
+ continue;
+ if (!key->order.empty()) {
+ const auto query = ov::as_type_ptr<ov::op::v1::Transpose>(node->get_input_node_shared_ptr(0));
+ if (!query || !ov::op::util::has_constant_value(query->get_input_node_shared_ptr(1), key->order))
+ continue;
+ }
+ concats.insert(key->concat);
+ concats.insert(value->concat);
+ }
+ return concats;
+}
+
} // namespace
const std::string& gguf_recurrent_states_key() {
@@ -207,13 +300,10 @@ static bool make_recurrent_states_stateful(const std::shared_ptr<ov::Model>& mod
"' must have a fully static shape, got ",
param->get_partial_shape());
- // The Result holding this state's new value: the one whose producing node carries the
- // state's output name. The builder names that node after the state (see the VIEW cases),
- // which is why those names have to survive translation.
+ // Translation names each Result after the output it holds.
std::shared_ptr<v0::Result> state_result;
for (const auto& r : model->get_results()) {
- const auto producer = r->get_input_node_shared_ptr(0);
- if (producer->get_friendly_name().find(out_name) != std::string::npos) {
+ if (r->get_friendly_name() == out_name) {
state_result = r;
break;
}
@@ -281,6 +371,12 @@ bool GGUFMakeStateful::run_on_model(const std::shared_ptr<ov::Model>& model) {
ov::ParameterVector params_to_remove;
ov::ResultVector results_to_remove;
ov::SinkVector new_sinks;
+ struct Cache {
+ std::shared_ptr<v6::ReadValue> read_value;
+ const ov::Node* concat;
+ ov::Shape empty_shape;
+ };
+ std::vector<Cache> caches;
// Same beam_idx Gather axis for every cache; hoisted out of the loop below.
auto axis0 = v0::Constant::create(ov::element::i64, ov::Shape{}, {0});
@@ -302,6 +398,7 @@ bool GGUFMakeStateful::run_on_model(const std::shared_ptr<ov::Model>& model) {
// Variable and its initial extent is 0 (no past on the first inference). Every other axis
// keeps the Parameter's declared dimension and so must be static to build the init constant.
ov::PartialShape var_shape = ps;
+ var_shape[0] = ov::Dimension::dynamic();
var_shape[axis] = ov::Dimension::dynamic();
auto var = std::make_shared<ov::op::util::Variable>(ov::op::util::VariableInfo{var_shape, et, cache_name});
@@ -340,6 +437,7 @@ bool GGUFMakeStateful::run_on_model(const std::shared_ptr<ov::Model>& model) {
// Reorder the past by beam_idx before appending, so each beam continues its own history.
auto past = std::make_shared<v8::Gather>(read_value, beam_idx, axis0);
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(set_rows->get_friendly_name());
new_sinks.push_back(std::make_shared<v6::Assign>(concat, var));
@@ -369,6 +467,25 @@ bool GGUFMakeStateful::run_on_model(const std::shared_ptr<ov::Model>& model) {
}
finalize_stateful_rewrite(model, results_to_remove, new_sinks, params_to_remove);
+ // Fused caches must start with the beam_idx batch. Plain CPU states need a constant init:
+ // a computed one pins the empty token axis and ignores resets.
+ const auto sdpa_caches = kv_concats_read_by_sdpa(model);
+ auto batch = std::make_shared<v3::ShapeOf>(beam_idx, ov::element::i64);
+ for (const auto& cache : caches) {
+ if (!sdpa_caches.count(cache.concat))
+ continue;
+ const auto& shape = cache.empty_shape;
+ auto target = std::make_shared<v0::Concat>(
+ ov::OutputVector{batch,
+ v0::Constant::create(ov::element::i64,
+ {shape.size() - 1},
+ std::vector<int64_t>(shape.begin() + 1, shape.end()))},
+ 0);
+ cache.read_value->input(0).replace_source_output(
+ std::make_shared<v3::Broadcast>(v0::Constant::create(cache.read_value->get_output_element_type(0), {}, {0}),
+ target));
+ }
+
// Recurrent states are independent of the KV caches; a hybrid stack (qwen35) has both.
make_recurrent_states_stateful(model);
diff --git a/src/frontends/gguf/src/quant/gguf.cpp b/src/frontends/gguf/src/quant/gguf.cpp
index b8878b106f8..971497aa560 100644
--- a/src/frontends/gguf/src/quant/gguf.cpp
+++ b/src/frontends/gguf/src/quant/gguf.cpp
@@ -95,10 +95,8 @@ TypeTraits type_traits(uint32_t type) {
}
}
-// Layout of the REPACKED tensors a quantized GGUF type is unpacked into: the element types and
-// shapes the gguf_fill_* functions write into quant_buf. Single source of truth for both the
-// pass-1 size reservation and the pass-2 view carving below, so the two cannot disagree about a
-// divisor. Returns nullopt for the non-quantized types, which are mmap views instead.
+// Repacked tensor types and shape divisors shared by validation and allocation.
+// Non-quantized tensors use mmap views instead.
struct QuantLayout {
ov::element::Type weight_type; // element type of the repacked weight blob
size_t weight_div; // innermost-dim divisor of the weight shape (8 = u32-packed u4)
@@ -133,8 +131,9 @@ std::optional<QuantLayout> quant_layout(uint32_t type) {
case GGUF_TYPE_Q4_K:
return QuantLayout{ov::element::u32, 8, ov::element::f16, 32, asymmetric};
case GGUF_TYPE_Q5_1:
- case GGUF_TYPE_Q5_K:
return QuantLayout{ov::element::i8, 1, ov::element::f16, 32, asymmetric};
+ case GGUF_TYPE_Q5_K:
+ return QuantLayout{ov::element::u8, 1, ov::element::f16, 32, asymmetric};
case GGUF_TYPE_MXFP4:
return QuantLayout{ov::element::f4e2m1, 1, ov::element::f8e8m0, 32, symmetric};
default:
@@ -496,13 +495,7 @@ GGUFLoad get_gguf_data(const std::string& file) {
// Tensor data starts at the next `alignment`-aligned offset after the info section.
uint64_t data_off = cur.offset() + ov::util::align_padding_size(alignment, cur.offset());
- // Bytes the repacked (weight, scale, zero-point) tensors of a quantized tensor occupy in
- // quant_buf, derived from its QuantLayout. Symmetric types have no zero-point; asymmetric
- // ones use the element type selected by gguf_zero_point_type.
- //
- // Every dim comes straight from the file, so the element and byte counts go through the
- // overflow-checked ov::util helpers: a wrapped product could otherwise under-size quant_buf
- // while the fill functions still write the real, attacker-controlled shape into it.
+ // Validate file-controlled shapes before allocating repacked tensors.
auto quant_sizes = [](const TensorInfo& ti, const QuantLayout& ql) -> std::array<size_t, 3> {
const ov::Shape shape = [&ti]() {
ov::Shape s;
@@ -530,26 +523,12 @@ GGUFLoad get_gguf_data(const std::string& file) {
return {bytes(ql.weight_type, weight_shape), bytes(ql.scale_type, scale_shape), z_bytes};
};
- // ---- Pass 1: size, and record, every tensor's slice of the repacked quantized data ----
- std::vector<std::array<size_t, 3>> quant_bytes(infos.size(), {0, 0, 0});
- size_t total_quant_bytes = 0;
- for (size_t i = 0; i < infos.size(); ++i) {
- const auto layout = quant_layout(infos[i].type);
- if (!layout) {
- continue;
- }
- quant_bytes[i] = quant_sizes(infos[i], *layout);
- for (const size_t part : quant_bytes[i]) {
- const bool overflow = ov::util::add_overflow(total_quant_bytes, part, total_quant_bytes);
- OPENVINO_ASSERT(!overflow, "[load_gguf] total quantized buffer size overflows size_t");
+ for (const auto& info : infos) {
+ if (const auto layout = quant_layout(info.type)) {
+ quant_sizes(info, *layout);
}
}
- // Single allocation for all repacked quantized data (IR-frontend AlignedBuffer pattern).
- auto quant_buf = std::make_shared<ov::AlignedBuffer>(total_quant_bytes > 0 ? total_quant_bytes : 1);
-
- // ---- Pass 2: materialize tensors, slicing into quant_buf for quantized ones ----
- size_t quant_offset = 0;
for (size_t idx = 0; idx < infos.size(); ++idx) {
const TensorInfo& ti = infos[idx];
GgufTensor tensor;
@@ -571,7 +550,7 @@ GGUFLoad get_gguf_data(const std::string& file) {
// ne[0] % 256 == 0 for Q6_K). Without this, a crafted or truncated file's flooring
// integer division below silently produces a `bsize` that disagrees with the
// independently-flooring `scale_shape` computed in quant_sizes, letting fill_* write
- // scales past the end of its (too-small) AlignedBuffer slice.
+ // scales past the end of its allocated tensor.
OPENVINO_ASSERT(ti.dim[0] % tr.items_per_block == 0,
"[load_gguf] tensor '",
ti.name,
@@ -612,22 +591,12 @@ GGUFLoad get_gguf_data(const std::string& file) {
ov::Shape scale_shape = shape;
scale_shape.back() /= layout->group_size;
- // Carve each repacked tensor out of the single quant_buf allocation, in the same order
- // and with the same sizes pass 1 reserved for it.
- char* buf_ptr = quant_buf->get_ptr<char>();
- std::shared_ptr<void> so_buf(quant_buf);
- size_t part = 0;
- const auto carve = [&](const ov::element::Type& et, const ov::Shape& s) {
- ov::Tensor view(et, s, static_cast<void*>(buf_ptr + quant_offset));
- quant_offset += quant_bytes[idx][part++];
- return ov::Tensor(view, so_buf);
- };
- ov::Tensor weights = carve(layout->weight_type, weight_shape);
- ov::Tensor scales = carve(layout->scale_type, scale_shape);
+ // Independent buffers let replaced weights be freed without retaining the whole model.
+ ov::Tensor weights(layout->weight_type, weight_shape);
+ ov::Tensor scales(layout->scale_type, scale_shape);
ov::Tensor zp;
if (layout->asymmetric) {
- // Preserve the native zero-point representation, including u8 for Q2_0.
- zp = carve(gguf_zero_point_type(name, static_cast<GgufTensorType>(ti.type)), scale_shape);
+ zp = ov::Tensor(gguf_zero_point_type(name, static_cast<GgufTensorType>(ti.type)), scale_shape);
}
if (ti.type == GGUF_TYPE_MXFP4) {
@@ -649,7 +618,7 @@ GGUFLoad get_gguf_data(const std::string& file) {
qtype.emplace(name_prefix + ".qtype", static_cast<GgufTensorType>(ti.type));
}
- return {std::move(metadata), std::move(arrays), std::move(qtype), std::move(mapped), std::move(quant_buf)};
+ return {std::move(metadata), std::move(arrays), std::move(qtype), std::move(mapped)};
}
std::map<std::string, GGUFMetaData> decoder_config_from_meta(
@@ -695,7 +664,11 @@ std::map<std::string, GGUFMetaData> decoder_config_from_meta(
}
config["hidden_size"] = metadata_to_int(metadata, arch + ".embedding_length");
config["max_position_embeddings"] = metadata_to_int_or(metadata, arch + ".context_length", 2048);
- config["rms_norm_eps"] = metadata_to_float(metadata, arch + ".attention.layer_norm_rms_epsilon");
+ config["pooling_type"] = metadata_to_int_or(metadata, arch + ".pooling_type", 0);
+ config["causal_attention"] = metadata_to_bool_or(metadata, arch + ".attention.causal", true) ? 1 : 0;
+ config["rms_norm_eps"] = metadata_to_float(
+ metadata,
+ arch + (arch == "jais2" ? ".attention.layer_norm_epsilon" : ".attention.layer_norm_rms_epsilon"));
config["rope_freq_base"] = metadata_to_float_or(metadata, arch + ".rope.freq_base", 10000.0f);
// Advisory: the dominant quant type of the file. Purely informational -- every weight carries
// its own type in the tensor info, which is what the dequant path uses. Optional because
@@ -816,7 +789,8 @@ std::map<std::string, GGUFMetaData> decoder_config_from_meta(
// absent (it does not reset to the global base first, unlike gemma2/gemma4/cohere2/etc.), so
// gemma3 SWA layers rope at freq_base=10000 while global layers use 1000000. See
// llama.cpp src/models/gemma3.cpp load_arch_hparams.
- const float def_freq_base_swa = (arch == "gemma3") ? 10000.0f : std::get<float>(config["rope_freq_base"]);
+ const float def_freq_base_swa =
+ (arch == "gemma3" || arch == "plamo3") ? 10000.0f : std::get<float>(config["rope_freq_base"]);
config["rope_freq_base_swa"] = metadata_to_float_or(metadata, arch + ".rope.freq_base_swa", def_freq_base_swa);
// has_swa: true when the GGUF carries either a sliding_window_pattern or a
@@ -867,7 +841,10 @@ std::map<std::string, GGUFMetaData> decoder_config_from_meta(
} else {
// No explicit pattern key. gemma3 defaults to period 6 (llama.cpp gemma3 load_arch_hparams
// passes swa_period=6 to get_key_or_arr); gpt-oss and others default to 2.
- config["swa_layer_pattern"] = arch == "gemma3" ? 6 : arch == "exaone4" ? 4 : 2;
+ config["swa_layer_pattern"] = arch == "gemma3" ? 6
+ : arch == "plamo3" ? 8
+ : (arch == "exaone4" || arch == "exaone-moe") ? 4
+ : 2;
config["swa_layer_flags"] = std::vector<int32_t>{};
}
@@ -878,7 +855,10 @@ std::map<std::string, GGUFMetaData> decoder_config_from_meta(
config["moe_layer_step"] = metadata_to_int_or(metadata, arch + ".interleave_moe_layer_step", 1);
config["expert_groups"] = metadata_to_int_or(metadata, arch + ".expert_group_count", 1);
config["expert_groups_used"] = metadata_to_int_or(metadata, arch + ".expert_group_used_count", 1);
- config["expert_gating_func"] = metadata_to_int_or(metadata, arch + ".expert_gating_func", 1);
+ auto expert_gating_func = metadata_to_int_or(metadata, arch + ".expert_gating_func", arch == "glm4moe" ? 2 : 1);
+ if (arch == "glm4moe" && expert_gating_func == 0)
+ expert_gating_func = 2;
+ config["expert_gating_func"] = expert_gating_func;
config["expert_weights_norm"] = metadata_to_bool_or(metadata, arch + ".expert_weights_norm", false) ? 1 : 0;
// Gemma2 attention soft-cap: tanh(QK^T * (1/cap)) * cap applied inside the attention.
diff --git a/src/frontends/gguf/src/quant/gguf.hpp b/src/frontends/gguf/src/quant/gguf.hpp
index 2f78bcd5de2..5786e1247ca 100644
--- a/src/frontends/gguf/src/quant/gguf.hpp
+++ b/src/frontends/gguf/src/quant/gguf.hpp
@@ -11,7 +11,6 @@
#include <variant>
#include <vector>
-#include "openvino/runtime/aligned_buffer.hpp"
#include "openvino/runtime/tensor.hpp"
#include "openvino/util/mmap_object.hpp"
@@ -86,15 +85,11 @@ struct GgufTensor {
using GGUFMetaData =
std::variant<std::monostate, float, int, ov::Tensor, std::string, std::vector<std::string>, std::vector<int32_t>>;
-// GGUFLoad result: (metadata, tensor arrays, qtype map, mmap, quant_buf).
-// - mmap: must stay alive while arrays tensors are used (non-quantized tensors are mmap views).
-// - quant_buf: single AlignedBuffer holding all repacked quantized weight/scale/bias data;
-// tensors in `arrays` for quantized weights are SharedBuffer slices into this buffer.
+// Parsed arrays own repacked quantized buffers and keep non-quantized mmap views alive.
using GGUFLoad = std::tuple<std::unordered_map<std::string, GGUFMetaData>,
std::unordered_map<std::string, ov::Tensor>,
std::unordered_map<std::string, GgufTensorType>,
- std::shared_ptr<ov::MappedMemory>,
- std::shared_ptr<ov::AlignedBuffer>>;
+ std::shared_ptr<ov::MappedMemory>>;
// Fill pre-allocated weights and f16 scales from a symmetric GGUF tensor
// (Q8_0/Q5_0/Q6_K: i8 weights; Q4_0/Q3_K: i4 weights packed as u8).
@@ -134,10 +129,7 @@ void dequant_row_q4_k_f32_for_test(const uint8_t* row, size_t cols, float* y);
void dequant_row_q5_k_f32_for_test(const uint8_t* row, size_t cols, float* y);
void dequant_row_q6_k_f32_for_test(const uint8_t* row, size_t cols, float* y);
-// Parse a GGUF file: returns (metadata, tensors-by-ggml-name, qtype map, mmap, quant_buf).
-// Non-quantized tensors are zero-copy views into the mmap (mmap must outlive arrays use).
-// Quantized tensors are SharedBuffer slices of a single AlignedBuffer (quant_buf) so all
-// repacked weight/scale/bias data lives in one allocation (IR-frontend pattern).
+// Parse GGUF metadata and tensors. Each repacked quantized tensor owns its buffer.
GGUFLoad get_gguf_data(const std::string& file);
// Extract the DECODER-family architecture config (architecture, layer_num, head_num, head_size,
diff --git a/src/frontends/gguf/src/quant/gguf_quants.cpp b/src/frontends/gguf/src/quant/gguf_quants.cpp
index 45ff3b55521..3649ecc2300 100644
--- a/src/frontends/gguf/src/quant/gguf_quants.cpp
+++ b/src/frontends/gguf/src/quant/gguf_quants.cpp
@@ -138,21 +138,146 @@ static inline void unpack_q5_block(const uint8_t* qh_ql, int8_t* dst, int bias)
}
}
+// Requantize one 32-value group with source values sc * source_q[k] - offset (source_q in
+// [0..15]) onto a NEW u4 grid with an integer zero-point, and pack it as 16 bytes of nibbles.
+// The algorithm follows NNCF's data-free INT4_ASYM baseline (range includes zero, min/max scale,
+// integral clipped zp), followed by one cheap least-squares scale refinement. Candidate errors
+// are evaluated with the actually stored f16 scale. A candidate is used only when it reduces
+// squared error without increasing the maximum error versus the rounded-zp representation of
+// the source nibbles.
+static void requantize_group_u4(const uint8_t* source_q,
+ float sc,
+ float offset,
+ ov::float16& out_scale,
+ uint8_t& out_zp,
+ uint8_t* out_packed) {
+ float values[32];
+ float min_value = 0.0f;
+ float max_value = 0.0f;
+ for (int k = 0; k < 32; ++k) {
+ values[k] = sc * static_cast<float>(source_q[k]) - offset;
+ min_value = std::min(min_value, values[k]);
+ max_value = std::max(max_value, values[k]);
+ }
+
+ struct Error {
+ double squared;
+ float max_abs;
+ };
+ const auto measure = [&](float runtime_scale, uint8_t zp, const uint8_t* quantized) {
+ Error error{0.0, 0.0f};
+ for (int k = 0; k < 32; ++k) {
+ const float diff = values[k] - runtime_scale * (static_cast<int>(quantized[k]) - zp);
+ error.squared += static_cast<double>(diff) * diff;
+ error.max_abs = std::max(error.max_abs, std::fabs(diff));
+ }
+ return error;
+ };
+
+ // Start from the previous compressed-FC representation. Requantization must not
+ // regress either its total error or its worst reconstructed value.
+ uint8_t best_q[32];
+ std::copy_n(source_q, 32, best_q);
+ ov::float16 best_scale(sc);
+ uint8_t best_zp = quantize_zp_u8(zp_from_offset(offset, sc));
+ Error best_error = measure(static_cast<float>(best_scale), best_zp, best_q);
+ const float fallback_max_error = best_error.max_abs;
+
+ float initial_scale = (max_value - min_value) / 15.0f;
+ if (std::fabs(initial_scale) < std::numeric_limits<float>::epsilon()) {
+ initial_scale = std::numeric_limits<float>::epsilon();
+ }
+ const auto rounded_zp = static_cast<long>(std::nearbyint(-min_value / initial_scale));
+ const uint8_t zp = static_cast<uint8_t>(std::clamp(rounded_zp, 0L, 15L));
+
+ const auto evaluate = [&](float scale_candidate, uint8_t* quantized) {
+ const ov::float16 scale_f16(scale_candidate);
+ const float runtime_scale = static_cast<float>(scale_f16);
+ if (!(runtime_scale > 0.0f) || !std::isfinite(runtime_scale)) {
+ return std::make_pair(
+ scale_f16,
+ Error{std::numeric_limits<double>::infinity(), std::numeric_limits<float>::infinity()});
+ }
+ for (int k = 0; k < 32; ++k) {
+ const long rounded = static_cast<long>(std::nearbyint(values[k] / runtime_scale)) + zp;
+ quantized[k] = static_cast<uint8_t>(std::clamp(rounded, 0L, 15L));
+ }
+ return std::make_pair(scale_f16, measure(runtime_scale, zp, quantized));
+ };
+
+ const auto accept = [&](const std::pair<ov::float16, Error>& candidate, const uint8_t* candidate_q) {
+ const auto& [scale, error] = candidate;
+ if (error.squared < best_error.squared && error.max_abs <= fallback_max_error) {
+ best_scale = scale;
+ best_zp = zp;
+ best_error = error;
+ std::copy_n(candidate_q, 32, best_q);
+ }
+ };
+
+ uint8_t candidate_q[32];
+ auto candidate = evaluate(initial_scale, candidate_q);
+ accept(candidate, candidate_q);
+
+ // With the min/max assignments fixed, this is the least-squares optimal scale for
+ // x ~= scale * (q-zp). Requantize once more with it and retain it only if the actual
+ // f16-scale reconstruction improves both criteria versus the retained representation.
+ double numerator = 0.0;
+ double denominator = 0.0;
+ for (int k = 0; k < 32; ++k) {
+ const int centered = static_cast<int>(candidate_q[k]) - zp;
+ numerator += static_cast<double>(values[k]) * centered;
+ denominator += static_cast<double>(centered) * centered;
+ }
+ if (denominator != 0.0) {
+ candidate = evaluate(static_cast<float>(numerator / denominator), candidate_q);
+ accept(candidate, candidate_q);
+ }
+
+ out_scale = best_scale;
+ out_zp = best_zp;
+ std::fill_n(out_packed, 16, 0);
+ for (int k = 0; k < 32; ++k) {
+ out_packed[k / 2] |= static_cast<uint8_t>(best_q[k] << (4 * (k % 2)));
+ }
+}
+
// Q4_1 asymmetric: block = |f16 scale|f16 min|32x4bit weights|.
// Dequant w = sc*q + mn = sc*(q - zp), zp = -mn/sc.
-// Outputs u32-packed u4 weights + f16 scales + zero-points (one per block).
+// Outputs u32-packed u4 weights + f16 scales + zero-points (one per block). With a u8 zp the
+// block is requantized to a new u4 grid with an integer zero-point, like Q4_K. Unlike Q4_K, a
+// Q4_1 block need not contain zero, and a one-sided block then gets a coarser grid that does.
void fill_q4_1(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr, ov::Tensor& zp_arr) {
const uint64_t bytes_per_block = 20; // 2 bytes scale, 2 bytes min, 32x0.5 byte weights
auto data = static_cast<const uint8_t*>(tensor.weights_data);
auto weights = static_cast<uint8_t*>(weights_arr.data());
auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
const ZeroPointWriter zp(zp_arr);
+ if (zp.is_integer()) {
+ notify_lossy_weight_approximation(LossyWeightApproximation::Q4_REQUANT);
+ }
ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
- const float sc = static_cast<float>(ov::float16::from_bits(*((uint16_t*)(data + i * bytes_per_block))));
- const float mn = static_cast<float>(ov::float16::from_bits(*((uint16_t*)(data + i * bytes_per_block + 2))));
- scales[i] = ov::float16(sc);
- zp.store(i, zp_from_offset(-mn, sc));
- unpack_32_4(data + i * bytes_per_block + 4, weights + i * 16);
+ const uint8_t* block = data + i * bytes_per_block;
+ const float sc = static_cast<float>(ov::float16::from_bits(*((uint16_t*)block)));
+ const float mn = static_cast<float>(ov::float16::from_bits(*((uint16_t*)(block + 2))));
+ if (!zp.is_integer()) {
+ scales[i] = ov::float16(sc);
+ zp.store(i, zp_from_offset(-mn, sc));
+ unpack_32_4(block + 4, weights + i * 16);
+ return;
+ }
+ OPENVINO_ASSERT(std::isfinite(sc) && std::isfinite(mn),
+ "[GGUF] Q4_1 block ",
+ i,
+ " has non-finite scale metadata");
+ uint8_t source_q[32];
+ for (int k = 0; k < 16; ++k) {
+ source_q[k] = block[4 + k] & 0x0F;
+ source_q[k + 16] = block[4 + k] >> 4;
+ }
+ uint8_t zp_value = 0;
+ requantize_group_u4(source_q, sc, -mn, scales[i], zp_value, weights + i * 16);
+ zp.store_integer(i, zp_value);
});
}
@@ -210,12 +335,8 @@ void unpack_256_4(const uint8_t* data, uint8_t* dst) {
// Dequant is w = scale*q - min, scale = d*sc_raw, min = dmin*m_raw.
//
// With an f16 zp, preserve the source nibbles and express the exact affine offset as min/scale.
-// With a u8 zp, faithfully decode one 32-value group to f32 and requantize it to a NEW u4 grid.
-// The latter follows NNCF's data-free INT4_ASYM baseline (range includes zero, min/max scale,
-// integral clipped zp), followed by one cheap least-squares scale refinement. Candidate errors
-// are evaluated with the actually stored f16 scale. A candidate is used only when it reduces
-// squared error without increasing the maximum error versus the former rounded-zp representation.
-// Only 32 f32 values are live per worker.
+// With a u8 zp, faithfully decode one 32-value group to f32 and requantize it to a NEW u4 grid
+// (see requantize_group_u4). Only 32 f32 values are live per worker.
void fill_q4_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr, ov::Tensor& zp_arr) {
const uint64_t bytes_per_block = kQ4K_BLOCK_BYTES;
const uint64_t n_super_block = tensor.bsize / bytes_per_block;
@@ -225,7 +346,7 @@ void fill_q4_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& sc
const ZeroPointWriter zp_out(zp_arr);
if (zp_out.is_integer()) {
// An integer zero-point means this tensor is being requantized onto a new u4 grid below.
- notify_lossy_weight_approximation(LossyWeightApproximation::Q4_K_REQUANT);
+ notify_lossy_weight_approximation(LossyWeightApproximation::Q4_REQUANT);
}
ov::parallel_for(n_super_block, [&](size_t i) {
@@ -250,100 +371,14 @@ void fill_q4_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& sc
continue;
}
- float values[32];
uint8_t source_q[32];
const uint8_t* source = block_data + 16 + (j / 2) * 32;
- float min_value = 0.0f;
- float max_value = 0.0f;
- for (int k = 0; k < 32; ++k) {
- const uint8_t q = (j % 2 == 0) ? (source[k] & 0x0F) : (source[k] >> 4);
- source_q[k] = q;
- values[k] = sc * static_cast<float>(q) - mn;
- min_value = std::min(min_value, values[k]);
- max_value = std::max(max_value, values[k]);
- }
-
- struct Error {
- double squared;
- float max_abs;
- };
- const auto measure = [&](float runtime_scale, uint8_t zp, const uint8_t* quantized) {
- Error error{0.0, 0.0f};
- for (int k = 0; k < 32; ++k) {
- const float diff = values[k] - runtime_scale * (static_cast<int>(quantized[k]) - zp);
- error.squared += static_cast<double>(diff) * diff;
- error.max_abs = std::max(error.max_abs, std::fabs(diff));
- }
- return error;
- };
-
- // Start from the previous compressed-FC representation. Requantization must not
- // regress either its total error or its worst reconstructed value.
- uint8_t best_q[32];
- std::copy_n(source_q, 32, best_q);
- ov::float16 best_scale(sc);
- uint8_t best_zp = quantize_zp_u8(zp_from_offset(mn, sc));
- Error best_error = measure(static_cast<float>(best_scale), best_zp, best_q);
- const float fallback_max_error = best_error.max_abs;
-
- float initial_scale = (max_value - min_value) / 15.0f;
- if (std::fabs(initial_scale) < std::numeric_limits<float>::epsilon()) {
- initial_scale = std::numeric_limits<float>::epsilon();
- }
- const auto rounded_zp = static_cast<long>(std::nearbyint(-min_value / initial_scale));
- const uint8_t zp = static_cast<uint8_t>(std::clamp(rounded_zp, 0L, 15L));
-
- const auto evaluate = [&](float scale_candidate, uint8_t* quantized) {
- const ov::float16 scale_f16(scale_candidate);
- const float runtime_scale = static_cast<float>(scale_f16);
- if (!(runtime_scale > 0.0f) || !std::isfinite(runtime_scale)) {
- return std::make_pair(
- scale_f16,
- Error{std::numeric_limits<double>::infinity(), std::numeric_limits<float>::infinity()});
- }
- for (int k = 0; k < 32; ++k) {
- const long rounded = static_cast<long>(std::nearbyint(values[k] / runtime_scale)) + zp;
- quantized[k] = static_cast<uint8_t>(std::clamp(rounded, 0L, 15L));
- }
- return std::make_pair(scale_f16, measure(runtime_scale, zp, quantized));
- };
-
- const auto accept = [&](const std::pair<ov::float16, Error>& candidate, const uint8_t* candidate_q) {
- const auto& [scale, error] = candidate;
- if (error.squared < best_error.squared && error.max_abs <= fallback_max_error) {
- best_scale = scale;
- best_zp = zp;
- best_error = error;
- std::copy_n(candidate_q, 32, best_q);
- }
- };
-
- uint8_t candidate_q[32];
- auto candidate = evaluate(initial_scale, candidate_q);
- accept(candidate, candidate_q);
-
- // With the min/max assignments fixed, this is the least-squares optimal scale for
- // x ~= scale * (q-zp). Requantize once more with it and retain it only if the actual
- // f16-scale reconstruction improves both criteria versus the retained representation.
- double numerator = 0.0;
- double denominator = 0.0;
for (int k = 0; k < 32; ++k) {
- const int centered = static_cast<int>(candidate_q[k]) - zp;
- numerator += static_cast<double>(values[k]) * centered;
- denominator += static_cast<double>(centered) * centered;
- }
- if (denominator != 0.0) {
- candidate = evaluate(static_cast<float>(numerator / denominator), candidate_q);
- accept(candidate, candidate_q);
- }
-
- scales[i * 8 + j] = best_scale;
- zp_out.store_integer(i * 8 + j, best_zp);
- uint8_t* destination = weights + i * 128 + j * 16;
- std::fill_n(destination, 16, 0);
- for (int k = 0; k < 32; ++k) {
- destination[k / 2] |= static_cast<uint8_t>(best_q[k] << (4 * (k % 2)));
+ source_q[k] = (j % 2 == 0) ? (source[k] & 0x0F) : (source[k] >> 4);
}
+ uint8_t zp_value = 0;
+ requantize_group_u4(source_q, sc, mn, scales[i * 8 + j], zp_value, weights + i * 128 + j * 16);
+ zp_out.store_integer(i * 8 + j, zp_value);
}
if (!zp_out.is_integer()) {
unpack_256_4(block_data + 16, weights + i * 128);
@@ -477,16 +512,54 @@ void dequant_row_q6_k_f32_for_test(const uint8_t* row, size_t cols, float* y) {
}
// Q5_K asymmetric: super-block = 2(d) + 2(dmin) + 12(scales) + 32(qh) + 128(ql).
-// 8 sub-blocks of 32 with 6-bit scale and 6-bit min. Output: i8 weights + f16 scales + zp.
-// Like Q4_K, dequant is w = scale*q - dmin*m; zp = dmin*m/scale. The zp element type selects
-// integer (u8, fuses) vs fractional (f16, faithful) -- see fill_q4_k.
+// 8 sub-blocks of 32 with 6-bit scale and 6-bit min. Output: u8 weights + f16 scales + zp.
+// Like Q4_K, dequant is w = scale*q - dmin*m; zp = dmin*m/scale. With an f16 zp the source
+// 5-bit values [0..31] are kept as they are (faithful). With a u8 zp each 32-value group is
+// decoded to f32 and requantized to a NEW 8-bit grid: min/max range including zero, integral
+// zp. The 8-bit grid is ~8x finer than the 5-bit source, so the added error stays far below
+// one source step, and the integer zp lets the dequant fold into a compressed FullyConnected.
void fill_q5_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr, ov::Tensor& zp_arr) {
const uint64_t bytes_per_block = kQ5K_BLOCK_BYTES;
const uint64_t n_super_block = tensor.bsize / bytes_per_block;
auto data = static_cast<const uint8_t*>(tensor.weights_data);
- auto weights = static_cast<int8_t*>(weights_arr.data());
+ auto weights = static_cast<uint8_t*>(weights_arr.data());
auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
const ZeroPointWriter zp(zp_arr);
+ if (zp.is_integer()) {
+ notify_lossy_weight_approximation(LossyWeightApproximation::Q5_K_REQUANT);
+ }
+
+ // 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));
+ }
+ };
ov::parallel_for(n_super_block, [&](size_t i) {
const uint8_t* block_data = data + i * bytes_per_block;
@@ -504,14 +577,13 @@ void fill_q5_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& sc
const float d1 = d * sc, m1 = dmin * m;
get_scale_min_k4(is + 1, scales_data, &sc, &m);
const float d2 = d * sc, m2 = dmin * m;
- scales[i * 8 + is] = ov::float16(d1);
- scales[i * 8 + is + 1] = ov::float16(d2);
- zp.store(i * 8 + is, zp_from_offset(m1, d1));
- zp.store(i * 8 + is + 1, zp_from_offset(m2, d2));
+ uint8_t q1[32], q2[32];
for (int l = 0; l < 32; ++l) {
- weights[i * 256 + j + l] = static_cast<int8_t>((ql[l] & 0xF) + ((qh[l] & u1) ? 16 : 0));
- weights[i * 256 + j + l + 32] = static_cast<int8_t>((ql[l] >> 4) + ((qh[l] & u2) ? 16 : 0));
+ 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);
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 cc51f252c49..c8adfe65712 100644
--- a/src/frontends/gguf/src/quant/weights.cpp
+++ b/src/frontends/gguf/src/quant/weights.cpp
@@ -86,8 +86,9 @@ WeightFormat get_weight_format(GgufTensorType qtype) {
case GGUF_TYPE_Q4_K:
return {FillKind::ASYMMETRIC, 32, ov::element::u32};
case GGUF_TYPE_Q5_1:
- case GGUF_TYPE_Q5_K:
return {FillKind::ASYMMETRIC, 32, ov::element::i8};
+ case GGUF_TYPE_Q5_K:
+ return {FillKind::ASYMMETRIC, 32, ov::element::u8};
case GGUF_TYPE_F16:
case GGUF_TYPE_F32:
case GGUF_TYPE_BF16:
@@ -149,11 +150,11 @@ ov::Shape per_group_shape(const ov::Shape& orig, size_t num_groups) {
return s;
}
-// Build a low-bit weight Constant wrapping `weight`'s bytes (no copy: the ov::Tensor is held
+// Build a Constant with an explicit shape wrapping `weight`'s bytes (no copy: the Tensor is held
// alive by the Constant's shared buffer).
-std::shared_ptr<ov::op::v0::Constant> make_compressed_weight_constant(ov::element::Type et,
- const ov::Shape& shape,
- const ov::Tensor& weight) {
+std::shared_ptr<ov::op::v0::Constant> make_shared_constant(ov::element::Type et,
+ const ov::Shape& shape,
+ const ov::Tensor& weight) {
// Shared-buffer ctor: the Constant wraps the bytes without copying and keeps the Tensor alive.
return std::make_shared<ov::op::v0::Constant>(et,
shape,
@@ -176,19 +177,17 @@ std::shared_ptr<ov::Node> make_compressed(const WeightTensors& tensors, ov::elem
const size_t num_groups = tensors.scales.get_shape().back();
const auto scale_shape = per_group_shape(orig_shape, num_groups);
- ov::Tensor scales = tensors.scales;
- scales.set_shape(scale_shape);
- ov::Tensor zp_t = tensors.zero_point;
- if (zp_t) {
- zp_t.set_shape(scale_shape);
- }
-
auto weights_node =
- make_compressed_weight_constant(et,
- grouped_weight_shape(orig_shape, num_groups, orig_shape.back() / num_groups),
- tensors.weight);
- auto scales_node = std::make_shared<ov::op::v0::Constant>(scales);
- const auto zp_node = zp_t ? std::make_shared<ov::op::v0::Constant>(zp_t) : nullptr;
+ make_shared_constant(et,
+ grouped_weight_shape(orig_shape, num_groups, orig_shape.back() / num_groups),
+ tensors.weight);
+ // Tensor copies share their shape metadata. View each buffer through a Constant
+ // without reshaping the caller's tensors: tied K/V projections reuse them.
+ auto scales_node = make_shared_constant(tensors.scales.get_element_type(), scale_shape, tensors.scales);
+ const auto zp_node =
+ tensors.zero_point
+ ? make_shared_constant(tensors.zero_point.get_element_type(), scale_shape, tensors.zero_point)
+ : nullptr;
auto final_shape_node =
std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{orig_shape.size()}, orig_shape);
@@ -235,8 +234,7 @@ std::shared_ptr<ov::Node> make_mxfp4(const WeightTensors& tensors) {
false);
auto w_f16 = std::make_shared<ov::op::v0::Convert>(w_grp, ov::element::f16);
- scales.set_shape(ov::Shape{rows, num_groups, 1});
- auto s_node = std::make_shared<ov::op::v0::Constant>(scales);
+ auto s_node = make_shared_constant(scales.get_element_type(), {rows, num_groups, 1}, scales);
auto s_f16 = std::make_shared<ov::op::v0::Convert>(s_node, ov::element::f16);
auto scaled = std::make_shared<ov::op::v1::Multiply>(w_f16, s_f16, ov::op::AutoBroadcastType::NUMPY);
@@ -257,7 +255,7 @@ static std::shared_ptr<ov::Node> build_q8_0_c_node(ov::Tensor weights, ov::Tenso
// The 2D form (group == cols, a single group per row) is what the CPU/GPU plugin fuses
// into an int8 MatMul; routing it through the grouped low_precision_dequantize path
// (3D weight + Reshape) defeats that fusion and roughly halves prefill throughput.
- auto weights_node = make_compressed_weight_constant(ov::element::i8, ov::Shape{rows, cols}, weights);
+ auto weights_node = make_shared_constant(ov::element::i8, ov::Shape{rows, cols}, weights);
auto weights_f16 = std::make_shared<ov::op::v0::Convert>(weights_node, ov::element::f16);
auto scales_node = std::make_shared<ov::op::v0::Constant>(scales); // {rows, 1}
auto scaled = std::make_shared<ov::op::v1::Multiply>(weights_f16, scales_node, ov::op::AutoBroadcastType::NUMPY);
@@ -287,6 +285,11 @@ void dequant_extracted_row_to_f32(const WeightTensors& tensors, size_t r, size_t
for (size_t k = 0; k < group; ++k) {
dst[k] = (static_cast<float>(q[k]) - zpf) * scale;
}
+ } else if (et == ov::element::u8) {
+ const auto* q = weight.data<uint8_t>() + r * cols + g * group;
+ for (size_t k = 0; k < group; ++k) {
+ dst[k] = (static_cast<float>(q[k]) - zpf) * scale;
+ }
} else if (et == ov::element::u2) {
// Q2_K / Q2_0: u2 weights, 4 per byte LSB-first, raw [0..3] with a zero-point.
const auto* bytes = static_cast<const uint8_t*>(weight.data()) + r * (cols / 4) + (g * group) / 4;
@@ -329,16 +332,19 @@ std::shared_ptr<ov::Node> requantize_extracted_q8_0_channelwise(const WeightTens
return build_q8_0_c_node(weights, scales, rows, cols);
}
+// token_embd/output weights: requantized to Q8_0_C on the raw-byte path, and kept on a faithful
+// f16 zero-point on the extracted-tensor path.
+bool is_embedding_or_output(const std::string& name) {
+ return name.rfind("token_embd.weight", 0) == 0 || name.rfind("output.weight", 0) == 0;
+}
+
// Decide whether a weight is requantized to Q8_0_C, mirroring llama.cpp's
// ggml_openvino_get_requant_type for the CPU/GPU (non-NPU) path.
bool needs_q8_0_c_requant(const std::string& name, GgufTensorType qtype) {
- if (name.rfind("token_embd.weight", 0) == 0 || name.rfind("output.weight", 0) == 0) {
- return true;
- }
- return qtype == GGUF_TYPE_Q5_K;
+ return 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 values.
+// 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() {
// Read once: this sits on a per-tensor path (gguf_zero_point_type is consulted for every
@@ -362,6 +368,7 @@ void notify_lossy_weight_approximation(LossyWeightApproximation kind) {
// once, however many thousands of weights are affected.
static std::once_flag requant_once;
static std::once_flag zero_point_once;
+ static std::once_flag q5_k_zero_point_once;
switch (kind) {
case LossyWeightApproximation::Q8_0_C_REQUANT:
@@ -373,10 +380,19 @@ void notify_lossy_weight_approximation(LossyWeightApproximation kind) {
<< std::endl;
});
break;
- case LossyWeightApproximation::Q4_K_REQUANT:
+ case LossyWeightApproximation::Q4_REQUANT:
std::call_once(zero_point_once, [] {
- std::cerr << "[GGUF] accuracy notice: Q4_K weights are faithfully decoded and requantized group-wise "
- "to OpenVINO u4. This adds a small quantization error, so results may differ slightly "
+ std::cerr << "[GGUF] accuracy notice: Q4_K / Q4_1 weights are faithfully decoded and requantized "
+ "group-wise to OpenVINO u4. This adds a small quantization error, so results may differ "
+ "slightly from the original GGUF weights. The integer zero-point keeps decompression "
+ "foldable into a compressed FullyConnected operation. Reported once per process."
+ << std::endl;
+ });
+ break;
+ case LossyWeightApproximation::Q5_K_REQUANT:
+ std::call_once(q5_k_zero_point_once, [] {
+ std::cerr << "[GGUF] accuracy notice: Q5_K weights are faithfully decoded and requantized group-wise "
+ "to OpenVINO u8. This adds a small quantization error, so results may differ slightly "
"from the original GGUF weights. The integer zero-point keeps decompression foldable "
"into a compressed FullyConnected operation. Reported once per process."
<< std::endl;
@@ -387,15 +403,18 @@ void notify_lossy_weight_approximation(LossyWeightApproximation kind) {
ov::element::Type gguf_zero_point_type(const std::string& name, GgufTensorType qtype) {
// The CPU compressed-FullyConnected fast path only folds the dequant when the zero-point is an
- // INTEGER constant; a fractional f16 one leaves a ~2x slower kernel. Q4_K matmul weights are
- // decoded and requantized to an OpenVINO u4 grid with an integer zero-point. Strict oracle
- // validation can request Q4_K's faithful f16 zero-point via OV_GGUF_Q4_K_ZP_F16. Q2_0's
- // zero-point is exactly 1, so u8 is faithful there. Other asymmetric formats keep f16 because
- // their zero-point can exceed u8 range. Q4_K tensors selected for Q8_0_C retain a faithful
- // f16 zero-point for that separate requantization path.
- const bool integer_zp = qtype == GGUF_TYPE_Q2_0 || (qtype == GGUF_TYPE_Q4_K && !q4_k_f16_zero_point_enabled() &&
- !needs_q8_0_c_requant(name, qtype));
- return integer_zp ? ov::element::u8 : ov::element::f16;
+ // 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
+ // 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());
+ return requantized && !is_embedding_or_output(name) ? ov::element::u8 : ov::element::f16;
}
std::shared_ptr<ov::Node> make_weight_node(const WeightTensors& tensors,
diff --git a/src/frontends/gguf/src/quant/weights.hpp b/src/frontends/gguf/src/quant/weights.hpp
index 74a3f18057b..5791879f8aa 100644
--- a/src/frontends/gguf/src/quant/weights.hpp
+++ b/src/frontends/gguf/src/quant/weights.hpp
@@ -20,9 +20,9 @@ namespace ov::frontend::gguf {
// Element type of the zero-point constant for an asymmetric quantized weight.
// Q2_0 always uses u8. The raw-byte Q8_0_C requantization path separately uses temporary f16
// zero-points for its host dequantizer, including Q2_0 embedding/output tensors.
-// Q4_K matmul weights are faithfully decoded and requantized to u4 with an integer zero-point,
-// which keeps the CPU compressed-FullyConnected path available. Q4_K tensors selected for the
-// channel-wise Q8_0_C path retain an f16 zero-point while feeding that separate requantization.
+// 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. Q5_K matmul
+// weights are requantized the same way to an 8-bit u8 grid. token_embd/output keep an f16 zero-point.
ov::element::Type gguf_zero_point_type(const std::string& name, GgufTensorType qtype);
// A lossy weight approximation the frontend deliberately makes, reported to the user once so a
@@ -30,8 +30,10 @@ ov::element::Type gguf_zero_point_type(const std::string& name, GgufTensorType q
enum class LossyWeightApproximation {
// token_embd / output / Q6_K / Q5_K tensors requantized channel-wise to Q8_0_C.
Q8_0_C_REQUANT,
- // Q4_K asymmetric weights faithfully decoded and requantized group-wise to OpenVINO u4.
- Q4_K_REQUANT,
+ // Q4_K / Q4_1 asymmetric weights faithfully decoded and requantized group-wise to OpenVINO u4.
+ Q4_REQUANT,
+ // Q5_K asymmetric weights faithfully decoded and requantized group-wise to OpenVINO u8.
+ Q5_K_REQUANT,
};
// Warn -- ONCE per process and per approximation kind -- that weights are being converted with a
@@ -51,6 +53,9 @@ struct WeightTensors {
ov::Tensor zero_point;
};
+// Quant type recorded for a weight as "<base>.qtype"; F16 when absent.
+GgufTensorType lookup_qtype(const std::string& base, const std::unordered_map<std::string, GgufTensorType>& qtypes);
+
// Build the OpenVINO node for one extracted GGUF weight. Quantized weights become a
// low-bitness compressed subgraph (u4/u8 weights + zero-point + f16 scale, Convert ->
// Subtract -> Multiply -> Reshape), matching what the cgraph path produces; F16/F32 weights
diff --git a/src/frontends/gguf/src/translate_session.cpp b/src/frontends/gguf/src/translate_session.cpp
index 1b3fd5377f2..b1054765659 100644
--- a/src/frontends/gguf/src/translate_session.cpp
+++ b/src/frontends/gguf/src/translate_session.cpp
@@ -46,6 +46,7 @@
#include "pass/prune_orphaned_parameters.hpp"
#include "transformations/common_optimizations/fuse_gated_delta_net.hpp"
#include "transformations/common_optimizations/nop_elimination.hpp"
+#include "transformations/common_optimizations/optimize_strided_slice.hpp"
#include "transformations/fp16_compression/mark_decompression_convert_constant_folding.hpp"
#include "transformations/op_conversions/convert_convertlike.hpp"
#include "utils.hpp"
@@ -290,6 +291,14 @@ std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputMo
}
}
+ // The architecture and projector metadata select what the GenAI adapters change, including
+ // adapters registered as transformation extensions.
+ if (builder)
+ resulting_model->get_rt_info()["gguf_architecture"] = builder->get_attribute("architecture");
+ if (!gguf_model_decoder->get_mmproj_config().empty()) {
+ resulting_model->get_rt_info()["gguf_mmproj"] = gguf_model_decoder->get_mmproj_config();
+ }
+
if (builder) {
resulting_model = resulting_model->clone();
}
@@ -368,6 +377,9 @@ std::shared_ptr<Model> TranslateSession::apply_transformations(std::shared_ptr<M
// StateManagementPattern, which admits no Convert between the KV-cache Concat and SDPA, and so
// silently disables the PagedAttention backend for every GGUF model.
manager.register_pass<ov::pass::EliminateConvert>();
+ // ggml VIEWs of disjoint ranges of one tensor (fused q/k/v, z/beta/alpha) become Slices; as one
+ // VariadicSplit the plugins can run them in place instead of as one copy kernel each.
+ manager.register_pass<ov::pass::GroupedSliceToVSplitOptimization>();
// Fuse a standalone Loop-based Gated Delta Net recurrence here (not in a plugin, which can't
// remove a Parameter without violating its I/O port-count invariant), only for models with a
diff --git a/src/frontends/gguf/src/utils.cpp b/src/frontends/gguf/src/utils.cpp
index f3f455e011c..36f52459603 100644
--- a/src/frontends/gguf/src/utils.cpp
+++ b/src/frontends/gguf/src/utils.cpp
@@ -4,9 +4,11 @@
#include "utils.hpp"
+#include <algorithm>
#include <cmath>
#include <cstddef>
#include <memory>
+#include <numeric>
#include <string>
#include "openvino/core/model.hpp"
@@ -20,13 +22,16 @@
#include "openvino/op/maximum.hpp"
#include "openvino/op/multiply.hpp"
#include "openvino/op/parameter.hpp"
+#include "openvino/op/reduce_sum.hpp"
#include "openvino/op/reshape.hpp"
#include "openvino/op/shape_of.hpp"
#include "openvino/op/sin.hpp"
#include "openvino/op/slice.hpp"
+#include "openvino/op/sqrt.hpp"
#include "openvino/op/squeeze.hpp"
#include "openvino/op/subtract.hpp"
#include "openvino/op/transpose.hpp"
+#include "openvino/op/variadic_split.hpp"
namespace ov::frontend::gguf {
@@ -53,14 +58,22 @@ std::pair<ov::Output<ov::Node>, ov::Output<ov::Node>> get_glu_inputs(const NodeC
const auto half_dim = last_dim / 2;
auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {-1});
- auto step = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
- auto start0 = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});
- auto stop0 = ov::op::v0::Constant::create(ov::element::i64, {1}, {half_dim});
- auto start1 = ov::op::v0::Constant::create(ov::element::i64, {1}, {half_dim});
- auto stop1 = ov::op::v0::Constant::create(ov::element::i64, {1}, {2 * half_dim});
-
- src0 = std::make_shared<ov::op::v8::Slice>(combined, start0, stop0, step, axis);
- src1 = std::make_shared<ov::op::v8::Slice>(combined, start1, stop1, step, axis);
+ if (last_dim % 2 == 0) {
+ // VariadicSplit is the form GLUFusion matches.
+ auto lengths = ov::op::v0::Constant::create(ov::element::i64, {2}, {half_dim, half_dim});
+ auto split = std::make_shared<ov::op::v1::VariadicSplit>(combined, axis, lengths);
+ src0 = split->output(0);
+ src1 = split->output(1);
+ } else {
+ auto step = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
+ auto start0 = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});
+ auto stop0 = ov::op::v0::Constant::create(ov::element::i64, {1}, {half_dim});
+ auto start1 = ov::op::v0::Constant::create(ov::element::i64, {1}, {half_dim});
+ auto stop1 = ov::op::v0::Constant::create(ov::element::i64, {1}, {2 * half_dim});
+
+ src0 = std::make_shared<ov::op::v8::Slice>(combined, start0, stop0, step, axis);
+ src1 = std::make_shared<ov::op::v8::Slice>(combined, start1, stop1, step, axis);
+ }
}
if (context.get_attribute<bool>("swapped")) {
@@ -91,8 +104,21 @@ int non_cont_dim(std::vector<size_t> ne, std::vector<size_t> nb) {
return 0;
}
-std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::op::v3::ShapeOf>& shape,
- const std::vector<int>& dims) {
+ov::Output<ov::Node> make_l2_norm(const ov::Output<ov::Node>& x, float eps) {
+ auto sum = std::make_shared<ov::op::v1::ReduceSum>(std::make_shared<ov::op::v1::Multiply>(x, x),
+ ov::op::v0::Constant::create(ov::element::i64, {1}, {-1}),
+ true);
+ auto norm = std::make_shared<ov::op::v1::Maximum>(std::make_shared<ov::op::v0::Sqrt>(sum),
+ ov::op::v0::Constant::create(ov::element::f32, {1}, {eps}));
+ return std::make_shared<ov::op::v1::Divide>(x, norm);
+}
+
+void name_output(const ov::Output<ov::Node>& out, const std::string& name) {
+ out.get_node_shared_ptr()->set_friendly_name(name);
+ out.get_node_shared_ptr()->output(0).set_names({name});
+}
+
+std::shared_ptr<ov::Node> gather_dims(const ov::Output<ov::Node>& shape, const std::vector<int>& dims) {
using namespace ov::op;
const auto zero = v0::Constant::create(ov::element::i32, ov::Shape{}, {0});
const auto dims_const = v0::Constant::create(ov::element::i32, ov::Shape{dims.size()}, dims);
@@ -100,7 +126,7 @@ std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::op::v3::Shape
}
std::shared_ptr<ov::Node> get_dimensions(const ov::Output<ov::Node>& output, const std::vector<int>& dims) {
- return get_dimensions(std::make_shared<ov::op::v3::ShapeOf>(output), dims);
+ return gather_dims(std::make_shared<ov::op::v3::ShapeOf>(output), dims);
}
OutputVector rename_outputs_with_suffix(OutputVector outputs, const std::string& suffix) {
@@ -221,8 +247,22 @@ std::pair<ov::Output<Node>, ov::Output<Node>> make_sin_cos(const RopeConfig& rop
float mscale = attn_factor;
if (imrope) {
std::vector<int64_t> gather_indices(n_dims_half);
+ const auto& sections = rope_config.sections;
+ FRONT_END_GENERAL_CHECK(std::all_of(sections.begin(),
+ sections.end(),
+ [](int32_t s) {
+ return s >= 0;
+ }),
+ "M-RoPE sections must be nonnegative");
+ // Four int32 counts always fit in 64 bits.
+ const int64_t total = std::accumulate(sections.begin(), sections.end(), int64_t{0});
for (size_t j = 0; j < n_dims_half; j++) {
- gather_indices[j] = j % 3;
+ const size_t sector = total ? j % static_cast<size_t>(total) : j;
+ gather_indices[j] = !total ? j % 3
+ : sector % 3 == 1 && sector < 3 * static_cast<size_t>(sections[1]) ? 1
+ : sector % 3 == 2 && sector < 3 * static_cast<size_t>(sections[2]) ? 2
+ : sector % 3 == 0 && sector < 3 * static_cast<size_t>(sections[0]) ? 0
+ : 3;
factor[j] = static_cast<float>(std::pow(theta_scale, j));
}
auto gather_indices_const =
diff --git a/src/frontends/gguf/src/utils.hpp b/src/frontends/gguf/src/utils.hpp
index 2859b2b3bb7..7d49b037ed8 100644
--- a/src/frontends/gguf/src/utils.hpp
+++ b/src/frontends/gguf/src/utils.hpp
@@ -49,11 +49,22 @@ std::vector<T> permute(const std::vector<T>& x, const std::vector<size_t>& perm)
return result;
}
+// Select entries out of an already computed shape vector. Prefer this over repeated get_dimensions
+// calls on one tensor, which build a fresh ShapeOf each time.
+std::shared_ptr<ov::Node> gather_dims(const ov::Output<ov::Node>& shape, const std::vector<int>& dims);
+
+// Use gather_dims for an existing shape: an Output overload would take its ShapeOf again.
std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::op::v3::ShapeOf>& shape,
- const std::vector<int>& dims);
+ const std::vector<int>& dims) = delete;
// Takes the Output rather than the node so a producer with several outputs keeps the right port.
std::shared_ptr<ov::Node> get_dimensions(const ov::Output<ov::Node>& output, const std::vector<int>& dims);
+// x / max(sqrt(sum(x^2, -1)), eps), matching ggml's l2_norm.
+ov::Output<ov::Node> make_l2_norm(const ov::Output<ov::Node>& x, float eps);
+
+/// \brief Give `out`'s producer and its first output tensor the same name.
+void name_output(const ov::Output<ov::Node>& out, const std::string& name);
+
// Take ownership of the temporary output vector assembled by translators, rename its producers,
// then return the same vector without an extra copy.
OutputVector rename_outputs_with_suffix(OutputVector outputs, const std::string& suffix);
diff --git a/src/frontends/gguf/tests/CMakeLists.txt b/src/frontends/gguf/tests/CMakeLists.txt
index 1d43f877c18..404adc07a60 100644
--- a/src/frontends/gguf/tests/CMakeLists.txt
+++ b/src/frontends/gguf/tests/CMakeLists.txt
@@ -24,6 +24,7 @@ set(FRONTEND_SRCS
"${FE_SRC_DIR}/utils.cpp"
"${FE_SRC_DIR}/helper_ops/set_rows_op.cpp"
"${FE_SRC_DIR}/pass/adapt_to_genai.cpp"
+ "${FE_SRC_DIR}/pass/adapt_mmproj_to_genai.cpp"
"${FE_SRC_DIR}/pass/lower_set_rows_stateless.cpp"
"${FE_SRC_DIR}/pass/make_stateful.cpp"
"${FE_SRC_DIR}/pass/prune_orphaned_parameters.cpp"
@@ -35,14 +36,18 @@ set(FRONTEND_SRCS
"${FE_SRC_DIR}/builder/gguf_builder_decoder.cpp"
"${FE_SRC_DIR}/builder/graph_emitter.cpp"
"${FE_SRC_DIR}/builder/arch_registry.cpp"
+ "${FE_SRC_DIR}/builder/projector_registry.cpp"
"${FE_SRC_DIR}/builder/decoder_config.cpp"
"${FE_SRC_DIR}/builder/model_kind.cpp"
"${FE_SRC_DIR}/extension/architecture.cpp"
+ "${FE_SRC_DIR}/extension/projector.cpp"
"${FE_SRC_DIR}/builder/api/graph_context.cpp"
"${FE_SRC_DIR}/builder/api/metadata.cpp"
"${FE_SRC_DIR}/builder/api/tensor_table.cpp"
"${FE_SRC_DIR}/builder/arch/decoder_builder.cpp"
"${FE_SRC_DIR}/builder/arch/mamba_builder.cpp"
+ "${FE_SRC_DIR}/builder/arch/mmproj_builder.cpp"
+ "${FE_SRC_DIR}/op/multimodal.cpp"
"${FE_SRC_DIR}/builder/blocks/attention.cpp"
"${FE_SRC_DIR}/builder/blocks/common.cpp"
"${FE_SRC_DIR}/builder/blocks/ffn.cpp"
@@ -97,6 +102,7 @@ set(FRONTEND_SRCS
)
set(TEST_SRCS
+ "${CMAKE_CURRENT_SOURCE_DIR}/test_mmproj.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/test_adapt_to_genai.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/test_arch_conversion.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/test_arch_accuracy.cpp"
@@ -154,6 +160,13 @@ install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/test_data"
PATTERN "*.npz"
PATTERN "manifest.txt")
+# tests/model_hub_tests/gguf/test_gguf_mmproj.py builds this oracle and reuses these helpers.
+install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/mmproj_oracle.cpp"
+ "${CMAKE_CURRENT_SOURCE_DIR}/mmproj_fixtures.py"
+ DESTINATION tests/model_hub_tests/gguf
+ COMPONENT tests
+ EXCLUDE_FROM_ALL)
+
# Sources compiled into the binary: resolve the visibility macros to local definitions, not dllimport.
target_compile_definitions(${TARGET_NAME} PRIVATE openvino_gguf_frontend_EXPORTS)
diff --git a/src/frontends/gguf/tests/embedding_oracle.cpp b/src/frontends/gguf/tests/embedding_oracle.cpp
new file mode 100644
index 00000000000..84bf5106a1b
--- /dev/null
+++ b/src/frontends/gguf/tests/embedding_oracle.cpp
@@ -0,0 +1,65 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <fstream>
+#include <string>
+#include <vector>
+
+#include "ggml-backend.h"
+#include "llama.h"
+
+int main(int argc, char** argv) {
+ if (argc != 3 && argc != 4)
+ return 2;
+ llama_backend_init();
+ ggml_backend_dev_t devices[] = {ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU), nullptr};
+ auto mp = llama_model_default_params();
+ if (!devices[0])
+ return 8;
+ mp.devices = devices;
+ mp.n_gpu_layers = 0;
+ auto* m = llama_model_load_from_file(argv[1], mp);
+ if (!m)
+ return 3;
+ auto cp = llama_context_default_params();
+ cp.n_ctx = 128;
+ cp.n_batch = cp.n_ubatch = 64;
+ cp.n_threads = cp.n_threads_batch = 4;
+ cp.embeddings = true;
+ cp.pooling_type = LLAMA_POOLING_TYPE_NONE;
+ cp.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_DISABLED;
+ auto* c = llama_init_from_model(m, cp);
+ if (!c)
+ return 4;
+ std::vector<llama_token> tokens{1, 2, 3};
+ if (argc == 4) {
+ std::string prompt = argv[3];
+ tokens.resize(64);
+ auto n = llama_tokenize(llama_model_get_vocab(m),
+ prompt.data(),
+ static_cast<int32_t>(prompt.size()),
+ tokens.data(),
+ 64,
+ true,
+ false);
+ if (n <= 0)
+ return 5;
+ tokens.resize(n);
+ }
+ auto batch = llama_batch_get_one(tokens.data(), static_cast<int32_t>(tokens.size()));
+ if (llama_decode(c, batch))
+ return 6;
+ const int32_t dim = llama_model_n_embd(m);
+ const int32_t count = static_cast<int32_t>(tokens.size());
+ std::ofstream out(argv[2], std::ios::binary);
+ out.write(reinterpret_cast<const char*>(&dim), sizeof(dim));
+ out.write(reinterpret_cast<const char*>(&count), sizeof(count));
+ out.write(reinterpret_cast<const char*>(tokens.data()), sizeof(llama_token) * count);
+ for (int i = 0; i < count; ++i)
+ out.write(reinterpret_cast<const char*>(llama_get_embeddings_ith(c, i)), dim * sizeof(float));
+ llama_free(c);
+ llama_model_free(m);
+ llama_backend_free();
+ return out ? 0 : 7;
+}
diff --git a/src/frontends/gguf/tests/gen_arch_accuracy.py b/src/frontends/gguf/tests/gen_arch_accuracy.py
index d04303374a3..2cff34953d9 100644
--- a/src/frontends/gguf/tests/gen_arch_accuracy.py
+++ b/src/frontends/gguf/tests/gen_arch_accuracy.py
@@ -9,8 +9,6 @@ Build architecture_oracle.cpp against a CPU-only llama.cpp (include/, ggml/inclu
link libllama, libggml, libggml-base). The generated NPZs are consumed without llama.cpp.
"""
import argparse
-import io
-import zipfile
from pathlib import Path
import subprocess
import tempfile
@@ -18,16 +16,38 @@ import tempfile
import gguf
import numpy as np
+from mmproj_fixtures import finish, save_npz
+
CASES = {
+ "qwen35": {}, "qwen35moe": {},
+ "qwen35moe-fused": {"architecture": "qwen35moe", "fused_experts": True},
+ # Real checkpoints quantize attn_gate apart from ssm_beta/ssm_alpha: F16 here selects the
+ # frontend's beta+alpha-only merge, and an F16 beta in layer 2 selects separate projections.
+ "qwen35-mixed": {"architecture": "qwen35", "f16": ("attn_gate", "blk.2.ssm_beta")},
"nemotron_h": {},
"mamba2": {}, "mamba2-tied": {"architecture": "mamba2", "tied": True},
- "llama": {}, "qwen2": {"bias": True}, "qwen3": {"qk": True},
+ "llama": {},
+ "llama-embed": {"embedding_output": True, "tied": True},
+ "llama-embed-noncausal": {"architecture": "llama-embed", "embedding_output": True, "tied": True, "causal": False},
+ "llama-embed-mean": {"architecture": "llama-embed", "embedding_output": True, "tied": True, "pooling": 1},
+ "llama-embed-cls": {"architecture": "llama-embed", "embedding_output": True, "tied": True, "pooling": 2},
+ "llama-embed-last": {"architecture": "llama-embed", "embedding_output": True, "tied": True, "pooling": 3},
+ "exaone-moe": {"qk": True, "moe": True, "shared": True, "lead": 1, "swa": True, "layers": 4},
+ "exaone-moe-nextn": {"architecture": "exaone-moe", "qk": True, "moe": True, "shared": True, "lead": 1, "swa": True, "layers": 4, "nextn": 1, "sigmoid": True, "selection_bias": True, "expert_scale": 2.5},
+ "glm4moe": {"qk": True, "moe": True, "shared": True, "lead": 1, "selection_bias": True, "sigmoid": True, "ffn_post_attn": True},
+ "jais2": {"layer_norm": True, "relu_squared": True, "bias": True},
+ "minimax-m2": {"moe": True, "full_qk": True, "selection_bias": True, "rope_dims": 4, "sigmoid": True},
+ "plamo3": {"qk": True, "fused": True, "fused_ffn": True, "post": True, "bare_post": True, "swa": True}, "qwen2": {"bias": True}, "qwen3": {"qk": True},
"phi3": {"fused": True, "fused_ffn": True}, "minicpm": {},
"olmoe": {"moe": True, "full_qk": True},
"hunyuan-dense": {"qk": True}, "hunyuan-moe": {"qk": True, "moe": True, "shared": True},
"qwen3moe": {"qk": True, "moe": True},
+ "gemma4-mqa": {"architecture": "gemma4"},
+ "gemma4-moe": {"architecture": "gemma4", "moe": True},
+ "gemma4-ple": {"architecture": "gemma4", "per_layer": 8, "layers": 4, "shared_kv": 2},
"gemma": {"mqa": True, "tied": True},
"gemma2": {"post": True, "swa": True, "tied": True, "softcap": True},
+ "gemma3": {"post": True, "swa": True, "tied": True, "qk": True, "linear": 8.0},
"exaone4": {"qk": True, "post_only": True},
"ernie4_5-moe": {"moe": True, "lead": 1, "selection_bias": True, "shared": True},
"bailingmoe2": {"qk": True, "fused": True, "moe": True, "lead": 1,
@@ -44,6 +64,16 @@ CASES = {
}
+def tensor_writer(writer, rng, f16=()):
+ """Uniform random F32 tensors; norm weights are centered at 1. Names containing an `f16`
+ entry are stored as F16."""
+ 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)
+ return tensor
+
+
def write_mamba2_model(path, opts, arch="mamba2"):
w = gguf.GGUFWriter(path, arch)
hybrid = arch == "nemotron_h"
@@ -64,13 +94,12 @@ def write_mamba2_model(path, opts, arch="mamba2"):
"state_size": state, "conv_kernel": kernel}.items():
w.add_uint32(arch + ".ssm." + key, value)
rng = np.random.default_rng(20260915)
-
- def tensor(name, shape, norm=False):
- values = rng.uniform(-1, 1, shape).astype(np.float32)
- w.add_tensor(name, 1 + values * .3 if norm else values * .2)
+ tensor = tensor_writer(w, rng)
tensor("token_embd.weight", (vocab, d))
tensor("output_norm.weight", (d,), True)
+ if opts.get("layer_norm"):
+ tensor("output_norm.bias", (d,))
if not opts.get("tied"):
tensor("output.weight", (vocab, d))
conv_dim = inner + 2 * groups * state
@@ -98,14 +127,156 @@ def write_mamba2_model(path, opts, arch="mamba2"):
tensor(p + "ssm_d", (heads, 1))
tensor(p + "ssm_norm.weight", (groups, inner // groups), True)
tensor(p + "ssm_out.weight", (d, inner))
- w.write_header_to_file()
- w.write_kv_data_to_file()
- w.write_tensors_to_file()
- w.close()
+ finish(w)
+
+
+def write_qwen35_model(path, arch, fused_experts=False, f16=()):
+ 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
+ inner, conv = state * vheads, state * (2 * groups + vheads)
+ w.add_context_length(128)
+ w.add_embedding_length(d)
+ w.add_block_count(4)
+ w.add_feed_forward_length(ff)
+ w.add_head_count(heads)
+ w.add_head_count_kv(kv)
+ w.add_key_length(head)
+ 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])
+ w.add_layer_norm_rms_eps(1e-5)
+ w.add_vocab_size(vocab)
+ w.add_tokenizer_model("none")
+ for key, value in {"inner_size": inner, "time_step_rank": vheads, "group_count": groups,
+ "state_size": state, "conv_kernel": kernel}.items():
+ w.add_uint32(arch + ".ssm." + key, value)
+ w.add_uint32(arch + ".full_attention_interval", 4)
+ moe = arch == "qwen35moe"
+ if moe:
+ w.add_expert_count(4)
+ w.add_expert_used_count(2)
+ w.add_expert_feed_forward_length(ff)
+ w.add_expert_shared_feed_forward_length(ff)
+ rng = np.random.default_rng(20260922)
+ tensor = tensor_writer(w, rng, f16)
+
+ tensor("token_embd.weight", (vocab, d))
+ tensor("output_norm.weight", (d,), True)
+ tensor("output.weight", (vocab, d))
+ for layer in range(4):
+ p = f"blk.{layer}."
+ 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))
+ 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))
+ 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))
+ for name in ("q", "k"):
+ tensor(p + f"attn_{name}_norm.weight", (head,), True)
+ tensor(p + "attn_output.weight", (d, heads * head))
+ if moe:
+ tensor(p + "ffn_gate_inp.weight", (4, d))
+ if fused_experts:
+ tensor(p + "ffn_gate_up_exps.weight", (4, 2 * ff, d))
+ else:
+ for name in ("gate", "up"):
+ tensor(p + f"ffn_{name}_exps.weight", (4, ff, d))
+ tensor(p + "ffn_down_exps.weight", (4, d, ff))
+ tensor(p + "ffn_gate_inp_shexp.weight", (d,))
+ for name, shape in (("gate", (ff, d)), ("up", (ff, d)), ("down", (d, ff))):
+ tensor(p + f"ffn_{name}" + ("_shexp" if moe else "") + ".weight", shape)
+ finish(w)
+
+
+def write_gemma4_model(path, opts):
+ """Layers alternate sliding/full attention; E2B/E4B-style options add per-layer
+ embeddings (`per_layer`) and reuse earlier KV in the last `shared_kv` layers, which keep
+ their unused K/V tensors as real checkpoints do."""
+ w = gguf.GGUFWriter(path, "gemma4")
+ d, heads, layers, vocab, ff = 32, 4, opts.get("layers", 2), 32, 48
+ per_layer, shared = opts.get("per_layer", 0), opts.get("shared_kv", 0)
+ 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([2, 1] * (layers // 2))
+ w.add_feed_forward_length(ff)
+ w.add_key_length(16)
+ w.add_value_length(16)
+ w.add_layer_norm_rms_eps(1e-6)
+ w.add_vocab_size(vocab)
+ w.add_tokenizer_model("none")
+ for key, value in {"attention.key_length_swa": 8, "attention.value_length_swa": 8,
+ "attention.sliding_window": 2, "attention.shared_kv_layers": shared,
+ "embedding_length_per_layer_input": per_layer, "rope.dimension_count": 16,
+ "rope.dimension_count_swa": 8}.items():
+ w.add_uint32("gemma4." + key, value)
+ w.add_array("gemma4.attention.sliding_window_pattern", [True, False] * (layers // 2))
+ w.add_float32("gemma4.rope.freq_base", 1000000.)
+ w.add_float32("gemma4.rope.freq_base_swa", 10000.)
+ w.add_float32("gemma4.final_logit_softcapping", 30.)
+ if opts.get("moe"):
+ w.add_expert_count(4)
+ w.add_expert_used_count(2)
+ w.add_uint32("gemma4.expert_feed_forward_length", 24)
+ rng = np.random.default_rng(20260922)
+ tensor = tensor_writer(w, rng)
+
+ tensor("token_embd.weight", (vocab, d))
+ tensor("output_norm.weight", (d,), True)
+ tensor("rope_freqs.weight", (8,), True)
+ if per_layer:
+ tensor("per_layer_token_embd.weight", (vocab, per_layer * layers))
+ tensor("per_layer_model_proj.weight", (per_layer * layers, d))
+ tensor("per_layer_proj_norm.weight", (per_layer,), True)
+ for layer in range(layers):
+ p = f"blk.{layer}."
+ swa = layer % 2 == 0
+ head, kv = (8, 2) if swa else (16, 1)
+ for name in ("attn_norm", "ffn_norm", "post_attention_norm", "post_ffw_norm"):
+ tensor(p + name + ".weight", (d,), True)
+ tensor(p + "attn_q.weight", (heads * head, d))
+ tensor(p + "attn_k.weight", (kv * head, d))
+ if swa:
+ tensor(p + "attn_v.weight", (kv * head, d))
+ for name in ("q", "k"):
+ tensor(p + f"attn_{name}_norm.weight", (head,), True)
+ tensor(p + "attn_output.weight", (d, heads * head))
+ for name, shape in (("gate", (ff, d)), ("up", (ff, d)), ("down", (d, ff))):
+ tensor(p + f"ffn_{name}.weight", shape)
+ tensor(p + "layer_output_scale.weight", (1,), True)
+ if per_layer:
+ tensor(p + "inp_gate.weight", (per_layer, d))
+ tensor(p + "proj.weight", (d, per_layer))
+ tensor(p + "post_norm.weight", (d,), True)
+ if opts.get("moe"):
+ for name in ("pre_ffw_norm_2", "post_ffw_norm_1", "post_ffw_norm_2"):
+ tensor(p + name + ".weight", (d,), True)
+ tensor(p + "ffn_gate_inp.weight", (4, d))
+ tensor(p + "ffn_gate_inp.scale", (d,), True)
+ tensor(p + "ffn_gate_up_exps.weight", (4, 48, d))
+ tensor(p + "ffn_down_exps.weight", (4, d, 24))
+ tensor(p + "ffn_down_exps.scale", (4,), True)
+ finish(w)
def write_model(path, arch, opts):
arch = opts.get("architecture", arch)
+ 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", ()))
if arch in ("mamba2", "nemotron_h"):
return write_mamba2_model(path, opts, arch)
w = gguf.GGUFWriter(path, arch)
@@ -114,17 +285,29 @@ def write_model(path, arch, opts):
layers = opts.get("layers", 2)
w.add_context_length(128)
w.add_embedding_length(d)
- w.add_block_count(layers)
+ w.add_block_count(layers + opts.get("nextn", 0))
+ if opts.get("nextn"):
+ w.add_nextn_predict_layers(opts["nextn"])
w.add_feed_forward_length(ff)
w.add_head_count(heads)
w.add_head_count_kv(kv)
w.add_key_length(head)
w.add_value_length(head)
- w.add_rope_dimension_count(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)
- w.add_layer_norm_rms_eps(1e-5)
+ if opts.get("layer_norm"):
+ w.add_layer_norm_eps(1e-5)
+ else:
+ w.add_layer_norm_rms_eps(1e-5)
w.add_vocab_size(vocab)
w.add_tokenizer_model("none")
+ if opts.get("embedding_output"):
+ w.add_uint32(arch + ".pooling_type", opts.get("pooling", 0))
+ w.add_bool(arch + ".attention.causal", opts.get("causal", True))
+ if opts.get("linear"):
+ w.add_rope_scaling_type(gguf.RopeScalingType.LINEAR)
+ w.add_rope_scaling_factor(opts["linear"])
+ w.add_rope_freq_base_swa(100.0)
if opts.get("yarn"):
w.add_rope_scaling_type(gguf.RopeScalingType.YARN)
w.add_rope_scaling_factor(opts["yarn"])
@@ -136,6 +319,8 @@ def write_model(path, arch, opts):
if opts.get("swa"):
w.add_sliding_window(2)
w.add_sliding_window_pattern(2)
+ if arch == "plamo3":
+ w.add_rope_freq_base_swa(100.0)
if opts.get("softcap"):
w.add_attn_logit_softcapping(2.0)
w.add_final_logit_softcapping(3.0)
@@ -150,7 +335,9 @@ def write_model(path, arch, opts):
w.add_expert_shared_count(int(opts.get("shared", False)))
w.add_expert_shared_feed_forward_length(ff if opts.get("shared") else 0)
w.add_uint32(arch + ".expert_gating_func", 2 if opts.get("sigmoid") else 1)
- if arch not in ("qwen3moe", "ernie4_5-moe", "mellum"):
+ 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"):
w.add_expert_weights_norm(arch != "olmoe")
if arch == "bailingmoe2":
w.add_expert_group_count(2)
@@ -158,24 +345,24 @@ def write_model(path, arch, opts):
if arch == "ernie4_5-moe":
w.add_interleave_moe_layer_step(2)
rng = np.random.default_rng(20260907)
-
- def tensor(name, shape, norm=False):
- values = rng.uniform(-1, 1, shape).astype(np.float32)
- values = (1 + values * .3) if norm else values * .2
- w.add_tensor(name, values)
+ tensor = tensor_writer(w, rng)
tensor("token_embd.weight", (vocab, d))
tensor("output_norm.weight", (d,), True)
+ if opts.get("layer_norm"):
+ tensor("output_norm.bias", (d,))
if not opts.get("tied"):
tensor("output.weight", (vocab, d))
for layer in range(layers):
p = f"blk.{layer}."
if not opts.get("post_only"):
- for name in ("attn_norm", "ffn_norm"):
+ for name in ("attn_norm", "post_attention_norm" if opts.get("ffn_post_attn") else "ffn_norm"):
tensor(p + name + ".weight", (d,), True)
+ if opts.get("layer_norm"):
+ tensor(p + name + ".bias", (d,))
if opts.get("post") or opts.get("post_only"):
for name in ("post_attention_norm", "post_ffw_norm"):
- tensor(p + name + ".weight", (d,), True)
+ tensor(p + name + ("" if opts.get("bare_post") else ".weight"), (d,), True)
if opts.get("fused"):
tensor(p + "attn_qkv.weight", ((heads + 2 * kv) * head, d))
else:
@@ -184,6 +371,8 @@ def write_model(path, arch, opts):
if opts.get("bias"):
tensor(p + f"attn_{name}.bias", (width,))
tensor(p + "attn_output.weight", (d, heads * head))
+ if opts.get("layer_norm"):
+ tensor(p + "attn_output.bias", (d,))
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)
@@ -198,44 +387,62 @@ def write_model(path, arch, opts):
if opts.get("shared"):
for name, shape in (("gate", (ff, d)), ("up", (ff, d)), ("down", (d, ff))):
tensor(p + f"ffn_{name}_shexp.weight", shape)
+ elif opts.get("relu_squared"):
+ for name, shape in (("up", (ff, d)), ("down", (d, ff))):
+ tensor(p + f"ffn_{name}.weight", shape)
+ tensor(p + f"ffn_{name}.bias", (shape[0],))
elif opts.get("fused_ffn"):
tensor(p + "ffn_up.weight", (2 * ff, d))
tensor(p + "ffn_down.weight", (d, ff))
else:
for name, shape in (("gate", (ff, d)), ("up", (ff, d)), ("down", (d, ff))):
tensor(p + f"ffn_{name}.weight", shape)
- w.write_header_to_file()
- w.write_kv_data_to_file()
- w.write_tensors_to_file()
- w.close()
+ 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 + "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)
+ for name, shape in (("gate", (ff, d)), ("up", (ff, d)), ("down", (d, ff))):
+ tensor(p + f"ffn_{name}.weight", shape)
+ tensor(p + "nextn.eh_proj.weight", (d, 2 * d))
+ for name in ("enorm", "hnorm"):
+ tensor(p + "nextn." + name + ".weight", (d,), True)
+ finish(w)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--oracle", required=True)
+ parser.add_argument("--embedding-oracle")
parser.add_argument("--out-dir", type=Path, default=Path(__file__).parent / "test_data/arch_accuracy")
parser.add_argument("--architectures", nargs="+", default=list(CASES))
args = parser.parse_args()
+ if not args.embedding_oracle and any(CASES[arch].get("embedding_output") for arch in args.architectures):
+ parser.error("--embedding-oracle is required to generate embedding fixtures")
args.out_dir.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory() as tmp:
for arch in args.architectures:
model = Path(tmp) / f"{arch}.gguf"
reference = model.with_suffix(".bin")
write_model(model, arch, CASES[arch])
- result = subprocess.run([args.oracle, str(model), str(reference)], capture_output=True)
+ oracle = args.embedding_oracle if CASES[arch].get("embedding_output") else args.oracle
+ result = subprocess.run([oracle, str(model), str(reference)], capture_output=True)
if result.returncode:
raise RuntimeError(f"{arch}: oracle failed\n{result.stderr.decode()}")
+ if CASES[arch].get("embedding_output"):
+ dim, count = np.fromfile(reference, dtype="<i4", count=2)
+ values = np.fromfile(reference, dtype="<f4", offset=8 + 4 * count).reshape(count, dim)
+ pool = CASES[arch].get("pooling", 0)
+ expected = values.mean(axis=0, keepdims=True) if pool == 1 else values[:1] if pool == 2 else values[-1:] if pool == 3 else values
+ save_npz(args.out_dir / f"{arch}.npz", {"model": np.fromfile(model, dtype=np.uint8), "embeddings": expected})
+ print(f"{arch}: embeddings {expected.shape}", flush=True)
+ 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
- # cnpy reads standard ZIP headers; NumPy's savez forces ZIP64 even for tiny arrays.
- with zipfile.ZipFile(args.out_dir / f"{arch}.npz", "w", compression=zipfile.ZIP_DEFLATED) as archive:
- for key, array in {"model": np.fromfile(model, dtype=np.uint8), "logits": logits}.items():
- payload = io.BytesIO()
- np.save(payload, array)
- info = zipfile.ZipInfo(key + ".npy", date_time=(1980, 1, 1, 0, 0, 0))
- info.compress_type = zipfile.ZIP_DEFLATED
- archive.writestr(info, payload.getvalue())
+ save_npz(args.out_dir / f"{arch}.npz", {"model": np.fromfile(model, dtype=np.uint8), "logits": logits})
print(f"{arch}: {model.stat().st_size} bytes, reference logits {logits.shape}", flush=True)
diff --git a/src/frontends/gguf/tests/gen_mmproj_accuracy.py b/src/frontends/gguf/tests/gen_mmproj_accuracy.py
new file mode 100644
index 00000000000..e18610f54ff
--- /dev/null
+++ b/src/frontends/gguf/tests/gen_mmproj_accuracy.py
@@ -0,0 +1,638 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+"""llama.cpp CPU oracle fixtures for GGUFMMProjAccuracy (one input grid) and
+GGUFMMProjDynamicAccuracy (two grids, prefixed 0. and 1., served by one compiled model).
+
+PYTHONPATH=<llama.cpp>/gguf-py python gen_mmproj_accuracy.py --oracle <mmproj_oracle> \
+ [--ops-oracle <mmproj_ops_oracle>] [--families ...]
+See test_data/mmproj_accuracy/README.md for the reference revision. --ops-oracle also
+regenerates the standalone op expectations.
+"""
+import argparse
+import os
+import subprocess
+import tempfile
+from pathlib import Path
+
+import gguf
+import numpy as np
+
+from mmproj_fixtures import TensorWriter, finish, merge_window_order, muse_glimmer_indices, save_npz, split_variants
+
+SINGLE_GRID = ("gemma3", "gemma3_fused", "gemma3_legacy", "idefics3", "janus_pro", "mlp", "mlp_norm", "mlp_feature",
+ "qwen2a", "ultravox", "voxtral", "musicflamingo", "meralion", "glma", "qwen2vl_merger",
+ "qwen2.5vl_merger", "qwen3vl_merger", "internvl", "internvl_qknorm", "qwen2.5vl_merger_window_video",
+ "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")
+TWO_GRID = ("muse-glimmer", "pixtral", "pixtral_merge", "phi4", "gemma4v", "gemma4uv", "gemma4uv_low_contrast",
+ "gemma4ua", "gemma4v_one_sided", "minicpmv4_6", "gemma4a", "deepseekocr", "deepseekocr2",
+ "deepseekocr_resize", "deepseekocr_overview", "deepseekocr2_overview", *REGRIDDED)
+
+
+def write_single_grid_model(path, projector, projection_width=6):
+ projector, _, variant = projector.partition("_") if projector.startswith("gemma3_") else (projector, "", "")
+ # Concatenated CLIP feature layers; InternViT-style whole-tensor QK norms.
+ if projector in ("mlp_feature", "internvl_qknorm"):
+ projector, _, variant = projector.partition("_")
+ if projector.startswith("resampler"):
+ projector, _, variant = projector.partition("_")
+ projection_width = 128 # one 128-wide cross-attention head
+ audio = projector in {"qwen2a", "ultravox", "voxtral", "musicflamingo", "meralion", "glma"}
+ clip = projector in {"mlp", "mlp_norm"}
+ qwen = projector in {"qwen2vl_merger", "qwen2.5vl_merger", "qwen3vl_merger"}
+ modality, prefix = ("audio", "a.") if audio else ("vision", "v.")
+ key = f"clip.{modality}."
+ w = gguf.GGUFWriter(path, "clip")
+ w.add_bool(f"clip.has_{modality}_encoder", True)
+ w.add_string("clip.projector_type", "mlp" if projector == "mlp_norm" else projector)
+ w.add_bool("clip.use_gelu", True)
+ if projector == "resampler":
+ if variant == "v4":
+ w.add_int32("clip.minicpmv_version", 4)
+ elif not variant:
+ w.add_int32("clip.minicpmv_version", 3)
+ w.add_uint32("clip.minicpmv_query_num", 3)
+ for name, value in {"embedding_length": 8, "feed_forward_length": 12, "block_count": 2,
+ "projection_dim": projection_width, "attention.head_count": 2}.items():
+ w.add_uint32(key + name, value)
+ w.add_float32(key + "attention.layer_norm_epsilon", 1e-5)
+ if variant == "feature":
+ w.add_array(key + "feature_layer", [1, 2])
+ rng = np.random.default_rng(1729)
+
+ def tensor(name, shape, norm=False):
+ if projector == "internvl" and name.startswith("mm."):
+ name = name.replace("mm.", "mm.model.mlp.", 1)
+ if variant == "legacy":
+ name = name.replace("ffn_up", "ffn_tmp").replace("ffn_down", "ffn_up").replace("ffn_tmp", "ffn_down")
+ values = rng.normal(0, 0.08, shape).astype(np.float32)
+ w.add_tensor(name, values + 1 if norm else values)
+
+ tensor(prefix + "position_embd.weight", (4900 if projector == "resampler" else
+ 17 if clip or projector == "internvl" else 16, 8))
+ if clip or projector == "internvl":
+ tensor("v.class_embd", (1, 8))
+ for i in range(2):
+ p = prefix + f"blk.{i}."
+ for name in ("ln1", "ln2"):
+ tensor(p + name + ".weight", (8,), True)
+ tensor(p + name + ".bias", (8,))
+ for name in (("attn_out",) if variant == "fused" else ("attn_q", "attn_k", "attn_v", "attn_out")):
+ tensor(p + name + ".weight", (8, 8))
+ if not (audio and name == "attn_k"):
+ tensor(p + name + ".bias", (8,))
+ if variant == "fused":
+ tensor(p + "attn_qkv.weight", (24, 8))
+ tensor(p + "attn_qkv.bias", (24,))
+ tensor(p + "attn_q_norm.weight", (4,), True)
+ tensor(p + "attn_k_norm.weight", (4,), True)
+ tensor(p + "ls1.weight", (8,))
+ tensor(p + "ls2.weight", (8,))
+ tensor(p + "out_scale.weight", (8,), True)
+ tensor(p + "attn_post_norm.weight", (8,), True)
+ tensor(p + "ffn_post_norm.weight", (8,), True)
+ if variant == "qknorm":
+ tensor(p + "attn_q_norm.weight", (8,), True)
+ tensor(p + "attn_k_norm.weight", (8,), True)
+ tensor(p + "ffn_up.weight", (12, 8))
+ tensor(p + "ffn_up.bias", (12,))
+ tensor(p + "ffn_down.weight", (8, 12))
+ tensor(p + "ffn_down.bias", (8,))
+ if projector == "qwen3vl_merger":
+ # The reference requires a fused projection for Qwen3 VL.
+ tensor(p + "attn_qkv.weight", (24, 8))
+ tensor(p + "attn_qkv.bias", (24,))
+ if projector == "qwen3vl_merger":
+ tensor("v.deepstack.0.norm.weight", (32,), True)
+ tensor("v.deepstack.0.norm.bias", (32,))
+ tensor("v.deepstack.0.fc1.weight", (12, 32))
+ tensor("v.deepstack.0.fc1.bias", (12,))
+ tensor("v.deepstack.0.fc2.weight", (6, 12))
+ tensor("v.deepstack.0.fc2.bias", (6,))
+ tensor(prefix + "post_ln.weight", (8,), True)
+ tensor(prefix + "post_ln.bias", (8,))
+ if not audio:
+ w.add_uint32(key + "image_size", 8)
+ w.add_uint32(key + "patch_size", 2)
+ w.add_uint32(key + "projector.scale_factor", 2)
+ w.add_array(key + "image_mean", [0.5, 0.5, 0.5])
+ w.add_array(key + "image_std", [0.5, 0.5, 0.5])
+ tensor("v.patch_embd.weight", (8, 3, 2, 2))
+ if not qwen or projector == "qwen3vl_merger":
+ tensor("v.patch_embd.bias", (8,))
+ if qwen:
+ w.add_uint32(key + "spatial_merge_size", 2)
+ w.add_uint32(key + "n_wa_pattern", 2 if projector == "qwen2.5vl_merger" else 0)
+ tensor("v.patch_embd.weight.1", (8, 3, 2, 2))
+ if projector == "resampler":
+ queries = 96 if variant == "v2" else 64 if variant == "v4" else 3
+ tensor("resampler.query", (queries, projection_width))
+ tensor("resampler.pos_embed_k", (16, projection_width))
+ tensor("resampler.proj.weight", (projection_width, projection_width))
+ tensor("resampler.kv.weight", (projection_width, 8))
+ for name in ("q", "k", "v", "out"):
+ tensor(f"resampler.attn.{name}.weight", (projection_width, projection_width))
+ tensor(f"resampler.attn.{name}.bias", (projection_width,))
+ for name in ("q", "kv", "post"):
+ tensor(f"resampler.ln_{name}.weight", (projection_width,), True)
+ tensor(f"resampler.ln_{name}.bias", (projection_width,))
+ elif projector == "gemma3":
+ tensor("mm.soft_emb_norm.weight", (8,), True)
+ tensor("mm.input_projection.weight", (8, projection_width))
+ elif projector == "idefics3":
+ tensor("mm.model.fc.weight", (6, 32))
+ elif qwen:
+ tensor("mm.0.weight", (12, 32))
+ tensor("mm.0.bias", (12,))
+ tensor("mm.2.weight", (6, 12))
+ tensor("mm.2.bias", (6,))
+ elif projector == "internvl":
+ tensor("mm.0.weight", (32,), True)
+ tensor("mm.0.bias", (32,))
+ tensor("mm.1.weight", (12, 32))
+ tensor("mm.1.bias", (12,))
+ tensor("mm.3.weight", (6, 12))
+ tensor("mm.3.bias", (6,))
+ elif clip:
+ tensor("mm.0.weight", (12, 16 if variant == "feature" else 8))
+ tensor("mm.0.bias", (12,))
+ tensor("mm.3.weight" if projector == "mlp_norm" else "mm.2.weight", (6, 12))
+ tensor("mm.3.bias" if projector == "mlp_norm" else "mm.2.bias", (6,))
+ if projector == "mlp_norm":
+ tensor("mm.1.weight", (12,), True)
+ tensor("mm.1.bias", (12,))
+ tensor("mm.4.weight", (6,), True)
+ tensor("mm.4.bias", (6,))
+ else:
+ tensor("mm.0.weight", (12, 8))
+ tensor("mm.0.bias", (12,))
+ tensor("mm.1.weight", (6, 12))
+ tensor("mm.1.bias", (6,))
+ else:
+ w.add_uint32(key + "num_mel_bins", 4)
+ w.add_uint32(key + "projector.stack_factor", 2)
+ tensor("a.conv1d.1.weight", (8, 4, 3))
+ tensor("a.conv1d.1.bias", (8, 1))
+ tensor("a.conv1d.2.weight", (8, 8, 3))
+ tensor("a.conv1d.2.bias", (8, 1))
+ if projector == "qwen2a":
+ tensor("mm.a.fc.weight", (6, 8))
+ tensor("mm.a.fc.bias", (6,))
+ elif projector == "meralion":
+ tensor("mm.a.norm_pre.weight", (16,), True)
+ tensor("mm.a.norm_pre.bias", (16,))
+ for i, shape in enumerate(((12, 16), (12, 12), (12, 12), (6, 12))):
+ tensor(f"mm.a.mlp.{i}.weight", shape)
+ tensor(f"mm.a.mlp.{i}.bias", (shape[0],))
+ else:
+ dim = 8 if projector == "musicflamingo" else 16
+ tensor("mm.a.mlp.1.weight", (24 if projector == "ultravox" else 12, dim))
+ tensor("mm.a.mlp.2.weight", (6, 12))
+ if projector == "ultravox":
+ tensor("mm.a.norm_pre.weight", (16,), True)
+ tensor("mm.a.norm_mid.weight", (12,), True)
+ if projector == "musicflamingo":
+ tensor("mm.a.mlp.1.bias", (12,))
+ tensor("mm.a.mlp.2.bias", (6,))
+ if projector == "glma":
+ tensor("mm.a.norm_pre.weight", (8,), True)
+ tensor("mm.a.norm_pre.bias", (8,))
+ tensor("mm.a.mlp.1.bias", (12,))
+ tensor("mm.a.mlp.2.bias", (6,))
+ tensor("v.boi", (1, 6))
+ tensor("v.eoi", (1, 6))
+ finish(w)
+ return audio
+
+
+def single_grid_inputs(projector, width, height):
+ """Raw oracle input, optional second video frame, encoder inputs and their family extras."""
+ audio = projector.removesuffix("_odd") in {"qwen2a", "ultravox", "voxtral", "musicflamingo", "meralion", "glma"}
+ window_video = projector.endswith("_window_video")
+ qwen = "vl_merger" in projector
+ shape = (height, width) if audio else (height, width, 3)
+ raw = np.random.default_rng(42).normal(0, 0.4, shape).astype(np.float32)
+ raw_second = np.random.default_rng(43).normal(0, 0.4, shape).astype(np.float32) if window_video else None
+ inputs = raw.reshape(1, height, 1, width) if audio else raw.transpose(2, 0, 1)[None]
+ extra = {}
+ if projector.startswith("resampler"):
+ rows, cols = np.indices((height // 2, width // 2))
+ extra["position_h"] = rows.astype(np.float32).reshape(1, 1, -1, 1)
+ extra["position_w"] = cols.astype(np.float32).reshape(1, 1, -1, 1)
+ extra["position_ids"] = ((70 * rows // (height // 2)) * 70 +
+ 70 * cols // (width // 2)).astype(np.int32).reshape(1, 1, 1, -1)
+ if qwen:
+ inputs = np.repeat(inputs, 2, axis=0)
+ indices = merge_window_order(height // 2, width // 2)
+ rows, cols = np.divmod(indices, width // 2)
+ extra["patch_indices"] = np.array(indices, np.int32).reshape(1, 1, 1, -1)
+ extra["position_ids"] = np.array([rows, cols, rows, cols], np.int32).reshape(1, 1, 1, -1)
+ extra["attention_mask"] = np.zeros((1, 1, len(indices), len(indices)), np.float32)
+ extra["output_indices"] = np.arange(len(indices) // 4, dtype=np.int32).reshape(1, 1, 1, -1)
+ if window_video:
+ inputs[1] = raw_second.transpose(2, 0, 1)
+ groups, windows = [], []
+ gh, gw = height // 4, width // 4
+ for y in range(0, gh, 28):
+ for x in range(0, gw, 28):
+ window = [yy * gw + xx for yy in range(y, min(y + 28, gh))
+ for xx in range(x, min(x + 28, gw))]
+ groups.extend(window)
+ windows.append(len(window) * 4)
+ permutation = np.array([4 * group + i for group in groups for i in range(4)])
+ extra["patch_indices"] = extra["patch_indices"][..., permutation]
+ extra["position_ids"] = np.array([rows[permutation], cols[permutation]] * 2,
+ np.int32).reshape(1, 1, 1, -1)
+ mask = np.full((len(indices), len(indices)), np.finfo(np.float32).min, np.float32)
+ offset = 0
+ for count in windows:
+ mask[offset:offset + count, offset:offset + count] = 0
+ offset += count
+ extra["attention_mask"] = mask[None, None]
+ extra["output_indices"] = np.argsort(groups).astype(np.int32).reshape(1, 1, 1, -1)
+ return raw, raw_second, inputs, extra
+
+
+def run_encoder_oracle(oracle, path, projector, width, height, raw, raw_second=None, env=None):
+ """Flat mmproj_oracle embeddings for `raw` (and an optional second video frame)."""
+ with tempfile.TemporaryDirectory() as directory:
+ directory = Path(directory)
+ raw.tofile(directory / "input.bin")
+ second = []
+ if raw_second is not None:
+ raw_second.tofile(directory / "second.bin")
+ second = [str(directory / "second.bin")]
+ audio = raw.ndim == 2
+ subprocess.run([str(oracle.resolve()), str(path), "audio" if audio else "vision",
+ str(width), str(height), str(directory / "input.bin"),
+ str(directory / "output.bin"), *second], check=True, env=env)
+ return np.fromfile(directory / "output.bin", dtype=np.float32)
+
+
+def single_grid_width(projector):
+ return 128 if projector.startswith("resampler") else 12 if projector == "qwen3vl_merger" else 6
+
+
+VARIANTS = ("_resize", "_overview", "_one_sided", "_low_contrast")
+# mmproj_ops_oracle output file -> test_data .npy name.
+OPS_EXPECTATIONS = {
+ "window_input": "mmproj_window_input", "windows": "mmproj_windows", "restored": "mmproj_restored",
+ "relative_table": "mmproj_relative_table", "relative": "mmproj_relative",
+ "vision": "vision_rope_expected", "imrope": "multimodal_imrope_expected",
+ "resize": "mmproj_interpolate_expected", "resize_corners": "mmproj_interpolate_corners_expected",
+ "resize_down": "mmproj_interpolate_down_expected",
+ "resize_down_corners": "mmproj_interpolate_down_corners_expected",
+ "im2col7": "mmproj_im2col7", "im2col9": "mmproj_im2col9",
+}
+
+
+def write_muse_model(path):
+ """Muse Glimmer: sparse/global windows, two-axis RoPE and pixel-shuffle merging."""
+ w = gguf.GGUFWriter(path, "clip")
+ t = TensorWriter(w, np.random.default_rng(20260922))
+ tensor, linear = t.tensor, t.linear
+ width, hidden, layers = 32, 48, 6
+ w.add_bool("clip.has_vision_encoder", True)
+ w.add_string("clip.projector_type", "muse-glimmer")
+ w.add_bool("clip.use_gelu", True)
+ for name, value in {"embedding_length": width, "feed_forward_length": hidden,
+ "block_count": layers, "projection_dim": 12, "attention.head_count": 4,
+ "image_size": 4, "patch_size": 2, "spatial_merge_size": 2,
+ "image_min_pixels": 16, "image_max_pixels": 4096}.items():
+ w.add_uint32("clip.vision." + name, value)
+ w.add_float32("clip.vision.attention.layer_norm_epsilon", 1e-5)
+ w.add_array("clip.vision.image_mean", [.5, .5, .5])
+ w.add_array("clip.vision.image_std", [.5, .5, .5])
+
+ def norm(name):
+ t.norm(name, width)
+
+ tensor("v.patch_embd.weight", (width, 3, 2, 2))
+ tensor("v.patch_embd.bias", (width,))
+ tensor("v.position_embd.weight", (9, width)) # 3x3 windows; the fixture grids leave partial ones
+ norm("v.pre_ln")
+ norm("v.post_ln")
+ for i in range(layers):
+ p = f"v.blk.{i}."
+ norm(p + "ln1")
+ norm(p + "ln2")
+ for name in ("attn_q", "attn_k", "attn_v", "attn_out"):
+ linear(p + name, width, width)
+ linear(p + "ffn_up", width, hidden)
+ linear(p + "ffn_down", hidden, width)
+ linear("mm.0", width * 4, 24, False)
+ linear("mm.1", 24, 20, False)
+ linear("mm.2", 20, 12, False)
+ finish(w)
+ return 12
+
+
+def write_grid_model(path, family):
+ if family == "muse-glimmer":
+ return write_muse_model(path)
+ family, variants = split_variants(family, *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
+ prefix, modality = ("a.", "audio") if audio else ("v.", "vision")
+ w = gguf.GGUFWriter(path, "clip")
+ t = TensorWriter(w, np.random.default_rng(2718))
+ tensor, linear, norm = t.tensor, t.linear, t.norm
+
+ w.add_bool(f"clip.has_{modality}_encoder", True)
+ w.add_string("clip.projector_type", family.removesuffix("_merge"))
+ w.add_bool("clip.use_gelu", True)
+ key = f"clip.{modality}."
+ for name, value in {"embedding_length": width, "feed_forward_length": hidden, "block_count": 0 if family in {"gemma4uv", "gemma4ua"} else 2,
+ "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":
+ 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))
+ tensor(f"a.conv1d.{i}.bias", (co, 1, 1))
+ norm(f"a.conv1d.{i}.norm", co, False)
+ linear("a.input_projection", 16, width)
+ for i in range(2):
+ p = f"a.blk.{i}."
+ for name in ("ffn_norm", "ffn_norm_1", "ffn_post_norm", "ffn_post_norm_1", "ln1", "ln2",
+ "attn_post_norm", "conv_norm", "norm_conv"):
+ norm(p + name, width, False)
+ for name in ("attn_q", "attn_k", "attn_v", "attn_out", "attn_k_rel", "conv_pw2"):
+ linear(p + name, width, width, False)
+ # Q-only input bounds catch clipping leaking into the shared K/V input.
+ w.add_tensor(p + "attn_q.input_min", np.array([-.2], np.float32))
+ w.add_tensor(p + "attn_q.input_max", np.array([.25], np.float32))
+ norm(p + "per_dim_scale", width // heads, False)
+ norm(p + "per_dim_k_scale", width // heads, False)
+ for suffix in ("", "_1"):
+ linear(p + "ffn_up" + suffix, width, hidden, False)
+ linear(p + "ffn_down" + suffix, hidden, width, False)
+ linear(p + "conv_pw1", width, width * 2, False)
+ tensor(p + "conv_dw.weight", (width, 5))
+ tensor(p + "conv_dw.bias", (width,))
+ linear("a.pre_encode.out", width, width)
+ norm("mm.a.soft_emb_norm", width, False)
+ linear("mm.a.input_projection", width, output, False)
+ elif audio:
+ w.add_uint32(key + "num_mel_bins", 640)
+ linear("mm.a.input_projection", 640, output, False)
+ else:
+ w.add_uint32(key + "image_size", 8)
+ w.add_uint32(key + "patch_size", 24 if low_contrast else 2)
+ w.add_uint32(key + "projector.scale_factor", 4 if family == "minicpmv4_6" else 2)
+ w.add_uint32(key + "image_min_pixels", 16)
+ w.add_uint32(key + "image_max_pixels", 4096)
+ w.add_array(key + "image_mean", [.5, .5, .5])
+ w.add_array(key + "image_std", [.5, .5, .5])
+ if family.startswith("deepseekocr"):
+ w.add_uint32(key + "sam.embedding_length", 8)
+ w.add_uint32(key + "sam.head_count", 2)
+ w.add_uint32(key + "sam.block_count", 3)
+ w.add_uint32(key + "window_size", 7)
+ if family == "deepseekocr2":
+ w.add_uint32(key + "attention.head_count_kv", 1)
+ tensor("v.resample_query_768.weight", (144, width))
+ tensor("v.resample_query_1024.weight", (256, width))
+ else:
+ tensor("v.class_embd", (width,))
+ tensor("v.position_embd.weight", (17, width))
+ tensor("v.image_newline", (output,))
+ tensor("v.view_seperator", (output,))
+ tensor("v.sam.patch_embd.weight", (8, 3, 16, 16))
+ tensor("v.sam.patch_embd.bias", (8,))
+ tensor("v.sam.pos_embd.weight", (16, 16, 8))
+ for i in range(12): # pinned loader requires 12 sets even in a shallow fixture
+ p = f"v.sam.blk.{i}."
+ norm(p + "pre_ln", 8)
+ norm(p + "post_ln", 8)
+ linear(p + "attn.qkv", 8, 24)
+ linear(p + "attn.out", 8, 8)
+ tensor(p + "attn.pos_h.weight", (13, 4))
+ tensor(p + "attn.pos_w.weight", (13, 4))
+ linear(p + "mlp.lin1", 8, 12)
+ linear(p + "mlp.lin2", 12, 8)
+ tensor("v.sam.neck.0.weight", (8, 8, 1, 1))
+ norm("v.sam.neck.1", 8)
+ tensor("v.sam.neck.2.weight", (8, 8, 3, 3))
+ norm("v.sam.neck.3", 8)
+ tensor("v.sam.net_2.weight", (8, 8, 3, 3))
+ tensor("v.sam.net_3.weight", (width, 8, 3, 3))
+ linear("mm.model.fc", width if family == "deepseekocr2" else width * 2, output)
+ if family == "gemma4uv":
+ patch_width = 3 * (48 if low_contrast else 4) ** 2
+ if low_contrast:
+ # Large, nearly constant patch-projection rows amplify errors in
+ # the mean of normalized low-contrast patches.
+ weights = np.broadcast_to(np.linspace(-30, 30, width)[:, None] / patch_width,
+ (width, patch_width)).copy()
+ w.add_tensor("v.patch_embd.weight", weights.astype(np.float32))
+ tensor("v.patch_embd.bias", (width,))
+ w.add_tensor("v.patch_norm.1.weight", np.ones(patch_width, np.float32))
+ w.add_tensor("v.patch_norm.1.bias", np.zeros(patch_width, np.float32))
+ else:
+ linear("v.patch_embd", patch_width, width)
+ norm("v.patch_norm.1", patch_width)
+ norm("v.patch_norm.2", width)
+ norm("v.patch_norm.3", width)
+ else:
+ tensor("v.patch_embd.weight", (width, 3, 2, 2))
+ if family != "gemma4v":
+ tensor("v.patch_embd.bias", (width,))
+ if family.startswith("gemma4"):
+ tensor("v.position_embd.weight", (2, 32, width))
+ linear("mm.input_projection", width, output, False)
+ if family == "gemma4v":
+ tensor("v.std_bias", (width,))
+ tensor("v.std_scale", (width,), True)
+ elif family == "phi4":
+ tensor("v.position_embd.weight", (16, width))
+ linear("mm.0", width, hidden)
+ linear("mm.2", hidden, output)
+ elif family.startswith("pixtral"):
+ tensor("v.token_embd.img_break", (output,))
+ linear("mm.1", width, hidden)
+ linear("mm.2", hidden, output)
+ if family.endswith("_merge"):
+ w.add_uint32(key + "spatial_merge_size", 2)
+ norm("mm.input_norm", width, False)
+ linear("mm.patch_merger", width * 4, width, False)
+ elif family == "minicpmv4_6":
+ tensor("v.position_embd.weight", (4900, width))
+ w.add_array(key + "wa_layer_indexes", [0])
+ p = "v.vit_merger."
+ norm(p + "ln1", width)
+ for name in ("attn_q", "attn_k", "attn_v", "attn_out"):
+ linear(p + name, width, width)
+ norm(p + "ds_ln", width * 4)
+ linear(p + "ds_ffn_up", width * 4, hidden)
+ linear(p + "ds_ffn_down", hidden, width)
+ norm("mm.input_norm", width * 4)
+ linear("mm.up", width * 4, hidden)
+ linear("mm.down", hidden, output)
+ if family != "gemma4uv":
+ norm("v.pre_ln", width)
+ norm("v.post_ln", width)
+ for i in range(2):
+ p = f"v.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 // 2 if family == "deepseekocr2" and name in {"attn_k", "attn_v"} else width)
+ if family == "gemma4v":
+ norm(p + "attn_post_norm", width, False)
+ norm(p + "ffn_post_norm", width, False)
+ norm(p + "attn_q_norm", width // heads, False)
+ norm(p + "attn_k_norm", width // heads, False)
+ # Nontrivial clipping catches omission or bias/clamp ordering errors.
+ for side in ("input", "output"):
+ if not one_sided or i == 0:
+ w.add_tensor(p + f"attn_q.{side}_min", np.array([-.2], np.float32))
+ if not one_sided or i == 1:
+ w.add_tensor(p + f"attn_q.{side}_max", np.array([.25], np.float32))
+ linear(p + "ffn_up", width, hidden)
+ linear(p + "ffn_down", hidden, width)
+ if family.startswith("pixtral") or family in {"gemma4v", "deepseekocr2"}:
+ linear(p + "ffn_gate", width, hidden)
+ finish(w)
+ return output
+
+
+def grid_inputs(family, width, height):
+ if family == "muse-glimmer":
+ raw = np.random.default_rng(42).uniform(-1, 1, (height, width, 3)).astype(np.float32)
+ 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)
+ 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.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))
+ side = width // 16
+ local = np.arange(7)
+ glob = np.arange(side)
+ result = {"relative_indices_local": (local[:, None] - local[None] + 6).astype(np.int32)[None, None],
+ "relative_indices_global": (glob[:, None] - glob[None] + side - 1).astype(np.int32)[None, None]}
+ if family == "deepseekocr2":
+ n = (width // 64) ** 2
+ result["pixel_values"] = raw.transpose(2, 0, 1)[None]
+ result["query_indices"] = np.arange(0 if n == 144 else 144, 144 if n == 144 else 400, dtype=np.int32).reshape(1, 1, 1, -1)
+ result["query_output_indices"] = np.arange(n, 2 * n, dtype=np.int32).reshape(1, 1, 1, -1)
+ result["position_ids"] = np.arange(2 * n, dtype=np.int32).reshape(1, 1, 1, -1)
+ q, k = np.indices((2 * n, 2 * n))
+ result["attention_mask"] = np.where((k < n) | ((q >= n) & (k <= q)), 0, -1e9).astype(np.float32)[None, None]
+ result["output_indices"] = np.arange(n + int(overview), dtype=np.int32).reshape(1, 1, 1, -1)
+ else:
+ batch = height // width
+ result["pixel_values"] = raw.reshape(batch, width, width, 3).transpose(0, 3, 1, 2)
+ grid = width // 64
+ result["position_indices"] = np.arange(0 if grid == 4 else 17, 17 if grid == 4 else 18 + grid * grid, dtype=np.int32).reshape(1, 1, 1, -1)
+ total = batch * grid * grid
+ order = [index for y in range(grid) for index in
+ ([b * grid * grid + y * grid + x for b in range(batch) for x in range(grid)] + [total])]
+ result["output_indices"] = np.array(order + ([total + 1] if overview else []), np.int32).reshape(1, 1, 1, -1)
+ return raw, result
+ result = {"pixel_values": raw.transpose(2, 0, 1)[None]}
+ patch = (48 if "_low_contrast" in variants else 4) if family == "gemma4uv" else 2
+ h, w = height // patch, width // patch
+ rows, cols = np.indices((h, w))
+ if family.startswith(("pixtral", "gemma4")):
+ result.update(position_x=cols.astype(np.int32).reshape(1, 1, 1, -1),
+ position_y=rows.astype(np.int32).reshape(1, 1, 1, -1))
+ if family == "minicpmv4_6":
+ result["position_ids"] = (70 * (70 * rows // h) + 70 * cols // w).astype(np.int32).reshape(1, 1, 1, -1)
+ order = merge_window_order(h, w)
+ result["window_indices"] = np.array(order, np.int32).reshape(1, 1, 1, -1)
+ result["inverse_window_indices"] = np.argsort(order).astype(np.int32).reshape(1, 1, 1, -1)
+ index = np.arange(h * w) // 4
+ result["attention_mask"] = np.where(index[:, None] == index[None], 0, np.finfo(np.float32).min).astype(np.float32)[None, None]
+ for name, dh, dw in (("vit_merger", h, w), ("merger", h // 2, w // 2)):
+ for i, (dy, dx) in enumerate(((0, 0), (0, 1), (1, 0), (1, 1))):
+ result[f"{name}.indices.{i}"] = np.array([(y + dy) * dw + x + dx
+ for y in range(0, dh, 2) for x in range(0, dw, 2)], np.int32).reshape(1, 1, 1, -1)
+ return raw, result
+
+
+def single_grid_fixture(oracle, family):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "model.gguf"
+ window_video = family.endswith("_window_video")
+ audio = write_single_grid_model(path, family.removesuffix("_window_video").removesuffix("_odd"))
+ qwen = "vl_merger" in family
+ width, height = (120, 16) if window_video else (16, 4) if audio else (12, 8) if qwen else (8, 8)
+ if family.startswith("resampler"):
+ width, height = (12, 8) if family == "resampler" else (8, 12)
+ if family.endswith("_odd"):
+ width = 18
+ raw, raw_second, inputs, extra = single_grid_inputs(family, width, height)
+ output = run_encoder_oracle(oracle, path, family, width, height, raw, raw_second)
+ output = output.reshape(1, 1, -1, single_grid_width(family))
+ return {"model": np.frombuffer(path.read_bytes(), np.uint8), "inputs": inputs, "embeddings": output, **extra}
+
+
+def two_grid_fixture(oracle, family):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "model.gguf"
+ if family in REGRIDDED:
+ projector = family.removesuffix("_grids")
+ write_single_grid_model(path, projector)
+ width_out = single_grid_width(projector)
+ sizes = [(12, 8), (8, 16)]
+ else:
+ width_out = write_grid_model(path, family)
+ sizes = {
+ "deepseekocr2": [(768, 768), (1024, 1024)],
+ "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)],
+ "gemma4ua": [(3, 640), (5, 640)],
+ "gemma4uv_low_contrast": [(96, 48), (48, 144)],
+ "muse-glimmer": [(12, 8), (4, 4)],
+ }.get(family, [(16, 8), (8, 24)])
+ environment = dict(os.environ, **({"GGUF_ORACLE_OVERVIEW": "1"} if family.endswith("_overview") else {}))
+ fixtures = {"model": np.frombuffer(path.read_bytes(), np.uint8)}
+ for step, (width, height) in enumerate(sizes):
+ if family in REGRIDDED:
+ raw, second, pixels, values = single_grid_inputs(projector, width, height)
+ values = {"pixel_values": pixels, **values}
+ embeddings = run_encoder_oracle(oracle, path, projector, width, height, raw, second)
+ 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()})
+ return fixtures
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--oracle", type=Path, required=True)
+ parser.add_argument("--ops-oracle", type=Path, help="Optional mmproj_ops_oracle executable")
+ parser.add_argument("--output", type=Path, default=Path(__file__).parent / "test_data/mmproj_accuracy")
+ parser.add_argument("--families", nargs="+", default=[*SINGLE_GRID, *TWO_GRID])
+ args = parser.parse_args()
+ args.output.mkdir(parents=True, exist_ok=True)
+ if args.ops_oracle:
+ with tempfile.TemporaryDirectory() as directory:
+ subprocess.run([str(args.ops_oracle.resolve()), directory], check=True)
+ for name, npy in OPS_EXPECTATIONS.items():
+ np.save(args.output.parent / f"{npy}.npy", np.fromfile(Path(directory) / f"{name}.bin", np.float32))
+ for family in args.families:
+ make = two_grid_fixture if family in TWO_GRID else single_grid_fixture
+ save_npz(args.output / f"{family}.npz", make(args.oracle, family))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/frontends/gguf/tests/gguf_writer.hpp b/src/frontends/gguf/tests/gguf_writer.hpp
index c9122d59a48..fd5660ed61c 100644
--- a/src/frontends/gguf/tests/gguf_writer.hpp
+++ b/src/frontends/gguf/tests/gguf_writer.hpp
@@ -6,6 +6,7 @@
#pragma once
+#include <cmath>
#include <cstdint>
#include <cstring>
#include <fstream>
@@ -21,6 +22,7 @@ enum : uint32_t {
GGUF_TYPE_FLOAT32 = 6,
GGUF_TYPE_BOOL = 7,
GGUF_TYPE_STRING = 8,
+ GGUF_TYPE_ARRAY = 9,
};
// ggml tensor type F32 (ggml.h GGML_TYPE_F32).
@@ -45,6 +47,35 @@ public:
put(static_cast<uint64_t>(v.size()));
m_kv.insert(m_kv.end(), v.begin(), v.end());
}
+ void kv_u32_array(const std::string& key, const std::vector<uint32_t>& values) {
+ kv_key(key, GGUF_TYPE_ARRAY);
+ put(uint32_t(GGUF_TYPE_UINT32));
+ put(uint64_t(values.size()));
+ for (auto value : values)
+ put(value);
+ }
+ void kv_str_array(const std::string& key, const std::vector<std::string>& values) {
+ kv_key(key, GGUF_TYPE_ARRAY);
+ put(uint32_t(GGUF_TYPE_STRING));
+ put(uint64_t(values.size()));
+ for (const auto& value : values)
+ put_str(m_kv, value);
+ }
+
+ // Fill with a deterministic nonzero pattern. `norm_ramp` slopes norm weights per element so a
+ // norm tensor is not indistinguishable from an identity.
+ void filled_tensor(const std::string& name,
+ const std::vector<uint64_t>& dims,
+ bool norm = false,
+ float norm_ramp = 0.f) {
+ size_t count = 1;
+ for (auto d : dims)
+ count *= d;
+ std::vector<float> values(count);
+ for (size_t i = 0; i < count; ++i)
+ values[i] = norm ? 1.f + norm_ramp * float(i) : 0.1f * std::sin(float(i + 1));
+ tensor(name, dims, values);
+ }
// dims uses GGUF order (fastest axis first). Empty values produce zero-filled data.
void tensor(const std::string& name, const std::vector<uint64_t>& dims, const std::vector<float>& values = {}) {
diff --git a/src/frontends/gguf/tests/mmproj_fixtures.py b/src/frontends/gguf/tests/mmproj_fixtures.py
new file mode 100644
index 00000000000..1eb6fe91276
--- /dev/null
+++ b/src/frontends/gguf/tests/mmproj_fixtures.py
@@ -0,0 +1,187 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+"""Shared helpers for the mmproj fixture generators."""
+import io
+import subprocess
+import tempfile
+import zipfile
+from pathlib import Path
+
+import numpy as np
+
+
+def finish(writer):
+ """Flush a gguf.GGUFWriter and close it."""
+ writer.write_header_to_file()
+ writer.write_kv_data_to_file()
+ writer.write_tensors_to_file()
+ writer.close()
+
+
+class TensorWriter:
+ """Random F32 fixture tensors added to a gguf.GGUFWriter; norm weights are centered at 1."""
+
+ def __init__(self, writer, rng, std=.08):
+ self.writer, self.rng, self.std = writer, rng, std
+
+ def tensor(self, name, shape, norm=False):
+ self.writer.add_tensor(name, (self.rng.normal(0, self.std, shape) + int(norm)).astype(np.float32))
+
+ def linear(self, name, inp, out, bias=True):
+ self.tensor(name + ".weight", (out, inp))
+ if bias:
+ self.tensor(name + ".bias", (out,))
+
+ def norm(self, name, size, bias=True):
+ self.tensor(name + ".weight", (size,), True)
+ if bias:
+ self.tensor(name + ".bias", (size,))
+
+
+def run_oracle(oracle, model, modality, width, height, raw, env=None):
+ """Run mmproj_oracle on `raw` and return its flat F32 embeddings."""
+ with tempfile.TemporaryDirectory() as directory:
+ directory = Path(directory)
+ raw.tofile(directory / "input.f32")
+ subprocess.run([str(Path(oracle).resolve()), str(model), modality, str(width), str(height),
+ str(directory / "input.f32"), str(directory / "output.f32")], check=True, env=env)
+ return np.fromfile(directory / "output.f32", np.float32)
+
+
+def merge_window_order(height, width, merge=2):
+ """Grid indices with each merge x merge window contiguous, windows in row-major order."""
+ return [(y + dy) * width + x + dx
+ for y in range(0, height, merge) for x in range(0, width, merge)
+ for dy in range(merge) for dx in range(merge)]
+
+
+def split_variants(name, *suffixes):
+ """Strip known fixture suffixes off `name`, returning (base, set of suffixes present)."""
+ present = set()
+ for suffix in suffixes:
+ if name.endswith(suffix):
+ present.add(suffix)
+ name = name[: -len(suffix)]
+ return name, present
+
+
+def save_npz(path, arrays):
+ """Write an .npz cnpy can read: NumPy's savez forces ZIP64 even for tiny arrays."""
+ with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as archive:
+ for key, array in arrays.items():
+ payload = io.BytesIO()
+ np.save(payload, np.ascontiguousarray(array))
+ info = zipfile.ZipInfo(key + ".npy", date_time=(1980, 1, 1, 0, 0, 0))
+ info.compress_type = zipfile.ZIP_DEFLATED
+ archive.writestr(info, payload.getvalue())
+
+
+def muse_glimmer_indices(height, width, window, merge=2):
+ """Encoder inputs matching clip.cpp's Muse Glimmer window and shuffle ordering. Every window is
+ padded to window^2 slots that repeat its first patch and are masked out as keys."""
+ if min(height, width, window, merge) <= 0 or height % merge or width % merge:
+ raise ValueError("Muse Glimmer grid must be positive and divisible by its merge size")
+ groups = [[y * width + x
+ for y in range(wy, min(wy + window, height))
+ for x in range(wx, min(wx + window, width))]
+ for wy in range(0, height, window) for wx in range(0, width, window)]
+ slots = window * window
+ order = np.array([i for group in groups for i in group + group[:1] * (slots - len(group))], np.int32)
+ valid = np.array([k < len(group) for group in groups for k in range(slots)])
+ inverse = np.empty(height * width, np.int32)
+ inverse[order[valid]] = np.flatnonzero(valid)
+ rows, cols = np.divmod(order, width)
+ def indices(values):
+ return np.asarray(values, np.int32).reshape(1, 1, 1, -1)
+ return {"patch_indices": indices(order), "output_indices": indices(inverse),
+ "position_x": indices(cols + 1), "position_y": indices(rows + 1),
+ "merge_indices": indices(merge_window_order(height, width, merge)),
+ "window_mask": np.where(valid, 0, -np.inf).astype(np.float32).reshape(len(groups), 1, 1, slots)}
+
+
+WHISPER_AUDIO = {"qwen2a", "ultravox", "voxtral", "musicflamingo", "meralion", "glma"}
+FIXED_VISION = {"gemma3", "idefics3", "internvl", "janus_pro", "mlp"}
+DYNAMIC_VISION = {"gemma4v", "gemma4uv", "pixtral", "qwen2vl_merger", "qwen2.5vl_merger", "qwen3vl_merger",
+ "muse-glimmer"}
+
+
+def vision_patch(metadata):
+ """Pixels per encoder patch; unified Gemma4 patches span scale_factor reference patches."""
+ patch = int(metadata["clip.vision.patch_size"])
+ if metadata["vision.projector"] == "gemma4uv":
+ patch *= int(metadata.get("clip.vision.projector.scale_factor", 3))
+ return patch
+
+
+def grid_unit(metadata, modality):
+ """Image side granularity (pixels) or audio frame granularity a checkpoint accepts."""
+ if modality == "audio":
+ return 1 if metadata["audio.projector"] in {"gemma4a", "gemma4ua"} else 32
+ return vision_patch(metadata) * int(metadata.get("vision.merge", 1))
+
+
+def checkpoint_inputs(metadata, modality, width, height=None, seed=42):
+ """Encoder inputs for a real checkpoint, read from its gguf_mmproj rt_info.
+
+ Returns (feeds, raw, width, height): feeds name the converted model's inputs, and raw with
+ width/height is what mmproj_oracle takes. For audio, width is the frame count.
+ """
+ projector = metadata[f"{modality}.projector"]
+ rng = np.random.default_rng(seed)
+ if modality == "audio":
+ if projector == "gemma4ua":
+ raw = rng.normal(0, .4, (640, width)).astype(np.float32)
+ return {"audio.waveform_frames": raw.T.reshape(1, 1, width, 640)}, raw, width, 640
+ mel = int(metadata["clip.audio.num_mel_bins"])
+ raw = rng.normal(0, .4, (mel, width)).astype(np.float32)
+ if projector == "gemma4a":
+ return {"audio.features": raw.reshape(1, 1, mel, width)}, raw, width, mel
+ if projector not in WHISPER_AUDIO:
+ raise ValueError(f"No audio input contract for {projector}")
+ ids = np.arange((width + 1) // 2, dtype=np.int32).reshape(1, 1, 1, -1)
+ return {"audio.features": raw.reshape(1, mel, 1, width), "audio.position_ids": ids}, raw, width, mel
+ if projector in FIXED_VISION:
+ width = height = int(metadata["clip.vision.image_size"])
+ elif projector not in DYNAMIC_VISION:
+ raise ValueError(f"No vision input contract for {projector}")
+ pixels = rng.uniform(0 if projector == "gemma4v" else -1, 1, (1, 3, height, width)).astype(np.float32)
+ feeds = {"vision.pixel_values": pixels}
+ raw = pixels[0].transpose(1, 2, 0)
+ if projector in FIXED_VISION:
+ return feeds, raw, width, height
+ patch = vision_patch(metadata)
+ gh, gw = height // patch, width // patch
+ index = lambda values: np.asarray(values, np.int32).reshape(1, 1, 1, -1)
+ if projector in {"gemma4v", "gemma4uv", "pixtral"}:
+ rows, cols = np.indices((gh, gw))
+ feeds.update({"vision.position_x": index(cols), "vision.position_y": index(rows)})
+ elif projector == "muse-glimmer":
+ feeds.update({"vision." + name: value for name, value in muse_glimmer_indices(
+ gh, gw, int(metadata["vision.window_size"]), int(metadata["vision.merge"])).items()})
+ else:
+ # Qwen: a still image is a repeated temporal pair, grouped into 2x2 merge windows.
+ order = np.array(merge_window_order(gh, gw), np.int32)
+ if projector == "qwen2.5vl_merger":
+ # llama.cpp's window attention: windows of window_size pixels in merged units.
+ window = int(metadata.get("clip.vision.window_size", 112)) // patch // 2
+ mh, mw = gh // 2, gw // 2
+ groups, sizes = [], []
+ for y in range(0, mh, window):
+ for x in range(0, mw, window):
+ block = [yy * mw + xx for yy in range(y, min(y + window, mh)) for xx in range(x, min(x + window, mw))]
+ groups += block
+ sizes.append(4 * len(block))
+ order = order.reshape(-1, 4)[groups].reshape(-1)
+ mask = np.full((order.size, order.size), np.finfo(np.float32).min, np.float32)
+ start = 0
+ for size in sizes:
+ mask[start:start + size, start:start + size] = 0
+ start += size
+ feeds["vision.attention_mask"] = mask[None, None]
+ feeds["vision.output_indices"] = index(np.argsort(groups))
+ rows, cols = np.divmod(order, gw)
+ feeds["vision.pixel_values"] = np.repeat(pixels, 2, axis=0)
+ feeds["vision.patch_indices"] = index(order)
+ feeds["vision.position_ids"] = index(np.concatenate([rows, cols, rows, cols]))
+ return feeds, raw, width, height
diff --git a/src/frontends/gguf/tests/mmproj_ops_oracle.cpp b/src/frontends/gguf/tests/mmproj_ops_oracle.cpp
new file mode 100644
index 00000000000..62612704e5e
--- /dev/null
+++ b/src/frontends/gguf/tests/mmproj_ops_oracle.cpp
@@ -0,0 +1,140 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+// Offline ggml oracle for the multimodal op tests. Link against the pinned ggml CPU libraries.
+// Usage: mmproj_ops_oracle <output directory>; writes one raw F32 file per expectation.
+#include <cmath>
+#include <filesystem>
+#include <fstream>
+#include <string>
+#include <vector>
+
+#include "ggml-backend.h"
+#include "ggml-cpu.h"
+#include "ggml.h"
+
+// Window partition/unpartition and SAM relative positions.
+int geometry(const std::filesystem::path& directory) {
+ auto* ctx = ggml_init({64 * 1024 * 1024, nullptr, false});
+ auto* input = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 3, 5, 3, 1);
+ for (int i = 0; i < 45; ++i)
+ static_cast<float*>(input->data)[i] = std::sin(float(i) * .13f);
+ auto* windows = ggml_win_part(ctx, input, 2);
+ auto* restored = ggml_win_unpart(ctx, windows, 5, 3, 2);
+ // SAM decomposed relative positions: resize a 3-entry [L, C] table to 2 * 3 - 1 rows, gather q - k + 2.
+ auto* table = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 4, 3);
+ for (int i = 0; i < 12; ++i)
+ static_cast<float*>(table->data)[i] = std::sin(float(i) * .37f);
+ auto* indices = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 9);
+ for (int q = 0; q < 3; ++q)
+ for (int k = 0; k < 3; ++k)
+ static_cast<int32_t*>(indices->data)[q * 3 + k] = q - k + 2;
+ auto* lengths = ggml_reshape_3d(ctx, ggml_cont(ctx, ggml_transpose(ctx, table)), 3, 1, 4);
+ auto* resized = ggml_cont(
+ ctx,
+ ggml_transpose(
+ ctx,
+ ggml_reshape_2d(ctx, ggml_interpolate(ctx, lengths, 5, 1, 4, 1, GGML_SCALE_MODE_BILINEAR), 5, 4)));
+ auto* relative = ggml_get_rows(ctx, resized, indices);
+ auto* graph = ggml_new_graph(ctx);
+ ggml_build_forward_expand(graph, restored);
+ ggml_build_forward_expand(graph, relative);
+ if (ggml_graph_compute_with_ctx(ctx, graph, 2) != GGML_STATUS_SUCCESS)
+ return 3;
+ const auto save = [&](const char* name, ggml_tensor* t) {
+ std::ofstream out(directory / name, std::ios::binary);
+ out.write(static_cast<char*>(t->data), ggml_nbytes(t));
+ };
+ save("window_input.bin", input);
+ save("windows.bin", windows);
+ save("restored.bin", restored);
+ save("relative_table.bin", table);
+ save("relative.bin", relative);
+ ggml_free(ctx);
+ return 0;
+}
+
+// One op per mode: vision/imrope RoPE, antialiased bilinear resize variants, or 2D im2col.
+int single_op(const std::string& mode, const std::filesystem::path& output) {
+ const bool vision = mode == "vision";
+ const bool resize = mode.find("resize") == 0;
+ const bool downsample = mode.find("resize_down") == 0;
+ const bool corners = mode.find("corners") != std::string::npos;
+ const bool im2col = mode.find("im2col") == 0;
+ const int image_width = mode == "im2col7" ? 7 : 9;
+ const int image_height = image_width == 7 ? 5 : 4;
+ auto* ctx = ggml_init({16 * 1024 * 1024, nullptr, true});
+ auto* x = im2col ? ggml_new_tensor_4d(ctx, GGML_TYPE_F32, image_width, image_height, 2, 1)
+ : resize ? ggml_new_tensor_4d(ctx, GGML_TYPE_F32, downsample ? 12 : 3, downsample ? 8 : 2, 2, 1)
+ : ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 64, 3, 2, 1);
+ auto* positions = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 8);
+ int vision_sections[4] = {16, 16, 16, 16};
+ int text_sections[4] = {8, 7, 9, 8};
+ auto* y = im2col ? ggml_im2col(ctx,
+ ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 3, 2, 2, 1),
+ x,
+ 2,
+ 1,
+ 1,
+ 0,
+ 1,
+ 1,
+ true,
+ GGML_TYPE_F32)
+ : resize ? ggml_interpolate(ctx,
+ x,
+ 5,
+ 4,
+ 2,
+ 1,
+ GGML_SCALE_MODE_BILINEAR | GGML_SCALE_FLAG_ANTIALIAS |
+ (corners ? GGML_SCALE_FLAG_ALIGN_CORNERS : 0))
+ : ggml_rope_multi(ctx,
+ x,
+ positions,
+ nullptr,
+ vision ? 32 : 64,
+ vision ? vision_sections : text_sections,
+ vision ? GGML_ROPE_TYPE_VISION : GGML_ROPE_TYPE_IMROPE,
+ 32768,
+ 10000.f,
+ 1.f,
+ 0.f,
+ 1.f,
+ 32.f,
+ 1.f);
+ auto* graph = ggml_new_graph(ctx);
+ ggml_build_forward_expand(graph, y);
+ auto backend = ggml_backend_cpu_init();
+ auto buffer = ggml_backend_alloc_ctx_tensors(ctx, backend);
+ std::vector<float> data(ggml_nelements(x));
+ for (size_t i = 0; i < data.size(); ++i)
+ data[i] = std::sin(float(i) * 0.13f);
+ const int32_t pos[8] = {3, 7, 11, 2, 5, 13, 17, 19};
+ ggml_backend_tensor_set(x, data.data(), 0, data.size() * sizeof(float));
+ ggml_backend_tensor_set(positions, pos, 0, sizeof(pos));
+ const auto status = ggml_backend_graph_compute(backend, graph);
+ if (status == GGML_STATUS_SUCCESS) {
+ data.resize(ggml_nelements(y));
+ ggml_backend_tensor_get(y, data.data(), 0, data.size() * sizeof(float));
+ std::ofstream out(output, std::ios::binary);
+ out.write(reinterpret_cast<const char*>(data.data()), data.size() * sizeof(float));
+ }
+ ggml_backend_buffer_free(buffer);
+ ggml_backend_free(backend);
+ ggml_free(ctx);
+ return status == GGML_STATUS_SUCCESS ? 0 : 1;
+}
+
+int main(int argc, char** argv) {
+ if (argc != 2)
+ return 2;
+ const std::filesystem::path directory(argv[1]);
+ std::filesystem::create_directories(directory);
+ int status = geometry(directory);
+ for (const char* mode :
+ {"vision", "imrope", "resize", "resize_corners", "resize_down", "resize_down_corners", "im2col7", "im2col9"})
+ status = status ? status : single_op(mode, directory / (std::string(mode) + ".bin"));
+ return status;
+}
diff --git a/src/frontends/gguf/tests/mmproj_oracle.cpp b/src/frontends/gguf/tests/mmproj_oracle.cpp
new file mode 100644
index 00000000000..5e45441fff1
--- /dev/null
+++ b/src/frontends/gguf/tests/mmproj_oracle.cpp
@@ -0,0 +1,74 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+// Offline reference generator. Link against the pinned llama.cpp libmtmd and libggml.
+// Usage: mmproj_oracle model.gguf vision|audio width height input.f32 output.f32
+#include <cstdlib>
+#include <filesystem>
+#include <fstream>
+#include <iostream>
+
+#include "clip-impl.h"
+#include "clip.h"
+#include "ggml-backend.h"
+
+int main(int argc, char** argv) {
+ if (argc != 7 && argc != 8)
+ return 2;
+ ggml_backend_load_all();
+ clip_context_params params{};
+ params.use_gpu = false;
+ params.flash_attn_type = CLIP_FLASH_ATTN_TYPE_DISABLED;
+ if (const char* directory = std::getenv("GGUF_ORACLE_DUMP")) {
+ std::filesystem::create_directories(directory);
+ params.cb_eval_user_data = const_cast<char*>(directory);
+ params.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());
+ auto path = std::filesystem::path(static_cast<const char*>(data)) / (std::string(tensor->name) + ".bin");
+ std::ofstream output(path, std::ios::binary);
+ output.write(bytes.data(), bytes.size());
+ return true;
+ };
+ }
+ const auto contexts = clip_init(argv[1], params);
+ const bool audio = std::string(argv[2]) == "audio";
+ auto* context = audio ? contexts.ctx_a : contexts.ctx_v;
+ if (!context)
+ return 3;
+ clip_image_f32 input;
+ const int width = std::stoi(argv[3]), height = std::stoi(argv[4]);
+ input.set_size({width, height}, false, audio);
+ input.add_viewsep = std::getenv("GGUF_ORACLE_OVERVIEW") != nullptr;
+ std::vector<float> values(size_t(width) * height * (audio ? 1 : 3));
+ std::ifstream file(argv[5], std::ios::binary);
+ file.read(reinterpret_cast<char*>(values.data()), values.size() * sizeof(float));
+ if (!file)
+ return 4;
+ input.cpy_buf(values);
+ std::vector<float> output(size_t(clip_n_output_tokens(context, &input)) * clip_n_mmproj_embd(context));
+ clip_image_f32_batch batch;
+ batch.is_audio = audio;
+ batch.entries.push_back(input);
+ if (argc == 8) {
+ std::ifstream second(argv[7], std::ios::binary);
+ second.read(reinterpret_cast<char*>(values.data()), values.size() * sizeof(float));
+ if (!second)
+ return 4;
+ input.cpy_buf(values);
+ batch.entries.push_back(input);
+ }
+ const bool ok = clip_image_batch_encode(context, 2, &batch, output);
+ if (ok) {
+ std::ofstream result(argv[6], std::ios::binary);
+ result.write(reinterpret_cast<const char*>(output.data()), output.size() * sizeof(float));
+ }
+ if (contexts.ctx_v)
+ clip_free(contexts.ctx_v);
+ if (contexts.ctx_a)
+ clip_free(contexts.ctx_a);
+ return ok ? 0 : 5;
+}
diff --git a/src/frontends/gguf/tests/op_test_utils.hpp b/src/frontends/gguf/tests/op_test_utils.hpp
index e987eaa8cf1..df30d5f2f3e 100644
--- a/src/frontends/gguf/tests/op_test_utils.hpp
+++ b/src/frontends/gguf/tests/op_test_utils.hpp
@@ -19,6 +19,8 @@
#include <algorithm>
#include <cmath>
#include <cstring>
+#include <filesystem>
+#include <fstream>
#include <map>
#include <memory>
#include <set>
@@ -26,6 +28,7 @@
#include <vector>
#include "cnpy.h"
+#include "common_test_utils/common_utils.hpp"
#include "common_test_utils/file_utils.hpp"
#include "gtest/gtest.h"
#include "op_table.hpp"
@@ -324,4 +327,66 @@ std::vector<T> load_npy(const std::string& stem) {
return std::vector<T>(begin, begin + arr.num_vals);
}
+// cnpy::npz_t is a vector of pairs, so look the entry up by name.
+inline const cnpy::NpyArray& npz_array(const cnpy::npz_t& arrays, const std::string& name) {
+ const auto it = std::find_if(arrays.begin(), arrays.end(), [&](const auto& entry) {
+ return entry.first == name;
+ });
+ OPENVINO_ASSERT(it != arrays.end(), "Missing reference array ", name);
+ return it->second;
+}
+
+// Normalized MSE, the acceptance metric for the accuracy fixtures: sum((a-e)^2) / sum(e^2).
+class Nmse {
+public:
+ void add(double actual, double expected) {
+ m_error += (actual - expected) * (actual - expected);
+ m_norm += expected * expected;
+ m_finite = m_finite && std::isfinite(actual);
+ }
+ bool all_finite() const {
+ return m_finite;
+ }
+ // Reference energy; a near-zero value means the fixture itself carries no signal.
+ double reference_norm() const {
+ return m_norm;
+ }
+ double value() const {
+ return m_error / m_norm;
+ }
+
+private:
+ double m_error = 0, m_norm = 0;
+ bool m_finite = true;
+};
+
+inline Nmse nmse(const float* actual, const float* expected, size_t count) {
+ Nmse result;
+ for (size_t i = 0; i < count; ++i)
+ result.add(actual[i], expected[i]);
+ return result;
+}
+
+inline void expect_nmse_below(const Nmse& metric, double limit, const std::string& context = {}) {
+ ASSERT_TRUE(metric.all_finite()) << context;
+ ASSERT_GT(metric.reference_norm(), 1e-12) << context;
+ EXPECT_LT(metric.value(), limit) << context;
+}
+
+// The GGUF bytes a reference npz stores as "model", written to a temporary file for its lifetime.
+struct TemporaryGguf {
+ std::string path =
+ (std::filesystem::temp_directory_path() / (ov::test::utils::generateTestFilePrefix() + ".gguf")).string();
+ explicit TemporaryGguf(const cnpy::NpyArray& bytes) {
+ std::ofstream file(path, std::ios::binary);
+ file.write(bytes.data<char>(), bytes.num_vals);
+ OPENVINO_ASSERT(file, "Cannot write ", path);
+ }
+ TemporaryGguf(const TemporaryGguf&) = delete;
+ TemporaryGguf& operator=(const TemporaryGguf&) = delete;
+ ~TemporaryGguf() {
+ std::filesystem::remove(path);
+ }
+};
+
} // namespace ov_gguf_test
diff --git a/src/frontends/gguf/tests/test_adapt_to_genai.cpp b/src/frontends/gguf/tests/test_adapt_to_genai.cpp
index 338e4efbd1d..9a086fda1a1 100644
--- a/src/frontends/gguf/tests/test_adapt_to_genai.cpp
+++ b/src/frontends/gguf/tests/test_adapt_to_genai.cpp
@@ -9,18 +9,25 @@
// several gguf inputs present together, which no single ggml op translation produces, and the two
// fixes below specifically need the exact node shapes translate_get_rows itself builds.
+#include <cmath>
+#include <functional>
#include <memory>
#include "common_test_utils/node_builders/constant.hpp"
#include "gtest/gtest.h"
#include "op_test_utils.hpp"
#include "openvino/frontend/gguf/adapt_to_genai.hpp"
+#include "openvino/frontend/gguf/make_stateful.hpp"
+#include "openvino/op/add.hpp"
#include "openvino/op/assign.hpp"
#include "openvino/op/broadcast.hpp"
#include "openvino/op/concat.hpp"
#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/divide.hpp"
#include "openvino/op/gather.hpp"
#include "openvino/op/matmul.hpp"
+#include "openvino/op/multiply.hpp"
#include "openvino/op/paged_attention.hpp"
#include "openvino/op/parameter.hpp"
#include "openvino/op/read_value.hpp"
@@ -30,6 +37,7 @@
#include "openvino/op/scaled_dot_product_attention.hpp"
#include "openvino/op/sink.hpp"
#include "openvino/op/squeeze.hpp"
+#include "openvino/op/tanh.hpp"
#include "openvino/op/transpose.hpp"
#include "openvino/op/unsqueeze.hpp"
#include "openvino/op/util/variable.hpp"
@@ -65,6 +73,36 @@ struct MinimalGgufModel {
std::shared_ptr<ov::Node> pe_tok;
};
+std::map<std::string, ov::Tensor> make_genai_inputs(size_t length, size_t past = 0) {
+ ov::Tensor ids(ov::element::i64, {1, length}), mask(ov::element::i64, {1, past + length});
+ ov::Tensor positions(ov::element::i64, {1, length}), beam(ov::element::i32, {1});
+ for (size_t i = 0; i < length; ++i) {
+ ids.data<int64_t>()[i] = int64_t(i);
+ positions.data<int64_t>()[i] = int64_t(past + i);
+ }
+ std::fill_n(mask.data<int64_t>(), mask.get_size(), 1);
+ beam.data<int32_t>()[0] = 0;
+ return {{"input_ids", ids}, {"attention_mask", mask}, {"position_ids", positions}, {"beam_idx", beam}};
+}
+
+// Expect 0 where `allowed(q, k)` and a large negative bias elsewhere in a [queries, keys] mask.
+void expect_mask(const float* mask,
+ size_t queries,
+ size_t keys,
+ const std::function<bool(size_t, size_t)>& allowed,
+ const std::function<bool(size_t)>& skip_query = {}) {
+ for (size_t q = 0; q < queries; ++q) {
+ if (skip_query && skip_query(q))
+ continue;
+ for (size_t k = 0; k < keys; ++k) {
+ if (allowed(q, k))
+ EXPECT_EQ(mask[q * keys + k], 0.f) << "q=" << q << " k=" << k;
+ else
+ EXPECT_LT(mask[q * keys + k], -1e4f) << "q=" << q << " k=" << k;
+ }
+ }
+}
+
MinimalGgufModel build_minimal_gguf_model(int64_t vocab = 4,
int64_t hidden = 2,
bool with_inp_out_ids = false,
@@ -92,6 +130,7 @@ MinimalGgufModel build_minimal_gguf_model(int64_t vocab = 4,
auto gather = std::make_shared<v8::Gather>(vocab_table, indices, axis0);
m.embd = std::make_shared<v0::Unsqueeze>(gather, axis0);
m.embd->set_friendly_name("Unsqueeze_test_embd");
+ m.embd->get_rt_info()["gguf.token_embedding"] = true;
ov::ParameterVector params{m.inp_tokens, inp_pos, self_kq_mask, token_len_per_seq, beam_idx};
if (with_inp_out_ids) {
@@ -185,6 +224,210 @@ TEST(GGUFAdaptToGenAI, NoOpWithoutGgufInputs) {
EXPECT_FALSE(AdaptToGenAI().run_on_model(model));
}
+TEST(GGUFAdaptToGenAI, EmbeddingModeExtractsLookupAndAcceptsInjectedValues) {
+ auto m = build_minimal_gguf_model();
+ // Keep an unreachable consumer alive across adaptation. Rewiring inp_tokens also
+ // updates this node, but it must not keep input_ids in the decoder's input contract.
+ auto detached = std::make_shared<v0::Convert>(m.inp_tokens, ov::element::i64);
+ AdaptToGenAI pass(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS);
+ ASSERT_TRUE(pass.run_on_model(m.model));
+ ASSERT_NE(pass.get_embedding_model(), nullptr);
+ EXPECT_EQ(find_parameter(m.model, "input_ids"), nullptr);
+ ASSERT_NE(find_parameter(m.model, "inputs_embeds"), nullptr);
+ EXPECT_NE(detached->input_value(0).get_node(), m.inp_tokens.get());
+ for (size_t length : {1, 3}) {
+ ov::Tensor ids(ov::element::i64, {1, length});
+ for (size_t i = 0; i < length; ++i)
+ ids.data<int64_t>()[i] = int64_t(i);
+ ov::TensorVector lookup{ov::Tensor(ov::element::f32, {1, length, 2})};
+ ASSERT_TRUE(pass.get_embedding_model()->evaluate(lookup, {ids}));
+ for (size_t i = 0; i < 2 * length; ++i)
+ EXPECT_EQ(lookup[0].data<float>()[i], float(i));
+ ov::TensorVector inputs;
+ for (const auto& p : m.model->get_parameters()) {
+ if (p->get_friendly_name() == "inputs_embeds") {
+ inputs.push_back(lookup[0]);
+ } else {
+ const auto shape = p->get_friendly_name() == "beam_idx" ? ov::Shape{1} : ov::Shape{1, length};
+ inputs.emplace_back(p->get_element_type(), shape);
+ std::memset(inputs.back().data(), 0, inputs.back().get_byte_size());
+ }
+ }
+ ov::TensorVector outputs{ov::Tensor(ov::element::f32, {1, length, 1})};
+ ASSERT_TRUE(m.model->evaluate(outputs, inputs));
+ ASSERT_EQ(outputs[0].get_shape(), (ov::Shape{1, length, 1}));
+ for (size_t i = 0; i < length; ++i)
+ EXPECT_EQ(outputs[0].data<float>()[i], float(4 * i + 1));
+ }
+ ov::Tensor batch_ids(ov::element::i64, {2, 1});
+ batch_ids.data<int64_t>()[0] = 1;
+ batch_ids.data<int64_t>()[1] = 3;
+ ov::TensorVector batch_embeddings{ov::Tensor(ov::element::f32, {2, 1, 2})};
+ ASSERT_TRUE(pass.get_embedding_model()->evaluate(batch_embeddings, {batch_ids}));
+ EXPECT_EQ(batch_embeddings[0].get_shape(), (ov::Shape{2, 1, 2}));
+ EXPECT_EQ(batch_embeddings[0].data<float>()[0], 2.f);
+ EXPECT_EQ(batch_embeddings[0].data<float>()[2], 6.f);
+ EXPECT_FALSE(pass.run_on_model(m.model));
+}
+
+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};
+ AdaptToGenAI pass(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS);
+ ASSERT_TRUE(pass.run_on_model(m.model));
+ EXPECT_EQ(find_parameter(m.model, "input_ids"), nullptr);
+ EXPECT_NE(find_parameter(m.model, "inputs_embeds"), nullptr);
+ EXPECT_EQ(m.model->input("per_layer_inputs").get_partial_shape(), (ov::PartialShape{-1, -1, 2, 1}));
+ const auto& lookup = pass.get_embedding_model();
+ ASSERT_EQ(lookup->outputs().size(), 1);
+ EXPECT_EQ(lookup->output(0).get_any_name(), "inputs_embeds");
+ const auto& per_layer = pass.get_per_layer_embedding_model();
+ ASSERT_NE(per_layer, nullptr);
+ EXPECT_EQ(per_layer->get_parameters().size(), 1);
+ EXPECT_EQ(per_layer->input(0).get_any_name(), "input_ids");
+ ASSERT_EQ(per_layer->outputs().size(), 1);
+ EXPECT_EQ(per_layer->output(0).get_any_name(), "per_layer_inputs");
+ EXPECT_EQ(per_layer->output(0).get_partial_shape(), (ov::PartialShape{-1, -1, 2, 1}));
+}
+
+// An untagged token lookup cannot be moved, so the language model keeps input_ids for it.
+TEST(GGUFAdaptToGenAI, EmbeddingModePreservesUntaggedAuxiliaryTokenLookup) {
+ auto m = build_minimal_gguf_model(4, 2, false, true);
+ AdaptToGenAI pass(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS);
+ ASSERT_TRUE(pass.run_on_model(m.model));
+ EXPECT_NE(find_parameter(m.model, "input_ids"), nullptr);
+ EXPECT_NE(find_parameter(m.model, "inputs_embeds"), nullptr);
+ EXPECT_EQ(pass.get_embedding_model()->get_parameters().size(), 1);
+}
+
+TEST(GGUFAdaptToGenAI, EmbeddingModeRetainsScalingOnce) {
+ auto m = build_minimal_gguf_model();
+ auto reduction = m.model->get_results().front()->input_value(0).get_node_shared_ptr();
+ reduction->input(0).replace_source_output(
+ std::make_shared<v1::Multiply>(m.embd, v0::Constant::create(ov::element::f32, {}, {7.f})));
+ auto reference = m.model->clone();
+ AdaptToGenAI().run_on_model(reference);
+ AdaptToGenAI pass(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS);
+ pass.run_on_model(m.model);
+ auto inputs = make_genai_inputs(3);
+ auto expected = run_on_cpu(reference, inputs);
+ auto lookup = run_on_cpu(pass.get_embedding_model(), {{"input_ids", inputs.at("input_ids")}});
+ inputs.erase("input_ids");
+ inputs.emplace("inputs_embeds", lookup);
+ auto actual = run_on_cpu(m.model, inputs);
+ ASSERT_EQ(actual.get_shape(), expected.get_shape());
+ for (size_t i = 0; i < actual.get_size(); ++i)
+ EXPECT_FLOAT_EQ(actual.data<float>()[i], expected.data<float>()[i]);
+}
+
+TEST(GGUFAdaptToGenAI, BatchedMaskKeepsSequencesSeparateAndExcludesPadding) {
+ auto m = build_minimal_gguf_model();
+ auto mask = find_parameter(m.model, "self_kq_mask");
+ m.model->add_results({std::make_shared<v0::Result>(mask)});
+ ASSERT_TRUE(AdaptToGenAI().run_on_model(m.model));
+ ov::Core core;
+ auto request = core.compile_model(m.model, "CPU").create_infer_request();
+ // The second sequence has two left-padding columns and one current token.
+ for (size_t past : {0, 2}) {
+ ov::Tensor ids(ov::element::i64, {2, 3}), positions(ov::element::i64, {2, 3});
+ ov::Tensor attention(ov::element::i64, {2, past + 3}), beams(ov::element::i32, {2});
+ std::fill_n(ids.data<int64_t>(), ids.get_size(), 1);
+ std::fill_n(attention.data<int64_t>(), attention.get_size(), 1);
+ attention.data<int64_t>()[past + 3] = attention.data<int64_t>()[past + 4] = 0;
+ for (size_t i = 0; i < 3; ++i) {
+ positions.data<int64_t>()[i] = past + i;
+ positions.data<int64_t>()[3 + i] = std::max<int64_t>(0, int64_t(past + i) - 2);
+ }
+ beams.data<int32_t>()[0] = 0;
+ beams.data<int32_t>()[1] = 1;
+ request.set_tensor("input_ids", ids);
+ request.set_tensor("attention_mask", attention);
+ request.set_tensor("position_ids", positions);
+ request.set_tensor("beam_idx", beams);
+ request.infer();
+ const auto actual = request.get_output_tensor(0);
+ ASSERT_EQ(actual.get_shape(), (ov::Shape{2, 1, 3, past + 3}));
+ for (size_t b = 0; b < 2; ++b) {
+ // Padded query rows are ignored by generation.
+ expect_mask(
+ actual.data<const float>() + b * 3 * (past + 3),
+ 3,
+ past + 3,
+ [&](size_t q, size_t k) {
+ return k <= past + q && (b == 0 || k >= 2);
+ },
+ [&](size_t q) {
+ return b == 1 && past + q < 2;
+ });
+ }
+ }
+}
+
+class GGUFAdaptToGenAIImageMask : public testing::TestWithParam<std::string> {};
+
+TEST_P(GGUFAdaptToGenAIImageMask, RespectsLayerTypeImageGroupsAndCachedPrefix) {
+ auto m = build_minimal_gguf_model();
+ m.model->get_rt_info()["gguf_architecture"] = GetParam();
+ m.model->get_rt_info()[ov::frontend::gguf::pass::gguf_swa_window_key()] = int64_t{3};
+ auto mask = find_parameter(m.model, "self_kq_mask");
+ auto swa_mask = ov::test::utils::make_param(ov::element::f32, ov::PartialShape{1, 1, -1, -1}, "self_kq_mask_swa");
+ m.model->add_parameters({swa_mask});
+ m.model->add_results({std::make_shared<v0::Result>(mask), std::make_shared<v0::Result>(swa_mask)});
+ AdaptToGenAI(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS).run_on_model(m.model);
+ // Adaptation replaces the original first result with logits; the retained mask is now first.
+ ov::Core core;
+ auto request = core.compile_model(m.model, "CPU").create_infer_request();
+ const std::vector<int64_t> types{0, 1, 1, 0, 1, 1, 0};
+ for (size_t past : {0, 3}) {
+ auto inputs = make_genai_inputs(types.size(), past);
+ inputs.erase("input_ids");
+ inputs.emplace("inputs_embeds", ov::Tensor(ov::element::f32, {1, types.size(), 2}));
+ ov::Tensor token_types(ov::element::i64, {1, types.size()});
+ std::copy(types.begin(), types.end(), token_types.data<int64_t>());
+ inputs.emplace("token_type_ids", token_types);
+ for (auto& entry : inputs)
+ request.set_tensor(entry.first, entry.second);
+ request.infer();
+ for (size_t layer = 0; layer < 2; ++layer) {
+ auto actual = request.get_output_tensor(layer);
+ ASSERT_EQ(actual.get_shape(), (ov::Shape{1, 1, types.size(), past + types.size()}));
+ const bool bidirectional = layer == 1 || GetParam() == "gemma3";
+ SCOPED_TRACE("layer=" + std::to_string(layer) + " past=" + std::to_string(past));
+ expect_mask(actual.data<const float>(), types.size(), past + types.size(), [&](size_t q, size_t k) {
+ const bool same_image = k >= past && types[q] == 1 && types[k - past] == 1 &&
+ ((q <= 2 && k - past <= 2) || (q >= 4 && k - past >= 4));
+ return (k <= past + q || (bidirectional && same_image)) && (layer == 0 || k + 3 > past + q);
+ });
+ }
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(Gemma,
+ GGUFAdaptToGenAIImageMask,
+ testing::Values(std::string("gemma3"), std::string("gemma4")),
+ [](const testing::TestParamInfo<std::string>& info) {
+ return info.param;
+ });
+
+TEST(GGUFAdaptToGenAI, EmbeddingModeMapsGenAIMultimodalPositionsToGGML) {
+ auto m = build_minimal_gguf_model();
+ m.model->get_rt_info()[ov::frontend::gguf::pass::gguf_imrope_key()] = true;
+ auto positions = find_parameter(m.model, "inp_pos");
+ m.model->add_results({std::make_shared<v0::Result>(positions)});
+ AdaptToGenAI(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS).run_on_model(m.model);
+ auto inputs = make_genai_inputs(2, 7);
+ inputs.erase("input_ids");
+ inputs.emplace("inputs_embeds", make_f32_tensor({1, 2, 2}, {1, 2, 3, 4}));
+ ov::Tensor coordinates(ov::element::i64, {4, 1, 2});
+ const std::vector<int64_t> data{3, 7, 11, 2, 5, 13, 17, 19};
+ std::copy(data.begin(), data.end(), coordinates.data<int64_t>());
+ inputs["position_ids"] = coordinates;
+ auto actual = run_on_cpu(m.model, inputs);
+ ASSERT_EQ(actual.get_shape(), (ov::Shape{1, 1, 1, 8}));
+ for (size_t i = 0; i < data.size(); ++i)
+ EXPECT_EQ(actual.data<int32_t>()[i], data[(i + 2) % data.size()]);
+}
+
// translate_get_rows's embedding lookup restores ggml's rank-4 form with Unsqueeze(axis=0),
// pinning the leading axis to a literal 1. AdaptToGenAI moves it to axis 1 so it instead mirrors
// input_ids' own (backend-dependent) leading dim -- see FixEmbdAxis in adapt_to_genai.cpp.
@@ -412,7 +655,7 @@ TEST(GGUFAdaptToGenAI, InpOutIdsRowSelectionCorrectUnderBothLayouts) {
// per token, without needing real RoPE weights or a llama.cpp oracle to compute an expected value.
namespace {
-std::shared_ptr<ov::Model> build_attention_gguf_model(int64_t vocab, int64_t hidden) {
+std::shared_ptr<ov::Model> build_attention_gguf_model(int64_t vocab, int64_t hidden, bool auxiliary_tokens = false) {
auto inp_tokens = ov::test::utils::make_param(ov::element::i32, ov::PartialShape{1, 1, 1, -1}, "inp_tokens");
auto inp_pos = ov::test::utils::make_param(ov::element::i32, ov::PartialShape{1, 1, 1, -1}, "inp_pos");
auto self_kq_mask = ov::test::utils::make_param(ov::element::f32, ov::PartialShape{1, 1, -1, -1}, "self_kq_mask");
@@ -437,12 +680,22 @@ std::shared_ptr<ov::Model> build_attention_gguf_model(int64_t vocab, int64_t hid
auto gather = std::make_shared<v8::Gather>(vocab_table, indices, axis0);
auto embd = std::make_shared<v0::Unsqueeze>(gather, axis0);
embd->set_friendly_name("embd");
+ embd->get_rt_info()["gguf.token_embedding"] = true;
// Flatten to [1, tokens, hidden] regardless of which axis (0 pre-fix, 1 post-fix) carries the
// real token count -- Reshape never reorders memory, so this is correct either way (same trick
// FixInpOutIdsRowSelect itself uses).
auto embd_3d_shape = v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{1, -1, hidden});
- auto embd_3d = std::make_shared<v1::Reshape>(embd, embd_3d_shape, false);
+ ov::Output<ov::Node> combined = embd;
+ if (auxiliary_tokens) {
+ auto auxiliary = std::make_shared<v8::Gather>(vocab_table, indices, axis0);
+ auto lifted = std::make_shared<v0::Unsqueeze>(auxiliary, axis0);
+ lifted->set_friendly_name("per_layer_tokens");
+ // Two layers of hidden / 2 values each, as Gemma4's per-layer token embedding.
+ lifted->get_rt_info()["gguf.per_layer_token_embedding"] = int64_t{2};
+ combined = std::make_shared<v1::Add>(embd, lifted);
+ }
+ auto embd_3d = std::make_shared<v1::Reshape>(combined, embd_3d_shape, false);
std::vector<float> zero_w(hidden * hidden, 0.0f);
auto w_zero = v0::Constant::create(ov::element::f32, {(size_t)hidden, (size_t)hidden}, zero_w);
@@ -502,6 +755,72 @@ std::shared_ptr<ov::Model> build_attention_gguf_model(int64_t vocab, int64_t hid
ov::ParameterVector{inp_tokens, inp_pos, self_kq_mask, token_len_per_seq, beam_idx});
}
+constexpr float lm_head_soft_cap = 5.0f;
+
+float lm_head_weight(int64_t row, int64_t col) {
+ return 0.25f * static_cast<float>(row - col);
+}
+
+// Replaces the logits Result's input with the LM head as the frontend emits it: a rank-4
+// [1, 1, tokens, hidden] MatMul against [vocab, hidden], optionally followed by Gemma's final-logit
+// softcap (x * (1/cap) -> tanh -> * cap) with [1, 1, 1, 1] scale constants.
+void attach_lm_head(const std::shared_ptr<ov::Model>& model,
+ const ov::Output<ov::Node>& hidden_states,
+ int64_t vocab,
+ int64_t hidden,
+ bool softcap) {
+ ov::Output<ov::Node> hidden_4d = hidden_states;
+ if (hidden_states.get_partial_shape().size() == 3) {
+ hidden_4d = std::make_shared<v0::Unsqueeze>(hidden_states, v0::Constant::create(ov::element::i64, {1}, {0}));
+ }
+ std::vector<float> weight(vocab * hidden);
+ for (int64_t v = 0; v < vocab; ++v) {
+ for (int64_t h = 0; h < hidden; ++h) {
+ weight[v * hidden + h] = lm_head_weight(v, h);
+ }
+ }
+ ov::Output<ov::Node> logits =
+ std::make_shared<v0::MatMul>(hidden_4d,
+ v0::Constant::create(ov::element::f32, {(size_t)vocab, (size_t)hidden}, weight),
+ false,
+ true);
+ if (softcap) {
+ auto scale_down = v0::Constant::create(ov::element::f32, {1, 1, 1, 1}, {1.0f / lm_head_soft_cap});
+ auto scale_up = v0::Constant::create(ov::element::f32, {1, 1, 1, 1}, {lm_head_soft_cap});
+ logits = std::make_shared<v1::Multiply>(logits, scale_down);
+ logits = std::make_shared<v0::Tanh>(logits);
+ logits = std::make_shared<v1::Multiply>(logits, scale_up);
+ }
+ model->get_results()[0]->input(0).replace_source_output(logits);
+ model->validate_nodes_and_infer_types();
+}
+
+// GenAI's gather/slice-before-matmul only finds the LM head as Result <- MatMul, optionally behind
+// Divide -> Tanh -> Multiply, with a rank-3 MatMul input; returns the MatMul when that holds.
+std::shared_ptr<v0::MatMul> find_genai_lm_head(const std::shared_ptr<ov::Model>& model, bool softcap) {
+ auto node = model->get_results()[0]->get_input_node_shared_ptr(0);
+ if (softcap) {
+ const auto scale_up = ov::as_type_ptr<v1::Multiply>(node);
+ if (!scale_up) {
+ return nullptr;
+ }
+ const auto tanh = ov::as_type_ptr<v0::Tanh>(scale_up->get_input_node_shared_ptr(0));
+ if (!tanh) {
+ return nullptr;
+ }
+ const auto scale_down = ov::as_type_ptr<v1::Divide>(tanh->get_input_node_shared_ptr(0));
+ if (!scale_down) {
+ return nullptr;
+ }
+ node = scale_down->get_input_node_shared_ptr(0);
+ }
+ auto matmul = ov::as_type_ptr<v0::MatMul>(node);
+ if (!matmul || matmul->get_input_partial_shape(0).size() != 3) {
+ return nullptr;
+ }
+ return matmul;
+}
+
} // namespace
TEST(GGUFAdaptToGenAI, SurvivesSDPAToPagedAttentionWithRealAttentionBlock) {
@@ -539,3 +858,132 @@ TEST(GGUFAdaptToGenAI, SurvivesSDPAToPagedAttentionWithRealAttentionBlock) {
EXPECT_EQ(q_shape[1].get_length(), hidden);
}
}
+
+class GGUFAdaptToGenAILmHead : public ::testing::TestWithParam<bool> {};
+
+// Without the rank-3 Result <- MatMul form, GenAI can't select the sampled tokens before the LM
+// head, and PagedAttention prefill projects every prompt token to vocab.
+TEST_P(GGUFAdaptToGenAILmHead, ExposesHeadForGenAITokenSelection) {
+ const bool softcap = GetParam();
+ const int64_t vocab = 6, hidden = 3;
+ auto m = build_minimal_gguf_model(vocab, hidden);
+ attach_lm_head(m.model, m.embd, vocab, hidden, softcap);
+
+ ASSERT_TRUE(AdaptToGenAI().run_on_model(m.model));
+ ASSERT_NO_THROW(m.model->validate_nodes_and_infer_types());
+ ASSERT_EQ(m.model->get_results().size(), 1);
+ ASSERT_NE(find_genai_lm_head(m.model, softcap), nullptr);
+ if (softcap) {
+ const auto tanh = m.model->get_results()[0]->get_input_node_shared_ptr(0)->get_input_node_shared_ptr(0);
+ const auto divisor = ov::as_type_ptr<v0::Constant>(tanh->get_input_node_ptr(0)->get_input_node_shared_ptr(1));
+ ASSERT_NE(divisor, nullptr);
+ EXPECT_FLOAT_EQ(divisor->cast_vector<float>()[0], lm_head_soft_cap);
+ }
+
+ ov::Core core;
+ auto request =
+ 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.0f;
+ for (int64_t h = 0; h < hidden; ++h) {
+ expected += lm_head_weight(v, h) * static_cast<float>(token * hidden + h);
+ }
+ if (softcap) {
+ expected = lm_head_soft_cap * std::tanh(expected / lm_head_soft_cap);
+ }
+ EXPECT_NEAR(logits.data<float>()[token * vocab + v], expected, 1e-4f);
+ }
+ }
+}
+
+// GenAI applies its token selection after SDPAToPagedAttention, so the head must keep its form there.
+TEST_P(GGUFAdaptToGenAILmHead, KeepsHeadFormThroughSDPAToPagedAttention) {
+ const bool softcap = GetParam();
+ 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, softcap);
+
+ ASSERT_TRUE(AdaptToGenAI().run_on_model(model));
+ ASSERT_TRUE(ov::pass::SDPAToPagedAttention().run_on_model(model));
+ ASSERT_NO_THROW(model->validate_nodes_and_infer_types());
+ EXPECT_NE(find_genai_lm_head(model, softcap), nullptr);
+}
+
+INSTANTIATE_TEST_SUITE_P(Softcap, GGUFAdaptToGenAILmHead, ::testing::Bool());
+
+// 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) {
+ auto model = build_attention_gguf_model(8, 4, true);
+ model->get_rt_info()["gguf_architecture"] = std::string("gemma4");
+ ASSERT_TRUE(AdaptToGenAI(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS).run_on_model(model));
+ ASSERT_EQ(find_parameter(model, "input_ids"), nullptr);
+ ASSERT_EQ(model->input("inputs_embeds").get_partial_shape().rank().get_length(), 3);
+ ASSERT_EQ(model->input("per_layer_inputs").get_partial_shape(), (ov::PartialShape{-1, -1, 2, 2}));
+ // Gemma4 variants with per-layer embeddings keep image attention causal.
+ ASSERT_EQ(find_parameter(model, "token_type_ids"), nullptr);
+ ASSERT_TRUE(ov::pass::SDPAToPagedAttention().run_on_model(model));
+ EXPECT_EQ(model->input("inputs_embeds").get_partial_shape(), (ov::PartialShape{-1, -1}));
+ // GenAI's continuous batching supplies per_layer_inputs as [tokens, 1, layers, width].
+ EXPECT_NO_THROW(
+ model->reshape({{"inputs_embeds", {5, 4}}, {"per_layer_inputs", {5, 1, 2, 2}}, {"position_ids", {5}}}));
+ EXPECT_NO_THROW(model->validate_nodes_and_infer_types());
+}
+
+class GGUFAdaptToGenAIEmbeddingMode : public ::testing::TestWithParam<bool> {};
+
+TEST_P(GGUFAdaptToGenAIEmbeddingMode, MatchesTokenModeAcrossCachedDecodeAndReset) {
+ const bool per_layer = GetParam();
+ auto original = build_attention_gguf_model(8, 4, per_layer);
+ auto embedded = original->clone();
+ AdaptToGenAI().run_on_model(original);
+ AdaptToGenAI adapter(AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS);
+ adapter.run_on_model(embedded);
+ ov::Core core;
+ auto tokens =
+ core.compile_model(original, "CPU", ov::hint::inference_precision(ov::element::f32)).create_infer_request();
+ auto values =
+ core.compile_model(embedded, "CPU", ov::hint::inference_precision(ov::element::f32)).create_infer_request();
+ auto lookup = core.compile_model(adapter.get_embedding_model(), "CPU").create_infer_request();
+ ov::InferRequest per_layer_lookup;
+ if (per_layer)
+ per_layer_lookup = core.compile_model(adapter.get_per_layer_embedding_model(), "CPU").create_infer_request();
+ for (int chat = 0; chat < 2; ++chat) {
+ size_t past = 0;
+ for (size_t length : {3, 1, 2}) {
+ auto inputs = make_genai_inputs(length, past);
+ lookup.set_tensor("input_ids", inputs.at("input_ids"));
+ lookup.infer();
+ for (const auto& entry : inputs) {
+ tokens.set_tensor(entry.first, entry.second);
+ if (entry.first != "input_ids")
+ values.set_tensor(entry.first, entry.second);
+ }
+ values.set_tensor("inputs_embeds", lookup.get_tensor("inputs_embeds"));
+ if (per_layer) {
+ per_layer_lookup.set_tensor("input_ids", inputs.at("input_ids"));
+ per_layer_lookup.infer();
+ values.set_tensor("per_layer_inputs", per_layer_lookup.get_tensor("per_layer_inputs"));
+ }
+ tokens.infer();
+ values.infer();
+ auto expected = tokens.get_output_tensor(), actual = values.get_output_tensor();
+ ASSERT_EQ(actual.get_shape(), expected.get_shape());
+ for (size_t i = 0; i < actual.get_size(); ++i)
+ EXPECT_NEAR(actual.data<float>()[i], expected.data<float>()[i], 1e-5f);
+ past += length;
+ }
+ tokens.reset_state();
+ values.reset_state();
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(PerLayerInputs, GGUFAdaptToGenAIEmbeddingMode, ::testing::Bool());
diff --git a/src/frontends/gguf/tests/test_arch_accuracy.cpp b/src/frontends/gguf/tests/test_arch_accuracy.cpp
index 4e5c848bf6d..586a5b2a261 100644
--- a/src/frontends/gguf/tests/test_arch_accuracy.cpp
+++ b/src/frontends/gguf/tests/test_arch_accuracy.cpp
@@ -5,22 +5,420 @@
#include <algorithm>
#include <cmath>
#include <cstdlib>
+#include <cstring>
#include <filesystem>
#include <fstream>
+#include <set>
#include "cnpy.h"
#include "common_test_utils/common_utils.hpp"
+#include "common_test_utils/test_assertions.hpp"
#include "gtest/gtest.h"
#include "op_test_utils.hpp"
#include "openvino/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/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/multiply.hpp"
+#include "openvino/op/paged_attention.hpp"
+#include "openvino/op/paged_gated_delta_net.hpp"
+#include "openvino/op/read_value.hpp"
+#include "openvino/op/unsqueeze.hpp"
#include "openvino/openvino.hpp"
+#include "openvino/pass/manager.hpp"
+#include "openvino/pass/sdpa_to_paged_attention.hpp"
namespace {
class GGUFArchitectureAccuracy : public ::testing::TestWithParam<const char*> {};
+// Check batching and beam reordering against independent stateful requests. The
+// same synthetic checkpoints are qualified against llama.cpp below.
+void check_batched_decode(const std::shared_ptr<ov::Model>& model) {
+ ov::Core core;
+ auto compiled = core.compile_model(model,
+ "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));
+ auto first = compiled.create_infer_request();
+ auto second = compiled.create_infer_request();
+ auto batch = compiled.create_infer_request();
+ const auto infer = [](ov::InferRequest& request,
+ size_t batch_size,
+ const std::vector<int64_t>& ids,
+ const std::vector<int64_t>& mask,
+ const std::vector<int64_t>& positions,
+ const std::vector<int32_t>& beams) {
+ const auto set_tensor =
+ [&](const char* name, const ov::element::Type& type, const ov::Shape& shape, const auto& values) {
+ ov::Tensor tensor(type, shape);
+ std::memcpy(tensor.data(), values.data(), tensor.get_byte_size());
+ request.set_tensor(name, tensor);
+ };
+ set_tensor("input_ids", ov::element::i64, {batch_size, ids.size() / batch_size}, ids);
+ set_tensor("attention_mask", ov::element::i64, {batch_size, mask.size() / batch_size}, mask);
+ set_tensor("position_ids", ov::element::i64, {batch_size, positions.size() / batch_size}, positions);
+ set_tensor("beam_idx", ov::element::i32, {batch_size}, beams);
+ request.infer();
+ auto output = request.get_tensor("logits");
+ return std::vector<float>(output.data<const float>(), output.data<const float>() + output.get_size());
+ };
+ const auto compare =
+ [](const std::vector<float>& actual, const std::vector<float>& first, const std::vector<float>& second) {
+ auto expected = first;
+ expected.insert(expected.end(), second.begin(), second.end());
+ ASSERT_EQ(actual.size(), expected.size());
+ ov_gguf_test::expect_nmse_below(ov_gguf_test::nmse(actual.data(), expected.data(), actual.size()), 1e-5);
+ };
+ auto a = infer(first, 1, {1, 2, 3}, {1, 1, 1}, {0, 1, 2}, {0});
+ auto b = infer(second, 1, {2, 3}, {1, 1}, {0, 1}, {0});
+ compare(infer(batch, 2, {1, 2, 3, 0, 2, 3}, {1, 1, 1, 0, 1, 1}, {0, 1, 2, 0, 0, 1}, {0, 0}), a, b);
+ 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);
+}
+
+TEST(GGUFMultimodalBackboneAdaptation, QwenAndGemmaSupportBatchesAndPagedAttention) {
+ for (const auto* family : {"qwen35", "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"));
+ ov::frontend::gguf::FrontEnd frontend;
+ frontend.add_extension(std::make_shared<ov::frontend::gguf::GenAIExtension>());
+ auto model = frontend.convert(frontend.load(temporary.path));
+ check_batched_decode(model);
+ ov::pass::Manager manager;
+ manager.register_pass<ov::pass::SDPAToPagedAttention>();
+ ASSERT_NO_THROW(manager.run_passes(model));
+ // Multiple tokens expose accidental [tokens,tokens,...] M-RoPE broadcasts.
+ model->reshape({{"input_ids", {5}}, {"position_ids", {5}}});
+ const bool gemma = std::string(family).find("gemma4") == 0;
+ size_t attention = 0, recurrent = 0;
+ for (const auto& node : model->get_ops()) {
+ if (auto pa = ov::as_type_ptr<ov::op::PagedAttentionExtension>(node)) {
+ ++attention;
+ const auto& query_shape = pa->get_input_partial_shape(0);
+ EXPECT_EQ(query_shape.rank(), 2);
+ EXPECT_EQ(query_shape[0], 5);
+ EXPECT_TRUE(query_shape[1] == 64 || (gemma && query_shape[1] == 32));
+ }
+ if (auto gdn = ov::as_type_ptr<ov::op::internal::PagedGatedDeltaNet>(node)) {
+ ++recurrent;
+ EXPECT_EQ(gdn->get_input_partial_shape(0)[0], 5);
+ }
+ }
+ EXPECT_EQ(attention, gemma ? (std::string(family) == "gemma4-ple" ? 4 : 2) : 1);
+ EXPECT_EQ(recurrent, gemma ? 0 : 3);
+ EXPECT_TRUE(model->get_sinks().empty());
+ }
+}
+
+// Gemma3/Gemma4 scale token lookups only, as in llama.cpp, so the scale belongs to the embedding
+// model and injected media embeddings reach the decoder unscaled.
+TEST(GGUFMultimodalBackboneAdaptation, GemmaEmbeddingModelOwnsTokenScaling) {
+ for (const auto* family : {"gemma3", "gemma4-mqa", "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"));
+ const auto convert = [&] {
+ ov::frontend::gguf::FrontEnd frontend;
+ frontend.add_extension(std::make_shared<ov::frontend::DecoderTransformationExtension>(
+ ov::frontend::gguf::pass::GGUFMakeStateful()));
+ return frontend.convert(frontend.load(temporary.path));
+ };
+ auto token_model = convert();
+ ov::frontend::gguf::pass::AdaptToGenAI().run_on_model(token_model);
+ ov::frontend::gguf::FrontEnd frontend;
+ auto extension = std::make_shared<ov::frontend::gguf::GenAIExtension>(
+ ov::frontend::gguf::GenAIExtension::InputMode::EMBEDS_TO_LOGITS);
+ frontend.add_extension(extension);
+ const auto input = frontend.load(temporary.path);
+ auto embedded_model = frontend.convert(input);
+ ASSERT_TRUE(extension->get_embedding_model());
+ EXPECT_EQ(bool(extension->get_per_layer_embedding_model()), std::string(family) == "gemma4-ple");
+ embedded_model = frontend.convert(input);
+ const auto embedding_model = extension->get_embedding_model();
+ const auto width = embedding_model->output("inputs_embeds").get_partial_shape()[2].get_length();
+ const auto embedding_ops = embedding_model->get_ops();
+ const bool scaled =
+ std::any_of(embedding_ops.begin(), embedding_ops.end(), [&](const std::shared_ptr<ov::Node>& node) {
+ if (!ov::is_type<ov::op::v1::Multiply>(node))
+ return false;
+ auto constant = ov::as_type_ptr<ov::op::v0::Constant>(node->get_input_node_shared_ptr(1));
+ return constant && ov::shape_size(constant->get_shape()) == 1 &&
+ std::abs(constant->cast_vector<float>()[0] - std::sqrt(float(width))) < 1e-4f;
+ });
+ EXPECT_TRUE(scaled) << "embedding model does not apply sqrt(n_embd)";
+
+ ov::Core core;
+ const auto compile = [&](const std::shared_ptr<ov::Model>& model) {
+ return core.compile_model(model, "CPU", ov::hint::inference_precision(ov::element::f32))
+ .create_infer_request();
+ };
+ auto tokens = compile(token_model), values = compile(embedded_model), lookup = compile(embedding_model);
+ ov::Tensor ids(ov::element::i64, {1, 3}), mask(ov::element::i64, {1, 3}), positions(ov::element::i64, {1, 3});
+ for (int64_t i = 0; i < 3; ++i) {
+ ids.data<int64_t>()[i] = i + 1;
+ positions.data<int64_t>()[i] = i;
+ }
+ std::fill_n(mask.data<int64_t>(), 3, 1);
+ ov::Tensor beam(ov::element::i32, {1});
+ beam.data<int32_t>()[0] = 0;
+ lookup.set_tensor("input_ids", ids);
+ lookup.infer();
+ for (auto* request : {&tokens, &values}) {
+ request->set_tensor("attention_mask", mask);
+ request->set_tensor("position_ids", positions);
+ request->set_tensor("beam_idx", beam);
+ }
+ tokens.set_tensor("input_ids", ids);
+ values.set_tensor("inputs_embeds", lookup.get_tensor("inputs_embeds"));
+ for (const auto& input : embedded_model->inputs()) {
+ if (input.get_names().count("token_type_ids")) {
+ ov::Tensor types(ov::element::i64, {1, 3});
+ std::fill_n(types.data<int64_t>(), 3, 0);
+ values.set_tensor("token_type_ids", types);
+ }
+ if (input.get_names().count("per_layer_inputs")) {
+ auto per_layer = compile(extension->get_per_layer_embedding_model());
+ per_layer.set_tensor("input_ids", ids);
+ per_layer.infer();
+ values.set_tensor("per_layer_inputs", per_layer.get_tensor("per_layer_inputs"));
+ }
+ }
+ tokens.infer();
+ values.infer();
+ const auto expected = tokens.get_output_tensor(), actual = values.get_output_tensor();
+ ASSERT_EQ(actual.get_shape(), expected.get_shape());
+ ov_gguf_test::expect_nmse_below(
+ ov_gguf_test::nmse(actual.data<const float>(), expected.data<const float>(), actual.get_size()),
+ 1e-10);
+ }
+}
+
+// Adapters registered as transformation extensions run during conversion and must already see
+// the architecture and projector metadata they select their changes by.
+TEST(GGUFMultimodalBackboneAdaptation, AdaptersRegisteredAsExtensionsSeeModelMetadata) {
+ using ov::frontend::DecoderTransformationExtension;
+ namespace pass = ov::frontend::gguf::pass;
+ const auto convert = [](const std::string& fixture, const std::vector<std::shared_ptr<ov::Extension>>& passes) {
+ auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/" + fixture);
+ const ov_gguf_test::TemporaryGguf temporary(ov_gguf_test::npz_array(arrays, "model"));
+ ov::frontend::gguf::FrontEnd frontend;
+ for (const auto& extension : passes)
+ frontend.add_extension(extension);
+ return frontend.convert(frontend.load(temporary.path));
+ };
+ const auto names = [](const auto& ports) {
+ std::set<std::string> result;
+ for (const auto& port : ports)
+ result.insert(port.get_any_name());
+ return result;
+ };
+ const auto language = convert("arch_accuracy/gemma3.npz",
+ {std::make_shared<DecoderTransformationExtension>(pass::GGUFMakeStateful()),
+ std::make_shared<DecoderTransformationExtension>(
+ pass::AdaptToGenAI(pass::AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS))});
+ EXPECT_EQ(names(language->inputs()).count("token_type_ids"), 1);
+ const auto vision = convert("mmproj_accuracy/qwen3vl_merger.npz",
+ {std::make_shared<DecoderTransformationExtension>(
+ pass::AdaptMmprojToGenAI(pass::AdaptMmprojToGenAI::Modality::VISION))});
+ EXPECT_EQ(names(vision->outputs()), (std::set<std::string>{"image_features", "deepstack_features.0"}));
+}
+
+// The Gated-DeltaNet key-head count divides the value-head count; a missing or zero one must
+// fail conversion with a message instead of dividing by zero.
+TEST(GGUFMultimodalBackboneAdaptation, GatedDeltaNetRejectsMissingOrZeroGroupCount) {
+ auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/arch_accuracy/qwen35.npz");
+ const auto& model = ov_gguf_test::npz_array(arrays, "model");
+ const std::string key = "qwen35.ssm.group_count";
+ for (const bool missing : {false, true}) {
+ SCOPED_TRACE(missing ? "missing" : "zero");
+ std::vector<uint8_t> bytes(model.data<uint8_t>(), model.data<uint8_t>() + model.num_vals);
+ const auto at = std::search(bytes.begin(), bytes.end(), key.begin(), key.end());
+ ASSERT_NE(at, bytes.end());
+ if (missing) {
+ at[key.size() - 1] = 'X'; // the loader then defaults the count to zero
+ } else {
+ const auto value = at + key.size() + sizeof(uint32_t); // after the u32 type tag
+ std::fill(value, value + sizeof(uint32_t), 0);
+ }
+ cnpy::NpyArray patched({bytes.size()}, sizeof(uint8_t), false);
+ std::copy(bytes.begin(), bytes.end(), patched.data<uint8_t>());
+ const ov_gguf_test::TemporaryGguf temporary(patched);
+ ov::frontend::gguf::FrontEnd frontend;
+ OV_EXPECT_THROW(frontend.convert(frontend.load(temporary.path)),
+ ov::Exception,
+ testing::HasSubstr("ssm.group_count"));
+ }
+}
+
+// The grouped-query KV broadcast may reach MakeStateful as Multiply(ones, Unsqueeze(kv)); the
+// cache read behind it must still be found, so the fused cache gets its batch-shaped initializer.
+TEST(GGUFMultimodalBackboneAdaptation, MakeStatefulFindsCachesBehindReversedGroupedQueryMultiply) {
+ auto arrays = cnpy::npz_load(ov_gguf_test::test_data_dir() + "/arch_accuracy/qwen3.npz");
+ const ov_gguf_test::TemporaryGguf temporary(ov_gguf_test::npz_array(arrays, "model"));
+ for (const bool reversed : {false, true}) {
+ SCOPED_TRACE(reversed ? "ones * kv" : "kv * ones");
+ size_t rewritten = 0;
+ const auto to_multiply = [&](const std::shared_ptr<ov::Model>& model) {
+ for (const auto& node : model->get_ordered_ops()) {
+ auto broadcast = ov::as_type_ptr<ov::op::v3::Broadcast>(node);
+ auto shape = broadcast ? ov::as_type_ptr<ov::op::v0::Constant>(broadcast->get_input_node_shared_ptr(1))
+ : nullptr;
+ if (!shape || !ov::is_type<ov::op::v0::Unsqueeze>(broadcast->get_input_node_ptr(0)))
+ continue;
+ auto ones = ov::op::v0::Constant::create(broadcast->get_output_element_type(0),
+ ov::Shape(shape->cast_vector<size_t>()),
+ {1.f});
+ const auto kv = broadcast->input_value(0);
+ ov::replace_node(broadcast,
+ reversed ? std::make_shared<ov::op::v1::Multiply>(ones, kv)
+ : std::make_shared<ov::op::v1::Multiply>(kv, ones));
+ broadcast->input(0).replace_source_output(ones); // the replaced node no longer reads kv
+ ++rewritten;
+ }
+ return rewritten > 0;
+ };
+ ov::frontend::gguf::FrontEnd frontend;
+ frontend.add_extension(std::make_shared<ov::frontend::DecoderTransformationExtension>(to_multiply));
+ frontend.add_extension(std::make_shared<ov::frontend::DecoderTransformationExtension>(
+ ov::frontend::gguf::pass::GGUFMakeStateful()));
+ std::shared_ptr<ov::Model> model;
+ ASSERT_NO_THROW(model = frontend.convert(frontend.load(temporary.path)));
+ ASSERT_GT(rewritten, 0u);
+ size_t batch_initialized = 0;
+ for (const auto& node : model->get_ordered_ops()) {
+ if (ov::is_type<ov::op::v6::ReadValue>(node) && node->get_input_size() == 1 &&
+ ov::is_type<ov::op::v3::Broadcast>(node->get_input_node_ptr(0)))
+ ++batch_initialized;
+ }
+ EXPECT_EQ(batch_initialized, rewritten);
+ }
+}
+
+TEST(GGUFEmbeddingAccuracy, TokenEmbeddingsAndPoolingMatchLlamaCPU) {
+ for (const auto* family :
+ {"llama-embed", "llama-embed-noncausal", "llama-embed-mean", "llama-embed-cls", "llama-embed-last"}) {
+ 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"));
+ ov::frontend::gguf::FrontEnd frontend;
+ auto model = frontend.convert(frontend.load(temporary.path));
+ ASSERT_EQ(model->get_results().size(), 1);
+ EXPECT_NO_THROW(model->output("embeddings"));
+ for (const auto mode : {ov::frontend::gguf::pass::AdaptToGenAI::InputMode::IDS_TO_LOGITS,
+ ov::frontend::gguf::pass::AdaptToGenAI::InputMode::EMBEDS_TO_LOGITS}) {
+ ov::frontend::gguf::pass::AdaptToGenAI adapter(mode);
+ EXPECT_FALSE(adapter.run_on_model(model));
+ }
+ ov::Core core;
+ auto compiled = core.compile_model(model,
+ "CPU",
+ ov::hint::inference_precision(ov::element::f32),
+ ov::hint::dynamic_quantization_group_size(0));
+ auto request = compiled.create_infer_request();
+ EXPECT_TRUE(request.query_state().empty());
+ const auto infer = [&](size_t count, bool compare_reference) {
+ for (const auto& input : compiled.inputs()) {
+ const auto name = input.get_any_name();
+ if (name == "token_len_per_seq") {
+ ov::Tensor lengths(ov::element::i64, {1});
+ lengths.data<int64_t>()[0] = count;
+ request.set_tensor(name, lengths);
+ } else if (name == "self_kq_mask") {
+ ov::Tensor mask(ov::element::f32, {1, 1, count, count});
+ for (size_t q = 0; q < count; ++q)
+ for (size_t k = 0; k < count; ++k)
+ mask.data<float>()[q * count + k] = k <= q ? 0.f : -INFINITY;
+ request.set_tensor(name, mask);
+ } else {
+ ASSERT_TRUE(name == "inp_tokens" || name == "inp_pos");
+ ov::Tensor values(ov::element::i32, {1, 1, 1, count});
+ for (size_t i = 0; i < count; ++i)
+ values.data<int32_t>()[i] = static_cast<int32_t>(i) + (name == "inp_tokens" ? 1 : 0);
+ request.set_tensor(name, values);
+ }
+ }
+ request.infer();
+ auto output = request.get_tensor("embeddings");
+ const auto& expected = ov_gguf_test::npz_array(arrays, "embeddings");
+ const bool pooled = std::string(family) != "llama-embed" && std::string(family) != "llama-embed-noncausal";
+ ASSERT_EQ(output.get_shape(), (ov::Shape{pooled ? 1 : count, expected.shape.back()}));
+ if (compare_reference || std::string(family) == "llama-embed") {
+ ov_gguf_test::expect_nmse_below(
+ ov_gguf_test::nmse(output.data<const float>(), expected.data<float>(), output.get_size()),
+ 1e-5);
+ }
+ };
+ infer(3, true);
+ infer(1, false);
+ infer(2, false);
+ infer(3, true);
+ }
+}
+
+TEST(GGUFEmbeddingAccuracy, RealCheckpointTokenEmbeddingsMatchLlamaCPU) {
+ const auto* directory = std::getenv("OV_GGUF_EMBEDDING_DATA");
+ if (!directory)
+ GTEST_SKIP() << "Set OV_GGUF_EMBEDDING_DATA for real embedding checkpoint validation";
+ const auto base = std::filesystem::path(directory) / "llama-embed";
+ std::ifstream file(base.string() + ".bin", std::ios::binary);
+ ASSERT_TRUE(file);
+ int32_t width = 0, count = 0;
+ file.read(reinterpret_cast<char*>(&width), sizeof(width));
+ file.read(reinterpret_cast<char*>(&count), sizeof(count));
+ ASSERT_GT(width, 0);
+ ASSERT_GT(count, 0);
+ ASSERT_LE(count, 64);
+ std::vector<int32_t> tokens(count);
+ std::vector<float> expected(static_cast<size_t>(count) * width);
+ file.read(reinterpret_cast<char*>(tokens.data()), tokens.size() * sizeof(int32_t));
+ file.read(reinterpret_cast<char*>(expected.data()), expected.size() * sizeof(float));
+ ASSERT_TRUE(file);
+ ov::frontend::gguf::FrontEnd frontend;
+ auto model = frontend.convert(frontend.load(base.string() + ".gguf"));
+ ov::Core core;
+ auto compiled = core.compile_model(model,
+ "CPU",
+ ov::hint::inference_precision(ov::element::f32),
+ ov::hint::dynamic_quantization_group_size(0),
+ ov::inference_num_threads(4));
+ auto request = compiled.create_infer_request();
+ for (const auto& input : compiled.inputs()) {
+ const auto name = input.get_any_name();
+ if (name == "token_len_per_seq") {
+ ov::Tensor lengths(ov::element::i64, {1});
+ lengths.data<int64_t>()[0] = count;
+ request.set_tensor(name, lengths);
+ } else if (name == "self_kq_mask") {
+ ov::Tensor mask(ov::element::f32, {1, 1, size_t(count), size_t(count)});
+ for (int q = 0; q < count; ++q)
+ for (int k = 0; k < count; ++k)
+ mask.data<float>()[q * count + k] = k <= q ? 0.f : -INFINITY;
+ request.set_tensor(name, mask);
+ } else {
+ ASSERT_TRUE(name == "inp_tokens" || name == "inp_pos");
+ ov::Tensor values(ov::element::i32, {1, 1, 1, size_t(count)});
+ for (int i = 0; i < count; ++i)
+ values.data<int32_t>()[i] = name == "inp_tokens" ? tokens[i] : i;
+ request.set_tensor(name, values);
+ }
+ }
+ request.infer();
+ auto output = request.get_tensor("embeddings");
+ ASSERT_EQ(output.get_shape(), (ov::Shape{size_t(count), size_t(width)}));
+ const auto metric = ov_gguf_test::nmse(output.data<const float>(), expected.data(), expected.size());
+ RecordProperty("nmse", std::to_string(metric.value()));
+ ov_gguf_test::expect_nmse_below(metric, 1e-5);
+}
+
TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {
const char* override_dir = std::getenv("OV_GGUF_ACCURACY_DATA");
const bool mamba = std::string(GetParam()).find("mamba2") == 0 || std::string(GetParam()) == "nemotron_h";
@@ -33,13 +431,7 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {
std::vector<float> reference;
int32_t vocab = 0;
std::string model_path = base.string() + ".gguf";
- struct TemporaryModel {
- std::string path;
- ~TemporaryModel() {
- if (!path.empty())
- std::filesystem::remove(path);
- }
- } temporary;
+ std::unique_ptr<ov_gguf_test::TemporaryGguf> temporary;
if (real_checkpoint) {
std::ifstream file(base.string() + ".bin", std::ios::binary);
ASSERT_TRUE(file) << base;
@@ -66,11 +458,7 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {
} else {
const auto arrays = cnpy::npz_load(base.string() + ".npz");
const auto array = [&](const std::string& name) -> const cnpy::NpyArray& {
- const auto it = std::find_if(arrays.begin(), arrays.end(), [&](const auto& entry) {
- return entry.first == name;
- });
- OPENVINO_ASSERT(it != arrays.end(), "Missing reference array ", name);
- return it->second;
+ return ov_gguf_test::npz_array(arrays, name);
};
const auto& logits = array("logits");
ASSERT_EQ(logits.shape.size(), 2);
@@ -78,19 +466,11 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {
vocab = static_cast<int32_t>(logits.shape[1]);
const auto* values = logits.data<float>();
reference.assign(values, values + 3 * vocab);
- temporary.path =
- (std::filesystem::temp_directory_path() / (ov::test::utils::generateTestFilePrefix() + ".gguf")).string();
- model_path = temporary.path;
- std::ofstream file(model_path, std::ios::binary);
- const auto& bytes = array("model");
- file.write(bytes.data<char>(), bytes.num_vals);
- ASSERT_TRUE(file);
+ 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::DecoderTransformationExtension>(ov::frontend::gguf::pass::GGUFMakeStateful()));
- fe.add_extension(
- std::make_shared<ov::frontend::DecoderTransformationExtension>(ov::frontend::gguf::pass::AdaptToGenAI()));
+ fe.add_extension(std::make_shared<ov::frontend::gguf::GenAIExtension>());
auto model = fe.convert(fe.load(model_path));
if (mamba) {
EXPECT_EQ(model->input("input_ids").get_partial_shape(), (ov::PartialShape{1, -1}));
@@ -127,17 +507,6 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {
request.infer();
return request.get_output_tensor();
};
- const auto nmse = [vocab](const float* actual, const float* expected) {
- double error = 0, norm = 0;
- for (int32_t i = 0; i < vocab; ++i) {
- EXPECT_TRUE(std::isfinite(actual[i]));
- const double difference = actual[i] - expected[i];
- error += difference * difference;
- norm += expected[i] * expected[i];
- }
- EXPECT_GT(norm, 1e-12) << "Reference must contain nonzero logits";
- return error / norm;
- };
size_t past = 0;
size_t step = 0;
size_t matching_tokens = 0;
@@ -148,12 +517,14 @@ 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 error = nmse(actual, expected);
+ const auto metric = ov_gguf_test::nmse(actual, expected, static_cast<size_t>(vocab));
+ 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;
const auto wanted = std::max_element(expected, expected + vocab) - expected;
matching_tokens += predicted == wanted;
RecordProperty("top1_match_step_" + std::to_string(step), predicted == wanted ? 1 : 0);
- RecordProperty("nmse_step_" + std::to_string(step), std::to_string(error));
+ RecordProperty("nmse_step_" + std::to_string(step), std::to_string(metric.value()));
if (real_checkpoint) {
// Real checkpoints can use different quantization arithmetic. Check the first prediction
// and continuation agreement; keep their full-logit metrics in the XML report.
@@ -161,7 +532,7 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {
EXPECT_EQ(predicted, wanted);
}
} else {
- EXPECT_LT(error, 1e-5) << "Normalized MSE against llama.cpp CPU";
+ EXPECT_LT(metric.value(), 1e-5) << "Normalized MSE against llama.cpp CPU";
}
past += tokens.size();
}
@@ -172,12 +543,14 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {
state.reset();
const auto logits = infer(schedule.front(), 0);
const auto* actual = logits.data<const float>() + logits.get_size() - vocab;
- const auto error = nmse(actual, reference.data());
+ const auto metric = ov_gguf_test::nmse(actual, reference.data(), static_cast<size_t>(vocab));
+ ASSERT_TRUE(metric.all_finite());
+ ASSERT_GT(metric.reference_norm(), 1e-12);
if (real_checkpoint)
EXPECT_EQ(std::max_element(actual, actual + vocab) - actual,
std::max_element(reference.begin(), reference.begin() + vocab) - reference.begin());
else
- EXPECT_LT(error, 1e-5) << "Fresh prefill after resetting recurrent states";
+ EXPECT_LT(metric.value(), 1e-5) << "Fresh prefill after resetting recurrent states";
}
if (real_checkpoint) {
EXPECT_GE(matching_tokens * 10, schedule.size() * 9) << "Fewer than 90% of greedy choices match";
@@ -186,7 +559,14 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {
INSTANTIATE_TEST_SUITE_P(Architectures,
GGUFArchitectureAccuracy,
- ::testing::Values("nemotron_h",
+ ::testing::Values("qwen35",
+ "qwen35-mixed",
+ "qwen35moe",
+ "qwen35moe-fused",
+ "gemma4-mqa",
+ "gemma4-moe",
+ "gemma4-ple",
+ "nemotron_h",
"mamba2",
"mamba2-tied",
"llama",
@@ -197,9 +577,16 @@ INSTANTIATE_TEST_SUITE_P(Architectures,
"olmoe",
"hunyuan-dense",
"hunyuan-moe",
+ "exaone-moe",
+ "exaone-moe-nextn",
+ "glm4moe",
+ "jais2",
+ "minimax-m2",
+ "plamo3",
"qwen3moe",
"gemma",
"gemma2",
+ "gemma3",
"exaone4",
"ernie4_5-moe",
"bailingmoe2",
diff --git a/src/frontends/gguf/tests/test_arch_conversion.cpp b/src/frontends/gguf/tests/test_arch_conversion.cpp
index 87b0e14b16b..d1237594ae5 100644
--- a/src/frontends/gguf/tests/test_arch_conversion.cpp
+++ b/src/frontends/gguf/tests/test_arch_conversion.cpp
@@ -180,19 +180,20 @@ struct Fingerprint {
const std::map<std::string, Fingerprint>& fingerprints() {
static const std::map<std::string, Fingerprint> fp{
- {"mamba2-dense.gguf.hdr", {289, 6}}, {"nemotron_h-dense.gguf.hdr", {278, 8}},
- {"bailingmoe2-moe.gguf.hdr", {470, 10}}, {"ernie4_5-moe-moe.gguf.hdr", {453, 10}},
+ {"mamba2-dense.gguf.hdr", {241, 6}}, {"nemotron_h-dense.gguf.hdr", {254, 8}},
+ {"bailingmoe2-moe.gguf.hdr", {489, 10}}, {"ernie4_5-moe-moe.gguf.hdr", {472, 10}},
{"exaone4-dense.gguf.hdr", {415, 11}}, {"gemma-dense.gguf.hdr", {365, 10}},
- {"gemma2-dense.gguf.hdr", {415, 11}}, {"glm4moe-moe.gguf.hdr", {482, 10}},
- {"gpt-oss-moe.gguf.hdr", {570, 11}}, {"hunyuan-dense-dense.gguf.hdr", {414, 10}},
- {"hunyuan-moe-moe.gguf.hdr", {550, 10}}, {"llama-dense.gguf.hdr", {398, 10}},
- {"llama-moe.gguf.hdr", {504, 10}}, {"maincoder-dense.gguf.hdr", {430, 10}},
- {"minicpm-dense.gguf.hdr", {396, 10}}, {"minicpm-moe.gguf.hdr", {502, 10}},
- {"minimax-m2-moe.gguf.hdr", {532, 10}}, {"mistral3-dense.gguf.hdr", {398, 10}},
- {"mistral3-moe.gguf.hdr", {504, 10}}, {"olmoe-moe.gguf.hdr", {532, 10}},
- {"phi3-dense.gguf.hdr", {378, 10}}, {"qwen2-dense.gguf.hdr", {366, 10}},
- {"qwen3-dense.gguf.hdr", {414, 10}}, {"qwen3moe-moe.gguf.hdr", {544, 10}},
- {"qwen35-dense.gguf.hdr", {391, 10}}, {"smollm3-dense.gguf.hdr", {382, 10}},
+ {"gemma2-dense.gguf.hdr", {415, 11}}, {"glm4moe-moe.gguf.hdr", {501, 10}},
+ {"gpt-oss-moe.gguf.hdr", {608, 11}}, {"hunyuan-dense-dense.gguf.hdr", {414, 10}},
+ {"hunyuan-moe-moe.gguf.hdr", {600, 10}}, {"llama-dense.gguf.hdr", {398, 10}},
+ {"llama-moe.gguf.hdr", {542, 10}}, {"maincoder-dense.gguf.hdr", {430, 10}},
+ {"minicpm-dense.gguf.hdr", {396, 10}}, {"minicpm-moe.gguf.hdr", {540, 10}},
+ {"minimax-m2-moe.gguf.hdr", {582, 10}}, {"mistral3-dense.gguf.hdr", {398, 10}},
+ {"mistral3-moe.gguf.hdr", {542, 10}}, {"olmoe-moe.gguf.hdr", {570, 10}},
+ {"phi3-dense.gguf.hdr", {368, 10}}, {"qwen2-dense.gguf.hdr", {366, 10}},
+ {"qwen3-dense.gguf.hdr", {414, 10}}, {"qwen3moe-moe.gguf.hdr", {582, 10}},
+ {"qwen35-dense.gguf.hdr", {360, 10}}, {"qwen35moe-moe.gguf.hdr", {532, 10}},
+ {"smollm3-dense.gguf.hdr", {382, 10}}, {"jais2-dense.gguf.hdr", {344, 10}},
};
return fp;
}
@@ -309,7 +310,7 @@ TEST_P(GGUFArchConversion, MatchesManifestExpectation) {
// The accept list must be what rejects it: a different failure means the file broke the
// reader or the builder somewhere it should never have reached.
ASSERT_FALSE(model) << fixture.header_file << " is marked `reject` but converted successfully. If the "
- << "builder now supports this architecture, add it to verified/experimental_archs() "
+ << "builder now supports this architecture, add it to the architecture catalog "
<< "and change the manifest line to `convert` with a fingerprint.";
EXPECT_NE(error.find("native GGUF builder does not support architecture"), std::string::npos)
<< fixture.header_file << " failed for a reason other than the architecture accept list, which means "
diff --git a/src/frontends/gguf/tests/test_architecture_extension.cpp b/src/frontends/gguf/tests/test_architecture_extension.cpp
index 324e0291c4d..e902d713b05 100644
--- a/src/frontends/gguf/tests/test_architecture_extension.cpp
+++ b/src/frontends/gguf/tests/test_architecture_extension.cpp
@@ -23,6 +23,7 @@
#include "openvino/frontend/gguf/adapt_to_genai.hpp"
#include "openvino/frontend/gguf/builder/graph_context.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/concat.hpp"
@@ -78,13 +79,7 @@ std::string write_decoder_gguf(const std::string& dir, const std::string& arch =
writer.kv_f32(arch + ".attn_logit_softcapping", 2.f);
writer.kv_u32(arch + ".attention.sliding_window", 2);
const auto weight = [&](const std::string& name, const std::vector<uint64_t>& shape, bool norm = false) {
- size_t count = 1;
- for (auto d : shape)
- count *= d;
- std::vector<float> values(count);
- for (size_t i = 0; i < count; ++i)
- values[i] = norm ? 1.f : 0.1f * std::sin(float(i + 1));
- writer.tensor(name, shape, values);
+ writer.filled_tensor(name, shape, norm);
};
weight("token_embd.weight", {8, 16});
weight("output_norm.weight", {8}, true);
@@ -136,6 +131,18 @@ TEST(GGUFArchitectureExtension, UnknownArchitectureIsRejectedWithoutAnExtension)
testing::HasSubstr("ArchitectureExtension")));
}
+TEST(GGUFArchitectureExtension, UnsupportedDiagnosticIncludesRegisteredArchitectures) {
+ ScratchDir scratch;
+ const auto path = write_decoder_gguf(scratch.path(), "unknown-decoder");
+ ASSERT_FALSE(path.empty());
+ ov::frontend::gguf::FrontEnd frontend;
+ frontend.add_extension(std::make_shared<ArchitectureExtension>("custom-decoder", RopeMode::Neox));
+ OV_EXPECT_THROW(frontend.convert(frontend.load(path)),
+ ov::Exception,
+ testing::AllOf(testing::HasSubstr("Supported:"), testing::HasSubstr("custom-decoder")));
+ OV_EXPECT_THROW(convert_with(path), ov::Exception, testing::Not(testing::HasSubstr("custom-decoder")));
+}
+
TEST(GGUFArchitectureExtension, DecoderDefinitionMatchesBuiltInGraph) {
ScratchDir scratch;
@@ -176,6 +183,32 @@ TEST(GGUFArchitectureExtension, DecoderRopeModeReachesTheBuilder) {
<< "the registered RoPE mode did not affect the graph, so it is not reaching the builder";
}
+TEST(GGUFGenAIExtension, RegistrationIsLocalAndConversionCanBeRepeated) {
+ ScratchDir scratch;
+ const auto path = write_decoder_gguf(scratch.path());
+ ASSERT_FALSE(path.empty());
+ ov::frontend::gguf::FrontEnd frontend;
+ auto extension = std::make_shared<ov::frontend::gguf::GenAIExtension>();
+ frontend.add_extension(extension);
+ const auto input = frontend.load(path);
+ for (size_t i = 0; i < 2; ++i) {
+ const auto model = frontend.convert(input);
+ EXPECT_EQ(model->get_variables().size(), 4);
+ EXPECT_NO_THROW(model->input("input_ids"));
+ EXPECT_NO_THROW(model->input("attention_mask"));
+ EXPECT_NO_THROW(model->input("position_ids"));
+ EXPECT_NO_THROW(model->input("beam_idx"));
+ EXPECT_EQ(model->output("logits").get_partial_shape().rank(), 3);
+ EXPECT_FALSE(extension->get_embedding_model());
+ }
+ const auto plain = convert_with(path);
+ EXPECT_TRUE(plain->get_variables().empty());
+ EXPECT_NO_THROW(plain->input("inp_tokens"));
+ OV_EXPECT_THROW(frontend.add_extension(std::make_shared<ov::frontend::gguf::GenAIExtension>()),
+ ov::Exception,
+ testing::HasSubstr("already registered"));
+}
+
TEST(GGUFArchitectureExtension, DecoderOptionsSelectTheActivation) {
ScratchDir scratch;
const auto path = write_decoder_gguf(scratch.path(), kUnknownArch);
@@ -422,10 +455,7 @@ TEST(GGUFArchitectureExtension, SharedDecoderBlocksMatchNumericallyAcrossPrefill
}},
RegistrationMode::Replace));
}
- frontend.add_extension(std::make_shared<ov::frontend::DecoderTransformationExtension>(
- ov::frontend::gguf::pass::GGUFMakeStateful()));
- frontend.add_extension(
- std::make_shared<ov::frontend::DecoderTransformationExtension>(ov::frontend::gguf::pass::AdaptToGenAI()));
+ frontend.add_extension(std::make_shared<ov::frontend::gguf::GenAIExtension>());
return frontend.convert(frontend.load(path));
};
auto builtin = load(false);
diff --git a/src/frontends/gguf/tests/test_builder_api.cpp b/src/frontends/gguf/tests/test_builder_api.cpp
index 9618315beaa..f99cc5999c4 100644
--- a/src/frontends/gguf/tests/test_builder_api.cpp
+++ b/src/frontends/gguf/tests/test_builder_api.cpp
@@ -303,6 +303,19 @@ TEST(GGUFBuilderAPI, RecurrentStateDeclarationReachesMakeStateful) {
EXPECT_EQ(model->get_sinks().size(), 1);
}
+// A named output can expose an input or another output; every name stays addressable.
+TEST(GGUFBuilderAPI, NamedOutputsKeepTheNamesOfTheValuesTheyExpose) {
+ Environment env;
+ GgufGraphContext graph(env.context);
+ auto input = graph.add_input("x", ov::element::f32, {1, 1, 1, 4});
+ graph.set_output(input, "first");
+ graph.set_output(input, "second");
+ auto model = convert(graph.finish());
+ EXPECT_NO_THROW(model->input("x"));
+ EXPECT_NO_THROW(model->output("first"));
+ EXPECT_NO_THROW(model->output("second"));
+}
+
TEST(GGUFBuilderAPI, SlidingWindowDeclarationSurvivesConversion) {
Environment env;
GgufGraphContext graph(env.context);
@@ -314,6 +327,41 @@ TEST(GGUFBuilderAPI, SlidingWindowDeclarationSurvivesConversion) {
EXPECT_THROW(graph.finish(), ov::Exception);
}
+TEST(GGUFArchitectureRegistry, SupportedListIncludesCustomFamiliesAndExtensions) {
+ ArchRegistry registry;
+ const auto builtin_names = registry.supported_archs();
+ EXPECT_EQ(builtin_names.count("clip"), 1);
+ EXPECT_EQ(builtin_names.count("mamba2"), 1);
+ EXPECT_EQ(builtin_names.count("nemotron_h"), 1);
+ EXPECT_EQ(builtin_names.count("qwen3"), 1);
+ Environment env;
+ env.metadata["general.architecture"] = std::string("clip");
+ EXPECT_FALSE(registry.find(env.context.metadata));
+ env.metadata["clip.vision.projector_type"] = std::string("mlp");
+ ASSERT_TRUE(registry.find(env.context.metadata));
+ EXPECT_EQ(registry.find(env.context.metadata)->id, "clip.mmproj");
+
+ registry.add_extension(std::make_shared<ArchitectureExtension>("custom-decoder", RopeMode::Neox));
+ EXPECT_EQ(registry.supported_archs().size(), builtin_names.size() + 1);
+ EXPECT_EQ(registry.supported_archs().count("custom-decoder"), 1);
+ EXPECT_NE(registry.describe_supported().find("custom-decoder"), std::string::npos);
+ EXPECT_EQ(ArchRegistry{}.supported_archs(), builtin_names);
+}
+
+TEST(GGUFArchitectureRegistry, SupportedNamesTrackReplacementAndDeduplicateHandlers) {
+ ArchRegistry registry({handler("vision"), handler("audio")});
+ EXPECT_EQ(registry.supported_archs(), (std::set<std::string>{"test"}));
+ EXPECT_EQ(registry.describe_supported(), "test");
+ auto replacement = handler("vision");
+ replacement.architecture = "other";
+ registry.add_extension(std::make_shared<ArchitectureExtension>(replacement, RegistrationMode::Replace));
+ EXPECT_EQ(registry.supported_archs(), (std::set<std::string>{"other", "test"}));
+ replacement.id = "audio";
+ registry.add_extension(std::make_shared<ArchitectureExtension>(replacement, RegistrationMode::Replace));
+ EXPECT_EQ(registry.supported_archs(), (std::set<std::string>{"other"}));
+ EXPECT_EQ(registry.describe_supported(), "other");
+}
+
TEST(GGUFArchitectureRegistry, DisjointHandlersForTheSameArchitectureCoexist) {
Environment env;
env.integer("modality", 1);
@@ -338,10 +386,12 @@ TEST(GGUFArchitectureRegistry, ReplacementIsExplicitAndInstancesAreIsolated) {
ArchRegistry second({handler("test")});
EXPECT_THROW(first.add(handler("test")), ov::Exception);
auto replacement = handler("test");
- replacement.maturity = Maturity::Verified;
+ replacement.match = [](const GgufMetadata&) {
+ return false;
+ };
first.add(replacement, RegistrationMode::Replace);
- EXPECT_EQ(first.find(env.context.metadata)->maturity, Maturity::Verified);
- EXPECT_EQ(second.find(env.context.metadata)->maturity, Maturity::Experimental);
+ EXPECT_FALSE(first.find(env.context.metadata));
+ EXPECT_TRUE(second.find(env.context.metadata));
EXPECT_THROW(first.add(handler("missing"), RegistrationMode::Replace), ov::Exception);
auto invalid = handler("invalid");
invalid.factory = {};
@@ -418,6 +468,36 @@ TEST(GGUFBuilderAPI, Gemma2RejectsZeroAttentionHeadsWithOrWithoutKeyLength) {
}
}
+TEST(GGUFBuilderAPI, SlidingWindowDefaultsMatchExaoneMoeAndPlamo3) {
+ for (const auto* family : {"exaone-moe", "plamo3"}) {
+ SCOPED_TRACE(family);
+ Environment env;
+ env.decoder();
+ env.integer("test.block_count", 8);
+ env.integer("test.attention.sliding_window", 128);
+ env.real("test.rope.freq_base", 1000000.f);
+ env.architecture(family);
+ DecoderConfig config(decoder_config_from_meta(env.metadata), env.weights);
+ const bool exaone = std::string(family) == "exaone-moe";
+ EXPECT_EQ(config.swa_layer_pattern, exaone ? 4 : 8);
+ EXPECT_TRUE(config.layer_is_swa(0));
+ EXPECT_FALSE(config.layer_is_swa(exaone ? 3 : 7));
+ EXPECT_EQ(config.rope_on_swa_only, exaone);
+ EXPECT_FLOAT_EQ(config.rope_freq_base_swa, exaone ? 1000000.f : 10000.f);
+ }
+}
+
+TEST(GGUFBuilderAPI, Glm4MoeDefaultsToSigmoidRouting) {
+ Environment env;
+ env.decoder();
+ env.architecture("glm4moe");
+ EXPECT_TRUE(DecoderConfig(decoder_config_from_meta(env.metadata), env.weights).moe_sigmoid_gating);
+ env.integer("glm4moe.expert_gating_func", 0);
+ EXPECT_TRUE(DecoderConfig(decoder_config_from_meta(env.metadata), env.weights).moe_sigmoid_gating);
+ env.integer("glm4moe.expert_gating_func", 1);
+ EXPECT_FALSE(DecoderConfig(decoder_config_from_meta(env.metadata), env.weights).moe_sigmoid_gating);
+}
+
TEST(GGUFBuilderAPI, ErnieInterleavesDenseAndExpertLayers) {
Environment env;
env.decoder();
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 fc951eb95cf..c77ede2cc47 100644
--- a/src/frontends/gguf/tests/test_data/arch_accuracy/README.md
+++ b/src/frontends/gguf/tests/test_data/arch_accuracy/README.md
@@ -1,20 +1,31 @@
# Native architecture accuracy references
-Each NPZ contains a small F32 GGUF (`model`, uint8 bytes) and three complete last-token
+Each decoder NPZ contains a small F32 GGUF (`model`, uint8 bytes) and three complete last-token
logit vectors (`logits`, float32). `gen_arch_accuracy.py` creates the weights;
`architecture_oracle.cpp` evaluates them with the real llama.cpp CPU backend.
+Embedding fixtures contain `embeddings` instead of `logits`, and cover causal/bidirectional
+per-token output plus mean, first-token and last-token pooling.
OpenVINO does not participate in reference generation.
-All 23 fixtures, including Muse Glimmer, reproduce byte-for-byte with upstream
-[ggml-org/llama.cpp `03fa73cb27f5c251b9528489b18d303b1366aca4`](https://github.com/ggml-org/llama.cpp/commit/03fa73cb27f5c251b9528489b18d303b1366aca4)
-(2026-09-08). Muse Glimmer support is included upstream; no fork is needed.
+The 40 decoder fixtures and five 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 (`gemma4-ple`). Reference revisions are:
+
+| Fixtures | Upstream llama.cpp CPU oracle |
+|---|---|
+| Decoder/embedding fixtures other than the Mamba cases below | `03fa73cb27f5c251b9528489b18d303b1366aca4` (2026-09-08; includes Muse Glimmer) |
+| `mamba2`, `mamba2-tied`, `nemotron_h` | `476c01efe88aad7880a8132d5d3a415f2ca75139`, recorded when these fixtures were added |
The cases use distinct nonzero weights and nonuniform norm scales, four query heads,
grouped-query attention (single KV head for Gemma), and token batches `[1,2,3]`, `[4]`,
-`[5,6]`. The same inference request preserves state across all three batches.
+`[5,6]`. Decoder requests preserve state across all three batches. Embedding fixtures evaluate `[1,2,3]`
+without caches; their tests also change input lengths on the same request.
Gemma2 and Muse Glimmer cross a two-token sliding window; SmolLM3 exercises its fourth,
NoPE layer. ERNIE omits `expert_shared_count`, as the real 21B checkpoint does. Bailing
-covers sigmoid routing, biased selection, group filtering, and a shared expert.
+covers sigmoid routing, biased selection, group filtering, and a shared expert. EXAONE MoE
+also covers sigmoid routing with scale 2.5 and trailing NextN tensors; MiniMax and Hunyuan
+omit expert-normalization metadata to exercise their mandatory normalization defaults.
Devstral adds three configurations under the existing `llama` and `mistral3` families.
Small models use unequal embedding/query widths. Devstral Small 2 crosses reduced original-context
@@ -27,7 +38,7 @@ F16 KV state and dynamic activation quantization disabled. It checks every logit
normalized MSE below `1e-5`. Missing references fail the test. These fixtures run in the
regular frontend suite, including offline CI; llama.cpp is only needed to regenerate them.
-To regenerate all fixtures, check out the revision above and build it with
+To regenerate selected fixtures, check out their revision above and build it with
`GGML_OPENVINO=OFF`. Run from `src/frontends/gguf/tests`, with `LLAMA_SRC` and
`LLAMA_BUILD` pointing to that checkout and its build directory:
@@ -36,10 +47,19 @@ c++ -std=c++17 architecture_oracle.cpp \
-I "$LLAMA_SRC/include" -I "$LLAMA_SRC/ggml/include" \
-L "$LLAMA_BUILD/bin" -Wl,-rpath,"$LLAMA_BUILD/bin" \
-lllama -lggml -lggml-base -o architecture_oracle
+c++ -std=c++17 embedding_oracle.cpp \
+ -I "$LLAMA_SRC/include" -I "$LLAMA_SRC/ggml/include" \
+ -L "$LLAMA_BUILD/bin" -Wl,-rpath,"$LLAMA_BUILD/bin" \
+ -lllama -lggml -lggml-base -o embedding_oracle
PYTHONPATH="$LLAMA_SRC/gguf-py" python3 gen_arch_accuracy.py \
- --oracle ./architecture_oracle
+ --oracle ./architecture_oracle --embedding-oracle ./embedding_oracle --architectures llama qwen3
```
+Choose other names from `CASES` in `gen_arch_accuracy.py`. For the Mamba group, build the oracle
+against its recorded revision and use `--architectures mamba2 mamba2-tied nemotron_h`.
+Omitting `--architectures` attempts every case with the supplied oracle; use it only for a
+deliberate full reference refresh and review the numerical changes and provenance together.
+
For an additional real-checkpoint check, create `<arch>.gguf` in a separate directory,
then run `architecture_oracle <arch>.gguf <arch>.bin "The capital of France is"`.
Set `OV_GGUF_ACCURACY_DATA` to that directory and filter the test to that architecture.
@@ -47,3 +67,7 @@ This performs prefill plus twelve reference-token decode steps, requires the sam
prediction and at least 90% matching greedy choices, and records per-step normalized MSE.
It does not claim exact logit agreement for the frontend's lossy quantized-weight path.
Use `OV_GGUF_Q4_K_ZP_F16=1` for Q4_K accuracy comparisons.
+
+For the embedding checkpoint, put `llama-embed.gguf` and the output of
+`embedding_oracle llama-embed.gguf llama-embed.bin "<prompt>"` in a directory and set
+`OV_GGUF_EMBEDDING_DATA` to it; `GGUFEmbeddingAccuracy` then compares per-token embeddings.
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/exaone-moe-nextn.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/exaone-moe-nextn.npz
new file mode 100644
index 00000000000..f61a10ec3b1
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/exaone-moe-nextn.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/exaone-moe.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/exaone-moe.npz
new file mode 100644
index 00000000000..07d0aabc504
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/exaone-moe.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/gemma3.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/gemma3.npz
new file mode 100644
index 00000000000..ddc2c1b7844
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/gemma3.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/gemma4-moe.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/gemma4-moe.npz
new file mode 100644
index 00000000000..a49654045c7
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/gemma4-moe.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/gemma4-mqa.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/gemma4-mqa.npz
new file mode 100644
index 00000000000..f5584cc740b
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/gemma4-mqa.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/gemma4-ple.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/gemma4-ple.npz
new file mode 100644
index 00000000000..39f934a3fcd
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/gemma4-ple.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/glm4moe.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/glm4moe.npz
new file mode 100644
index 00000000000..f4d9406e495
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/glm4moe.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/hunyuan-moe.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/hunyuan-moe.npz
index 3c4f51b084e..9a88586d041 100644
Binary files a/src/frontends/gguf/tests/test_data/arch_accuracy/hunyuan-moe.npz and b/src/frontends/gguf/tests/test_data/arch_accuracy/hunyuan-moe.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/jais2.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/jais2.npz
new file mode 100644
index 00000000000..4b5037b0878
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/jais2.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/llama-embed-cls.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/llama-embed-cls.npz
new file mode 100644
index 00000000000..932b262089b
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/llama-embed-cls.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/llama-embed-last.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/llama-embed-last.npz
new file mode 100644
index 00000000000..aac5d6e6563
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/llama-embed-last.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/llama-embed-mean.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/llama-embed-mean.npz
new file mode 100644
index 00000000000..7b8cb6c9557
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/llama-embed-mean.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/llama-embed-noncausal.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/llama-embed-noncausal.npz
new file mode 100644
index 00000000000..5111bad742f
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/llama-embed-noncausal.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/llama-embed.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/llama-embed.npz
new file mode 100644
index 00000000000..52ce0249f54
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/llama-embed.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/minimax-m2.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/minimax-m2.npz
new file mode 100644
index 00000000000..a9b31c64584
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/minimax-m2.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/plamo3.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/plamo3.npz
new file mode 100644
index 00000000000..8933ffed335
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/plamo3.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/qwen35-mixed.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen35-mixed.npz
new file mode 100644
index 00000000000..ed140826947
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen35-mixed.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/qwen35.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen35.npz
new file mode 100644
index 00000000000..77d1e95b738
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen35.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/qwen35moe-fused.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen35moe-fused.npz
new file mode 100644
index 00000000000..93d2b6ab59d
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen35moe-fused.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/qwen35moe.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen35moe.npz
new file mode 100644
index 00000000000..b20464f1dfc
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen35moe.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 d407aed9bef..4763d912452 100644
--- a/src/frontends/gguf/tests/test_data/arch_fixtures/manifest.txt
+++ b/src/frontends/gguf/tests/test_data/arch_fixtures/manifest.txt
@@ -1,5 +1,5 @@
-# GGUF per-architecture conversion fixtures -- see gen_arch_fixtures.py (generator, run offline) and
-# test_arch_conversion.cpp (consumer). Generated from llama.cpp 476c01efe88aad7880a8132d5d3a415f2ca75139 at seed 1.
+# GGUF per-architecture conversion fixtures -- see gen_arch_fixtures.py (generator) and
+# test_arch_conversion.cpp (consumer). Generated from llama.cpp 86a9c79f866799eb0e7e89c03578ccfbcc5d808e at seed 1.
#
# One line per fixture:
# <file> <data_bytes> <expectation>
@@ -57,7 +57,7 @@ hunyuan_vl-dense.gguf.hdr 4732800 reject
hy_v3-moe.gguf.hdr 11815360 reject
internlm2-dense.gguf.hdr 4730752 reject
jais-dense.gguf.hdr 4745856 reject
-jais2-dense.gguf.hdr 3956480 broken
+jais2-dense.gguf.hdr 3956480 convert
jamba-dense.gguf.hdr 6061856 reject
kimi-linear-moe.gguf.hdr 2833984 reject
lfm2-dense.gguf.hdr 4731520 reject
@@ -98,7 +98,7 @@ qwen2moe-moe.gguf.hdr 9455872 reject
qwen2vl-dense.gguf.hdr 4731264 reject
qwen3-dense.gguf.hdr 4733824 convert
qwen35-dense.gguf.hdr 5271040 convert
-qwen35moe-moe.gguf.hdr 9995904 reject
+qwen35moe-moe.gguf.hdr 9995904 convert
qwen3moe-moe.gguf.hdr 7096192 convert
qwen3next-moe.gguf.hdr 11044416 reject
qwen3vl-dense.gguf.hdr 4733824 reject
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/README.md b/src/frontends/gguf/tests/test_data/mmproj_accuracy/README.md
new file mode 100644
index 00000000000..df485fb5993
--- /dev/null
+++ b/src/frontends/gguf/tests/test_data/mmproj_accuracy/README.md
@@ -0,0 +1,60 @@
+# Multimodal projector accuracy references
+
+Each NPZ holds a small random F32 `clip` GGUF (`model`, uint8 bytes), the encoder inputs and
+the embeddings that the real llama.cpp CPU encoder produces for them. OpenVINO does not
+participate in reference generation. The regular frontend test run consumes these files; no
+llama.cpp build or model download is needed unless they are regenerated.
+
+`gen_mmproj_accuracy.py` generates both suites:
+
+| Suite | Layout | Families |
+|---|---|---|
+| `GGUFMMProjAccuracy` | `inputs`, `embeddings` and family-specific index inputs | `gemma3` (+`_fused`, `_legacy`), `idefics3`, `janus_pro`, `mlp` (+`_norm`, `_feature`), `internvl` (+`_qknorm`), `resampler` (+`_v2`, `_v4`), `qwen2vl_merger`, `qwen2.5vl_merger` (+`_window_video`), `qwen3vl_merger`, `qwen2a`, `ultravox`, `voxtral` (+`_odd`), `musicflamingo`, `meralion`, `glma` |
+| `GGUFMMProjDynamicAccuracy` | two input sizes as `0.*` and `1.*`; one compiled model must serve both | `muse-glimmer`, `pixtral` (+`_merge`), `phi4`, `gemma4v` (+`_one_sided`), `gemma4uv` (+`_low_contrast`), `gemma4ua`, `gemma4a`, `minicpmv4_6`, `deepseekocr` (+`_resize`, `_overview`), `deepseekocr2` (+`_overview`); `qwen2.5vl_merger_grids` and `resampler_grids` rerun single-grid fixture models |
+
+Suffixes select fixture variants, for example fused QKV, legacy FFN names, concatenated CLIP
+feature layers, whole-tensor QK norms, an odd frame count, one-sided clipping bounds or OCR
+overview separators. Both suites compare the raw encoder and its `AdaptMmprojToGenAI` form
+with normalized MSE below `1e-5`.
+
+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.
+
+## Reference revision
+
+All fixtures and op expectations come from llama.cpp
+[`03fa73cb27f5c251b9528489b18d303b1366aca4`](https://github.com/ggml-org/llama.cpp/commit/03fa73cb27f5c251b9528489b18d303b1366aca4),
+which has aligned-corner position interpolation, the Muse Glimmer encoder, and a `ggml_clamp`
+that no longer clamps its source in place. The Gemma4 fixtures clip only the Q input, so
+clipping that leaks into the shared K/V input fails them.
+
+## Regenerating
+
+Build the oracles against a CPU-only llama.cpp checkout (`GGML_OPENVINO=OFF`), with `LLAMA_SRC`
+and `LLAMA_BUILD` pointing to the checkout and its build directory. Run from
+`src/frontends/gguf/tests`:
+
+```sh
+c++ -std=c++17 mmproj_oracle.cpp -I "$LLAMA_SRC/tools/mtmd" -I "$LLAMA_SRC/include" \
+ -I "$LLAMA_SRC/ggml/include" -L "$LLAMA_BUILD/bin" -Wl,-rpath,"$LLAMA_BUILD/bin" \
+ -lmtmd -lllama -lggml -lggml-base -o mmproj_oracle
+c++ -std=c++17 mmproj_ops_oracle.cpp -I "$LLAMA_SRC/ggml/include" -L "$LLAMA_BUILD/bin" \
+ -Wl,-rpath,"$LLAMA_BUILD/bin" -lggml -lggml-base -lggml-cpu -o mmproj_ops_oracle
+PYTHONPATH="$LLAMA_SRC/gguf-py" python3 gen_mmproj_accuracy.py --oracle ./mmproj_oracle \
+ --ops-oracle ./mmproj_ops_oracle
+```
+
+`--families` regenerates a subset. `mmproj_oracle` takes
+`model vision|audio width height input.f32 output.f32 [second_frame.f32]`;
+`GGUF_ORACLE_DUMP=<directory>` writes its intermediate F32 tensors, and
+`GGUF_ORACLE_OVERVIEW=1` adds the OCR view separator. `mmproj_fixtures.py` holds the helpers
+shared by the generator and the model hub tests.
+
+## Real checkpoints
+
+`tests/model_hub_tests/gguf/test_gguf_mmproj.py` compares downloaded projector files with
+`mmproj_oracle`, which it builds at the revision above, on an F32 copy of the same weights.
+See [testing](../../../docs/testing.md#real-checkpoints) for pytest commands, dependencies,
+oracle caches, and local-file lists, and [coverage limits](../../../docs/mmproj.md#validation-coverage)
+for checkpoint tolerance overrides and skipped cases.
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/deepseekocr.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/deepseekocr.npz
new file mode 100644
index 00000000000..782e38652d2
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/deepseekocr.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/deepseekocr2.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/deepseekocr2.npz
new file mode 100644
index 00000000000..9fa0e780d8c
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/deepseekocr2.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/deepseekocr2_overview.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/deepseekocr2_overview.npz
new file mode 100644
index 00000000000..b44a3d408f7
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/deepseekocr2_overview.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/deepseekocr_overview.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/deepseekocr_overview.npz
new file mode 100644
index 00000000000..451636974ec
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/deepseekocr_overview.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/deepseekocr_resize.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/deepseekocr_resize.npz
new file mode 100644
index 00000000000..40a9e87147f
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/deepseekocr_resize.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma3.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma3.npz
new file mode 100644
index 00000000000..ff0f4691bd6
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma3.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma3_fused.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma3_fused.npz
new file mode 100644
index 00000000000..68906dabdd1
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma3_fused.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma3_legacy.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma3_legacy.npz
new file mode 100644
index 00000000000..5128712a76d
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma3_legacy.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma4a.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma4a.npz
new file mode 100644
index 00000000000..db6c9e2abb3
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma4a.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma4ua.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma4ua.npz
new file mode 100644
index 00000000000..7be73034453
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma4ua.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma4uv.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma4uv.npz
new file mode 100644
index 00000000000..266981b3bae
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma4uv.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma4uv_low_contrast.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma4uv_low_contrast.npz
new file mode 100644
index 00000000000..4276439d3e6
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma4uv_low_contrast.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma4v.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma4v.npz
new file mode 100644
index 00000000000..9e615a81d5c
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma4v.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma4v_one_sided.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma4v_one_sided.npz
new file mode 100644
index 00000000000..1ea2cb8abce
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/gemma4v_one_sided.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/glma.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/glma.npz
new file mode 100644
index 00000000000..9d078f96804
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/glma.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/idefics3.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/idefics3.npz
new file mode 100644
index 00000000000..ea88c347a8b
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/idefics3.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/internvl.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/internvl.npz
new file mode 100644
index 00000000000..04390683340
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/internvl.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/internvl_qknorm.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/internvl_qknorm.npz
new file mode 100644
index 00000000000..5f8fe815fdb
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/internvl_qknorm.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/janus_pro.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/janus_pro.npz
new file mode 100644
index 00000000000..852ffa58067
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/janus_pro.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/meralion.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/meralion.npz
new file mode 100644
index 00000000000..c239b33203f
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/meralion.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/minicpmv4_6.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/minicpmv4_6.npz
new file mode 100644
index 00000000000..76e8eae2fac
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/minicpmv4_6.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/mlp.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/mlp.npz
new file mode 100644
index 00000000000..0e17372b8c5
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/mlp.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/mlp_feature.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/mlp_feature.npz
new file mode 100644
index 00000000000..e133a44435f
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/mlp_feature.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/mlp_norm.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/mlp_norm.npz
new file mode 100644
index 00000000000..3f3e1f78e89
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/mlp_norm.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/muse-glimmer.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/muse-glimmer.npz
new file mode 100644
index 00000000000..81ff3c4a367
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/muse-glimmer.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/musicflamingo.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/musicflamingo.npz
new file mode 100644
index 00000000000..0a8d35e808f
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/musicflamingo.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/phi4.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/phi4.npz
new file mode 100644
index 00000000000..7c6ca628477
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/phi4.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/pixtral.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/pixtral.npz
new file mode 100644
index 00000000000..abba8cc23fc
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/pixtral.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/pixtral_merge.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/pixtral_merge.npz
new file mode 100644
index 00000000000..86a4ccc6048
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/pixtral_merge.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen2.5vl_merger.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen2.5vl_merger.npz
new file mode 100644
index 00000000000..8a0cdd18505
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen2.5vl_merger.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen2.5vl_merger_grids.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen2.5vl_merger_grids.npz
new file mode 100644
index 00000000000..e4dc38f934e
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen2.5vl_merger_grids.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen2.5vl_merger_window_video.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen2.5vl_merger_window_video.npz
new file mode 100644
index 00000000000..7f3c3912d5e
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen2.5vl_merger_window_video.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen2a.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen2a.npz
new file mode 100644
index 00000000000..5853a10dfa0
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen2a.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen2vl_merger.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen2vl_merger.npz
new file mode 100644
index 00000000000..92777503cb6
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen2vl_merger.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen3vl_merger.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen3vl_merger.npz
new file mode 100644
index 00000000000..a0a16827288
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/qwen3vl_merger.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/resampler.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/resampler.npz
new file mode 100644
index 00000000000..061092e6551
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/resampler.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/resampler_grids.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/resampler_grids.npz
new file mode 100644
index 00000000000..d79bb77e71a
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/resampler_grids.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/resampler_v2.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/resampler_v2.npz
new file mode 100644
index 00000000000..989e5ca065c
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/resampler_v2.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/resampler_v4.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/resampler_v4.npz
new file mode 100644
index 00000000000..7466dacdaba
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/resampler_v4.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/ultravox.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/ultravox.npz
new file mode 100644
index 00000000000..193550a77de
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/ultravox.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/voxtral.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/voxtral.npz
new file mode 100644
index 00000000000..2c45c1abf9f
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/voxtral.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_accuracy/voxtral_odd.npz b/src/frontends/gguf/tests/test_data/mmproj_accuracy/voxtral_odd.npz
new file mode 100644
index 00000000000..ed9455875ff
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_accuracy/voxtral_odd.npz differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_im2col7.npy b/src/frontends/gguf/tests/test_data/mmproj_im2col7.npy
new file mode 100644
index 00000000000..77f66e06c30
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_im2col7.npy differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_im2col9.npy b/src/frontends/gguf/tests/test_data/mmproj_im2col9.npy
new file mode 100644
index 00000000000..aff6d1c6920
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_im2col9.npy differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_interpolate_corners_expected.npy b/src/frontends/gguf/tests/test_data/mmproj_interpolate_corners_expected.npy
new file mode 100644
index 00000000000..ed71ebb511b
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_interpolate_corners_expected.npy differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_interpolate_down_corners_expected.npy b/src/frontends/gguf/tests/test_data/mmproj_interpolate_down_corners_expected.npy
new file mode 100644
index 00000000000..271b369f809
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_interpolate_down_corners_expected.npy differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_interpolate_down_expected.npy b/src/frontends/gguf/tests/test_data/mmproj_interpolate_down_expected.npy
new file mode 100644
index 00000000000..b035baf884d
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_interpolate_down_expected.npy differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_interpolate_expected.npy b/src/frontends/gguf/tests/test_data/mmproj_interpolate_expected.npy
new file mode 100644
index 00000000000..1aaf9d0bf1b
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_interpolate_expected.npy differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_relative.npy b/src/frontends/gguf/tests/test_data/mmproj_relative.npy
new file mode 100644
index 00000000000..98281e772c5
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_relative.npy differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_relative_table.npy b/src/frontends/gguf/tests/test_data/mmproj_relative_table.npy
new file mode 100644
index 00000000000..7c74939d092
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_relative_table.npy differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_restored.npy b/src/frontends/gguf/tests/test_data/mmproj_restored.npy
new file mode 100644
index 00000000000..893d8596d1a
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_restored.npy differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_window_input.npy b/src/frontends/gguf/tests/test_data/mmproj_window_input.npy
new file mode 100644
index 00000000000..893d8596d1a
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_window_input.npy differ
diff --git a/src/frontends/gguf/tests/test_data/mmproj_windows.npy b/src/frontends/gguf/tests/test_data/mmproj_windows.npy
new file mode 100644
index 00000000000..ee32b7f6baa
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/mmproj_windows.npy differ
diff --git a/src/frontends/gguf/tests/test_data/multimodal_imrope_expected.npy b/src/frontends/gguf/tests/test_data/multimodal_imrope_expected.npy
new file mode 100644
index 00000000000..97ef6a2d2d1
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/multimodal_imrope_expected.npy differ
diff --git a/src/frontends/gguf/tests/test_data/vision_rope_expected.npy b/src/frontends/gguf/tests/test_data/vision_rope_expected.npy
new file mode 100644
index 00000000000..be75a8ab2c9
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/vision_rope_expected.npy differ
diff --git a/src/frontends/gguf/tests/test_dequant_vs_ggml.cpp b/src/frontends/gguf/tests/test_dequant_vs_ggml.cpp
index 8059f1d47ce..6babd7a2db7 100644
--- a/src/frontends/gguf/tests/test_dequant_vs_ggml.cpp
+++ b/src/frontends/gguf/tests/test_dequant_vs_ggml.cpp
@@ -15,10 +15,12 @@
// Tolerance: ggml stores K-quant scales as f16 and the dequant subgraph runs in f16,
// so allow ~3e-3 (matching llama.cpp's MAX_QUANTIZATION_TOTAL_ERROR-class thresholds).
+#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <string>
+#include <tuple>
#include <vector>
#include "gtest/gtest.h"
@@ -229,3 +231,87 @@ INSTANTIATE_TEST_SUITE_P(AllQuantTypes,
[](const ::testing::TestParamInfo<DeqCase>& i) {
return std::string(i.param.stem);
});
+
+// Gemma4 global attention can reuse one quantized tensor for both K and V.
+// Constructing its first decompression graph must not reshape the shared scales.
+TEST(GGUFDequant, SharedExtractedWeightsKeepGroupLayout) {
+ constexpr size_t rows = 4, cols = 256, groups = cols / 32;
+ for (const auto type : {GGUF_TYPE_Q4_0, GGUF_TYPE_Q4_K}) {
+ const bool asymmetric = type == GGUF_TYPE_Q4_K;
+ const std::string stem = asymmetric ? "q4_k" : "q4_0";
+ SCOPED_TRACE(stem);
+ const auto bytes = load_npy<uint8_t>(stem + "_qbytes");
+ const auto reference = load_npy<float>(stem + "_deq");
+ GgufTensor source{};
+ source.type = type;
+ source.ndim = 2;
+ source.dim[0] = cols;
+ source.dim[1] = rows;
+ source.num_weights = rows * cols;
+ source.bsize = bytes.size();
+ source.weights_data = bytes.data();
+ WeightTensors tensors;
+ tensors.weight =
+ ov::Tensor(asymmetric ? ov::element::u32 : ov::element::i4, {rows, asymmetric ? cols / 8 : cols});
+ tensors.scales = ov::Tensor(ov::element::f16, {rows, groups});
+ if (asymmetric) {
+ tensors.zero_point = ov::Tensor(ov::element::f16, {rows, groups});
+ gguf_fill_asym(source, tensors.weight, tensors.scales, tensors.zero_point);
+ } else {
+ gguf_fill_sym(source, tensors.weight, tensors.scales);
+ }
+ const auto first = make_weight_node(tensors, type, "key");
+ EXPECT_EQ(tensors.scales.get_shape(), (ov::Shape{rows, groups}));
+ if (asymmetric) {
+ EXPECT_EQ(tensors.zero_point.get_shape(), (ov::Shape{rows, groups}));
+ }
+ const auto second = make_weight_node(tensors, type, "value");
+ const auto a = eval_as_f32(first);
+ const auto b = eval_as_f32(second);
+ ASSERT_EQ(a.size(), reference.size());
+ ASSERT_EQ(b.size(), reference.size());
+ for (size_t i = 0; i < reference.size(); ++i) {
+ EXPECT_EQ(a[i], b[i]);
+ EXPECT_NEAR(a[i], reference[i], 3e-3f);
+ }
+ }
+}
+
+// Matmul weights take an integer zero-point, so Q4_1 is requantized to u4 and Q5_K to u8.
+// The public byte-level entry point decodes Q4_1 and sends Q5_K through Q8_0_C instead, so
+// fill as the loader does. Each 32-value group lands on a grid spanning [min(lo,0), max(hi,0)]:
+// every value is within half a step of it, up to f16 scale rounding.
+TEST(GGUFDequant, IntegerZeroPointRequantizationTracksGgml) {
+ constexpr size_t rows = kRows, cols = kCols, groups = cols / 32;
+ for (const auto& [type, stem, levels] :
+ {std::tuple{GGUF_TYPE_Q4_1, "q4_1", 15.f}, std::tuple{GGUF_TYPE_Q5_K, "q5_k", 255.f}}) {
+ SCOPED_TRACE(stem);
+ const auto bytes = load_npy<uint8_t>(std::string(stem) + "_qbytes");
+ const auto reference = load_npy<float>(std::string(stem) + "_deq");
+ GgufTensor source{};
+ source.type = type;
+ source.ndim = 2;
+ source.dim[0] = cols;
+ source.dim[1] = rows;
+ source.num_weights = rows * cols;
+ source.bsize = bytes.size();
+ source.weights_data = bytes.data();
+ const auto qtype = static_cast<GgufTensorType>(type);
+ ASSERT_EQ(gguf_zero_point_type("blk.0.ffn_up.weight", qtype), ov::element::u8);
+ const bool packed = type == GGUF_TYPE_Q4_1;
+ WeightTensors tensors;
+ tensors.weight = ov::Tensor(packed ? ov::element::u32 : ov::element::u8, {rows, packed ? cols / 8 : cols});
+ tensors.scales = ov::Tensor(ov::element::f16, {rows, groups});
+ tensors.zero_point = ov::Tensor(ov::element::u8, {rows, groups});
+ gguf_fill_asym(source, tensors.weight, tensors.scales, tensors.zero_point);
+ const auto values = eval_as_f32(make_weight_node(tensors, qtype, "blk.0.ffn_up.weight"));
+ ASSERT_EQ(values.size(), reference.size());
+ for (size_t group = 0; group < rows * groups; ++group) {
+ const auto begin = reference.begin() + group * 32;
+ const auto [lo, hi] = std::minmax_element(begin, begin + 32);
+ const float range = std::max(*hi, 0.f) - std::min(*lo, 0.f);
+ for (size_t k = group * 32; k < group * 32 + 32; ++k)
+ ASSERT_LE(std::fabs(values[k] - reference[k]), range * (0.5f / levels + 1e-3f)) << "group " << group;
+ }
+ }
+}
diff --git a/src/frontends/gguf/tests/test_extensions.cpp b/src/frontends/gguf/tests/test_extensions.cpp
index b1c9e2ecb82..a8d6875d3df 100644
--- a/src/frontends/gguf/tests/test_extensions.cpp
+++ b/src/frontends/gguf/tests/test_extensions.cpp
@@ -209,7 +209,7 @@ TEST(GGUFExtensions, GGUFMakeStatefulExtensionYieldsStatefulCache) {
const auto& info = model->get_variables()[0]->get_info();
EXPECT_EQ(info.variable_id, "cache");
EXPECT_EQ(info.data_type, ov::element::f16);
- EXPECT_EQ(info.data_shape, ov::PartialShape({1, -1, 2, 4}));
+ EXPECT_EQ(info.data_shape, ov::PartialShape({-1, -1, 2, 4}));
}
// skip_caches leaves a named cache stateless while other caches are converted. A sliding-window
@@ -374,14 +374,13 @@ TEST(GGUFExtensions, ArbitraryTransformationExtensionRuns) {
namespace {
// A model with one static-shape Parameter/Result recurrent-state pair, optionally alongside a KV
-// cache SetRows write (kv_cache_write_builder's shape) to model a hybrid stack. state_out is an
-// arbitrary op fed by the state Parameter; its friendly name is what
-// make_recurrent_states_stateful matches a Result's producer against (see make_stateful.cpp).
+// cache SetRows write (kv_cache_write_builder's shape) to model a hybrid stack. Like translation,
+// the state's Result is named after the state output.
std::shared_ptr<ov::Model> recurrent_state_model(bool with_kv_cache) {
auto state_in = ov::test::utils::make_param(ov::element::f32, ov::Shape{1, 2, 4}, "state_in");
auto state_out = std::make_shared<ov::op::v0::Abs>(state_in);
- state_out->set_friendly_name("state_out");
auto state_result = std::make_shared<ov::op::v0::Result>(state_out);
+ state_result->set_friendly_name("state_out");
ov::ParameterVector params{state_in};
ov::ResultVector results{state_result};
@@ -420,7 +419,7 @@ TEST(GGUFExtensions, GGUFMakeStatefulRewritesRecurrentOnlyState) {
EXPECT_NE(p->get_friendly_name(), "state_in");
}
for (const auto& r : model->get_results()) {
- EXPECT_EQ(r->get_input_node_shared_ptr(0)->get_friendly_name().find("state_out"), std::string::npos);
+ EXPECT_NE(r->get_friendly_name(), "state_out");
}
}
@@ -484,8 +483,9 @@ TEST(GGUFExtensions, GGUFMakeStatefulNormalizesCausalConvCache) {
v0::Constant::create(ov::element::i64, {1}, {std::numeric_limits<int64_t>::max()}),
v0::Constant::create(ov::element::i64, {1}, {1}),
v0::Constant::create(ov::element::i64, {1}, {3}));
- update->set_friendly_name("conv_state_out");
- model->add_results({std::make_shared<v0::Result>(update)});
+ auto update_result = std::make_shared<v0::Result>(update);
+ update_result->set_friendly_name("conv_state_out");
+ model->add_results({update_result});
model->get_rt_info()[pass::gguf_recurrent_states_key()] = std::vector<std::string>{"conv_state", "conv_state_out"};
pass::GGUFMakeStateful normalize;
diff --git a/src/frontends/gguf/tests/test_mmproj.cpp b/src/frontends/gguf/tests/test_mmproj.cpp
new file mode 100644
index 00000000000..3fe4387c211
--- /dev/null
+++ b/src/frontends/gguf/tests/test_mmproj.cpp
@@ -0,0 +1,557 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <algorithm>
+#include <cmath>
+#include <filesystem>
+
+#include "builder/api/metadata_store.hpp"
+#include "builder/arch_registry.hpp"
+#include "builder/projector_registry.hpp"
+#include "cnpy.h"
+#include "common_test_utils/common_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/gguf/adapt_mmproj_to_genai.hpp"
+#include "openvino/frontend/gguf/extension/projector.hpp"
+#include "openvino/frontend/gguf/frontend.hpp"
+#include "openvino/openvino.hpp"
+#include "openvino/pass/serialize.hpp"
+
+namespace {
+class GGUFMMProj : public ::testing::Test {
+protected:
+ ov_gguf_test::GgufWriter writer;
+ std::string path =
+ (std::filesystem::temp_directory_path() / (ov::test::utils::generateTestFilePrefix() + ".gguf")).string();
+ void SetUp() override {
+ writer.kv_str("general.architecture", "clip");
+ writer.kv_bool("clip.use_gelu", true);
+ }
+ void TearDown() override {
+ std::filesystem::remove(path);
+ std::filesystem::remove(path + ".xml");
+ std::filesystem::remove(path + ".bin");
+ }
+ void weight(const std::string& name, const std::vector<uint64_t>& dims, bool norm = false) {
+ writer.filled_tensor(name, dims, norm, 0.01f);
+ }
+ void encoder(const std::string& modality, const std::string& projector) {
+ const auto meta = "clip." + modality + ".";
+ const auto p = modality == "vision" ? std::string("v.") : std::string("a.");
+ writer.kv_bool("clip.has_" + modality + "_encoder", true);
+ writer.kv_str(meta + "projector_type", projector);
+ writer.kv_u32(meta + "embedding_length", 8);
+ writer.kv_u32(meta + "feed_forward_length", 12);
+ writer.kv_u32(meta + "block_count", 1);
+ writer.kv_u32(meta + "projection_dim", 6);
+ writer.kv_u32(meta + "attention.head_count", 2);
+ writer.kv_f32(meta + "attention.layer_norm_epsilon", 1e-5f);
+ weight(p + "position_embd.weight", {8, 16});
+ for (const auto* n : {"ln1", "ln2"}) {
+ weight(p + "blk.0." + n + ".weight", {8}, true);
+ weight(p + "blk.0." + n + ".bias", {8});
+ }
+ for (const auto* n : {"attn_q", "attn_k", "attn_v", "attn_out"})
+ weight(p + "blk.0." + n + ".weight", {8, 8});
+ weight(p + "blk.0.ffn_up.weight", {8, 12});
+ weight(p + "blk.0.ffn_down.weight", {12, 8});
+ if (modality == "vision") {
+ writer.kv_u32(meta + "image_size", 8);
+ writer.kv_u32(meta + "patch_size", 2);
+ writer.kv_u32(meta + "projector.scale_factor", 2);
+ weight("v.patch_embd.weight", {2, 2, 3, 8});
+ weight("v.patch_embd.bias", {8});
+ weight("mm.soft_emb_norm.weight", {8}, true);
+ weight("mm.input_projection.weight", {6, 8});
+ } else {
+ writer.kv_u32(meta + "num_mel_bins", 4);
+ weight("a.conv1d.1.weight", {3, 4, 8});
+ weight("a.conv1d.2.weight", {3, 8, 8});
+ weight("a.conv1d.1.bias", {1, 8});
+ weight("a.conv1d.2.bias", {1, 8});
+ weight("mm.a.fc.weight", {8, 6});
+ weight("mm.a.fc.bias", {6});
+ }
+ }
+ std::shared_ptr<ov::Model> convert() {
+ EXPECT_TRUE(writer.write(path));
+ ov::frontend::gguf::FrontEnd frontend;
+ return frontend.convert(frontend.load(path));
+ }
+};
+
+TEST_F(GGUFMMProj, ExtensionAddsOneBranchAlongsideBuiltinVision) {
+ using namespace ov::frontend::gguf;
+ encoder("vision", "gemma3");
+ writer.kv_bool("clip.has_audio_encoder", true);
+ writer.kv_str("clip.audio.projector_type", "custom-audio");
+ ASSERT_TRUE(writer.write(path));
+ FrontEnd frontend;
+ std::shared_ptr<ArchitectureExtension> extension = std::make_shared<ProjectorExtension>(ProjectorDefinition{
+ "clip.audio.custom",
+ "clip",
+ "audio",
+ "custom-audio",
+ [](GgufGraphContext& graph) {
+ auto input = graph.add_input("audio.custom", ov::element::f32, {1, 1, 2, 3});
+ return ProjectorResult{graph.node("GGML_OP_SCALE", {input}, 0, {{"scale", 2.0f}, {"bias", 0.0f}}),
+ {{"audio.merge", "1"}}};
+ },
+ {}});
+ frontend.add_extension(extension);
+ auto model = frontend.convert(frontend.load(path));
+ ASSERT_EQ(model->inputs().size(), 2);
+ ASSERT_EQ(model->outputs().size(), 2);
+ EXPECT_EQ(model->get_rt_info<std::string>({"gguf_mmproj", "audio.projector"}), "custom-audio");
+ EXPECT_EQ(model->get_rt_info<std::string>({"gguf_mmproj", "vision.projector"}), "gemma3");
+ auto request = ov::Core{}.compile_model(model, "CPU").create_infer_request();
+ auto audio = request.get_tensor("audio.custom");
+ std::fill_n(audio.data<float>(), audio.get_size(), 3.0f);
+ auto vision = request.get_tensor("vision.pixel_values");
+ std::fill_n(vision.data<float>(), vision.get_size(), 0.0f);
+ request.infer();
+ auto output = request.get_tensor("audio.embeddings");
+ for (size_t i = 0; i < output.get_size(); ++i)
+ EXPECT_FLOAT_EQ(output.data<float>()[i], 6.0f);
+ FrontEnd isolated;
+ OV_EXPECT_THROW(isolated.convert(isolated.load(path)), ov::Exception, testing::HasSubstr("custom-audio"));
+}
+
+TEST_F(GGUFMMProj, ExtensionReusesBuiltinProjectorAndReplacementIsExplicit) {
+ using namespace ov::frontend::gguf;
+ encoder("vision", "custom-gemma3");
+ ASSERT_TRUE(writer.write(path));
+ ProjectorDefinition definition{"clip.vision.alias",
+ "clip",
+ "vision",
+ "custom-gemma3",
+ [](GgufGraphContext& graph) {
+ return build_builtin_projector(graph, "vision", "gemma3");
+ },
+ {}};
+ FrontEnd frontend;
+ frontend.add_extension(std::make_shared<ProjectorExtension>(definition));
+ auto model = frontend.convert(frontend.load(path));
+ EXPECT_EQ(model->output().get_shape(), (ov::Shape{1, 1, 4, 6}));
+ EXPECT_EQ(model->get_rt_info<std::string>({"gguf_mmproj", "vision.projector"}), "custom-gemma3");
+ EXPECT_THROW(frontend.add_extension(std::make_shared<ProjectorExtension>(definition)), ov::Exception);
+ definition.build = [](GgufGraphContext& graph) {
+ return ProjectorResult{graph.add_input("replacement", ov::element::f32, {1, 1, 2, 3}), {}};
+ };
+ frontend.add_extension(std::make_shared<ProjectorExtension>(definition, RegistrationMode::Replace));
+ EXPECT_EQ(frontend.convert(frontend.load(path))->output().get_shape(), (ov::Shape{1, 1, 2, 3}));
+ definition.id = "missing";
+ EXPECT_THROW(frontend.add_extension(std::make_shared<ProjectorExtension>(definition, RegistrationMode::Replace)),
+ ov::Exception);
+}
+
+TEST_F(GGUFMMProj, ExtensionReplacesOnlyOneBuiltinComponent) {
+ using namespace ov::frontend::gguf;
+ encoder("vision", "gemma3");
+ encoder("audio", "qwen2a");
+ ASSERT_TRUE(writer.write(path));
+ ProjectorDefinition definition{
+ "clip.vision.gemma3",
+ "clip",
+ "vision",
+ "gemma3",
+ [](GgufGraphContext& graph) {
+ auto input = graph.add_input("replacement", ov::element::f32, {1, 1, 2, 3});
+ return ProjectorResult{graph.node("GGML_OP_SCALE", {input}, 0, {{"scale", 2.0f}, {"bias", 0.0f}}), {}};
+ },
+ {}};
+ FrontEnd frontend;
+ frontend.add_extension(std::make_shared<ProjectorExtension>(definition, RegistrationMode::Replace));
+ auto model = frontend.convert(frontend.load(path));
+ EXPECT_EQ(model->output("vision.embeddings").get_shape(), (ov::Shape{1, 1, 2, 3}));
+ EXPECT_EQ(model->get_rt_info<std::string>({"gguf_mmproj", "audio.projector"}), "qwen2a");
+ EXPECT_EQ(model->inputs().size(), 3);
+ EXPECT_NO_THROW(model->input("replacement"));
+ EXPECT_NO_THROW(model->input("audio.features"));
+ EXPECT_NO_THROW(model->input("audio.position_ids"));
+}
+
+TEST_F(GGUFMMProj, LoadedInputRetainsProjectorRegistrationSnapshot) {
+ using namespace ov::frontend::gguf;
+ encoder("vision", "custom");
+ ASSERT_TRUE(writer.write(path));
+ ProjectorDefinition definition{"custom",
+ "clip",
+ "vision",
+ "custom",
+ [](GgufGraphContext& graph) {
+ return ProjectorResult{graph.add_input("first", ov::element::f32, {1, 1, 2, 3}),
+ {}};
+ },
+ {}};
+ FrontEnd frontend;
+ frontend.add_extension(std::make_shared<ProjectorExtension>(definition));
+ const auto loaded = frontend.load(path);
+ definition.build = [](GgufGraphContext& graph) {
+ return ProjectorResult{graph.add_input("second", ov::element::f32, {1, 1, 4, 5}), {}};
+ };
+ frontend.add_extension(std::make_shared<ProjectorExtension>(definition, RegistrationMode::Replace));
+ EXPECT_EQ(frontend.convert(loaded)->output().get_shape(), (ov::Shape{1, 1, 2, 3}));
+ EXPECT_EQ(frontend.convert(frontend.load(path))->output().get_shape(), (ov::Shape{1, 1, 4, 5}));
+}
+
+TEST(GGUFProjectorRegistry, SeparateListsPredicatesAndAmbiguity) {
+ using namespace ov::frontend::gguf;
+ ArchRegistry registry;
+ const auto architectures = registry.supported_archs();
+ const auto projectors = registry.projectors().supported_projectors().size();
+ ProjectorDefinition definition{"custom",
+ "clip",
+ "vision",
+ "custom",
+ [](GgufGraphContext&) {
+ return ProjectorResult{};
+ },
+ {}};
+ registry.add_extension(std::make_shared<ProjectorExtension>(definition));
+ EXPECT_EQ(registry.supported_archs(), architectures);
+ EXPECT_EQ(registry.projectors().supported_projectors().size(), projectors + 1);
+ EXPECT_EQ(ArchRegistry{}.projectors().supported_projectors().size(), projectors);
+ std::unordered_map<std::string, GGUFMetaData> metadata{{"general.architecture", std::string("clip")}};
+ detail::MetadataStore store{metadata};
+ GgufMetadata view(store);
+ ASSERT_TRUE(registry.projectors().find(view, "vision", "custom"));
+ EXPECT_FALSE(registry.projectors().find(view, "audio", "custom"));
+ definition.id = "conditional";
+ definition.match = [](const GgufMetadata& meta) {
+ return meta.has("custom.flag");
+ };
+ registry.add_extension(std::make_shared<ProjectorExtension>(definition));
+ EXPECT_TRUE(registry.projectors().find(view, "vision", "custom"));
+ metadata["custom.flag"] = std::string("present");
+ EXPECT_THROW(registry.projectors().find(view, "vision", "custom"), ov::Exception);
+ metadata["general.architecture"] = std::string("other");
+ EXPECT_FALSE(registry.projectors().find(view, "vision", "custom"));
+ definition.build = {};
+ EXPECT_THROW(registry.add_extension(std::make_shared<ProjectorExtension>(definition)), ov::Exception);
+}
+
+TEST_F(GGUFMMProj, EmptyBranchIsRejected) {
+ using namespace ov::frontend::gguf;
+ encoder("vision", "empty");
+ ASSERT_TRUE(writer.write(path));
+ FrontEnd frontend;
+ frontend.add_extension(std::make_shared<ProjectorExtension>(ProjectorDefinition{"empty",
+ "clip",
+ "vision",
+ "empty",
+ [](GgufGraphContext&) {
+ return ProjectorResult{};
+ },
+ {}}));
+ OV_EXPECT_THROW(frontend.convert(frontend.load(path)), ov::Exception, testing::HasSubstr("returned no output"));
+}
+
+TEST_F(GGUFMMProj, Gemma3CompilesAndMetadataSurvivesSerialization) {
+ encoder("vision", "gemma3");
+ writer.kv_u32_array("clip.test.integer_array", {2, 7, 19});
+ writer.kv_str_array("clip.test.string_array", {"a,b", "", "c:d"});
+ auto model = convert();
+ ASSERT_EQ(model->inputs().size(), 1);
+ EXPECT_EQ(model->input().get_any_name(), "vision.pixel_values");
+ EXPECT_EQ(model->output().get_shape(), (ov::Shape{1, 1, 4, 6}));
+ ov::serialize(model, path + ".xml", path + ".bin");
+ ov::Core core;
+ auto restored = core.read_model(path + ".xml");
+ EXPECT_EQ(restored->get_rt_info<std::string>({"gguf_mmproj", "vision.projector"}), "gemma3");
+ EXPECT_EQ(restored->get_rt_info<std::string>({"gguf_mmproj", "clip.test.integer_array"}), "2,7,19");
+ EXPECT_EQ(restored->get_rt_info<std::string>({"gguf_mmproj", "clip.test.string_array"}), "3:a,b0:3:c:d");
+ EXPECT_EQ(restored->get_rt_info<std::string>({"gguf_mmproj", "clip.test.string_array.encoding"}),
+ "length-prefixed-strings");
+ auto request =
+ core.compile_model(model, "CPU", ov::hint::inference_precision(ov::element::f32)).create_infer_request();
+ auto input = request.get_input_tensor();
+ for (size_t i = 0; i < input.get_size(); ++i)
+ input.data<float>()[i] = std::sin(float(i));
+ request.infer();
+ auto output = request.get_output_tensor();
+ double energy = 0;
+ for (size_t i = 0; i < output.get_size(); ++i) {
+ EXPECT_TRUE(std::isfinite(output.data<float>()[i]));
+ energy += std::abs(output.data<float>()[i]);
+ }
+ EXPECT_GT(energy, 0.01);
+}
+
+TEST_F(GGUFMMProj, MixedFileHasIndependentVisionAndAudioBranches) {
+ encoder("vision", "gemma3");
+ encoder("audio", "qwen2a");
+ auto model = convert();
+ ASSERT_EQ(model->outputs().size(), 2);
+ EXPECT_EQ(model->output(0).get_any_name(), "vision.embeddings");
+ EXPECT_EQ(model->output(1).get_any_name(), "audio.embeddings");
+ auto vision = model->clone();
+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;
+ Adapter(Adapter::Modality::VISION).run_on_model(vision);
+ EXPECT_EQ(vision->inputs().size(), 1);
+ EXPECT_EQ(vision->input().get_any_name(), "pixel_values");
+ EXPECT_EQ(vision->output().get_shape(), (ov::Shape{1, 4, 6}));
+ ov::Core core;
+ auto request =
+ core.compile_model(model, "CPU", ov::hint::inference_precision(ov::element::f32)).create_infer_request();
+ ov::Tensor pixels(ov::element::f32, {1, 3, 8, 8});
+ std::fill_n(pixels.data<float>(), pixels.get_size(), 0.5f);
+ request.set_tensor("vision.pixel_values", pixels);
+ for (size_t frames : {8, 12}) {
+ ov::Tensor features(ov::element::f32, {1, 4, 1, frames});
+ std::fill_n(features.data<float>(), features.get_size(), 0.25f);
+ ov::Tensor ids(ov::element::i32, {1, 1, 1, frames / 2});
+ for (size_t i = 0; i < ids.get_size(); ++i)
+ ids.data<int32_t>()[i] = int32_t(i);
+ request.set_tensor("audio.features", features);
+ request.set_tensor("audio.position_ids", ids);
+ request.infer();
+ EXPECT_EQ(request.get_tensor("audio.embeddings").get_shape(), (ov::Shape{1, 1, frames / 4, 6}));
+ }
+}
+
+TEST_F(GGUFMMProj, UnsupportedSecondModalityIsNotSilentlyDiscarded) {
+ encoder("vision", "gemma3");
+ 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");
+ EXPECT_NO_THROW(convert());
+}
+
+// Legacy Qwen2.5 Omni files name one global projector for both encoders.
+TEST_F(GGUFMMProj, Qwen25OmniResolvesProjectorPerModality) {
+ encoder("vision", "unused_modality_key");
+ encoder("audio", "unused_modality_key");
+ writer.kv_str("clip.projector_type", "qwen2.5o");
+ writer.kv_u32("clip.vision.spatial_merge_size", 2);
+ writer.kv_u32("clip.vision.n_wa_pattern", 2);
+ weight("v.patch_embd.weight.1", {2, 2, 3, 8});
+ weight("mm.0.weight", {32, 12});
+ weight("mm.0.bias", {12});
+ weight("mm.2.weight", {12, 6});
+ weight("mm.2.bias", {6});
+ auto model = convert();
+ EXPECT_EQ(model->get_rt_info<std::string>({"gguf_mmproj", "vision.projector"}), "qwen2.5vl_merger");
+ EXPECT_EQ(model->get_rt_info<std::string>({"gguf_mmproj", "audio.projector"}), "qwen2a");
+ ASSERT_EQ(model->outputs().size(), 2);
+ for (const auto* name : {"vision.attention_mask", "vision.output_indices", "audio.features"}) {
+ const auto inputs = model->inputs();
+ EXPECT_TRUE(std::any_of(inputs.begin(), inputs.end(), [&](const ov::Output<ov::Node>& input) {
+ return input.get_names().count(name);
+ })) << name;
+ }
+}
+
+TEST_F(GGUFMMProj, ResamplerRejectsUnknownVersion) {
+ encoder("vision", "resampler");
+ writer.kv_u32("clip.minicpmv_version", 999);
+ OV_EXPECT_THROW(convert(), ov::Exception, testing::HasSubstr("resampler' version 999"));
+}
+
+TEST_F(GGUFMMProj, ResamplerRejectsInconsistentQueries) {
+ encoder("vision", "resampler");
+ writer.kv_u32("clip.minicpmv_query_num", 3);
+ weight("resampler.query", {256, 2});
+ OV_EXPECT_THROW(convert(), ov::Exception, testing::HasSubstr("query tensor matching query_count"));
+}
+
+TEST_F(GGUFMMProj, ResamplerRequiresQueryNormalization) {
+ encoder("vision", "resampler");
+ weight("resampler.query", {256, 96});
+ OV_EXPECT_THROW(convert(), ov::Exception, testing::HasSubstr("resampler.ln_q.weight"));
+}
+
+class GGUFMMProjAccuracy : public ::testing::TestWithParam<const char*> {
+protected:
+ cnpy::npz_t arrays;
+ std::shared_ptr<ov::Model> model;
+ ov::Core core;
+ std::unique_ptr<ov_gguf_test::TemporaryGguf> model_file;
+
+ const cnpy::NpyArray& array(const std::string& name) const {
+ return ov_gguf_test::npz_array(arrays, name);
+ }
+ void SetUp() override {
+ arrays = cnpy::npz_load((std::filesystem::path(ov_gguf_test::test_data_dir()) / "mmproj_accuracy" /
+ (std::string(GetParam()) + ".npz"))
+ .string());
+ model_file = std::make_unique<ov_gguf_test::TemporaryGguf>(array("model"));
+ ov::frontend::gguf::FrontEnd frontend;
+ model = frontend.convert(frontend.load(model_file->path));
+ }
+ ov::InferRequest compile(const std::shared_ptr<ov::Model>& current) {
+ return core
+ .compile_model(current,
+ "CPU",
+ ov::hint::inference_precision(ov::element::f32),
+ ov::hint::dynamic_quantization_group_size(0),
+ ov::inference_num_threads(2))
+ .create_infer_request();
+ }
+ ov::Tensor tensor(const std::string& name, ov::element::Type type) const {
+ const auto& values = array(name);
+ ov::Tensor result(type, values.shape);
+ OPENVINO_ASSERT(result.get_byte_size() == values.num_vals * values.word_size,
+ "Reference tensor type mismatch: ",
+ name);
+ std::memcpy(result.data(), values.data<char>(), result.get_byte_size());
+ return result;
+ }
+};
+
+TEST_P(GGUFMMProjAccuracy, EmbeddingsMatchLlamaCPU) {
+ if (std::string(GetParam()).find("resampler") == 0) {
+ const std::string name = GetParam();
+ EXPECT_EQ(model->get_rt_info<std::string>({"gguf_mmproj", "vision.query_count"}),
+ name == "resampler_v2" ? "96"
+ : name == "resampler_v4" ? "64"
+ : "3");
+ EXPECT_EQ(model->get_rt_info<std::string>({"gguf_mmproj", "vision.minicpmv_version"}),
+ name == "resampler_v2" ? "2"
+ : name == "resampler_v4" ? "4"
+ : "3");
+ }
+ auto request = compile(model);
+ const auto& inputs = array("inputs");
+ auto data = tensor("inputs", ov::element::f32);
+ const bool audio = model->has_rt_info({"gguf_mmproj", "audio.projector"});
+ request.set_tensor(audio ? "audio.features" : "vision.pixel_values", data);
+ if (audio) {
+ const auto frames = inputs.shape.back() / 2;
+ ov::Tensor ids(ov::element::i32, {1, 1, 1, frames});
+ for (size_t i = 0; i < frames; ++i)
+ ids.data<int32_t>()[i] = int32_t(i);
+ request.set_tensor("audio.position_ids", ids);
+ }
+ for (const auto& input : model->inputs()) {
+ const auto name = input.get_any_name();
+ if (name.rfind("vision.", 0) == 0 && name != "vision.pixel_values") {
+ request.set_tensor(name, tensor(name.substr(7), input.get_element_type()));
+ }
+ }
+ request.infer();
+ const auto actual = request.get_output_tensor();
+ const auto& expected = array("embeddings");
+ ASSERT_EQ(actual.get_shape(), expected.shape);
+ ov_gguf_test::expect_nmse_below(
+ ov_gguf_test::nmse(actual.data<const float>(), expected.data<float>(), actual.get_size()),
+ 1e-5);
+
+ // Adaptation must preserve every feature, including the channel-packed
+ // DeepStack branches, while exposing independently executable modalities.
+ auto adapted = model->clone();
+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;
+ Adapter(audio ? Adapter::Modality::AUDIO : Adapter::Modality::VISION).run_on_model(adapted);
+ auto adapted_request = compile(adapted);
+ for (const auto& input : adapted->inputs())
+ adapted_request.set_tensor(
+ input.get_any_name(),
+ request.get_tensor(std::string(audio ? "audio." : "vision.") + input.get_any_name()));
+ adapted_request.infer();
+ const size_t branches = adapted->outputs().size();
+ const size_t width = expected.shape.back() / branches;
+ for (size_t branch = 0; branch < branches; ++branch) {
+ const auto output = adapted_request.get_output_tensor(branch);
+ EXPECT_EQ(output.get_shape(), (ov::Shape{expected.shape[1], expected.shape[2], width}));
+ ov_gguf_test::Nmse adapted_metric;
+ for (size_t i = 0; i < output.get_size(); ++i)
+ adapted_metric.add(output.data<const float>()[i],
+ expected.data<float>()[(i / width) * width * branches + branch * width + i % width]);
+ ov_gguf_test::expect_nmse_below(adapted_metric, 1e-5);
+ }
+}
+
+class GGUFMMProjDynamicAccuracy : public GGUFMMProjAccuracy {};
+
+// The low-contrast fixture's patch projection cancels to rounding noise, which differs with the
+// platform's summation order (3e-5 on ARM64). Dropping its recentering raises the error to 1e-3.
+double dynamic_accuracy_limit(const std::string& family) {
+ return family == "gemma4uv_low_contrast" ? 1e-4 : 1e-5;
+}
+
+TEST_P(GGUFMMProjDynamicAccuracy, ReusesCompiledModelAcrossGrids) {
+ for (bool adapt : {false, true}) {
+ auto current = model->clone();
+ const bool audio = model->has_rt_info({"gguf_mmproj", "audio.projector"});
+ using Adapter = ov::frontend::gguf::pass::AdaptMmprojToGenAI;
+ if (adapt)
+ Adapter(audio ? Adapter::Modality::AUDIO : Adapter::Modality::VISION).run_on_model(current);
+ auto request = compile(current);
+ for (int step : {0, 1, 0}) {
+ for (const auto& input : current->inputs()) {
+ const auto name = input.get_any_name();
+ const auto key = std::to_string(step) + "." + (adapt ? name : name.substr(audio ? 6 : 7));
+ request.set_tensor(name, tensor(key, input.get_element_type()));
+ }
+ request.infer();
+ const auto output = request.get_output_tensor();
+ const auto& expected = array(std::to_string(step) + ".embeddings");
+ auto shape = expected.shape;
+ if (adapt)
+ 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()),
+ dynamic_accuracy_limit(GetParam()),
+ std::string(GetParam()) + " step=" + std::to_string(step) + " adapted=" + std::to_string(adapt));
+ }
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(Reference,
+ GGUFMMProjDynamicAccuracy,
+ ::testing::Values("muse-glimmer",
+ "qwen2.5vl_merger_grids",
+ "resampler_grids",
+ "pixtral",
+ "pixtral_merge",
+ "phi4",
+ "gemma4v",
+ "gemma4v_one_sided",
+ "gemma4uv",
+ "gemma4uv_low_contrast",
+ "gemma4ua",
+ "minicpmv4_6",
+ "gemma4a",
+ "deepseekocr",
+ "deepseekocr2",
+ "deepseekocr_resize",
+ "deepseekocr_overview",
+ "deepseekocr2_overview"));
+
+INSTANTIATE_TEST_SUITE_P(Reference,
+ GGUFMMProjAccuracy,
+ ::testing::Values("gemma3",
+ "gemma3_fused",
+ "gemma3_legacy",
+ "idefics3",
+ "janus_pro",
+ "qwen2a",
+ "ultravox",
+ "voxtral",
+ "musicflamingo",
+ "mlp",
+ "mlp_norm",
+ "mlp_feature",
+ "meralion",
+ "glma",
+ "qwen2vl_merger",
+ "qwen2.5vl_merger",
+ "qwen3vl_merger",
+ "internvl",
+ "internvl_qknorm",
+ "qwen2.5vl_merger_window_video",
+ "voxtral_odd",
+ "resampler",
+ "resampler_v2",
+ "resampler_v4"));
+} // namespace
diff --git a/src/frontends/gguf/tests/test_ops.cpp b/src/frontends/gguf/tests/test_ops.cpp
index 956d0fbe2b6..153718ff5e7 100644
--- a/src/frontends/gguf/tests/test_ops.cpp
+++ b/src/frontends/gguf/tests/test_ops.cpp
@@ -14,12 +14,17 @@
#include "op_table.hpp"
#include "op_test_utils.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/divide.hpp"
+#include "openvino/op/extractimagepatches.hpp"
#include "openvino/op/eye.hpp"
#include "openvino/op/multiply.hpp"
#include "openvino/op/result.hpp"
#include "openvino/op/selective_ssm.hpp"
#include "openvino/op/slice.hpp"
#include "openvino/op/topk.hpp"
+#include "transformations/convert_precision.hpp"
+#include "transformations/rt_info/disable_precision_conversion.hpp"
#include "utils.hpp"
using namespace ov_gguf_test;
@@ -2177,7 +2182,7 @@ TEST(GGUFOps, FlashAttnExtFlatKvWithMask) {
// T on this layout (head_axis == 1), not n_head, so with n_head != T the reshape either throws a
// shape mismatch or silently broadcasts the wrong values into the softmax denominator. Using
// n_head=2 and T=3 (both != 1, and different from each other) makes either failure mode observable.
-TEST(GGUFOps, FlashAttnExtWithSinksCgraphLayout) {
+void check_flash_attn_ext_with_sinks(bool f32_attention) {
const size_t n_head = 2, T = 3, Tk = 3, D = 2;
const float scale = 1.0f;
auto model = SingleOpBuilder()
@@ -2189,6 +2194,7 @@ TEST(GGUFOps, FlashAttnExtWithSinksCgraphLayout) {
.input("sinks", ov::element::f32, {n_head})
.output("out", ov::element::f32, {1, T, n_head, D})
.attr<float>("scale", scale)
+ .attr<bool>("f32_attention", f32_attention)
.build();
std::vector<float> q, k, v;
@@ -2235,7 +2241,15 @@ TEST(GGUFOps, FlashAttnExtWithSinksCgraphLayout) {
}
}
}
- expect_near(out, expected, 2e-2f); // fp16 SDPA
+ expect_near(out, expected, 2e-2f);
+}
+
+TEST(GGUFOps, FlashAttnExtWithSinksCgraphLayout) {
+ check_flash_attn_ext_with_sinks(false);
+}
+
+TEST(GGUFOps, FlashAttnExtWithSinksF32Attention) {
+ check_flash_attn_ext_with_sinks(true);
}
// GatedDeltaNet, reference (Loop) path. With head size S=1 the gate last-dim equals S_v, so this is
@@ -2319,7 +2333,7 @@ TEST(GGUFOps, GatedDeltaNetMultipleSnapshotSlotsRejected) {
// fused ov::op::internal::GatedDeltaNet op instead of the Loop scan. B=H=1, T=2, D=Dv=2. We assert
// the fused op is actually emitted and that its result matches the core reference recurrence.
// NOTE: a model on this path contains an internal op and is therefore NOT IR-serializable
-// (see src/frontends/gguf/docs/internal_ops.md).
+// (see src/frontends/gguf/docs/runtime.md).
TEST(GGUFOps, GatedDeltaNetFused) {
const int64_t B = 1, T = 2, H = 1, D = 2; // head size D = Dv = 2, scalar gate
auto qkv_shp = ov::PartialShape{B, T, H, D};
@@ -2397,6 +2411,37 @@ TEST(GGUFOps, GatedDeltaNetFused) {
expect_near(out, expected, 1e-4f);
}
+// Requested Q/K normalization follows ggml, x / max(||x||, eps), also for vectors below eps-scale
+// norms: q = k = [1e-4, 0] normalize to [1, 0], so one update with v = [1, 0] attends 1/sqrt(2).
+TEST(GGUFOps, GatedDeltaNetFusedQkNormFollowsGgmlForSmallVectors) {
+ const int64_t B = 1, T = 1, H = 1, D = 2;
+ auto qkv_shp = ov::PartialShape{B, T, H, D};
+ auto gate_shp = ov::PartialShape{B, T, H, 1};
+ auto model = SingleOpBuilder()
+ .op("GGML_OP_GATED_DELTA_NET")
+ .input("q", ov::element::f32, qkv_shp)
+ .input("k", ov::element::f32, qkv_shp)
+ .input("v", ov::element::f32, qkv_shp)
+ .input("g", ov::element::f32, gate_shp)
+ .input("beta", ov::element::f32, gate_shp)
+ .input("state", ov::element::f32, ov::PartialShape{B, H, D, D})
+ .output("out", ov::element::f32, {1, 1, (T + D) * B, D * H})
+ .attr("fuse_qk_l2norm", true)
+ .attr("qk_l2_norm_eps", 1e-6f)
+ .build();
+ const ov::Shape qkv{1, 1, 1, 2}, gate{1, 1, 1, 1};
+ auto out = run_on_cpu(model,
+ {{"q", make_f32_tensor(qkv, {1e-4f, 0})},
+ {"k", make_f32_tensor(qkv, {1e-4f, 0})},
+ {"v", make_f32_tensor(qkv, {1, 0})},
+ {"g", make_f32_tensor(gate, {0})},
+ {"beta", make_f32_tensor(gate, {1})},
+ {"state", make_f32_tensor({1, 1, 2, 2}, {0, 0, 0, 0})}});
+ ASSERT_GE(out.get_size(), 2u);
+ EXPECT_NEAR(out.data<const float>()[0], 1.0f / std::sqrt(2.0f), 1e-4f);
+ EXPECT_NEAR(out.data<const float>()[1], 0.0f, 1e-6f);
+}
+
// GatedDeltaNet, fused-op path with MULTIPLE HEADS (H=2). qwen3-next real dims are H=32; the
// single-head tests above (H=1) collapse the head axis so they never exercise the per-head packing
// of attn/state into the flat output. This reproduces the multi-head case: for B=1, T tokens and
@@ -2747,6 +2792,38 @@ TEST(GGUFOps, Im2col1D) {
expect_near(out, expected, 1e-4f);
}
+TEST(GGUFOps, MultimodalPoolingAndConvolution) {
+ auto pool = SingleOpBuilder()
+ .op("GGML_OP_POOL_2D")
+ .input("x", ov::element::f32, {1, 1, 2, 4})
+ .output("out", ov::element::f32, {1, 1, 1, 2})
+ .op_case(2)
+ .attr<std::vector<int32_t>>("pool_params", {2, 2, 2, 2, 0, 0})
+ .build();
+ const auto x = make_f32_tensor({1, 1, 2, 4}, {1, 2, 3, 4, 5, 6, 7, 8});
+ expect_near(run_on_cpu(pool, {{"x", x}}), {3.5f, 5.5f}, 1e-6f);
+ auto conv = SingleOpBuilder()
+ .op("GGML_OP_CONV_2D")
+ .input("w", ov::element::f32, {1, 1, 2, 2})
+ .input("x", ov::element::f32, {1, 1, 2, 4})
+ .output("out", ov::element::f32, {1, 1, 1, 2})
+ .attr<std::vector<int64_t>>("conv_params", {2, 2, 0, 0, 1, 1})
+ .build();
+ 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, GeluErf) {
+ auto model = SingleOpBuilder()
+ .op("GGML_UNARY_OP_GELU_ERF")
+ .input("x", ov::element::f32, {1, 1, 1, 5})
+ .output("out", ov::element::f32, {1, 1, 1, 5})
+ .build();
+ std::vector<float> values{-2, -1, 0, 1, 2}, expected;
+ for (auto x : values)
+ expected.push_back(0.5f * x * (1.f + std::erf(x / std::sqrt(2.f))));
+ expect_near(run_on_cpu(model, {{"x", make_f32_tensor({1, 1, 1, 5}, values)}}), expected, 1e-6f);
+}
+
// Cpy: a ggml copy is a dtype convert to the destination type. i32 -> f32 upcast round-trips
// the integer values exactly.
TEST(GGUFOps, Cpy) {
@@ -3263,6 +3340,33 @@ TEST(GGUFOps, DivBroadcast) {
expect_near(out, {1, 1, 3, 2});
}
+// Only the Divide stays in f32 under f16 inference: the MoE weight renormalization (Gemma 4 26B)
+// is multiplied by a constant per-expert scale, which must not end up in a different precision.
+TEST(GGUFOps, DivKeepsOnlyItselfInF32) {
+ auto model = SingleOpBuilder()
+ .op("GGML_OP_DIV")
+ .input("a", ov::element::f32, {2, 3})
+ .input("b", ov::element::f32, {2, 3})
+ .output("out", ov::element::f32, {2, 3})
+ .build();
+ auto result = model->get_results()[0];
+ auto div = result->get_input_node_shared_ptr(0);
+ ASSERT_TRUE(ov::is_type<ov::op::v1::Divide>(div));
+ auto scale = ov::op::v0::Constant::create(ov::element::f32, {2, 3}, {1, 2, 3, 4, 5, 6});
+ result->input(0).replace_source_output(std::make_shared<ov::op::v1::Multiply>(div, scale));
+ model->validate_nodes_and_infer_types();
+
+ // The configuration the GPU plugin uses for f16 inference.
+ ov::pass::ConvertPrecision({{ov::element::f32, ov::element::f16}}, {}, true, false, true).run_on_model(model);
+
+ ASSERT_NO_THROW(model->validate_nodes_and_infer_types());
+ EXPECT_TRUE(ov::is_conversion_disabled(div, ov::element::f16));
+ EXPECT_EQ(div->get_output_element_type(0), ov::element::f32);
+ for (const auto& param : model->get_parameters()) {
+ EXPECT_FALSE(ov::is_conversion_disabled(param, ov::element::f16)) << param->get_friendly_name();
+ }
+}
+
// Div over an empty token axis, as produced by a non-final chunked-prefill chunk (see
// MulMatIdEmptyTokens). Both operands are empty, so the ggml-style repeat has nothing to repeat and
// must be skipped rather than computing a 0/0 repeat count.
@@ -3527,3 +3631,187 @@ TEST(GGUFOps, SolveTriDynamicBatchDimensions) {
}
} // namespace
+
+TEST(GGUFOps, MultimodalRopeMatchesIndependentSections) {
+ // Reference: mmproj_ops_oracle.cpp, pinned ggml CPU. Three heads, differing
+ // coordinates on all four axes, and unequal IMROPE sections exercise layout and routing.
+ for (bool vision : {false, true}) {
+ RopeConfig config;
+ config.n_dims = vision ? 32 : 64;
+ config.n_ctx_orig = 32768;
+ config.freq_base = 10000.f;
+ config.freq_scale = config.attn_factor = 1.f;
+ config.beta_fast = 32.f;
+ config.beta_slow = 1.f;
+ config.sections = vision ? std::array<int32_t, 4>{16, 16, 16, 16} : std::array<int32_t, 4>{8, 7, 9, 8};
+ auto model = SingleOpBuilder()
+ .op("GGML_OP_ROPE")
+ .input("data", ov::element::f32, {1, -1, 3, 64})
+ .input("pos", ov::element::i32, {1, 1, 1, -1})
+ .output("out", ov::element::f32, {1, -1, 3, 64})
+ .op_case((vision ? 3 : 2) << 16)
+ .attr<RopeConfig>("rope_config", config)
+ .build();
+ std::vector<float> data(384);
+ for (size_t i = 0; i < data.size(); ++i)
+ data[i] = std::sin(float(i) * 0.13f);
+ ov::Tensor positions(ov::element::i32, {1, 1, 1, 8});
+ const std::vector<int32_t> values{3, 7, 11, 2, 5, 13, 17, 19};
+ std::copy(values.begin(), values.end(), positions.data<int32_t>());
+ auto actual = run_on_cpu(model, {{"data", make_f32_tensor({1, 2, 3, 64}, data)}, {"pos", positions}});
+ expect_near(actual, load_npy<float>(vision ? "vision_rope_expected" : "multimodal_imrope_expected"));
+ }
+}
+
+TEST(GGUFOps, InterpolateBilinearAntialiasDynamicSize) {
+ for (bool corners : {false, true}) {
+ // Reference: mmproj_ops_oracle.cpp resize modes, ggml CPU.
+ auto model = SingleOpBuilder()
+ .op("GGML_OP_UPSCALE")
+ .input("data", ov::element::f32, {1, 2, -1, -1})
+ .input("sizes", ov::element::i64, {2})
+ .output("out", ov::element::f32, {1, 2, -1, -1})
+ .attr<int>("interpolation_mode", 1 | 0x200 | (corners ? 0x100 : 0))
+ .build();
+ std::vector<float> data(12);
+ for (size_t i = 0; i < data.size(); ++i)
+ data[i] = std::sin(float(i) * 0.13f);
+ ov::Tensor sizes(ov::element::i64, {2});
+ sizes.data<int64_t>()[0] = 4;
+ sizes.data<int64_t>()[1] = 5;
+ auto actual = run_on_cpu(model, {{"data", make_f32_tensor({1, 2, 2, 3}, data)}, {"sizes", sizes}});
+ expect_near(actual,
+ load_npy<float>(corners ? "mmproj_interpolate_corners_expected" : "mmproj_interpolate_expected"));
+ // Downsampling exercises clipped filter support at the border of a learned position grid.
+ data.resize(2 * 8 * 12);
+ for (size_t i = 0; i < data.size(); ++i)
+ data[i] = std::sin(float(i) * 0.13f);
+ actual = run_on_cpu(model, {{"data", make_f32_tensor({1, 2, 8, 12}, data)}, {"sizes", sizes}});
+ expect_near(
+ actual,
+ load_npy<float>(corners ? "mmproj_interpolate_down_corners_expected" : "mmproj_interpolate_down_expected"));
+ }
+}
+
+TEST(GGUFOps, Im2colDynamicRectangularGridsMatchCPU) {
+ auto model = SingleOpBuilder()
+ .op("GGML_OP_IM2COL")
+ .input("kernel", ov::element::f32, {1, 2, 2, 3})
+ .input("image", ov::element::f32, {1, 2, -1, -1})
+ .output("out", ov::element::f32, {1, -1, -1, 12})
+ .attr<std::vector<int32_t>>("im2col_params", {2, 1, 1, 0, 1, 1, 1})
+ .build();
+ ov::Core core;
+ auto request =
+ core.compile_model(model, "CPU", ov::hint::inference_precision(ov::element::f32)).create_infer_request();
+ for (size_t width : {7, 9}) {
+ const size_t height = width == 7 ? 5 : 4;
+ std::vector<float> values(2 * height * width);
+ for (size_t i = 0; i < values.size(); ++i)
+ values[i] = std::sin(float(i) * 0.13f);
+ request.set_tensor("image", make_f32_tensor({1, 2, height, width}, values));
+ request.infer();
+ EXPECT_EQ(request.get_output_tensor().get_shape(), (ov::Shape{1, height - 1, (width + 1) / 2, 12}));
+ expect_near(request.get_output_tensor(), load_npy<float>("mmproj_im2col" + std::to_string(width)));
+ }
+}
+
+// Non-overlapping patches (stride == kernel, Gemma 4 unified vision) avoid ExtractImagePatches,
+// which the GPU plugin can't compile for dynamic image sizes, and crop partial patches the same way.
+TEST(GGUFOps, Im2colNonOverlappingPatches) {
+ const size_t IC = 2, KH = 2, KW = 3;
+ auto model = SingleOpBuilder()
+ .op("GGML_OP_IM2COL")
+ .input("kernel", ov::element::f32, {1, IC, KH, KW})
+ .input("image", ov::element::f32, {1, IC, -1, -1})
+ .output("out", ov::element::f32, {1, -1, -1, IC * KH * KW})
+ .attr<std::vector<int32_t>>("im2col_params", {KW, KH, 0, 0, 1, 1, 1})
+ .build();
+ for (const auto& op : model->get_ops()) {
+ EXPECT_FALSE(ov::is_type<ov::op::v3::ExtractImagePatches>(op));
+ }
+ ov::Core core;
+ auto request =
+ core.compile_model(model, "CPU", ov::hint::inference_precision(ov::element::f32)).create_infer_request();
+ for (const auto& [height, width] : {std::pair<size_t, size_t>{4, 6}, {5, 7}}) {
+ std::vector<float> image(IC * height * width);
+ for (size_t i = 0; i < image.size(); ++i)
+ image[i] = static_cast<float>(i);
+ request.set_tensor("image", make_f32_tensor({1, IC, height, width}, image));
+ request.infer();
+ const size_t OH = height / KH, OW = width / KW;
+ std::vector<float> expected;
+ for (size_t oh = 0; oh < OH; ++oh)
+ for (size_t ow = 0; ow < OW; ++ow)
+ for (size_t c = 0; c < IC; ++c)
+ for (size_t kh = 0; kh < KH; ++kh)
+ for (size_t kw = 0; kw < KW; ++kw)
+ expected.push_back(image[(c * height + oh * KH + kh) * width + ow * KW + kw]);
+ EXPECT_EQ(request.get_output_tensor().get_shape(), (ov::Shape{1, OH, OW, IC * KH * KW}));
+ expect_near(request.get_output_tensor(), expected);
+ }
+}
+
+// Geometry expectations generated by mmproj_ops_oracle.cpp against pinned ggml CPU.
+TEST(GGUFOps, WindowPartitionPadsRectangularGrid) {
+ auto model = SingleOpBuilder()
+ .op("GGML_OP_WIN_PART")
+ .input("x", ov::element::f32, {1, -1, -1, 3})
+ .output("out", ov::element::f32, {-1, 2, 2, 3})
+ .attr<int64_t>("window", 2)
+ .build();
+ auto result = run_on_cpu(model, {{"x", make_f32_tensor({1, 3, 5, 3}, load_npy<float>("mmproj_window_input"))}});
+ EXPECT_EQ(result.get_shape(), (ov::Shape{6, 2, 2, 3}));
+ expect_near(result, load_npy<float>("mmproj_windows"));
+}
+
+TEST(GGUFOps, WindowUnpartitionRemovesPadding) {
+ auto model = SingleOpBuilder()
+ .op("GGML_OP_WIN_UNPART")
+ .input("x", ov::element::f32, {-1, 2, 2, 3})
+ .input("reference", ov::element::f32, {1, -1, -1, 3})
+ .output("out", ov::element::f32, {1, -1, -1, 3})
+ .attr<int64_t>("window", 2)
+ .build();
+ auto result = run_on_cpu(model,
+ {{"x", make_f32_tensor({6, 2, 2, 3}, load_npy<float>("mmproj_windows"))},
+ {"reference", make_f32_tensor({1, 3, 5, 3}, load_npy<float>("mmproj_window_input"))}});
+ expect_near(result, load_npy<float>("mmproj_restored"));
+}
+
+TEST(GGUFOps, IndexedRelativePositionsMatchCPU) {
+ auto model = SingleOpBuilder()
+ .op("GGML_OP_GET_REL_POS")
+ .op_case(1)
+ .input("table", ov::element::f32, {3, 4})
+ .input("indices", ov::element::i32, {1, 3, 3})
+ .output("out", ov::element::f32, {3, 3, 4})
+ .build();
+ std::vector<int32_t> indices;
+ for (int32_t q = 0; q < 3; ++q)
+ for (int32_t k = 0; k < 3; ++k)
+ indices.push_back(q - k + 2);
+ ov::Tensor ids(ov::element::i32, {1, 3, 3});
+ std::copy(indices.begin(), indices.end(), ids.data<int32_t>());
+ auto result =
+ run_on_cpu(model,
+ {{"table", make_f32_tensor({3, 4}, load_npy<float>("mmproj_relative_table"))}, {"indices", ids}});
+ expect_near(result, load_npy<float>("mmproj_relative"));
+}
+
+TEST(GGUFOps, ReferenceReshapeTracksSpatialDimensions) {
+ auto model = SingleOpBuilder()
+ .op("GGML_OP_RESHAPE")
+ .input("x", ov::element::f32, {1, 1, 3, -1})
+ .input("reference", ov::element::f32, {1, 3, -1, -1})
+ .output("out", ov::element::f32, {1, 3, -1, -1})
+ .attr<std::vector<int64_t>>("reshape_target", {1, 3, 0, 0})
+ .attr<std::vector<int64_t>>("shape_axes", {-1, -1, 2, 3})
+ .build();
+ const auto values = load_npy<float>("mmproj_window_input");
+ auto result = run_on_cpu(
+ model,
+ {{"x", make_f32_tensor({1, 1, 3, 15}, values)}, {"reference", make_f32_tensor({1, 3, 3, 5}, values)}});
+ EXPECT_EQ(result.get_shape(), (ov::Shape{1, 3, 3, 5}));
+ expect_near(result, values);
+}
diff --git a/src/frontends/gguf/tests/test_parser.cpp b/src/frontends/gguf/tests/test_parser.cpp
index aa9adfa620f..94f8941ffd1 100644
--- a/src/frontends/gguf/tests/test_parser.cpp
+++ b/src/frontends/gguf/tests/test_parser.cpp
@@ -7,6 +7,7 @@
#include <utility>
#include "common_test_utils/common_utils.hpp"
+#include "gguf_writer.hpp"
#include "op_test_utils.hpp"
#include "quant/weights.hpp"
@@ -29,7 +30,8 @@ protected:
GgufTensorType type,
uint64_t cols,
uint64_t rows,
- const std::vector<uint8_t>& data = {}) {
+ const std::vector<uint8_t>& data = {},
+ const std::string& architecture = {}) {
std::ofstream out(m_path, std::ios::binary);
ASSERT_TRUE(out);
const auto put = [&out](auto value) {
@@ -37,8 +39,16 @@ protected:
};
put(uint32_t{0x46554747});
put(uint32_t{3});
- put(uint64_t{1}); // tensor count
- put(uint64_t{0}); // metadata count
+ put(uint64_t{1}); // tensor count
+ put(uint64_t{architecture.empty() ? 0u : 1u}); // metadata count
+ if (!architecture.empty()) {
+ const std::string key = "general.architecture";
+ put(uint64_t{key.size()});
+ out.write(key.data(), key.size());
+ put(uint32_t(ov_gguf_test::GGUF_TYPE_STRING));
+ put(uint64_t{architecture.size()});
+ out.write(architecture.data(), architecture.size());
+ }
put(uint64_t{name.size()});
out.write(name.data(), name.size());
put(uint32_t{2});
@@ -84,6 +94,52 @@ TEST_F(GGUFParser, Q2_0KeepsIntegerZeroPointsForAllWeightNames) {
}
}
+// Q4_K uses an integer zero-point by default and the faithful f16 one under OV_GGUF_Q4_K_ZP_F16,
+// for language and projector models alike.
+TEST_F(GGUFParser, Q4KZeroPointModeAppliesToLanguageAndProjectorModels) {
+ const auto bytes = load_npy<uint8_t>("q4_k_qbytes");
+ const auto reference = load_npy<float>("q4_k_deq");
+ const auto expected_zp = gguf_zero_point_type("v.blk.0.attn_q.weight", GGUF_TYPE_Q4_K);
+ // The integer zero-point requantizes each group onto a u4 grid: up to half a step of error (~0.04 here).
+ const float tolerance = expected_zp == ov::element::f16 ? 3e-3f : 5e-2f;
+ for (const std::string architecture : {"clip", "qwen35", "qwen35moe", "gemma4", "muse-glimmer", ""}) {
+ SCOPED_TRACE(architecture);
+ ASSERT_NO_FATAL_FAILURE(write_tensor("v.blk.0.attn_q.weight", GGUF_TYPE_Q4_K, 256, 4, bytes, architecture));
+ const auto loaded = get_gguf_data(m_path);
+ const auto& arrays = std::get<1>(loaded);
+ const auto& zp = arrays.at("v.blk.0.attn_q.zp");
+ ASSERT_EQ(zp.get_element_type(), expected_zp);
+ const auto node = make_weight_node({arrays.at("v.blk.0.attn_q.weight"), arrays.at("v.blk.0.attn_q.scales"), zp},
+ GGUF_TYPE_Q4_K,
+ "v.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(), reference.size());
+ for (size_t i = 0; i < reference.size(); ++i)
+ EXPECT_NEAR(output.data<float>()[i], reference[i], tolerance);
+ }
+}
+
+TEST_F(GGUFParser, QuantizedBuffersOutliveParserResult) {
+ const auto bytes = load_npy<uint8_t>("q2_k_qbytes");
+ const auto reference = load_npy<float>("q2_k_deq");
+ ASSERT_NO_FATAL_FAILURE(write_tensor("blk.0.attn_q.weight", GGUF_TYPE_Q2_K, 256, 4, bytes));
+ WeightTensors tensors;
+ {
+ const auto loaded = get_gguf_data(m_path);
+ const auto& arrays = std::get<1>(loaded);
+ tensors = {arrays.at("blk.0.attn_q.weight"), arrays.at("blk.0.attn_q.scales"), arrays.at("blk.0.attn_q.zp")};
+ }
+ ov::test::utils::removeFile(m_path);
+ const auto node = make_weight_node(tensors, GGUF_TYPE_Q2_K, "blk.0.attn_q");
+ tensors = {};
+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{node}, ov::ParameterVector{});
+ const auto output = run_on_cpu(model, {});
+ ASSERT_EQ(output.get_size(), reference.size());
+ for (size_t i = 0; i < reference.size(); ++i)
+ EXPECT_NEAR(output.data<const float>()[i], reference[i], 3e-3f);
+}
+
TEST_F(GGUFParser, AcceptsEmptyQuantizedTensors) {
constexpr std::array types{
std::pair{"Q4_0", GGUF_TYPE_Q4_0},
diff --git a/src/frontends/gguf/tests/test_weights.cpp b/src/frontends/gguf/tests/test_weights.cpp
index f0532b26948..6833c9627d7 100644
--- a/src/frontends/gguf/tests/test_weights.cpp
+++ b/src/frontends/gguf/tests/test_weights.cpp
@@ -300,10 +300,13 @@ TEST(GGUFWeight, RejectsMissingAuxiliaryTensors) {
EXPECT_THROW(make_weight_node(without_zero_point, GGUF_TYPE_Q4_K), ov::Exception);
}
-TEST(GGUFWeight, UsesIntegerZeroPointForQ4KMatmulWeights) {
+TEST(GGUFWeight, UsesIntegerZeroPointForRequantizedMatmulWeights) {
using namespace ov::frontend::gguf;
EXPECT_EQ(gguf_zero_point_type("blk.0.attn_q.weight", GGUF_TYPE_Q4_K), ov::element::u8);
+ EXPECT_EQ(gguf_zero_point_type("blk.0.ffn_down.weight", GGUF_TYPE_Q4_1), ov::element::u8);
+ EXPECT_EQ(gguf_zero_point_type("blk.0.ssm_out.weight", GGUF_TYPE_Q5_K), ov::element::u8);
EXPECT_EQ(gguf_zero_point_type("token_embd.weight", GGUF_TYPE_Q4_K), ov::element::f16);
+ EXPECT_EQ(gguf_zero_point_type("output.weight", GGUF_TYPE_Q5_K), ov::element::f16);
EXPECT_EQ(gguf_zero_point_type("blk.0.attn_q.weight", GGUF_TYPE_Q2_0), ov::element::u8);
}
diff --git a/tests/model_hub_tests/gguf/dequantize_mmproj.py b/tests/model_hub_tests/gguf/dequantize_mmproj.py
new file mode 100644
index 00000000000..d8d97f037b6
--- /dev/null
+++ b/tests/model_hub_tests/gguf/dequantize_mmproj.py
@@ -0,0 +1,47 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+"""Create an F32 copy of represented GGUF weights for llama.cpp CPU validation.
+
+Use gguf-py from the pinned llama.cpp checkout. This preserves the quantized
+checkpoint's represented weights; it does not recover the publisher's weights.
+The pinned llama-quantize executable rejects the clip architecture.
+"""
+import argparse
+from pathlib import Path
+
+import gguf
+import numpy as np
+
+
+def dequantize_mmproj(source, destination):
+ """Write an F32 copy of every tensor in source to destination, keeping all metadata."""
+ reader = gguf.GGUFReader(source)
+ writer = gguf.GGUFWriter(destination, reader.fields["general.architecture"].contents(), use_temp_file=True)
+ if "general.alignment" in reader.fields:
+ writer.add_custom_alignment(int(reader.fields["general.alignment"].contents()))
+ for name, field in reader.fields.items():
+ if name.startswith("GGUF.") or name in ("general.architecture", "general.alignment"):
+ continue
+ writer.add_key_value(name, field.contents(), field.types[0],
+ field.types[-1] if len(field.types) > 1 else None)
+ for tensor in reader.tensors:
+ writer.add_tensor(tensor.name, gguf.dequantize(tensor.data, tensor.tensor_type).astype(np.float32))
+ writer.write_header_to_file()
+ writer.write_kv_data_to_file()
+ writer.write_tensors_to_file()
+ writer.close()
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("source", type=Path)
+ parser.add_argument("destination", type=Path)
+ args = parser.parse_args()
+ if args.source.resolve() == args.destination.resolve():
+ parser.error("Source and destination must differ")
+ dequantize_mmproj(args.source, args.destination)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/model_hub_tests/gguf/gguf_mmproj_nightly b/tests/model_hub_tests/gguf/gguf_mmproj_nightly
new file mode 100644
index 00000000000..96240a43e99
--- /dev/null
+++ b/tests/model_hub_tests/gguf/gguf_mmproj_nightly
@@ -0,0 +1,9 @@
+# Larger multimodal projector files, checked like gguf_mmproj_precommit.
+#
+# Format: projector,repo_id,filename[,mark,reason]
+qwen2.5vl_merger,ggml-org/Qwen2.5-VL-3B-Instruct-GGUF,mmproj-Qwen2.5-VL-3B-Instruct-Q8_0.gguf
+gemma3,ggml-org/gemma-3-4b-it-GGUF,mmproj-model-f16.gguf
+gemma4v+gemma4a,unsloth/gemma-4-E2B-it-GGUF,mmproj-F16.gguf
+ultravox,ggml-org/ultravox-v0_5-llama-3_2-1b-GGUF,mmproj-ultravox-v0_5-llama-3_2-1b-f16.gguf
+qwen2.5vl_merger+qwen2a,ggml-org/Qwen2.5-Omni-3B-GGUF,mmproj-Qwen2.5-Omni-3B-Q8_0.gguf
+deepseekocr,ggml-org/deepseek-ocr-GGUF,mmproj-DeepSeek-OCR-Q8_0.gguf,skip,the test has no input contract for SAM tiles and views yet
diff --git a/tests/model_hub_tests/gguf/gguf_mmproj_precommit b/tests/model_hub_tests/gguf/gguf_mmproj_precommit
new file mode 100644
index 00000000000..0af00f9774e
--- /dev/null
+++ b/tests/model_hub_tests/gguf/gguf_mmproj_precommit
@@ -0,0 +1,16 @@
+# Small multimodal projector files (mmproj-*.gguf) checked against llama.cpp's CPU encoder,
+# which test_gguf_mmproj.py builds at the pinned revision in llama_cpp_oracle.py.
+#
+# Format: projector,repo_id,filename[,mark,reason]
+# projector - the file's encoder projector types, "+"-joined when it has vision and audio
+# (see src/frontends/gguf/docs/mmproj.md)
+# repo_id - Hugging Face Hub repo hosting the file
+# filename - the projector file in that repo
+# mark - optional: "skip", "xfail", or "nmse=<limit>" to replace the device's limit
+# reason - required if mark is set
+idefics3,ggml-org/SmolVLM-256M-Instruct-GGUF,mmproj-SmolVLM-256M-Instruct-Q8_0.gguf
+qwen3vl_merger,unsloth/Qwen3.5-0.8B-GGUF,mmproj-F16.gguf
+internvl,ggml-org/InternVL3-1B-Instruct-GGUF,mmproj-InternVL3-1B-Instruct-Q8_0.gguf
+pixtral,ggml-org/pixtral-12b-GGUF,mmproj-pixtral-12b-Q8_0.gguf
+qwen2vl_merger,ggml-org/Qwen2-VL-2B-Instruct-GGUF,mmproj-Qwen2-VL-2B-Instruct-Q8_0.gguf,nmse=2e-4,llama.cpp's patch embedding is 5e-4 off float64 (OpenVINO 4e-6) and 32 layers amplify it to 9e-5
+voxtral,ggml-org/Voxtral-Mini-3B-2507-GGUF,mmproj-Voxtral-Mini-3B-2507-Q8_0.gguf
diff --git a/tests/model_hub_tests/gguf/gguf_models_nightly b/tests/model_hub_tests/gguf/gguf_models_nightly
index 4859f54c915..29ac5038822 100644
--- a/tests/model_hub_tests/gguf/gguf_models_nightly
+++ b/tests/model_hub_tests/gguf/gguf_models_nightly
@@ -26,11 +26,11 @@ mellum,bartowski/Mellum2-12B-A2.5B-Instruct-GGUF,Mellum2-12B-A2.5B-Instruct-Q4_K
devstral-small,bartowski/mistralai_Devstral-Small-2507-GGUF,mistralai_Devstral-Small-2507-Q4_K_M.gguf
devstral-small2,bartowski/mistralai_Devstral-Small-2-24B-Instruct-2512-GGUF,mistralai_Devstral-Small-2-24B-Instruct-2512-Q4_K_M.gguf
deepseek2-ocr,aditya00196/DeepSeek-OCR-2-Q4_K_M.gguf,DeepSeek-OCR-2-Q4_K_M.gguf
-gpt-oss,unsloth/gpt-oss-20b-GGUF,gpt-oss-20b-Q4_K_M.gguf,skip,"Needs ~120 GiB peak anon RAM to convert+compile (see the memory table in supported_models.md); the largest CI runner is 64 GiB"
-hunyuan-moe,,,skip,"No small checkpoint publicly available (see supported_models.md)"
-glm4moe,,,skip,"Smallest checkpoint (GLM-4.5-Air) is ~40 GiB, impractical even for nightly"
-exaone-moe,,,skip,"Smallest checkpoint is ~9 GiB / 32B, not currently validated (see supported_models.md)"
-minimax-m2,,,skip,"Smallest checkpoint is ~78 GiB, impractical even for nightly"
-jais2,,,skip,"No small checkpoint publicly available (see supported_models.md)"
+gpt-oss,unsloth/gpt-oss-20b-GGUF,gpt-oss-20b-Q4_K_M.gguf,skip,"Needs ~120 GiB peak anonymous RAM to convert and compile; the largest CI runner is 64 GiB"
+hunyuan-moe,unsloth/Hunyuan-A13B-Instruct-GGUF,Hunyuan-A13B-Instruct-Q2_K.gguf,skip,"80B MoE checkpoint requires a dedicated runner; file alone is 27.4 GiB"
+glm4moe,mradermacher/ArliAI_GLM-4.5-Air-Derestricted_REAP50_Creative-i1-GGUF,ArliAI_GLM-4.5-Air-Derestricted_REAP50_Creative.i1-Q2_K.gguf,skip,"Pruned GLM-4.5-Air checkpoint requires a dedicated runner; file alone is 21.7 GiB"
+exaone-moe,mradermacher/K-EXAONE-236B-A23B-GGUF,K-EXAONE-236B-A23B.Q2_K.gguf,skip,"236B MoE checkpoint exceeds the 64 GiB nightly runner; file alone is 80.6 GiB"
+minimax-m2,mradermacher/MiniMax-M2.1-REAP-50-i1-GGUF,MiniMax-M2.1-REAP-50.i1-Q2_K.gguf,skip,"Pruned MiniMax-M2.1 checkpoint requires a dedicated runner; file alone is 39.6 GiB"
+jais2,mradermacher/JAIS2-IT-0.3-GGUF,JAIS2-IT-0.3.Q4_K_M.gguf
nemotron_h,bartowski/nvidia_Nemotron-H-8B-Reasoning-128K-GGUF,nvidia_Nemotron-H-8B-Reasoning-128K-Q4_K_M.gguf
mamba2-2.7b,Nicholas55555/mamba2-2.7b-Q8_0-GGUF,mamba2-2.7b-q8_0.gguf
diff --git a/tests/model_hub_tests/gguf/gguf_models_precommit b/tests/model_hub_tests/gguf/gguf_models_precommit
index 159f18ef395..af1d323af1e 100644
--- a/tests/model_hub_tests/gguf/gguf_models_precommit
+++ b/tests/model_hub_tests/gguf/gguf_models_precommit
@@ -29,6 +29,7 @@ gemma4,unsloth/gemma-4-E4B-it-GGUF,gemma-4-E4B-it-Q4_K_M.gguf
llama-embed,sabafallah/llama-nemotron-embed-1b-v2-GGUF,llama-nemotron-embed-1b-v2-Q4_K_M.gguf
exaone4,LGAI-EXAONE/EXAONE-4.0-1.2B-GGUF,EXAONE-4.0-1.2B-Q4_K_M.gguf
plamo3,mmnga-o/plamo-3-nict-2b-base-gguf,plamo-3-nict-2b-base-Q4_K_M.gguf
+llama-embed,mradermacher/llama-nemotron-embed-1b-v2-GGUF,llama-nemotron-embed-1b-v2.Q4_K_M.gguf
smollm3,bartowski/HuggingFaceTB_SmolLM3-3B-GGUF,HuggingFaceTB_SmolLM3-3B-Q4_K_M.gguf
maincoder,mradermacher/Maincoder-1B-GGUF,Maincoder-1B.Q4_K_M.gguf
mistral3,mradermacher/Ministral-3b-instruct-GGUF,Ministral-3b-instruct.Q4_K_M.gguf
diff --git a/tests/model_hub_tests/gguf/llama_cpp_oracle.py b/tests/model_hub_tests/gguf/llama_cpp_oracle.py
new file mode 100644
index 00000000000..960c9f8ef92
--- /dev/null
+++ b/tests/model_hub_tests/gguf/llama_cpp_oracle.py
@@ -0,0 +1,106 @@
+# -*- coding: utf-8 -*-
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+"""Build the pinned llama.cpp CPU encoder oracle for the mmproj model tests.
+
+The reference values come from llama.cpp itself at test time, so no stored expectations go
+stale. The build fetches one upstream commit, builds only libmtmd and its dependencies, and
+compiles mmproj_oracle.cpp from the GGUF frontend tests against it. Results are cached per
+revision under GGUF_LLAMA_CPP_CACHE (default: ~/.cache/openvino_gguf_llama_cpp).
+Set GGUF_MMPROJ_ORACLE to an already built mmproj_oracle to skip the build; the checkout is
+still fetched for its gguf-py package.
+"""
+
+import contextlib
+import fcntl
+import os
+import shutil
+import subprocess
+from pathlib import Path
+
+LLAMA_CPP_REPO = "https://github.com/ggml-org/llama.cpp"
+# The revision the GGUF frontend's mmproj fixtures are generated with.
+LLAMA_CPP_REVISION = "03fa73cb27f5c251b9528489b18d303b1366aca4"
+
+
+def frontend_test_file(name: str) -> Path:
+ """A file shared with src/frontends/gguf/tests, installed next to this module."""
+ here = Path(__file__).resolve().parent
+ for candidate in (here / name, here.parents[2] / "src" / "frontends" / "gguf" / "tests" / name):
+ if candidate.exists():
+ return candidate
+ raise FileNotFoundError(f"{name} is neither installed next to {here} nor in the source tree")
+
+
+def _run(args, **kwargs):
+ subprocess.run([str(arg) for arg in args], check=True, **kwargs)
+
+
+def _compilers():
+ cc = os.environ.get("CC") or shutil.which("clang") or shutil.which("cc")
+ cxx = os.environ.get("CXX") or shutil.which("clang++") or shutil.which("c++")
+ if not cc or not cxx:
+ raise RuntimeError("Building the llama.cpp oracle needs a C and C++ compiler")
+ return cc, cxx
+
+
+def _root() -> Path:
+ cache = Path(os.environ.get("GGUF_LLAMA_CPP_CACHE", Path.home() / ".cache" / "openvino_gguf_llama_cpp"))
+ return cache / LLAMA_CPP_REVISION
+
+
+def _locked():
+ """Serialize fetching and building across processes that share the cache."""
+ root = _root()
+ root.mkdir(parents=True, exist_ok=True)
+ with open(root / ".lock", "w") as lock:
+ fcntl.flock(lock, fcntl.LOCK_EX)
+ try:
+ yield root
+ finally:
+ fcntl.flock(lock, fcntl.LOCK_UN)
+
+
+def _checkout(root: Path) -> Path:
+ source = root / "src"
+ if not (source / "CMakeLists.txt").exists():
+ shutil.rmtree(source, ignore_errors=True)
+ source.mkdir(parents=True)
+ _run(["git", "init", "-q"], cwd=source)
+ _run(["git", "fetch", "-q", "--depth", "1", LLAMA_CPP_REPO, LLAMA_CPP_REVISION], cwd=source)
+ _run(["git", "checkout", "-q", "FETCH_HEAD"], cwd=source)
+ return source
+
+
+def llama_cpp_checkout() -> Path:
+ """The pinned llama.cpp source tree, fetched on first use."""
+ with _locked() as root:
+ return _checkout(root)
+
+
+def build_mmproj_oracle() -> Path:
+ if prebuilt := os.environ.get("GGUF_MMPROJ_ORACLE"):
+ return Path(prebuilt)
+ with _locked() as root:
+ oracle = root / "mmproj_oracle"
+ if not oracle.exists():
+ _build(root, _checkout(root), oracle)
+ return oracle
+
+
+def _build(root: Path, source: Path, oracle: Path):
+ build = root / "build"
+ cc, cxx = _compilers()
+ _run(["cmake", "-S", source, "-B", build, "-G", "Ninja", "-DCMAKE_BUILD_TYPE=Release",
+ f"-DCMAKE_C_COMPILER={cc}", f"-DCMAKE_CXX_COMPILER={cxx}", "-DGGML_NATIVE=OFF",
+ "-DLLAMA_CURL=OFF", "-DLLAMA_BUILD_TESTS=OFF", "-DLLAMA_BUILD_EXAMPLES=OFF",
+ "-DLLAMA_BUILD_SERVER=OFF", "-DLLAMA_BUILD_TOOLS=ON"], stdout=subprocess.DEVNULL)
+ _run(["cmake", "--build", build, "--target", "mtmd"], stdout=subprocess.DEVNULL)
+ libraries = build / "bin"
+ _run([cxx, "-std=c++17", "-O2", frontend_test_file("mmproj_oracle.cpp"),
+ "-I", source / "tools" / "mtmd", "-I", source / "include", "-I", source / "ggml" / "include",
+ "-L", libraries, f"-Wl,-rpath,{libraries}",
+ "-lmtmd", "-lllama", "-lggml", "-lggml-base", "-o", oracle.with_suffix(f".{os.getpid()}.tmp")])
+ oracle.with_suffix(f".{os.getpid()}.tmp").replace(oracle)
diff --git a/tests/model_hub_tests/gguf/test_gguf.py b/tests/model_hub_tests/gguf/test_gguf.py
index fdc5de1a30d..b120fa657a3 100644
--- a/tests/model_hub_tests/gguf/test_gguf.py
+++ b/tests/model_hub_tests/gguf/test_gguf.py
@@ -7,10 +7,8 @@
#
# Each test downloads one .gguf file, converts it, compiles it, and runs two forward steps,
# feeding the cache/state outputs of the first step into the second. The checks cover finite,
-# correctly shaped logits and populated, changing KV caches. The suite does not build a tokenizer
-# because it verifies frontend conversion/inference correctness rather than text coherence (which
-# src/frontends/gguf/tests/compare_with_llama.py and the GenAI-based harness described in
-# supported_models.md already cover for the architectures where that matters).
+# correctly shaped logits and populated, changing KV caches. It does not compare tokens or logits
+# with a reference; see the OV_GGUF_ACCURACY_DATA replay in tests/test_data/arch_accuracy/README.md.
#
# gguf_models_precommit lists the small (<=~4B parameter) architectures, run on every commit.
# gguf_models_nightly lists the rest (up to ~30B), run nightly given their download size.
@@ -21,7 +19,7 @@ import pytest
from models_hub_common.constants import clean_hf_cache_dir, hf_cache_dir
from models_hub_common.utils import cleanup_dir
-from utils import assert_valid_logits, parse_gguf_model_list, run_gguf_model
+from utils import assert_valid_logits, parse_gguf_model_list, run_gguf_embedding_model, run_gguf_model
class TestGGUF:
@@ -36,6 +34,10 @@ class TestGGUF:
if mark == "xfail":
pytest.xfail(reason)
+ if arch == "llama-embed":
+ run_gguf_embedding_model(repo_id, filename, device=ie_device)
+ return
+
logits = run_gguf_model(repo_id, filename, device=ie_device)
assert_valid_logits(logits)
diff --git a/tests/model_hub_tests/gguf/test_gguf_mmproj.py b/tests/model_hub_tests/gguf/test_gguf_mmproj.py
new file mode 100644
index 00000000000..b1bd28dd00a
--- /dev/null
+++ b/tests/model_hub_tests/gguf/test_gguf_mmproj.py
@@ -0,0 +1,136 @@
+# -*- coding: utf-8 -*-
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+#
+# Verifies the GGUF frontend's multimodal projector conversion against real mmproj-*.gguf files
+# from the Hugging Face Hub. Each test converts the file, compiles every encoder it declares, and
+# compares the embeddings with llama.cpp's CPU encoder, built at a pinned revision during the test
+# session (see llama_cpp_oracle.py). llama.cpp runs an F32 copy of the same represented weights,
+# so the comparison measures conversion and execution, not the file's quantization.
+#
+# Encoders with dynamic input sizes run twice on one compiled model, at two grid shapes.
+#
+# To check local files, list them with an empty repo_id and an absolute filename in a file of
+# the same format, and point GGUF_MMPROJ_LIST at it; it replaces the precommit list.
+
+import os
+import sys
+
+import numpy as np
+import openvino as ov
+import pytest
+from openvino.frontend import FrontEndManager
+
+from models_hub_common.constants import clean_hf_cache_dir, hf_cache_dir
+from models_hub_common.utils import cleanup_dir
+from llama_cpp_oracle import build_mmproj_oracle, frontend_test_file, llama_cpp_checkout
+from utils import gguf_hub_download, parse_gguf_model_list
+
+# Input builders and the dequantizer are shared with src/frontends/gguf/tests.
+sys.path.insert(0, str(frontend_test_file("mmproj_fixtures.py").parent))
+from mmproj_fixtures import DYNAMIC_VISION, checkpoint_inputs, grid_unit, run_oracle # noqa: E402
+
+# CPU runs in F32 like the frontend's accuracy suites; other devices are not yet calibrated.
+NMSE_LIMIT = {"CPU": 1e-5}
+DEFAULT_NMSE_LIMIT = 1e-4
+
+
[email protected](scope="module")
+def oracle():
+ # The pinned checkout's gguf-py writes the F32 reference copies.
+ sys.path.insert(0, str(llama_cpp_checkout() / "gguf-py"))
+ return build_mmproj_oracle()
+
+
+def encoder(model, modality):
+ """The subgraph that computes one modality's embeddings, with only its own inputs."""
+ output = model.output(modality + ".embeddings")
+ reachable, pending = set(), [output.get_node()]
+ while pending:
+ node = pending.pop()
+ if node not in reachable:
+ reachable.add(node)
+ pending += [value.get_node() for value in node.input_values()]
+ return ov.Model([output], [p for p in model.get_parameters() if p in reachable])
+
+
+def input_sizes(metadata, modality):
+ """One or two (width, height) shapes the encoder accepts; audio uses (frames, None)."""
+ projector = metadata[modality + ".projector"]
+ unit = grid_unit(metadata, modality)
+ if modality == "audio":
+ frames = {"gemma4ua": (9, 13), "gemma4a": (101, 152)}.get(projector, (16 * unit, 25 * unit))
+ return [(count, None) for count in frames]
+ if projector not in DYNAMIC_VISION:
+ return [(None, None)]
+ return [(8 * unit, 4 * unit), (4 * unit, 6 * unit)]
+
+
+def nmse(actual, expected):
+ error = actual.astype(np.float64) - expected
+ energy = float(np.dot(expected.astype(np.float64), expected))
+ return float(np.dot(error, error)) / energy if energy > 0 else float("inf")
+
+
+class TestGGUFMMProj:
+ def teardown_method(self):
+ if clean_hf_cache_dir:
+ cleanup_dir(hf_cache_dir)
+
+ def run(self, projector, repo_id, filename, mark, reason, ie_device, oracle, tmp_path):
+ limit = NMSE_LIMIT.get(ie_device, DEFAULT_NMSE_LIMIT)
+ if mark and mark.startswith("nmse="):
+ limit, mark = float(mark[len("nmse="):]), None
+ assert mark in (None, "skip", "xfail"), f"Unknown mark {mark!r} for {projector}"
+ if mark == "skip":
+ pytest.skip(reason)
+ if mark == "xfail":
+ pytest.xfail(reason)
+ from dequantize_mmproj import dequantize_mmproj
+
+ path = gguf_hub_download(repo_id, filename) if repo_id else filename
+ frontend = FrontEndManager().load_by_framework("gguf")
+ model = frontend.convert(frontend.load(path))
+ metadata = model.get_rt_info(["gguf_mmproj"]).value
+ modalities = [m for m in ("vision", "audio") if m + ".projector" in metadata]
+ assert "+".join(metadata[m + ".projector"] for m in modalities) == projector
+ reference = tmp_path / "reference-F32.gguf"
+ dequantize_mmproj(path, reference)
+ try:
+ self.compare(model, metadata, modalities, projector, reference, oracle, ie_device, limit)
+ finally:
+ reference.unlink()
+
+ @staticmethod
+ def compare(model, metadata, modalities, projector, reference, oracle, ie_device, limit):
+ core = ov.Core()
+ for modality in modalities:
+ request = core.compile_model(encoder(model, modality), ie_device, {
+ "INFERENCE_PRECISION_HINT": "f32", "DYNAMIC_QUANTIZATION_GROUP_SIZE": 0,
+ }).create_infer_request()
+ for width, height in input_sizes(metadata, modality):
+ feeds, raw, width, height = checkpoint_inputs(metadata, modality, width, height)
+ expected = run_oracle(oracle, reference, modality, width, height, raw)
+ request.infer(feeds)
+ actual = request.get_output_tensor().data.reshape(-1)
+ label = f"{projector} {modality} {width}x{height}"
+ assert actual.shape == expected.shape, f"{label}: {actual.shape} vs llama.cpp {expected.shape}"
+ assert np.isfinite(actual).all(), f"{label}: non-finite embeddings"
+ error = nmse(actual, expected)
+ print(f"{label}: normalized MSE {error:.3g} (limit {limit})")
+ assert error < limit, f"{label}: normalized MSE {error:.3g} against llama.cpp exceeds {limit}"
+
+ @pytest.mark.parametrize(
+ "projector,repo_id,filename,mark,reason",
+ parse_gguf_model_list(
+ os.environ.get("GGUF_MMPROJ_LIST", os.path.join(os.path.dirname(__file__), "gguf_mmproj_precommit"))))
+ @pytest.mark.precommit
+ def test_gguf_mmproj_precommit(self, projector, repo_id, filename, mark, reason, ie_device, oracle, tmp_path):
+ self.run(projector, repo_id, filename, mark, reason, ie_device, oracle, tmp_path)
+
+ @pytest.mark.parametrize(
+ "projector,repo_id,filename,mark,reason",
+ parse_gguf_model_list(os.path.join(os.path.dirname(__file__), "gguf_mmproj_nightly")))
+ @pytest.mark.nightly
+ def test_gguf_mmproj_nightly(self, projector, repo_id, filename, mark, reason, ie_device, oracle, tmp_path):
+ self.run(projector, repo_id, filename, mark, reason, ie_device, oracle, tmp_path)
diff --git a/tests/model_hub_tests/gguf/utils.py b/tests/model_hub_tests/gguf/utils.py
index af0a4216338..62e29c4b503 100644
--- a/tests/model_hub_tests/gguf/utils.py
+++ b/tests/model_hub_tests/gguf/utils.py
@@ -234,6 +234,39 @@ def run_gguf_model(repo_id: str, filename: str, device: str = "CPU"):
return _run_two_steps(compiled_model, is_imrope, recurrent_states)
+def run_gguf_embedding_model(repo_id: str, filename: str, device: str = "CPU"):
+ model = convert_gguf_model(gguf_hub_download(repo_id, filename))
+ compiled = ov.Core().compile_model(model, device)
+ request = compiled.create_infer_request()
+ assert not request.query_state(), "Embedding model exposes decoder state"
+ output = compiled.output("embeddings")
+ previous = None
+ for count in (3, 1, 3):
+ feed = {}
+ for port in compiled.inputs:
+ name = port.get_any_name()
+ if name == "inp_tokens":
+ values = np.arange(1, count + 1, dtype=np.int32).reshape(1, 1, 1, count)
+ elif name == "inp_pos":
+ values = np.arange(count, dtype=np.int32).reshape(1, 1, 1, count)
+ elif name == "token_len_per_seq":
+ values = np.array([count], dtype=np.int64)
+ elif name == "self_kq_mask":
+ values = np.where(np.arange(count)[None, :] <= np.arange(count)[:, None],
+ 0, -np.inf).astype(np.float32).reshape(1, 1, count, count)
+ else:
+ raise AssertionError(f"Unexpected embedding input {name}")
+ feed[name] = ov.Tensor(values)
+ embeddings = np.array(request.infer(feed)[output], copy=True)
+ assert embeddings.ndim == 2 and embeddings.shape[0] in (1, count)
+ assert embeddings.shape[1] > 1 and np.isfinite(embeddings).all()
+ assert np.any(embeddings != 0), "Embedding model produced only zeros"
+ if count == 3:
+ if previous is not None:
+ np.testing.assert_allclose(embeddings, previous, rtol=1e-5, atol=1e-6)
+ previous = embeddings
+
+
def assert_valid_logits(logits: np.ndarray):
"""Basic correctness: a real (non-empty), finite tensor of logits over some vocabulary.
diff --git a/tests/requirements_gguf b/tests/requirements_gguf
index b40c5a7c188..a188d99d6b6 100644
--- a/tests/requirements_gguf
+++ b/tests/requirements_gguf
@@ -3,9 +3,12 @@
# The tests only need numpy (to build input tensors), pytest, and huggingface_hub (to
# download the .gguf checkpoints). No tokenizer / transformers / framework dependency:
# the suite feeds synthetic token ids and checks conversion + a single forward step,
-# not generated text.
+# not generated text. The mmproj tests also build the llama.cpp reference encoder with
+# cmake and ninja, using the system C++ compiler and git.
numpy==1.26.4; python_version < "3.12"
numpy==2.2.1; python_version >= "3.12"
pytest==7.0.1
pytest-html==4.2.0
huggingface-hub==0.25.2
+cmake==3.31.6
+ninja==1.11.1.3