Skip to content

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

[GGUF FE] Runtime extension mechanism for adding architectures (#37892)

Maxim Vafind70556622b92
diff --git a/.github/workflows/job_cxx_unit_tests.yml b/.github/workflows/job_cxx_unit_tests.yml
index fb88285f5d2..5cf64004f85 100644
--- a/.github/workflows/job_cxx_unit_tests.yml
+++ b/.github/workflows/job_cxx_unit_tests.yml
@@ -134,6 +134,12 @@ jobs:
${{ env.SOURCE_COMMAND }} ${{ env.SETUPVARS }}
${{ env.INSTALL_TEST_DIR }}/ov_gguf_frontend_tests --gtest_print_time=1 --gtest_output=xml:${{ env.INSTALL_TEST_DIR }}/TEST-GGUFFrontend.xml
+ - name: GGUF architecture library tests
+ if: fromJSON(inputs.affected-components).GGUF_FE.test
+ run: |
+ ${{ env.SOURCE_COMMAND }} ${{ env.SETUPVARS }}
+ ${{ env.INSTALL_TEST_DIR }}/ov_gguf_architecture_library_tests --gtest_print_time=1 --gtest_output=xml:${{ env.INSTALL_TEST_DIR }}/TEST-GGUFArchitectureLibrary.xml
+
- name: PaddlePaddle frontend tests
if: ${{ fromJSON(inputs.affected-components).PDPD_FE.test && runner.os != 'Windows' }} # Ticket: 149651
run: |
diff --git a/src/frontends/gguf/.gitignore b/src/frontends/gguf/.gitignore
index f671f608a0a..1033a544739 100644
--- a/src/frontends/gguf/.gitignore
+++ b/src/frontends/gguf/.gitignore
@@ -1,3 +1,4 @@
-# The root .gitignore's "[Bb]uild*/" rule (meant for CMake build output dirs) also matches
-# the src/builder/ source directory by name. Re-include it; this is tracked source code.
+# Re-include builder directories matched by the root [Bb]uild*/ rule.
+# Git requires the parent directory to be included before its files.
!src/builder
+!dev_api/openvino/frontend/gguf/builder
diff --git a/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/decoder_options.hpp b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/decoder_options.hpp
new file mode 100644
index 00000000000..ba59cfa952b
--- /dev/null
+++ b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/decoder_options.hpp
@@ -0,0 +1,50 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <optional>
+
+#include "openvino/frontend/gguf/decoder.hpp"
+#include "openvino/frontend/gguf/visibility.hpp"
+
+namespace ov::frontend::gguf {
+
+enum class RopeMode { Normal, Neox, Interleaved };
+
+// Architecture overrides; unset options retain detection. Dimensions and derived plans stay internal.
+struct GGUF_FRONTEND_API DecoderOptions {
+ std::optional<bool> qk_norm_after_rope;
+ std::optional<bool> post_norm_only;
+ std::optional<bool> normalize_expert_weights;
+ std::optional<bool> geglu;
+ std::optional<bool> value_norm;
+ std::optional<bool> embedding_norm;
+ std::optional<bool> rope_on_swa_only;
+ std::optional<float> post_norm_epsilon;
+ std::optional<float> swa_rope_frequency_base;
+ std::optional<int> swa_rope_dimensions;
+ std::optional<int> sliding_window;
+ std::optional<int> rope_skip_period;
+};
+
+// Value snapshot; changes do not affect the shared decoder configuration.
+struct GGUF_FRONTEND_API DecoderDimensions {
+ int layers;
+ int embedding;
+ float norm_epsilon;
+};
+
+// Per-layer snapshot from decoder_attention configuration, including KV heads and SWA RoPE.
+struct GGUF_FRONTEND_API DecoderLayerParameters {
+ int query_heads;
+ int kv_heads;
+ int head_size;
+ float attention_scale;
+ RopeConfig rope;
+ bool sliding_window;
+ bool recurrent;
+};
+
+} // namespace ov::frontend::gguf
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
new file mode 100644
index 00000000000..83a21df40ff
--- /dev/null
+++ b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/graph_context.hpp
@@ -0,0 +1,89 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <map>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "openvino/core/any.hpp"
+#include "openvino/frontend/gguf/builder/decoder_options.hpp"
+#include "openvino/frontend/gguf/builder/model_builder.hpp"
+#include "openvino/frontend/gguf/builder/tensor_table.hpp"
+#include "openvino/frontend/gguf/builder/value.hpp"
+#include "openvino/frontend/gguf/decoder.hpp"
+#include "openvino/frontend/gguf/visibility.hpp"
+
+namespace ov {
+namespace frontend {
+namespace gguf {
+
+// Graph operations and shared decoder blocks. Operands use GGML order; shapes use OpenVINO order.
+class GGUF_FRONTEND_API GgufGraphContext {
+public:
+ explicit GgufGraphContext(const BuildContext& ctx);
+ ~GgufGraphContext();
+
+ GgufGraphContext(const GgufGraphContext&) = delete;
+ GgufGraphContext& operator=(const GgufGraphContext&) = delete;
+
+ // Model configuration
+ const GgufMetadata& metadata() const;
+ // Call once before using decoder blocks; optional for other families.
+ // Options are validated before deriving execution plans and graph metadata.
+ DecoderDimensions configure_decoder(RopeMode rope, const DecoderOptions& options = {});
+ DecoderLayerParameters decoder_layer_parameters(int layer) const;
+ GgufValue decoder_attention(int layer, const GgufValue& normalized_input);
+ GgufValue decoder_ffn(int layer, const GgufValue& normalized_input);
+ const std::string& arch() const;
+ GgufTensors tensors();
+
+ // Inputs
+ // GET_ROWS(tok_embd, inp_tokens), creating inp_tokens on first use.
+ GgufValue build_inp_embd(const GgufValue& tok_embd);
+ // Position indices consumed by RoPE.
+ GgufValue build_inp_pos();
+ // Row selector for the last layer's output (inp_out_ids).
+ GgufValue build_inp_out_ids();
+ // Declare masks, KV write indices, and token lengths before the layer loop.
+ // The SWA mask is included when requested here or by configure_decoder.
+ void build_attn_inp_kv(bool swa = false);
+ GgufValue add_input(const std::string& name, ov::element::Type type, const ov::PartialShape& shape);
+
+ // Invoke a registered converter; its OpenVINO outputs supply shape/type inference.
+ GgufValue node(const std::string& op_type,
+ const std::vector<GgufValue>& inputs,
+ int op_case = 0,
+ const std::map<std::string, ov::Any>& attrs = {});
+
+ // Declare the position contract before emitting nodes; config.per_op selects per-node tables.
+ void configure_rope(const RopeConfig& config);
+
+ // Normalization
+
+ // RMS norm with optional weight scaling; an empty w leaves it unscaled.
+ GgufValue build_norm(const GgufValue& cur, const GgufValue& w, float eps);
+ // LayerNorm with optional weight and bias.
+ GgufValue build_norm_ln(const GgufValue& cur, const GgufValue& w, const GgufValue& b, float eps);
+
+ // Outputs and state
+ void set_output(const GgufValue& logits);
+ // 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.
+ void add_recurrent_state(const GgufValue& input, const GgufValue& update);
+ // Validate and seal the finished graph. Call once, last.
+ std::shared_ptr<GgufGraph> finish();
+
+private:
+ friend class GgufTensors;
+ struct Impl;
+ std::unique_ptr<Impl> m_impl;
+};
+
+} // namespace gguf
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/metadata.hpp b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/metadata.hpp
new file mode 100644
index 00000000000..351cc3211e2
--- /dev/null
+++ b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/metadata.hpp
@@ -0,0 +1,53 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstdint>
+#include <optional>
+#include <string>
+#include <vector>
+
+#include "openvino/frontend/gguf/visibility.hpp"
+
+namespace ov {
+namespace frontend {
+namespace gguf {
+
+namespace detail {
+// Keep the parser metadata representation out of the developer API.
+struct MetadataStore;
+struct MetadataAccess;
+} // namespace detail
+
+// Read-only metadata view. Missing or incompatible scalar values return nullopt; callers
+// choose defaults with std::optional::value_or or diagnose required keys. Numeric reads accept
+// compatible widths, so extensions do not depend on the GGUF writer's integer/float precision.
+class GGUF_FRONTEND_API GgufMetadata {
+public:
+ explicit GgufMetadata(const detail::MetadataStore& store) : m_store(&store) {}
+
+ bool has(const std::string& key) const;
+
+ std::optional<int64_t> get_int(const std::string& key) const;
+ std::optional<double> get_float(const std::string& key) const;
+ std::optional<bool> get_bool(const std::string& key) const;
+ std::optional<std::string> get_str(const std::string& key) const;
+
+ // Empty vector when the key is absent or is not an array of that kind.
+ std::vector<int64_t> get_int_array(const std::string& key) const;
+ std::vector<double> get_float_array(const std::string& key) const;
+ std::vector<std::string> get_str_array(const std::string& key) const;
+
+ // `general.architecture`, or "" when the file does not name one.
+ std::string architecture() const;
+
+private:
+ friend struct detail::MetadataAccess;
+ const detail::MetadataStore* m_store;
+};
+
+} // namespace gguf
+} // namespace frontend
+} // namespace ov
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
new file mode 100644
index 00000000000..d3071d0ffeb
--- /dev/null
+++ b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/model_builder.hpp
@@ -0,0 +1,48 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <memory>
+#include <string>
+
+#include "openvino/frontend/gguf/builder/metadata.hpp"
+#include "openvino/frontend/gguf/visibility.hpp"
+
+namespace ov {
+namespace frontend {
+namespace gguf {
+
+// Opaque graph produced by GgufGraphContext; defined in builder/gguf_graph.hpp.
+struct GgufGraph;
+
+namespace detail {
+struct WeightStore;
+}
+
+// Borrowed metadata and weights, valid only during the synchronous factory/build call.
+// Returned graphs retain the weight storage; builders must not retain this view afterward.
+struct GGUF_FRONTEND_API BuildContext {
+ GgufMetadata metadata;
+
+ // `general.architecture` as the file spells it.
+ std::string arch;
+
+ // Opaque weight tables accessed through GgufTensors.
+ detail::WeightStore* weights = nullptr;
+};
+
+// Whole-model builder for any family, registered through ArchitectureDefinition.
+// See docs/porting_a_llama_cpp_model.md for external and built-in registration.
+class GGUF_FRONTEND_API ModelBuilder {
+public:
+ virtual ~ModelBuilder();
+
+ // Emit the whole model and return the finished graph.
+ virtual std::shared_ptr<GgufGraph> build() = 0;
+};
+
+} // namespace gguf
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/tensor_table.hpp b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/tensor_table.hpp
new file mode 100644
index 00000000000..31ba4bea836
--- /dev/null
+++ b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/tensor_table.hpp
@@ -0,0 +1,41 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <string>
+
+#include "openvino/frontend/gguf/builder/value.hpp"
+#include "openvino/frontend/gguf/visibility.hpp"
+
+namespace ov {
+namespace frontend {
+namespace gguf {
+
+class GgufGraphContext;
+
+// Weight lookup by GGUF name. Each present weight is emitted once as a GGML_OP_NONE leaf.
+class GGUF_FRONTEND_API GgufTensors {
+public:
+ explicit GgufTensors(GgufGraphContext& ctx) : m_ctx(&ctx) {}
+
+ // Weight by full GGUF name (e.g. "token_embd.weight", "blk.3.attn_q.bias"). Empty if absent.
+ GgufValue operator()(const std::string& gguf_name) const;
+
+ // Required weight; throws with the tensor and architecture names if absent.
+ GgufValue require(const std::string& gguf_name) const;
+
+ // Check presence without emitting a graph node.
+ bool has(const std::string& gguf_name) const;
+
+ // Weight of layer `il` by suffix: layer(3, "attn_norm.weight") -> "blk.3.attn_norm.weight".
+ GgufValue layer(int il, const std::string& suffix) const;
+
+private:
+ GgufGraphContext* m_ctx;
+};
+
+} // namespace gguf
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/value.hpp b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/value.hpp
new file mode 100644
index 00000000000..19a5eb9e423
--- /dev/null
+++ b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/value.hpp
@@ -0,0 +1,62 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <string>
+#include <utility>
+
+#include "openvino/core/node.hpp"
+#include "openvino/core/partial_shape.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "openvino/frontend/gguf/visibility.hpp"
+
+namespace ov {
+namespace frontend {
+namespace gguf {
+
+// Named OpenVINO output; shape and type come from OpenVINO inference.
+// Default construction yields an empty handle, also used for absent optional weights.
+class GGUF_FRONTEND_API GgufValue {
+public:
+ GgufValue() = default;
+
+ GgufValue(std::string name, ov::Output<ov::Node> value) : m_name(std::move(name)), m_value(std::move(value)) {}
+
+ const std::string& name() const {
+ return m_name;
+ }
+
+ // Logical shape in OpenVINO order: [ne3, ne2, ne1, ne0] for a rank-4 value.
+ const ov::PartialShape& shape() const {
+ static const ov::PartialShape unknown = ov::PartialShape::dynamic();
+ return empty() ? unknown : m_value.get_partial_shape();
+ }
+
+ ov::element::Type type() const {
+ return empty() ? ov::element::dynamic : m_value.get_element_type();
+ }
+
+ // GGML dimension i, counted from the last shape axis. Returns -1 for an empty value
+ // or dynamic dimension, and 1 beyond the rank.
+ int64_t ne(size_t i) const;
+
+ // False for an empty handle.
+ explicit operator bool() const {
+ return m_value.get_node() != nullptr;
+ }
+
+ bool empty() const {
+ return m_value.get_node() == nullptr;
+ }
+
+private:
+ friend class GgufGraphContext;
+ std::string m_name;
+ ov::Output<ov::Node> m_value;
+};
+
+} // namespace gguf
+} // namespace frontend
+} // namespace ov
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
new file mode 100644
index 00000000000..1ca92b0ceef
--- /dev/null
+++ b/src/frontends/gguf/dev_api/openvino/frontend/gguf/extension/architecture.hpp
@@ -0,0 +1,63 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <functional>
+#include <memory>
+#include <string>
+
+#include "openvino/core/extension.hpp"
+#include "openvino/frontend/gguf/builder/decoder_options.hpp"
+#include "openvino/frontend/gguf/builder/model_builder.hpp"
+#include "openvino/frontend/gguf/visibility.hpp"
+
+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.
+struct GGUF_FRONTEND_API ArchitectureDefinition {
+ using BuilderFactory = std::function<std::shared_ptr<ModelBuilder>(const BuildContext&)>;
+ using MatchFn = std::function<bool(const GgufMetadata&)>;
+
+ std::string id; // Unique handler identity, e.g. "clip.vision".
+ 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;
+};
+
+// Use the native decoder resolver and blocks. Options are collected before configuration is resolved.
+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);
+
+class GGUF_FRONTEND_API ArchitectureExtension : public ov::Extension {
+public:
+ OPENVINO_RTTI("gguf::ArchitectureExtension", "", ov::Extension);
+ 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() override;
+
+ const ArchitectureDefinition& definition() const {
+ return m_definition;
+ }
+ RegistrationMode registration_mode() const {
+ return m_mode;
+ }
+
+private:
+ ArchitectureDefinition m_definition;
+ RegistrationMode m_mode;
+};
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/docs/adding_an_architecture.md b/src/frontends/gguf/docs/adding_an_architecture.md
index ad9aadb6a4f..6672fac0b8c 100644
--- a/src/frontends/gguf/docs/adding_an_architecture.md
+++ b/src/frontends/gguf/docs/adding_an_architecture.md
@@ -11,39 +11,46 @@ translators (`src/op/*.cpp`) run for both the native path and the llama.cpp cgra
| File | Responsibility | Knows about |
|---|---|---|
-| [`graph_emitter.hpp`](../src/builder/graph_emitter.hpp) | `add_op` / `add_input` / `add_weight` + shape & type bookkeeping | nothing about transformers |
+| [`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 | names only |
-| [`model_kind.hpp`](../src/builder/model_kind.hpp) | which model *family* a file holds | raw metadata |
-| [`gguf_builder.cpp`](../src/builder/gguf_builder.cpp) | parse → detect family → dispatch to a `ModelBuilder` | the entry point |
+| [`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.
-## The 90% case: add a name
+## Two routes: in-tree, or an extension
-Most new architectures in the transformer family need **no code** — the builder auto-detects
-their structure from the GGUF tensor table and metadata. To enable one, add its
-`general.architecture` string to `verified_archs()` (or `experimental_archs()`) in
+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
-const std::set<std::string>& experimental_archs() {
- static const std::set<std::string> archs = {
- "llama-embed", "exaone4", ...,
- "your-arch", // <-- add here
- };
- return archs;
-}
+{"your-arch", RopeMode::Neox, Maturity::Experimental},
```
-Then check whether RoPE is NEOX (rotate-halves) or NORMAL (rotate consecutive pairs) for the
-arch and, if NEOX, add it to `arch_uses_neox_rope()` in the same file (mirror
-`llama_model_rope_type` in llama.cpp). That is the whole change for a same-family arch.
+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)
@@ -51,15 +58,15 @@ arch and, if NEOX, add it to `arch_uses_neox_rope()` in the same file (mirror
| Feature | Detected from |
|---|---|
-| Per-head Q/K norm (qwen3, hunyuan) | `blk.0.attn_q_norm.weight` |
+| 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) | `blk.<lead>.ffn_gate_exps.weight` |
-| Shared experts | `expert_shared_count` metadata + `ffn_*_shexp.weight` |
-| Hybrid dense-lead MoE | `leading_dense_block_count` metadata |
+| 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 |
@@ -77,6 +84,7 @@ are handled by the per-layer accessors on `DecoderConfig` — the single source
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)
@@ -113,23 +121,24 @@ To add such a feature:
## Adding a new model FAMILY (mmproj, audio, encoder-decoder)
-An architecture is data; a **family** is code. A family is a distinct graph shape with its own
+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.
-Instead:
-
-1. Detect it in [`model_kind.cpp`](../src/builder/model_kind.cpp). mmproj files set
- `general.architecture = "clip"` and carry `clip.has_vision_encoder` / `clip.has_audio_encoder`
- (llama.cpp `tools/mtmd/clip-impl.h`), so `detect_model_kind()` already classifies them; the
- check runs *before* any decoder hyperparameter is read, because those keys do not exist there.
-2. Add a metadata reader next to `decoder_config_from_meta()` for that family's key layout, and a
- config struct next to `DecoderConfig`.
-3. Subclass [`ModelBuilder`](../src/builder/model_builder.hpp) in `arch/`, reusing `GraphEmitter`
- and `blocks/common`. A ViT needs its own attention — non-causal, no KV cache, no RoPE — so it
- will not reuse `blocks::attention`; this is the same split llama.cpp makes between
- `llm_graph_context` and `clip_graph`.
-4. Add a branch in `build_ggml_graph_from_gguf()`.
+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.
@@ -140,6 +149,18 @@ passes (`MakeStateful`, `AdaptToGenAI`) are caller-registered rather than built
## 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"))`.
@@ -151,3 +172,9 @@ passes (`MakeStateful`, `AdaptToGenAI`) are caller-registered rather than built
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/how_to_add_op.md b/src/frontends/gguf/docs/how_to_add_op.md
index a6fc5d1f922..8021d134838 100644
--- a/src/frontends/gguf/docs/how_to_add_op.md
+++ b/src/frontends/gguf/docs/how_to_add_op.md
@@ -70,18 +70,41 @@ the graph-fingerprint gate rely on.
| `get_input(idx)` / `get_input(name)` | Operand as `Output<Node>` |
| `has_input(name)` | Test an optional operand first |
| `get_input_size()` | Actual operand count |
-| `get_input_shape(idx)` / `get_output_shape()` | **Static ggml** shape — use when the live OV shape is dynamic (KV-cache path) |
+| `get_input(idx).get_partial_shape()` | Shape inferred by OpenVINO, including dynamic dimensions |
+| `get_input_shape(idx)` | Source layout when supplied by a cgraph decoder; otherwise the inferred input shape padded to GGML rank four |
+| `get_output_shape()` | Legacy cgraph destination layout; unavailable for native builder operations |
| `get_input_view_element_offset(idx)` | Element (not byte) offset for a ggml VIEW operand |
| `get_op_case()` | Structural variant (convenience wrapper, defaults to 0) |
-| `get_output_type()` | Declared output element type |
| `get_attribute<T>(name[, default])` | Any other typed op parameter |
Helpers in [`src/utils.hpp`](../src/utils.hpp): `num_inputs_check`, `get_dimensions`,
`rename_outputs_with_suffix`, `make_sin_cos` (RoPE), `process_view_input`.
-Insert a `Convert` to `get_output_type()` when the op may change element type (`CONCAT`, `CPY`,
-`SET_ROWS`, `GET_ROWS`) rather than assuming the input type. Prefer `ov::op::vX::OpName` over
-`opsetX::OpName`, per the repository convention.
+`TOP_K` accepts an `int64_t` attribute `k`; OpenVINO infers the output shape from the input
+and this parameter. For compatibility, decoders that omit `k` must supply a static last
+output dimension, where ggml stores `k`. An unknown `k` is rejected, never inferred from
+the input width.
+
+Converters must infer intermediate shapes from their OpenVINO operands, reading only the axes
+needed for the operation. A dynamic token axis does not prevent reading a static head width.
+Use explicit attributes for operation parameters: `reshape_target` / `special_zero`, `view_slice`,
+`repeats`, and TopK `k`. Source destination shapes may provide compatibility defaults for existing
+cgraph importers; native builders never manufacture them. A new converter also serves `GgufGraphContext::node`
+without a separate shape implementation in the builder.
+
+Result-type rules belong in the converter, not in the builder or architecture. `MUL_MAT` and
+`MUL_MAT_ID` produce F32, `TOP_K`/`ARGSORT` produce I32, and `GET_ROWS` returns I32 for integer
+rows and F32 for floating/quantized rows. Type-preserving operations use their input type;
+`SET`, `SET_ROWS` and `CPY` use the destination operand. Construct the OpenVINO computation in
+the appropriate precision; casting an already-overflowed F16 matrix product to F32 is too late.
+
+Only operations with an explicit destination-type parameter accept `dst_type`: a one-input `CPY`
+represents a cast, and `IM2COL` takes the type chosen by the caller. Those converters also accept
+legacy cgraph `output_type` metadata when no destination type can otherwise be determined.
+Native graph nodes have no output-type field or default-type table. A new converter derives its
+own result type from operation semantics, inputs and attributes.
+
+Prefer `ov::op::vX::OpName` over `opsetX::OpName`, per the repository convention.
## Test, and the coverage gate
diff --git a/src/frontends/gguf/docs/porting_a_llama_cpp_model.md b/src/frontends/gguf/docs/porting_a_llama_cpp_model.md
new file mode 100644
index 00000000000..05d99881d9a
--- /dev/null
+++ b/src/frontends/gguf/docs/porting_a_llama_cpp_model.md
@@ -0,0 +1,521 @@
+# 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)` declares other outputs. `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/supported_models.md b/src/frontends/gguf/docs/supported_models.md
index e6842dfc100..7f2507a755c 100644
--- a/src/frontends/gguf/docs/supported_models.md
+++ b/src/frontends/gguf/docs/supported_models.md
@@ -1,17 +1,17 @@
# GGUF Frontend — Supported Models
-This document lists the model architectures the GGUF frontend can convert and run
-end-to-end. An architecture is listed as **Supported** only when at least one *real*
-(non-synthetic) model of that architecture has been verified to load, convert, and
-produce coherent output through the frontend.
+The frontend accepts graphs from two paths:
-Verification is done by running a real `.gguf` through the OpenVINO backend swap in
-`llama.cpp` (`llama-completion`, CPU device, stateful execution) and confirming the
-generated text is coherent and matches the pure-ggml CPU reference for the same prompt.
+- **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.
-## Supported architectures
+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.
-Each row was verified with the named real model.
+## llama.cpp cgraph path
+
+Validated architectures and model examples:
| Architecture | Verified model | Notes |
|---|---|---|
@@ -24,16 +24,12 @@ Each row was verified with the named real model.
| `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. |
-`llama`, `qwen2`, `qwen3`, `olmoe`, `gemma4`, and `qwen35` were verified with a fresh
-end-to-end run of the model named above. `qwen3moe` and `gemma3` were verified in earlier
-development on the models named above.
-
-Quantization formats verified in the above runs: `Q2_K`, `Q4_0`, `Q4_K_M`, `Q6_K`,
+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.
-## How verification was performed
+### Verification
```sh
GGML_OPENVINO_DEVICE=CPU GGML_OPENVINO_STATEFUL_EXECUTION=1 \
@@ -42,162 +38,133 @@ GGML_OPENVINO_DEVICE=CPU GGML_OPENVINO_STATEFUL_EXECUTION=1 \
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 (e.g. `hunyuan`) is **not** counted as supported.
+that loads but emits garbage is **not** counted as supported.
-## Architectures accepted by the native `.gguf` builder
+## Native GGUF path
-Everything above is about the **llama.cpp cgraph** path. This section covers the *other*
-decoder — the native `.gguf` builder (`DecoderBuilder` in
-[`src/builder/arch/decoder_builder.cpp`](../src/builder/arch/decoder_builder.cpp)), which is what
-OpenVINO GenAI uses. The two paths share all op
-translators but have separate architecture lists.
-
-The builder's accept-list is the union of two sets, both defined in
+The native architecture catalog is defined in
[`src/builder/arch_registry.cpp`](../src/builder/arch_registry.cpp):
-- **`verified_archs()`** — convert + compile + generation checked against a reference on a
- real checkpoint.
-- **`experimental_archs()`** — expected to work via the builder's GGUF-tensor-table
- auto-detection, but not end-to-end verified. These convert and emit a one-time
- `OPENVINO_WARN` so callers know they are best-effort.
+- **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.
-Anything not in either set is rejected with an explicit `OPENVINO_ASSERT` at load time
-rather than converting into a silently wrong graph.
+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_archs()` — 11 architectures
+### Verified — 23 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 |
-| `qwen2` | qwen2 / qwen2.5 |
-| `qwen3` | QK-norm |
+| `maincoder` | NORMAL RoPE; learned QK-norm after RoPE |
+| `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 |
+| `olmoe` | full-width QK-norm and MoE |
| `phi3` | fused QKV |
-| `minicpm` | NORMAL rope + scalar embedding/residual/logit scales |
-| `hunyuan-dense` | NEOX rope + learned per-head Q/K norm after RoPE |
-| `olmoe` | OLMoE 1B-7B (MoE) |
-| `qwen35` | Qwen3.5/3.6 (and the Ternary-Bonsai backbone): hybrid Gated-DeltaNet + full attention, M-RoPE, interleaved query+gate projection. Greedy / batch 1 only |
-| `gpt-oss` | MoE + attention sinks + SWA + OAI gated activation |
-| `gemma3` | post-norms + final logit soft-cap |
-| `gemma4` | SWA, per-layer embeddings, shared KV |
+| `qwen2` | qwen2 / qwen2.5 |
+| `qwen3` | QK-norm before RoPE |
+| `qwen35` | hybrid GatedDeltaNet + full attention, interleaved M-RoPE; greedy / batch 1 only |
+| `qwen3moe` | NEOX RoPE, per-head QK-norm and normalized expert weights |
+| `smollm3` | NORMAL RoPE, skipped on every fourth layer |
-### `experimental_archs()` — 19 architectures
+### Experimental — 7 architectures
-| Architecture | Notes |
+| Architecture | Status / limitation |
|---|---|
-| `llama-embed` | Bidirectional LLaMA (embedding model, no causal mask) |
-| `exaone4` | EXAONE 4.0: NEOX rope, post-norms (attn + ffn) |
-| `plamo3` | PLaMo-3: NEOX rope, post-norms (attn + ffn) |
-| `smollm3` | SmolLM3: NORMAL rope + SWA |
-| `hunyuan-moe` | NEOX rope, MoE routing, QK-norm |
-| `glm4moe` | GLM 4.5 MoE: 1 dense lead layer, MoE + attn post-norm |
-| `exaone-moe` | EXAONE MoE: SWA + MoE, shared expert |
-| `minimax-m2` | Minimax M2: pure MoE |
-| `ernie4_5-moe` | Ernie 4.5 MoE: NORMAL rope, dense lead layers + MoE stride |
-| `bailingmoe2` | BailingMoe V2: MoE + shared expert + QK-norm |
-| `maincoder` | Maincoder-1B: NORMAL rope, QK-norm (auto-detected) |
-| `mistral3` | Ministral-3B: NORMAL rope, dense |
-| `muse-glimmer` | Muse Glimmer (Meta Onyx): NORMAL rope on SWA layers only (global layers are NoPE), sigmoid attention output gate, QK-norm, pre+post norms, final logit soft-cap |
-| `mellum` | JetBrains Mellum: pure MoE |
-| `deepseek2-ocr` | DeepSeekOCR: dense lead layers + MoE |
-| `jais2` | JAIS-2: dense (biases auto-detected) |
-| `qwen3moe` | Qwen3 MoE; same topology as `olmoe`. Demoted: degenerate output through the builder |
-| `gemma` | Gemma 2B / 7B. Demoted: throws through the builder (see below) |
-| `gemma2` | post-norms + attention soft-cap. Demoted: degenerate output through the builder |
-
-RoPE flavor is **not** in these tables because it is a separate switch: archs listed in
-`arch_uses_neox_rope()` use NEOX (rotate-halves), everything else uses NORMAL (rotate
-consecutive pairs). Adding an arch to the accept-list without also classifying its RoPE is
-the most common way to get a model that loads and produces garbage.
-
-### Measured status through OpenVINO GenAI
-
-Every architecture above was run through GenAI on CPU (`gguf_arch_check`, greedy, SDPA
-backend) on the checkpoint named below. "Generates" means the model answered *"The capital
-of France is"* correctly and coherently; **`llama.cpp` ref** is the same `.gguf` through
-`llama-cli` on the default ggml CPU backend, which distinguishes a frontend bug from a
-model/checkpoint that is simply weak on the prompt.
-
-| Arch | Set | Model used | GenAI | llama.cpp ref |
-|---|---|---|---|---|
-| `llama` | verified | Llama-3.2-1B-Instruct Q4_K_M | generates | generates |
-| `qwen2` | verified | Qwen2.5-0.5B-Instruct Q4_K_M | generates | generates |
-| `qwen3` | verified | Qwen3-0.6B Q8_0 | generates (reasoning preamble) | same |
-| `phi3` | verified | Phi-3-mini-4k-instruct Q4 | generates | generates |
-| `minicpm` | verified | MiniCPM-2B-dpo Q4_K_M | generates | generates |
-| `hunyuan-dense` | verified | Hunyuan-0.5B-Instruct Q8_0 | matches reference | same |
-| `olmoe` | verified | OLMoE-1B-7B-Instruct Q4_K_M | generates | generates |
-| `qwen3moe` | experimental | Qwen3-0.9B-A0.6B Q4_K_M | **degenerate** | generates |
-| `gpt-oss` | verified | gpt-oss-20b MXFP4 | generates (harmony format) | same |
-| `gemma` | experimental | gemma-2b Q4_K_M | **throws** (SDPA shape mismatch) | degenerate too |
-| `gemma2` | experimental | gemma-2-2b-it Q4_K_M | **degenerate** | generates |
-| `gemma3` | verified | gemma-3-1b-it Q4_K_M | generates | generates |
-| `gemma4` | verified | gemma-4-E4B-it Q4_K_M | generates | generates |
-| `llama-embed` | experimental | llama-nemotron-embed-1b-v2 Q4_K_M | repeats (embedding model) | degenerate too |
-| `exaone4` | experimental | EXAONE-4.0-1.2B Q4_K_M | **degenerate** | generates |
-| `plamo3` | experimental | plamo-3-nict-2b-base Q4_K_M | **degenerate** | degenerate too |
-| `smollm3` | experimental | SmolLM3-3B Q4_K_M | generates (reasoning preamble) | same |
-| `maincoder` | experimental | Maincoder-1B Q4_K_M | generates | generates |
-| `mistral3` | experimental | Ministral-3-3B-Instruct-2512 Q4_K_M | generates | generates |
-| `muse-glimmer` | experimental | Muse-Glimmer-30B Q4_0 | generates | generates |
-| `qwen35` | verified | Qwen3.5-0.8B Q8_0 | generates | generates |
-| `qwen35` (Bonsai) | verified | Ternary-Bonsai-27B Q2_g64 | generates | generates |
-| `deepseek2-ocr` | experimental | deepseek-ocr-2 Q4_K_M | generates | generates |
-| `ernie4_5-moe` | experimental | ERNIE-4.5-21B-A3B Q4_K_M | **degenerate** (blank) | generates |
-| `bailingmoe2` | experimental | Ling-mini-2.0 Q2_K | generates | generates |
-| `mellum` | experimental | Mellum2-12B-A2.5B-Instruct Q4_K_M | generates | generates |
-| `hunyuan-moe` | experimental | — | not tested (no checkpoint) | — |
-| `glm4moe` | experimental | — | not tested (smallest GLM-4.5-Air ≈ 40 GiB) | — |
-| `exaone-moe` | experimental | — | not tested (smallest ≈ 9 GiB, 32B) | — |
-| `minimax-m2` | experimental | — | not tested (smallest ≈ 78 GiB) | — |
-| `jais2` | experimental | — | not tested (no checkpoint) | — |
-
-Two caveats on reading this table. `llama-embed` is an *embedding* model, so degenerate
-greedy completion is expected of it, not a defect. `gemma` (v1 base) and `plamo3` (base, not
-instruct) are degenerate on the reference too, so those rows are checkpoint/prompt artifacts
-rather than frontend bugs.
-
-That leaves **4 architectures that generate correctly under llama.cpp but not through the
-builder** — `qwen3moe`, `gemma2`, `exaone4` and `ernie4_5-moe` (blank output) —
-i.e. real conversion defects, plus `gemma`, which throws instead of converting cleanly.
-`qwen3moe`, `gemma2` and `gemma` were previously misclassified as
-`verified_archs()`; they have been moved to `experimental_archs()` (and now emit the one-time
-`OPENVINO_WARN`) until the underlying defects are fixed and re-verified.
-
-**`qwen35` is greedy / batch-1 only.** The recurrent conv and delta states are a single
-static-shaped block with no batch axis, and `MakeStateful` does not reorder them by `beam_idx` the
-way it reorders a KV cache. Beam search or batch > 1 therefore **fails at inference** with a shape
-mismatch on the conv window's `Concat` — it does not silently mix state across beams, so no wrong
-output can be produced. Prefix caching and PagedAttention are unavailable for the same reason: a
-recurrent state cannot be re-derived from a cached prefix, and cannot be paged. Verified
-token-for-token against llama.cpp on two real checkpoints (Qwen3.5-0.8B Q8_0, Ternary-Bonsai-27B
-Q2_g64), with final-logits agreement within 1.0% / 0.12% of llama.cpp — in line with the noise
-already present on the *verified* `qwen3` arch through the same harness.
-
-A packaging gotcha worth knowing: **`Ternary-Bonsai-27B-Q2_0.gguf` is not upstream `Q2_0`** — it
-does not load in llama.cpp either. It's packed **g128** (one f16 scale per 128 weights) while
-`GGML_TYPE_Q2_0` is **g64** (18 bytes per 64 weights); use `Ternary-Bonsai-27B-Q2_g64.gguf`
-instead. The frontend rejects the mispacked file safely (`data runs past EOF`) rather than
-dequantizing garbage.
-
-`muse-glimmer`'s row was decided by the *tokenizer*, not the graph: the converted graph reproduces
-llama.cpp token-for-token, but GenAI's GGUF tokenizer builder only honored
-`tokenizer.ggml.add_bos_token` on the SentencePiece path, silently dropping the leading BOS on the
-BPE (`gpt2`) path that this (BOS-sensitive) model uses. Same gap affected `llama3`/`mistral3` the
-same way; fixed in `gguf_tokenizer.cpp` by emitting BOS/EOS as a `CombineSegments` segment on every
-tokenizer path.
-
-## Adding a new architecture
-
-Support for a new architecture is a combination of:
-1. **Ops** — every ggml op in the model's compute graph must have a frontend translator
- (`src/op/<name>.cpp`) and backend admission.
-2. **Weights** — every quantization format used by the model's tensors must be handled by
- the weight path (`src/quant/weights.cpp`).
-3. **Real-model verification** — run a real `.gguf` end-to-end as above before adding the
- architecture to the Supported table.
-
-For the native builder specifically, see
-[`adding_an_architecture.md`](adding_an_architecture.md) — for a same-family arch the change
-is usually just adding the name to `experimental_archs()` plus the `arch_uses_neox_rope()`
-classification, and promotion to `verified_archs()` should require the GenAI-vs-llama.cpp
-comparison above.
+| `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 |
+
+### Numerical regression coverage
+
+[`GGUFArchitectureAccuracy`](../tests/test_arch_accuracy.cpp) contains 23 small, nonzero F32
+fixtures covering 19 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`.
+
+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.
+
+### Reference-checked checkpoints
+
+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.
+
+| Architecture | Real checkpoint | Matching choices |
+|---|---|---|
+| `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 |
+| `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 |
+| `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.
+
+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.
+
+### Runtime limitations
+
+- **`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.
diff --git a/src/frontends/gguf/examples/architecture_extension/CMakeLists.txt b/src/frontends/gguf/examples/architecture_extension/CMakeLists.txt
new file mode 100644
index 00000000000..7f95ab7f2e1
--- /dev/null
+++ b/src/frontends/gguf/examples/architecture_extension/CMakeLists.txt
@@ -0,0 +1,9 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+cmake_minimum_required(VERSION 3.16)
+project(gguf_projector_extension LANGUAGES CXX)
+find_package(OpenVINO REQUIRED)
+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)
diff --git a/src/frontends/gguf/examples/architecture_extension/extension.cpp b/src/frontends/gguf/examples/architecture_extension/extension.cpp
new file mode 100644
index 00000000000..6d99d128192
--- /dev/null
+++ b/src/frontends/gguf/examples/architecture_extension/extension.cpp
@@ -0,0 +1,8 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "projector.hpp"
+
+OPENVINO_CREATE_EXTENSIONS(std::vector<ov::Extension::Ptr>{
+ std::make_shared<ov::frontend::gguf::ArchitectureExtension>(example::projector_architecture())});
diff --git a/src/frontends/gguf/examples/architecture_extension/projector.cpp b/src/frontends/gguf/examples/architecture_extension/projector.cpp
new file mode 100644
index 00000000000..a942cdad774
--- /dev/null
+++ b/src/frontends/gguf/examples/architecture_extension/projector.cpp
@@ -0,0 +1,39 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "projector.hpp"
+
+#include "openvino/core/except.hpp"
+#include "openvino/frontend/gguf/builder/graph_context.hpp"
+
+namespace example {
+namespace {
+using namespace ov::frontend::gguf;
+
+// A small non-decoder family: project a variable number of embedding vectors. This source uses
+// only installed builder API headers and is compiled unchanged in the plugin and catalog tests.
+class Projector : public ModelBuilder {
+public:
+ explicit Projector(const BuildContext& context) : m_context(context) {}
+
+ std::shared_ptr<GgufGraph> build() override {
+ GgufGraphContext graph(m_context);
+ const auto weight = graph.tensors().require("projection.weight");
+ OPENVINO_ASSERT(weight.ne(0) > 0, "Projector requires a static input width");
+ const auto input = graph.add_input("embeddings", ov::element::f32, {1, 1, -1, weight.ne(0)});
+ graph.set_output(graph.node("GGML_OP_MUL_MAT", {weight, input}));
+ return graph.finish();
+ }
+
+private:
+ BuildContext m_context;
+};
+} // namespace
+
+ov::frontend::gguf::ArchitectureDefinition projector_architecture() {
+ return {"example.projector", "example-projector", [](const ov::frontend::gguf::BuildContext& context) {
+ return std::make_shared<Projector>(context);
+ }};
+}
+} // namespace example
diff --git a/src/frontends/gguf/examples/architecture_extension/projector.hpp b/src/frontends/gguf/examples/architecture_extension/projector.hpp
new file mode 100644
index 00000000000..594631aed51
--- /dev/null
+++ b/src/frontends/gguf/examples/architecture_extension/projector.hpp
@@ -0,0 +1,11 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/frontend/gguf/extension/architecture.hpp"
+
+namespace example {
+ov::frontend::gguf::ArchitectureDefinition projector_architecture();
+}
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 5229968b9f3..cfbb3255568 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
@@ -31,6 +31,7 @@ namespace 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.
///
+/// 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.
///
diff --git a/src/frontends/gguf/include/openvino/frontend/gguf/frontend.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/frontend.hpp
index 2d01551a670..9accac4d44c 100644
--- a/src/frontends/gguf/include/openvino/frontend/gguf/frontend.hpp
+++ b/src/frontends/gguf/include/openvino/frontend/gguf/frontend.hpp
@@ -38,27 +38,22 @@ public:
/// AHEAD of the frontend's built-in lowerings. A caller that wants an OpenVINO KV cache
/// 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.
- /// - `ov::detail::SOExtension` — shared-library extension; its inner extension is
- /// recursively registered.
- /// - `ov::BaseOpExtension` — op-level extension; all attached extensions are
- /// recursively registered.
+ /// - `ov::detail::SOExtension` — shared-library extension; its inner extension is recursively registered.
+ /// - `ov::BaseOpExtension` — recursively registers attached op-level extensions.
///
/// \param extension Extension to register.
void add_extension(const std::shared_ptr<ov::Extension>& extension) override;
protected:
- /// \brief Check if FrontEnd can recognize the model from the given parts.
- /// \param variants A single element holding a `std::shared_ptr<GgufDecoder>`. No other variant
- /// is recognized in this frontend: file-path (`.gguf`) loading is not yet implemented.
- /// \return True iff variants holds exactly that; false otherwise.
+ /// \brief Recognize a GgufDecoder or a .gguf file with GGUF magic.
+ /// \param variants First element is a shared_ptr<GgufDecoder> or a file path.
bool supported_impl(const std::vector<ov::Any>& variants) const override;
- /// \brief Load the input model from a GgufDecoder.
- /// \param variants A single element holding a `std::shared_ptr<GgufDecoder>` -- a decoder
- /// supplied by a direct linker, wrapping an already-built ggml graph (the llama.cpp
- /// cgraph path). File-path (`.gguf`) loading, built per-architecture by the native
- /// builder, is not yet implemented in this frontend.
+ /// \brief Load a GgufDecoder, or parse a .gguf file and select its builder for convert().
+ /// \param variants First element is a shared_ptr<GgufDecoder> or a file path.
/// \return InputModel::Ptr
InputModel::Ptr load_impl(const std::vector<ov::Any>& variants) const override;
diff --git a/src/frontends/gguf/src/CMakeLists.txt b/src/frontends/gguf/src/CMakeLists.txt
index e5c7a60c0ca..2149a48989b 100644
--- a/src/frontends/gguf/src/CMakeLists.txt
+++ b/src/frontends/gguf/src/CMakeLists.txt
@@ -2,13 +2,11 @@
# SPDX-License-Identifier: Apache-2.0
#
-# The GGUF frontend converts GGUF models to OpenVINO. It installs the library + headers alongside
-# the other frontends (LINKABLE_FRONTEND, no SKIP_INSTALL) so direct linkers -- the llama.cpp
-# ggml-openvino backend and OpenVINO GenAI -- can link openvino::frontend::gguf, and it is
-# discoverable via FrontEndManager so core.read_model("model.gguf") selects it by the .gguf
-# extension + GGUF magic (see supported_impl / get_front_end_data in frontend.cpp). Two ingest
-# paths converge on the same op translators: a live GgufDecoder (cgraph path) and a native
-# .gguf-file builder.
+# Native GGUF files and supplied GgufDecoder graphs use the same op translators.
+# The linkable frontend requires explicit selection by framework name.
+# dev_api/ installs the extension API; it does not promise compatibility across releases.
+set(GGUF_FRONTEND_DEV_API "${CMAKE_CURRENT_SOURCE_DIR}/../dev_api")
+
ov_add_frontend(NAME gguf
LINKABLE_FRONTEND
FILEDESCRIPTION "FrontEnd to convert GGUF models"
@@ -16,5 +14,15 @@ ov_add_frontend(NAME gguf
ov_build_target_faster(openvino_gguf_frontend PCH)
+# Expose builder API headers to consumers of openvino::frontend::gguf in build and install trees.
+target_include_directories(openvino_gguf_frontend
+ PUBLIC $<BUILD_INTERFACE:${GGUF_FRONTEND_DEV_API}>)
+
+install(DIRECTORY "${GGUF_FRONTEND_DEV_API}/openvino"
+ DESTINATION ${FRONTEND_INSTALL_INCLUDE}
+ COMPONENT ${OV_CPACK_COMP_CORE_DEV}
+ ${OV_CPACK_COMP_CORE_DEV_EXCLUDE_ALL}
+ FILES_MATCHING PATTERN "*.hpp")
+
# ov::parallel_for (quant dequant) needs the threading (TBB) include directories.
ov_set_threading_interface_for(openvino_gguf_frontend)
diff --git a/src/frontends/gguf/src/builder/api/graph_context.cpp b/src/frontends/gguf/src/builder/api/graph_context.cpp
new file mode 100644
index 00000000000..8d451a7ff44
--- /dev/null
+++ b/src/frontends/gguf/src/builder/api/graph_context.cpp
@@ -0,0 +1,243 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+// Generic graph operations and adapters to the shared native decoder blocks.
+
+#include "openvino/frontend/gguf/builder/graph_context.hpp"
+
+#include <algorithm>
+#include <limits>
+#include <set>
+
+#include "builder/api/graph_context_impl.hpp"
+#include "builder/blocks/ffn.hpp"
+#include "builder/blocks/gated_delta_net.hpp"
+
+namespace ov {
+namespace frontend {
+namespace gguf {
+
+using ov::element::f32;
+using ov::element::i32;
+using ov::element::i64;
+
+namespace {
+
+// Dynamic extent, for model-input Parameters.
+constexpr int64_t D = -1;
+
+} // namespace
+
+GgufGraphContext::GgufGraphContext(const BuildContext& ctx) {
+ OPENVINO_ASSERT(ctx.weights, "[GGUF] builder: BuildContext has no weight table");
+ m_impl = std::make_unique<Impl>(ctx);
+}
+
+GgufGraphContext::~GgufGraphContext() = default;
+
+const GgufMetadata& GgufGraphContext::metadata() const {
+ return m_impl->build_ctx.metadata;
+}
+
+DecoderDimensions GgufGraphContext::configure_decoder(RopeMode rope, const DecoderOptions& options) {
+ m_impl->check_open();
+ OPENVINO_ASSERT(!m_impl->decoder, "[GGUF] decoder is already configured");
+ auto normalized = decoder_config_from_meta(detail::MetadataAccess::get(metadata()).map);
+ auto config = std::make_unique<DecoderConfig>(normalized, m_impl->build_ctx.weights->weights, rope, options);
+ auto& graph = *m_impl->emitter.graph();
+ graph.has_rope = true;
+ graph.rope_config = config->rope_config;
+ graph.use_per_op_rope = config->use_per_op_rope;
+ graph.swa_window_size = config->swa_window_size;
+ const DecoderDimensions dimensions{config->n_layer, config->n_embd, config->rms_eps};
+ m_impl->kv = blocks::KvCachePlan::build(*config);
+ m_impl->decoder = std::move(config);
+ return dimensions;
+}
+
+DecoderLayerParameters GgufGraphContext::decoder_layer_parameters(int layer) const {
+ m_impl->check_layer(layer);
+ const auto& cfg = *m_impl->decoder;
+ return {cfg.n_head,
+ cfg.layer_n_head_kv(layer),
+ cfg.layer_head_size(layer),
+ cfg.layer_kq_scale(layer),
+ cfg.layer_rope_config(layer),
+ cfg.layer_is_swa(layer),
+ cfg.is_recurrent_layer(layer)};
+}
+
+GgufValue GgufGraphContext::decoder_attention(int layer, const GgufValue& input) {
+ m_impl->check_layer(layer);
+ m_impl->value_name(input);
+ const auto& cfg = *m_impl->decoder;
+ auto& emitter = m_impl->emitter;
+ const auto output = cfg.is_recurrent_layer(layer)
+ ? blocks::gated_delta_net(emitter, cfg, layer, input.name())
+ : blocks::attention(emitter, cfg, m_impl->kv, layer, input.name());
+ return GgufValue(output, emitter.value(output));
+}
+
+GgufValue GgufGraphContext::decoder_ffn(int layer, const GgufValue& input) {
+ m_impl->check_layer(layer);
+ m_impl->value_name(input);
+ const auto& cfg = *m_impl->decoder;
+ auto& emitter = m_impl->emitter;
+ const auto prefix = "blk." + std::to_string(layer) + ".";
+ const auto output = cfg.layer_is_moe(layer) ? blocks::moe_ffn(emitter, cfg, prefix, input.name())
+ : cfg.is_geglu ? blocks::geglu_ffn(emitter, cfg, prefix, input.name())
+ : blocks::dense_ffn(emitter, cfg, prefix, input.name());
+ return GgufValue(output, emitter.value(output));
+}
+
+const std::string& GgufGraphContext::arch() const {
+ return m_impl->build_ctx.arch;
+}
+
+GgufTensors GgufGraphContext::tensors() {
+ return GgufTensors(*this);
+}
+
+// ---- model inputs ----
+
+GgufValue GgufGraphContext::add_input(const std::string& name, ov::element::Type type, const ov::PartialShape& shape) {
+ m_impl->check_open();
+ OPENVINO_ASSERT(shape.rank().is_static() && shape.size() <= 4, "[GGUF] input rank must be known and at most four");
+ auto& e = m_impl->emitter;
+ if (e.has_model_input(name)) {
+ const auto& previous = e.graph()->model_inputs.at(name);
+ OPENVINO_ASSERT(previous->get_output_partial_shape(0) == shape && previous->get_output_element_type(0) == type,
+ "[GGUF] conflicting declarations for input ",
+ name);
+ }
+ if (!e.has_model_input(name)) {
+ OPENVINO_ASSERT(!e.graph()->values->count(name) && !e.has_weight(name),
+ "[GGUF] input name is already used: ",
+ name);
+ e.add_input(name, type, shape);
+ }
+ return GgufValue(name, e.value(name));
+}
+
+GgufValue GgufGraphContext::build_inp_embd(const GgufValue& tok_embd) {
+ OPENVINO_ASSERT(tok_embd, "[GGUF] build_inp_embd: the token embedding weight is missing");
+ auto tokens = add_input("inp_tokens", i32, ov::PartialShape({1, 1, 1, D}));
+ return node("GGML_OP_GET_ROWS", {tok_embd, tokens});
+}
+
+GgufValue GgufGraphContext::build_inp_pos() {
+ return add_input("inp_pos", i32, ov::PartialShape({1, 1, 1, D}));
+}
+
+GgufValue GgufGraphContext::build_inp_out_ids() {
+ return add_input("inp_out_ids", i32, ov::PartialShape({1, 1, 1, D}));
+}
+
+void GgufGraphContext::build_attn_inp_kv(bool swa) {
+ add_input("self_kq_mask", f32, ov::PartialShape({1, 1, D, D}));
+ if (swa || (m_impl->decoder && m_impl->decoder->has_swa)) {
+ add_input("self_kq_mask_swa", f32, ov::PartialShape({1, 1, D, D}));
+ }
+ add_input("inp_kv_idx", i32, ov::PartialShape({1, 1, 1, D}));
+ add_input("token_len_per_seq", i64, ov::PartialShape({1}));
+}
+
+GgufValue GgufGraphContext::node(const std::string& op_type,
+ const std::vector<GgufValue>& inputs,
+ int op_case,
+ const std::map<std::string, ov::Any>& attrs) {
+ m_impl->check_open();
+ std::vector<std::string> names;
+ names.reserve(inputs.size());
+ for (const auto& input : inputs) {
+ names.push_back(m_impl->value_name(input));
+ }
+ const auto name = m_impl->fresh(op_type);
+ m_impl->emitter.add_op(op_type, name, names, op_case, attrs);
+ return GgufValue(name, m_impl->emitter.value(name));
+}
+
+void GgufGraphContext::configure_rope(const RopeConfig& config) {
+ m_impl->check_open();
+ auto& graph = *m_impl->emitter.graph();
+ graph.has_rope = true;
+ graph.rope_config = config;
+ graph.use_per_op_rope = config.per_op;
+}
+
+// Normalization blocks
+
+GgufValue GgufGraphContext::build_norm(const GgufValue& cur, const GgufValue& w, float eps) {
+ auto out = node("GGML_OP_RMS_NORM", {cur}, 0, {{"eps", eps}});
+ return w ? node("GGML_OP_MUL", {out, w}) : out;
+}
+
+GgufValue GgufGraphContext::build_norm_ln(const GgufValue& cur, const GgufValue& w, const GgufValue& b, float eps) {
+ auto out = node("GGML_OP_NORM", {cur}, 0, {{"eps", eps}});
+ if (w) {
+ out = node("GGML_OP_MUL", {out, w});
+ }
+ if (b) {
+ out = node("GGML_OP_ADD", {out, b});
+ }
+ return out;
+}
+
+void GgufGraphContext::set_output(const GgufValue& logits) {
+ m_impl->check_open();
+ m_impl->emitter.graph()->model_output_names.push_back(m_impl->value_name(logits));
+}
+
+void GgufGraphContext::set_sliding_window(int64_t tokens) {
+ m_impl->check_open();
+ OPENVINO_ASSERT(tokens > 0 && tokens <= std::numeric_limits<int>::max(),
+ "[GGUF] sliding window must be a positive int");
+ m_impl->emitter.graph()->swa_window_size = static_cast<int>(tokens);
+}
+
+void GgufGraphContext::add_recurrent_state(const GgufValue& input, const GgufValue& update) {
+ m_impl->check_open();
+ m_impl->value_name(input);
+ m_impl->value_name(update);
+ OPENVINO_ASSERT(m_impl->emitter.has_model_input(input.name()),
+ "[GGUF] recurrent state must refer to a model input and an update");
+ OPENVINO_ASSERT(input.type() == update.type() && input.shape().compatible(update.shape()),
+ "[GGUF] recurrent state input and update must have compatible shapes and equal types");
+ auto& graph = *m_impl->emitter.graph();
+ for (const auto& pair : graph.recurrent_states) {
+ OPENVINO_ASSERT(pair.first != input.name() && pair.second != update.name(),
+ "[GGUF] recurrent state is already registered");
+ }
+ graph.recurrent_states.emplace_back(input.name(), update.name());
+ if (std::find(graph.model_output_names.begin(), graph.model_output_names.end(), update.name()) ==
+ graph.model_output_names.end())
+ set_output(update);
+}
+
+std::shared_ptr<GgufGraph> GgufGraphContext::finish() {
+ m_impl->check_open();
+ const auto graph = m_impl->emitter.graph();
+ OPENVINO_ASSERT(!graph->model_output_names.empty(), "[GGUF] graph has no outputs");
+ std::set<std::string> available;
+ for (const auto& entry : graph->model_inputs)
+ available.insert(entry.first);
+ for (const auto& entry : graph->model_extra_inputs)
+ available.insert(entry.first);
+ for (const auto& node : graph->nodes) {
+ for (const auto& input : node.input_names) {
+ OPENVINO_ASSERT(available.count(input), "[GGUF] node '", node.name, "' uses unknown value '", input, "'");
+ }
+ available.insert(node.output_name);
+ }
+ std::set<std::string> outputs;
+ for (const auto& output : graph->model_output_names) {
+ OPENVINO_ASSERT(available.count(output), "[GGUF] unknown output '", output, "'");
+ OPENVINO_ASSERT(outputs.insert(output).second, "[GGUF] duplicate output '", output, "'");
+ }
+ m_impl->finished = true;
+ return graph;
+}
+
+} // namespace gguf
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/gguf/src/builder/api/graph_context_impl.hpp b/src/frontends/gguf/src/builder/api/graph_context_impl.hpp
new file mode 100644
index 00000000000..01a7efcf95f
--- /dev/null
+++ b/src/frontends/gguf/src/builder/api/graph_context_impl.hpp
@@ -0,0 +1,60 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+// Shared implementation for graph operations and emitting weight lookups.
+
+#pragma once
+
+#include <string>
+
+#include "builder/api/metadata_store.hpp"
+#include "builder/blocks/attention.hpp"
+#include "builder/graph_emitter.hpp"
+#include "openvino/core/except.hpp"
+#include "openvino/frontend/gguf/builder/graph_context.hpp"
+
+namespace ov {
+namespace frontend {
+namespace gguf {
+
+struct GgufGraphContext::Impl {
+ explicit Impl(const BuildContext& ctx)
+ : build_ctx(ctx),
+ emitter(ctx.weights->weights, ctx.weights->qtypes, ctx.arch, ctx.weights->translators) {}
+
+ BuildContext build_ctx;
+ std::unique_ptr<DecoderConfig> decoder;
+ blocks::KvCachePlan kv;
+ bool finished = false;
+ void check_open() const {
+ OPENVINO_ASSERT(!finished, "[GGUF] graph is already finished");
+ }
+ void check_layer(int layer) const {
+ check_open();
+ OPENVINO_ASSERT(decoder, "[GGUF] call configure_decoder before using decoder blocks");
+ OPENVINO_ASSERT(layer >= 0 && layer < decoder->n_layer, "[GGUF] decoder layer is out of range");
+ }
+ const std::string& value_name(const GgufValue& value) const {
+ OPENVINO_ASSERT(value, "[GGUF] builder received an empty value");
+ OPENVINO_ASSERT(emitter.value(value.name()) == value.m_value,
+ "[GGUF] value '",
+ value.name(),
+ "' does not belong to this graph");
+ return value.name();
+ }
+ GraphEmitter emitter;
+
+ // Generate unique names for builder operations. Shared decoder blocks use layer prefixes.
+ int seq = 0;
+ std::string fresh(const std::string& op) {
+ std::string name;
+ do {
+ name = op + "_" + std::to_string(seq++);
+ } while (emitter.graph()->values->count(name) || emitter.has_weight(name));
+ return name;
+ }
+};
+
+} // namespace gguf
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/gguf/src/builder/api/metadata.cpp b/src/frontends/gguf/src/builder/api/metadata.cpp
new file mode 100644
index 00000000000..94802c4d08a
--- /dev/null
+++ b/src/frontends/gguf/src/builder/api/metadata.cpp
@@ -0,0 +1,106 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/frontend/gguf/builder/metadata.hpp"
+
+#include <type_traits>
+
+#include "builder/api/metadata_store.hpp"
+#include "openvino/op/constant.hpp"
+
+namespace ov::frontend::gguf {
+namespace {
+
+const GGUFMetaData* find(const detail::MetadataStore& store, const std::string& key) {
+ const auto it = store.map.find(key);
+ return it == store.map.end() ? nullptr : &it->second;
+}
+
+template <typename T>
+std::vector<T> tensor_values(const ov::Tensor& tensor) {
+ const auto type = tensor.get_element_type();
+ // Keep typed reads strict; OpenVINO handles numeric widths and element conversion.
+ if (type == ov::element::string || type.is_dynamic() ||
+ (!type.is_integral() && !(std::is_floating_point_v<T> && type.is_real())))
+ return {};
+ return ov::op::v0::Constant(tensor).cast_vector<T>();
+}
+
+template <typename T>
+std::optional<T> number(const GGUFMetaData* value) {
+ if (!value)
+ return std::nullopt;
+ if (const auto* v = std::get_if<int>(value))
+ return static_cast<T>(*v);
+ if constexpr (std::is_floating_point_v<T>) {
+ if (const auto* v = std::get_if<float>(value))
+ return static_cast<T>(*v);
+ }
+ if (const auto* t = std::get_if<ov::Tensor>(value); t && t->get_size() == 1) {
+ const auto values = tensor_values<T>(*t);
+ if (!values.empty())
+ return values.front();
+ }
+ return std::nullopt;
+}
+
+template <typename T>
+std::optional<T> stored_value(const GGUFMetaData* value) {
+ if (value)
+ if (const auto* v = std::get_if<T>(value))
+ return *v;
+ return std::nullopt;
+}
+
+template <typename T>
+std::vector<T> array(const GGUFMetaData* value) {
+ if (value)
+ if (const auto* t = std::get_if<ov::Tensor>(value))
+ return tensor_values<T>(*t);
+ return {};
+}
+} // namespace
+
+bool GgufMetadata::has(const std::string& key) const {
+ return find(*m_store, key) != nullptr;
+}
+
+std::optional<int64_t> GgufMetadata::get_int(const std::string& key) const {
+ return number<int64_t>(find(*m_store, key));
+}
+
+std::optional<double> GgufMetadata::get_float(const std::string& key) const {
+ return number<double>(find(*m_store, key));
+}
+
+std::optional<bool> GgufMetadata::get_bool(const std::string& key) const {
+ if (auto i = get_int(key))
+ return *i != 0;
+ return std::nullopt;
+}
+
+std::optional<std::string> GgufMetadata::get_str(const std::string& key) const {
+ return stored_value<std::string>(find(*m_store, key));
+}
+
+std::vector<int64_t> GgufMetadata::get_int_array(const std::string& key) const {
+ const auto* value = find(*m_store, key);
+ if (const auto v = stored_value<std::vector<int32_t>>(value))
+ return {v->begin(), v->end()};
+ return array<int64_t>(value);
+}
+
+std::vector<double> GgufMetadata::get_float_array(const std::string& key) const {
+ return array<double>(find(*m_store, key));
+}
+
+std::vector<std::string> GgufMetadata::get_str_array(const std::string& key) const {
+ return stored_value<std::vector<std::string>>(find(*m_store, key)).value_or(std::vector<std::string>{});
+}
+
+std::string GgufMetadata::architecture() const {
+ return get_str("general.architecture").value_or("");
+}
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/api/metadata_store.hpp b/src/frontends/gguf/src/builder/api/metadata_store.hpp
new file mode 100644
index 00000000000..504f417e7d8
--- /dev/null
+++ b/src/frontends/gguf/src/builder/api/metadata_store.hpp
@@ -0,0 +1,46 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+// Internal storage behind the opaque metadata and weight views.
+
+#pragma once
+
+#include <map>
+#include <string>
+#include <unordered_map>
+
+#include "node_context.hpp"
+#include "openvino/frontend/gguf/builder/metadata.hpp"
+#include "openvino/runtime/tensor.hpp"
+#include "quant/gguf.hpp"
+
+namespace ov {
+namespace frontend {
+namespace gguf {
+
+class GraphEmitter;
+
+namespace detail {
+
+// The parsed KV metadata, behind GgufMetadata.
+struct MetadataStore {
+ const std::unordered_map<std::string, GGUFMetaData>& map;
+};
+
+struct MetadataAccess {
+ static const MetadataStore& get(const GgufMetadata& metadata) {
+ return *metadata.m_store;
+ }
+};
+
+// Borrowed parser weight and quantization tables.
+struct WeightStore {
+ std::unordered_map<std::string, ov::Tensor>& weights;
+ std::unordered_map<std::string, GgufTensorType>& qtypes;
+ const std::unordered_map<std::string, CreatorFunction>* translators = nullptr;
+};
+
+} // namespace detail
+} // namespace gguf
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/gguf/src/builder/api/tensor_table.cpp b/src/frontends/gguf/src/builder/api/tensor_table.cpp
new file mode 100644
index 00000000000..e49aa338ce7
--- /dev/null
+++ b/src/frontends/gguf/src/builder/api/tensor_table.cpp
@@ -0,0 +1,70 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/frontend/gguf/builder/tensor_table.hpp"
+
+#include "builder/api/graph_context_impl.hpp"
+#include "openvino/core/except.hpp"
+#include "openvino/frontend/gguf/builder/graph_context.hpp"
+#include "openvino/frontend/gguf/builder/model_builder.hpp"
+#include "openvino/frontend/gguf/builder/value.hpp"
+#include "openvino/util/common_util.hpp"
+
+namespace ov {
+namespace frontend {
+namespace gguf {
+
+int64_t GgufValue::ne(size_t i) const {
+ if (empty() || shape().rank().is_dynamic()) {
+ return -1;
+ }
+ const size_t rank = shape().size();
+ if (i >= rank) {
+ return 1;
+ }
+ const auto& d = shape()[rank - 1 - i];
+ return d.is_static() ? d.get_length() : -1;
+}
+
+ModelBuilder::~ModelBuilder() = default;
+
+bool GgufTensors::has(const std::string& gguf_name) const {
+ return (*m_ctx->m_impl).emitter.has_weight(gguf_name);
+}
+
+GgufValue GgufTensors::operator()(const std::string& gguf_name) const {
+ auto& impl = (*m_ctx->m_impl);
+ auto& e = impl.emitter;
+ if (!e.has_weight(gguf_name)) {
+ return GgufValue();
+ }
+ impl.check_open();
+ if (!e.weight_emitted(gguf_name)) {
+ if (ov::util::ends_with(gguf_name, ".weight")) {
+ e.add_weight(gguf_name);
+ } else {
+ e.add_named_weight(gguf_name);
+ }
+ }
+ return GgufValue(gguf_name, e.value(gguf_name));
+}
+
+GgufValue GgufTensors::require(const std::string& gguf_name) const {
+ auto v = (*this)(gguf_name);
+ OPENVINO_ASSERT(v,
+ "[GGUF] model is missing expected weight tensor '",
+ gguf_name,
+ "' for architecture '",
+ m_ctx->arch(),
+ "'");
+ return v;
+}
+
+GgufValue GgufTensors::layer(int il, const std::string& suffix) const {
+ return (*this)("blk." + std::to_string(il) + "." + suffix);
+}
+
+} // namespace gguf
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/gguf/src/builder/arch/decoder_builder.cpp b/src/frontends/gguf/src/builder/arch/decoder_builder.cpp
index dafcfb278dc..e33f0444ad6 100644
--- a/src/frontends/gguf/src/builder/arch/decoder_builder.cpp
+++ b/src/frontends/gguf/src/builder/arch/decoder_builder.cpp
@@ -37,9 +37,12 @@ constexpr int64_t D = -1;
DecoderBuilder::DecoderBuilder(const std::map<std::string, GGUFMetaData>& config,
std::unordered_map<std::string, ov::Tensor>& weights,
- std::unordered_map<std::string, GgufTensorType>& qtypes)
- : m_cfg(config, weights),
- m_emit(weights, qtypes, m_cfg.arch),
+ std::unordered_map<std::string, GgufTensorType>& qtypes,
+ std::optional<RopeMode> rope,
+ const DecoderOptions& options,
+ const std::unordered_map<std::string, CreatorFunction>* translators)
+ : m_cfg(config, weights, rope, options),
+ m_emit(weights, qtypes, m_cfg.arch, translators),
m_kv(blocks::KvCachePlan::build(m_cfg)) {
auto& graph = *m_emit.graph();
graph.has_rope = true;
@@ -68,7 +71,6 @@ void DecoderBuilder::build_inputs() {
// 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}));
- m_emit.set_tensor_meta("inp_kv_idx", ps({1, 1, 1, T}), i32);
// 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.
@@ -81,12 +83,7 @@ void DecoderBuilder::build_inputs() {
std::string DecoderBuilder::build_embeddings() {
// GET_ROWS(token_embd.weight, inp_tokens) -> "embd"
m_emit.add_weight("token_embd.weight");
- m_emit.set_tensor_meta("inp_tokens", ps({1, 1, 1, T}), i32);
- std::string cur = m_emit.add_op("GGML_OP_GET_ROWS",
- "embd",
- {"token_embd.weight", "inp_tokens"},
- ps({1, 1, T, m_cfg.n_embd}),
- f32);
+ std::string cur = m_emit.add_op("GGML_OP_GET_ROWS", "embd", {"token_embd.weight", "inp_tokens"});
// MiniCPM scales the embeddings by a constant.
if (m_cfg.embedding_scale != 1.0f) {
cur = blocks::scale(m_emit, cur, m_cfg.embedding_scale, "embd_scaled");
@@ -94,13 +91,7 @@ std::string DecoderBuilder::build_embeddings() {
// 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) {
- cur = m_emit.add_op("GGML_OP_RMS_NORM",
- "embd_normed",
- {cur},
- m_emit.shape_of_tensor(cur),
- f32,
- 0,
- {{"eps", m_cfg.rms_eps}});
+ cur = m_emit.add_op("GGML_OP_RMS_NORM", "embd_normed", {cur}, 0, {{"eps", m_cfg.rms_eps}});
}
return cur;
}
@@ -132,34 +123,28 @@ void DecoderBuilder::build_per_layer_embeddings(const std::string& embd) {
// CONT node: translate_cont's PERMUTE case is a pass-through, since translate_permute already
// emitted a real Transpose, so ggml's ggml_cont would convert to nothing here.
auto reshape_to_layer_major = [&](const std::string& flat, const std::string& name) {
- const auto& flat_shape = m_emit.shape_of_tensor(flat);
- const int64_t t = flat_shape[2].is_static() ? flat_shape[2].get_length() : 1;
- auto split = m_emit.add_op("GGML_OP_RESHAPE", name + "_split", {flat}, ps({1, t, n_layer, pe}), f32, 1);
- return m_emit.add_op("GGML_OP_PERMUTE", name, {split}, ps({1, n_layer, t, pe}), f32, 1);
+ auto split =
+ m_emit.add_op("GGML_OP_RESHAPE",
+ name + "_split",
+ {flat},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{0, -1, n_layer, pe}}, {"special_zero", true}});
+ return m_emit.add_op("GGML_OP_PERMUTE", name, {split}, 1);
};
m_emit.add_weight("per_layer_token_embd.weight");
m_emit.add_weight("per_layer_model_proj.weight");
m_emit.add_weight("per_layer_proj_norm.weight");
- const int pe_total = pe * n_layer;
// Token embedding lookup: [1,1,T, pe_total] -> reshape to [1, n_layer, T, pe]
- auto pe_flat = m_emit.add_op("GGML_OP_GET_ROWS",
- "pe_tok_flat",
- {"per_layer_token_embd.weight", "inp_tokens"},
- ps({1, 1, T, pe_total}),
- f32);
+ 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");
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]
// per_layer_model_proj is [n_embd, pe_total] -> output [pe_total] per token
- auto proj_flat = m_emit.add_op("GGML_OP_MUL_MAT",
- "pe_proj_flat",
- {"per_layer_model_proj.weight", embd},
- ps({1, 1, T, pe_total}),
- f32);
+ auto proj_flat = m_emit.add_op("GGML_OP_MUL_MAT", "pe_proj_flat", {"per_layer_model_proj.weight", embd});
const float proj_scale = 1.0f / std::sqrt(static_cast<float>(m_cfg.n_embd));
proj_flat = blocks::scale(m_emit, proj_flat, proj_scale, "pe_proj_flat_scaled");
@@ -167,30 +152,13 @@ void DecoderBuilder::build_per_layer_embeddings(const std::string& embd) {
auto proj_4d = reshape_to_layer_major(proj_flat, "pe_proj_4d");
// RMS_NORM + per_layer_proj_norm weight (applied over last dim = pe)
- auto proj_norm = m_emit.add_op("GGML_OP_RMS_NORM",
- "pe_proj_rms",
- {proj_4d},
- ps({1, n_layer, T, pe}),
- f32,
- 0,
- {{"eps", m_cfg.rms_eps}});
- m_emit.set_tensor_meta("per_layer_proj_norm.weight", ps({1, 1, 1, pe}), f32);
- auto proj_normed = m_emit.add_op("GGML_OP_MUL",
- "pe_proj_normed",
- {proj_norm, "per_layer_proj_norm.weight"},
- ps({1, n_layer, T, pe}),
- f32);
+ auto proj_norm = m_emit.add_op("GGML_OP_RMS_NORM", "pe_proj_rms", {proj_4d}, 0, {{"eps", m_cfg.rms_eps}});
+ auto proj_normed = m_emit.add_op("GGML_OP_MUL", "pe_proj_normed", {proj_norm, "per_layer_proj_norm.weight"});
// Sum token embd + projection, scale by 1/sqrt(2)
- auto pe_sum = m_emit.add_op("GGML_OP_ADD", "pe_sum", {proj_normed, pe_tok}, ps({1, n_layer, T, pe}), f32);
+ auto pe_sum = m_emit.add_op("GGML_OP_ADD", "pe_sum", {proj_normed, pe_tok});
const float inv_sqrt2 = 1.0f / std::sqrt(2.0f);
- m_emit.add_op("GGML_OP_SCALE",
- "per_layer_embd",
- {pe_sum},
- ps({1, n_layer, T, pe}),
- f32,
- 0,
- {{"scale", inv_sqrt2}, {"bias", 0.0f}});
+ m_emit.add_op("GGML_OP_SCALE", "per_layer_embd", {pe_sum}, 0, {{"scale", inv_sqrt2}, {"bias", 0.0f}});
}
std::string DecoderBuilder::inject_per_layer_embedding(int il, const std::string& cur, const std::string& inpSA) {
@@ -199,7 +167,6 @@ std::string DecoderBuilder::inject_per_layer_embedding(int il, const std::string
// per-layer slice, projects back to n_embd, post-norms, then adds residual.
// per_layer_token_embd (global) is pre-projected before the loop.
const std::string p = "blk." + std::to_string(il) + ".";
- const int pe = m_cfg.n_embd_per_layer;
// Slice out this layer's [1,1,T,pe] chunk (dim 1 at index il). The second input is passed
// purely as a shape reference: per_layer_embd is stored layer-major, so the slice's token axis
@@ -216,8 +183,6 @@ std::string DecoderBuilder::inject_per_layer_embedding(int il, const std::string
m_emit.add_op("GGML_OP_VIEW",
pl_slice,
{"per_layer_embd", pl_shape_ref},
- ps({1, 1, T, pe}),
- f32,
104, // layer-index slice using the "layer_idx" attribute
{{"layer_idx", int64_t(il)}});
@@ -227,26 +192,24 @@ std::string DecoderBuilder::inject_per_layer_embedding(int il, const std::string
std::string pl_slice_used = pl_slice;
if (il == m_cfg.n_layer - 1) {
pl_slice_used = p + "per_layer_slice_sel";
- m_emit.add_op("GGML_OP_GET_ROWS", pl_slice_used, {pl_slice, "inp_out_ids"}, ps({1, 1, T, pe}), f32);
+ m_emit.add_op("GGML_OP_GET_ROWS", pl_slice_used, {pl_slice, "inp_out_ids"});
}
// gate: cur -> inp_gate.weight -> GELU -> [1,1,T,pe]
m_emit.add_weight(p + "inp_gate.weight");
- auto gated =
- m_emit.add_op("GGML_OP_MUL_MAT", p + "inp_gate_mm", {p + "inp_gate.weight", cur}, ps({1, 1, T, pe}), f32);
- gated = m_emit.add_op("GGML_UNARY_OP_GELU", p + "inp_gate_gelu", {gated}, ps({1, 1, T, pe}), f32);
+ auto gated = m_emit.add_op("GGML_OP_MUL_MAT", p + "inp_gate_mm", {p + "inp_gate.weight", cur});
+ gated = m_emit.add_op("GGML_UNARY_OP_GELU", p + "inp_gate_gelu", {gated});
// elementwise multiply by per-layer slice
- auto mul_pe = m_emit.add_op("GGML_OP_MUL", p + "pe_mul", {gated, pl_slice_used}, ps({1, 1, T, pe}), f32);
+ auto mul_pe = m_emit.add_op("GGML_OP_MUL", p + "pe_mul", {gated, pl_slice_used});
// project back to n_embd
m_emit.add_weight(p + "proj.weight");
- auto pe_proj =
- m_emit.add_op("GGML_OP_MUL_MAT", p + "pe_proj", {p + "proj.weight", mul_pe}, ps({1, 1, T, m_cfg.n_embd}), f32);
+ auto pe_proj = m_emit.add_op("GGML_OP_MUL_MAT", p + "pe_proj", {p + "proj.weight", mul_pe});
// post-norm + residual add
pe_proj = blocks::rms_norm(m_emit, pe_proj, p + "post_norm.weight", p + "pe_post_norm", m_cfg.rms_eps);
- return m_emit.add_op("GGML_OP_ADD", p + "pe_out", {cur, pe_proj}, ps({1, 1, T, m_cfg.n_embd}), f32);
+ return m_emit.add_op("GGML_OP_ADD", p + "pe_out", {cur, pe_proj});
}
std::string DecoderBuilder::build_layer(int il, const std::string& layer_in) {
@@ -258,44 +221,35 @@ std::string DecoderBuilder::build_layer(int il, const std::string& layer_in) {
// (muse-glimmer's post-norms use a tighter 1e-8 than its pre-norms).
const float post_eps = m_cfg.post_norm_eps > 0.0f ? m_cfg.post_norm_eps : m_cfg.rms_eps;
- // attn_norm (key varies by arch: "attn_norm.weight" for most, "post_attention_norm.weight"
- // for exaone4)
const std::string attn_norm =
- 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
+ : blocks::rms_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.
// It produces the same thing the attention path does -- the sublayer output before
// the residual -- so the shared FFN tail below is reused verbatim.
- const std::string gdn_out = blocks::gated_delta_net(m_emit, m_cfg, il, attn_norm, T);
+ 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) {
- ao = m_emit.add_op("GGML_OP_GET_ROWS",
- p + "attn_out_g",
- {gdn_out, "inp_out_ids"},
- ps({1, 1, T, m_cfg.n_embd}),
- f32);
- sa = m_emit.add_op("GGML_OP_GET_ROWS",
- p + "inpSA_g",
- {inpSA, "inp_out_ids"},
- ps({1, 1, T, m_cfg.n_embd}),
- f32);
+ 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"});
}
- auto ffn_inp_r = m_emit.add_op("GGML_OP_ADD", p + "ffn_inp", {ao, sa}, ps({1, 1, T, m_cfg.n_embd}), f32);
+ auto ffn_inp_r = m_emit.add_op("GGML_OP_ADD", p + "ffn_inp", {ao, sa});
auto ffn_norm_r = blocks::rms_norm(m_emit, ffn_inp_r, p + m_cfg.ffn_norm_key, p + "ffn_norm", m_cfg.rms_eps);
// Mirror the non-recurrent FFN dispatch below: Qwen3-Next is MoE for every trunk layer
// (llama.cpp routes both the GDN and full-attention layers through build_moe_ffn), so a
// real model has no per-layer dense FFN tensors here and dense_ffn's weight_tensor lookup
// would assert.
- const bool is_moe_layer_r = m_cfg.is_moe && (il >= m_cfg.n_dense_lead);
- auto down_r = is_moe_layer_r ? blocks::moe_ffn(m_emit, m_cfg, p, ffn_norm_r, T)
- : m_cfg.is_geglu ? blocks::geglu_ffn(m_emit, m_cfg, p, ffn_norm_r, T)
- : blocks::dense_ffn(m_emit, m_cfg, p, ffn_norm_r, T);
- return m_emit.add_op("GGML_OP_ADD", p + "l_out", {down_r, ffn_inp_r}, ps({1, 1, T, m_cfg.n_embd}), f32);
+ const bool is_moe_layer_r = m_cfg.layer_is_moe(il);
+ auto down_r = is_moe_layer_r ? blocks::moe_ffn(m_emit, m_cfg, p, ffn_norm_r)
+ : m_cfg.is_geglu ? blocks::geglu_ffn(m_emit, m_cfg, p, ffn_norm_r)
+ : blocks::dense_ffn(m_emit, m_cfg, p, ffn_norm_r);
+ return m_emit.add_op("GGML_OP_ADD", p + "l_out", {down_r, ffn_inp_r});
}
- std::string attn_out = blocks::attention(m_emit, m_cfg, m_kv, il, attn_norm, T);
+ std::string attn_out = blocks::attention(m_emit, m_cfg, m_kv, il, attn_norm);
// MiniCPM scales the attention sublayer output before the residual add.
if (m_cfg.residual_scale != 1.0f) {
@@ -304,12 +258,8 @@ 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) {
- ao = m_emit.add_op("GGML_OP_GET_ROWS",
- p + "attn_out_g",
- {attn_out, "inp_out_ids"},
- ps({1, 1, T, m_cfg.n_embd}),
- f32);
- sa = m_emit.add_op("GGML_OP_GET_ROWS", p + "inpSA_g", {inpSA, "inp_out_ids"}, ps({1, 1, T, m_cfg.n_embd}), f32);
+ 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.
@@ -317,16 +267,18 @@ std::string DecoderBuilder::build_layer(int il, const std::string& layer_in) {
ao = blocks::rms_norm(m_emit, ao, p + "post_attention_norm.weight", p + "attn_post_norm", post_eps);
}
- auto ffn_inp = m_emit.add_op("GGML_OP_ADD", p + "ffn_inp", {ao, sa}, ps({1, 1, T, m_cfg.n_embd}), f32);
+ 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 = 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
+ : blocks::rms_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.is_moe && (il >= m_cfg.n_dense_lead);
- std::string down = is_moe_layer ? blocks::moe_ffn(m_emit, m_cfg, p, ffn_norm, T)
- : m_cfg.is_geglu ? blocks::geglu_ffn(m_emit, m_cfg, p, ffn_norm, T)
- : blocks::dense_ffn(m_emit, m_cfg, p, ffn_norm, T);
+ 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)
+ : 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.
if (m_cfg.residual_scale != 1.0f) {
down = blocks::scale(m_emit, down, m_cfg.residual_scale, p + "ffn_out_scaled");
@@ -336,7 +288,7 @@ std::string DecoderBuilder::build_layer(int il, const std::string& layer_in) {
down = blocks::rms_norm(m_emit, down, p + "post_ffw_norm.weight", p + "ffn_post_norm", post_eps);
}
- cur = m_emit.add_op("GGML_OP_ADD", p + "l_out", {down, ffn_inp}, ps({1, 1, T, m_cfg.n_embd}), f32);
+ cur = m_emit.add_op("GGML_OP_ADD", p + "l_out", {down, ffn_inp});
if (m_cfg.n_embd_per_layer > 0) {
cur = inject_per_layer_embedding(il, cur, inpSA);
@@ -345,11 +297,7 @@ std::string DecoderBuilder::build_layer(int il, const std::string& layer_in) {
// Gemma4: per-layer output scale (layer_output_scale.weight is a scalar [1]).
if (m_emit.has_weight(p + "layer_output_scale.weight")) {
m_emit.add_named_weight(p + "layer_output_scale.weight");
- cur = m_emit.add_op("GGML_OP_MUL",
- p + "scaled_out",
- {cur, p + "layer_output_scale.weight"},
- m_emit.shape_of_tensor(cur),
- f32);
+ cur = m_emit.add_op("GGML_OP_MUL", p + "scaled_out", {cur, p + "layer_output_scale.weight"});
}
return cur;
}
@@ -360,8 +308,7 @@ std::string DecoderBuilder::build_head(const std::string& in) {
const std::string lm_head_w = m_emit.has_weight("output.weight") ? "output.weight" : "token_embd.weight";
m_emit.add_weight(lm_head_w);
- const int n_vocab = static_cast<int>(m_emit.weight_tensor(lm_head_w).get_shape()[0]); // rows = vocab
- auto logits = m_emit.add_op("GGML_OP_MUL_MAT", "result_output", {lm_head_w, cur}, ps({1, 1, T, n_vocab}), f32);
+ auto logits = m_emit.add_op("GGML_OP_MUL_MAT", "result_output", {lm_head_w, cur});
// MiniCPM scales the logits (1/(n_embd/dim_model_base)).
if (m_cfg.logit_scale != 1.0f) {
logits = blocks::scale(m_emit, logits, m_cfg.logit_scale, "result_output_scaled");
@@ -369,8 +316,7 @@ std::string DecoderBuilder::build_head(const std::string& in) {
// Gemma2/Gemma3 final logit soft-cap: tanh(logits / cap) * cap.
if (m_cfg.final_logit_soft_cap != 0.0f) {
logits = blocks::scale(m_emit, logits, 1.0f / m_cfg.final_logit_soft_cap, "logits_softcap_scaled");
- logits =
- m_emit.add_op("GGML_UNARY_OP_TANH", "logits_softcap_tanh", {logits}, m_emit.shape_of_tensor(logits), f32);
+ logits = m_emit.add_op("GGML_UNARY_OP_TANH", "logits_softcap_tanh", {logits});
logits = blocks::scale(m_emit, logits, m_cfg.final_logit_soft_cap, "result_output_softcapped");
}
return logits;
diff --git a/src/frontends/gguf/src/builder/arch/decoder_builder.hpp b/src/frontends/gguf/src/builder/arch/decoder_builder.hpp
index 9d4e5ec7789..a19c919a64f 100644
--- a/src/frontends/gguf/src/builder/arch/decoder_builder.hpp
+++ b/src/frontends/gguf/src/builder/arch/decoder_builder.hpp
@@ -9,10 +9,11 @@
#include <string>
#include <unordered_map>
+#include "builder/arch_registry.hpp"
#include "builder/blocks/attention.hpp"
#include "builder/decoder_config.hpp"
#include "builder/graph_emitter.hpp"
-#include "builder/model_builder.hpp"
+#include "openvino/frontend/gguf/builder/model_builder.hpp"
#include "quant/gguf.hpp"
namespace ov {
@@ -36,7 +37,10 @@ class DecoderBuilder : public ModelBuilder {
public:
DecoderBuilder(const std::map<std::string, GGUFMetaData>& config,
std::unordered_map<std::string, ov::Tensor>& weights,
- std::unordered_map<std::string, GgufTensorType>& qtypes);
+ std::unordered_map<std::string, GgufTensorType>& qtypes,
+ std::optional<RopeMode> rope = {},
+ const DecoderOptions& options = {},
+ const std::unordered_map<std::string, CreatorFunction>* translators = nullptr);
std::shared_ptr<GgufGraph> build() override;
@@ -62,12 +66,6 @@ private:
DecoderConfig m_cfg;
GraphEmitter m_emit;
blocks::KvCachePlan m_kv;
-
- // Per-node output shapes are STATIC, like the cgraph decoder (which builds the graph for a
- // concrete token length). We use a representative token length T; the translators emit dynamic
- // reshapes (-1 / 0) where needed, and MakeStateful + the dynamic input Parameters carry the
- // real dynamic-ness. T affects only the per-node shape metadata.
- static constexpr int64_t T = 1;
};
} // namespace gguf
diff --git a/src/frontends/gguf/src/builder/arch_registry.cpp b/src/frontends/gguf/src/builder/arch_registry.cpp
index 400271d1a76..5a22493a60c 100644
--- a/src/frontends/gguf/src/builder/arch_registry.cpp
+++ b/src/frontends/gguf/src/builder/arch_registry.cpp
@@ -1,97 +1,138 @@
// Copyright (C) 2018-2026 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
-// The native builder's architecture accept list, and the one per-architecture property that
-// cannot be derived from the GGUF tensor table (the RoPE mode).
-//
-// Adding a same-family architecture is a one-line change here and nothing else: the decoder
-// builder derives everything else -- QK-norm, biases, fused QKV, MoE routing, SWA, soft-caps --
-// from the tensor table and metadata. See docs/adding_an_architecture.md.
#include "arch_registry.hpp"
-namespace ov {
-namespace frontend {
-namespace gguf {
+#include "openvino/core/except.hpp"
+
+namespace ov::frontend::gguf {
+
+namespace {
+struct DecoderEntry {
+ const char* name;
+ RopeMode rope;
+ Maturity maturity;
+};
+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},
+};
+} // 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));
+ }
+ // Add custom definitions here; their factories and builders are shared with external plugins.
+ return definitions;
+}
bool arch_uses_neox_rope(const std::string& arch) {
- return arch == "qwen2" || arch == "qwen3" || arch == "phi3" || arch == "hunyuan-dense" || arch == "gpt-oss" ||
- arch == "gemma" || arch == "gemma2" || arch == "gemma3" || arch == "gemma4" || arch == "olmoe" ||
- // H2 2025 dense additions
- arch == "exaone4" || arch == "plamo3" || arch == "mellum" ||
- // H2 2025 MoE additions
- arch == "hunyuan-moe" || arch == "glm4moe" || arch == "bailingmoe2" || arch == "exaone-moe" ||
- arch == "minimax-m2" ||
- // H2 2025 VL backbone / other
- arch == "jais2" || arch == "deepseek2-ocr";
+ for (const auto& entry : decoders) {
+ if (arch == entry.name)
+ return entry.rope == RopeMode::Neox;
+ }
+ return false;
}
const std::set<std::string>& verified_archs() {
- static const std::set<std::string> archs = {
- "llama", // llama-2 / llama-3
- "qwen2", // qwen2 / qwen2.5
- "qwen3",
- "phi3", // phi-3 (fused QKV)
- "minicpm", // NORMAL rope + scalar scales
- "hunyuan-dense", // NEOX rope + per-head QK-norm after RoPE
- "olmoe", // OLMoE 1B-7B (MoE)
- // Qwen3.5/3.6 hybrid: Gated-DeltaNet linear attention on 3 of every 4 layers, full
- // attention with M-RoPE and an interleaved query+gate projection on the rest. Verified
- // token-exact against llama.cpp on Qwen3.5-0.8B-Q8_0 and Ternary-Bonsai-27B-Q2_g64.
- // GREEDY / BATCH 1 ONLY: the recurrent conv and delta states are not reordered by
- // beam_idx and have a static batch of 1, so beam search or batch > 1 fails at inference
- // (a Concat shape mismatch on the conv window) rather than producing wrong output.
- "qwen35",
- "gpt-oss", // MoE + sinks + SWA
- "gemma3", // Gemma 3: post-norms + final logit soft-cap
- "gemma4", // Gemma 4: SWA, per-layer embeddings, shared KV
- };
- return archs;
+ static const auto names = [] {
+ std::set<std::string> result;
+ for (const auto& entry : decoders)
+ if (entry.maturity == Maturity::Verified)
+ result.insert(entry.name);
+ return result;
+ }();
+ return names;
}
const std::set<std::string>& experimental_archs() {
- static const std::set<std::string> archs = {
- // H2 2025: dense
- "llama-embed", // Bidirectional LLaMA (embedding, no causal mask)
- "exaone4", // EXAONE 4.0: NEOX rope, post-norms (attn+ffn)
- "plamo3", // PLaMo-3: NEOX rope, post-norms (attn+ffn)
- "smollm3", // SmolLM3: NORMAL rope + SWA
- // H2 2025: MoE
- "hunyuan-moe", // Hunyuan MoE: NEOX rope, MoE routing, QK-norm
- "glm4moe", // GLM 4.5 MoE: NEOX rope, 1 dense lead layer, MoE + attn post-norm
- "exaone-moe", // EXAONE MoE: NEOX rope, SWA + MoE, shared expert
- "minimax-m2", // Minimax M2: NEOX rope, pure MoE
- "ernie4_5-moe", // Ernie 4.5 MoE: NORMAL rope, dense lead layers + MoE stride
- "bailingmoe2", // BailingMoe V2: NEOX rope, MoE + shared expert + QK-norm
- // 2026: dense
- "maincoder", // Maincoder-1B: NORMAL rope, QK-norm (auto-detected)
- "mistral3", // Ministral-3B: NORMAL rope, dense
- "muse-glimmer", // Muse Glimmer (Meta Onyx): NORMAL rope on SWA layers only (global
- // layers are NoPE), sigmoid attention output gate, QK-norm,
- // pre+post norms, final logit soft-cap
- // 2026: MoE
- "mellum", // JetBrains Mellum: NEOX rope, pure MoE
- "deepseek2-ocr", // DeepSeekOCR: NEOX rope, dense lead layers + MoE
- "jais2", // JAIS-2: NEOX rope, dense (biases auto-detected)
- // Demoted from verified_archs(): the GenAI-vs-llama.cpp measured status (see
- // docs/supported_models.md) found these produce degenerate output (or, for `gemma`,
- // throw) through the native builder despite passing conversion. Re-promote once fixed.
- "qwen3moe", // Qwen3 MoE: same topology as olmoe
- "gemma", // Gemma 2B / 7B
- "gemma2", // Gemma 2: post-norms + attention soft-cap
- };
- return archs;
+ static const auto names = [] {
+ std::set<std::string> result;
+ for (const auto& entry : decoders)
+ if (entry.maturity == Maturity::Experimental)
+ result.insert(entry.name);
+ return result;
+ }();
+ return names;
}
const std::set<std::string>& supported_archs() {
- static const std::set<std::string> archs = [] {
- std::set<std::string> a = verified_archs();
- a.insert(experimental_archs().begin(), experimental_archs().end());
- return a;
+ static const auto names = [] {
+ auto result = verified_archs();
+ result.insert(experimental_archs().begin(), experimental_archs().end());
+ return result;
}();
- return archs;
+ return names;
+}
+
+ArchRegistry::ArchRegistry(std::vector<ArchitectureDefinition> definitions) {
+ for (auto& definition : definitions)
+ add(std::move(definition), RegistrationMode::Add);
+}
+
+void ArchRegistry::add(ArchitectureDefinition definition, RegistrationMode mode) {
+ OPENVINO_ASSERT(!definition.id.empty() && !definition.architecture.empty(),
+ "[GGUF] architecture definition requires a handler id and architecture name");
+ OPENVINO_ASSERT(definition.factory, "[GGUF] architecture '", definition.id, "' has no builder factory");
+ const auto existing = m_definitions.find(definition.id);
+ if (mode == RegistrationMode::Add) {
+ OPENVINO_ASSERT(existing == m_definitions.end(),
+ "[GGUF] duplicate architecture handler '",
+ definition.id,
+ "'; use RegistrationMode::Replace to replace it explicitly");
+ } else {
+ OPENVINO_ASSERT(existing != m_definitions.end(),
+ "[GGUF] cannot replace unknown architecture handler '",
+ definition.id,
+ "'");
+ }
+ const auto id = definition.id;
+ m_definitions[id] = std::make_shared<const ArchitectureDefinition>(std::move(definition));
+}
+
+void ArchRegistry::add_extension(const ArchitectureExtension::Ptr& ext) {
+ OPENVINO_ASSERT(ext, "[GGUF] null ArchitectureExtension");
+ add(ext->definition(), ext->registration_mode());
+}
+
+std::shared_ptr<const ArchitectureDefinition> ArchRegistry::find(const GgufMetadata& meta) const {
+ std::shared_ptr<const ArchitectureDefinition> found;
+ for (const auto& [id, definition] : m_definitions) {
+ if (!definition->matches(meta))
+ continue;
+ OPENVINO_ASSERT(!found, "[GGUF] architecture handlers '", found->id, "' and '", id, "' both claim this file");
+ found = definition;
+ }
+ return found;
+}
+
+std::string ArchRegistry::describe_supported() const {
+ std::string out;
+ for (const auto& [id, definition] : m_definitions) {
+ out += (out.empty() ? "" : ", ") + id;
+ }
+ return out;
+}
+
+const ArchRegistry& default_arch_registry() {
+ static const ArchRegistry registry;
+ return registry;
}
-} // namespace gguf
-} // namespace frontend
-} // namespace ov
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/arch_registry.hpp b/src/frontends/gguf/src/builder/arch_registry.hpp
index 59edd3ef231..bb80a95d91a 100644
--- a/src/frontends/gguf/src/builder/arch_registry.hpp
+++ b/src/frontends/gguf/src/builder/arch_registry.hpp
@@ -4,38 +4,37 @@
#pragma once
+#include <map>
#include <set>
-#include <string>
+#include <vector>
-namespace ov {
-namespace frontend {
-namespace gguf {
+#include "openvino/frontend/gguf/extension/architecture.hpp"
+
+namespace ov::frontend::gguf {
-// gguf ROPE op-case (see ggml-decoder.cpp::compute_op_case). The high 16 bits encode the
-// mode: NORMAL=0 (llama/minicpm: rotate consecutive pairs), NEOX=1 (qwen/phi/hunyuan:
-// rotate halves). The input is not a VIEW here so the low bits stay 0.
constexpr int ROPE_OP_CASE_NORMAL = 0x00000000;
constexpr int ROPE_OP_CASE_NEOX = 0x00010000;
-// IMROPE=2: interleaved multimodal rope (qwen35 / qwen3vl). inp_pos carries 4 mrope sections.
constexpr int ROPE_OP_CASE_IMROPE = 0x00020000;
-
-// Architectures whose rope is NEOX (rotate-halves); everything else in the supported set
-// uses NORMAL (rotate consecutive pairs). Mirrors llama_model_rope_type.
bool arch_uses_neox_rope(const std::string& arch);
-
-// Architectures END-TO-END VERIFIED on the generic decoder builder: convert + compile + generation
-// checked against the reference (native llama.cpp / HF) on a real checkpoint. Safe to rely on.
const std::set<std::string>& verified_archs();
-
-// Architectures EXPECTED to work via the generic builder's GGUF-tensor-table auto-detection, but
-// NOT yet end-to-end verified on a real checkpoint. Enabled (they convert), but conversion emits a
-// one-time warning so callers know they are best-effort. Promote to verified_archs() once a model
-// of the family has been checked against the reference. See docs/adding_an_architecture.md.
const std::set<std::string>& experimental_archs();
-
-// All architectures the native builder accepts = verified + experimental.
const std::set<std::string>& supported_archs();
-} // namespace gguf
-} // namespace frontend
-} // namespace ov
+// Single catalog for built-in decoder and custom-family definitions.
+std::vector<ArchitectureDefinition> builtin_architectures();
+
+class ArchRegistry {
+public:
+ explicit ArchRegistry(std::vector<ArchitectureDefinition> definitions = builtin_architectures());
+ 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::string describe_supported() const;
+
+private:
+ std::map<std::string, std::shared_ptr<const ArchitectureDefinition>> m_definitions;
+};
+
+const ArchRegistry& default_arch_registry();
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/builder/blocks/attention.cpp b/src/frontends/gguf/src/builder/blocks/attention.cpp
index f959f319df3..18248880570 100644
--- a/src/frontends/gguf/src/builder/blocks/attention.cpp
+++ b/src/frontends/gguf/src/builder/blocks/attention.cpp
@@ -43,8 +43,7 @@ std::string attention(GraphEmitter& e,
const DecoderConfig& cfg,
const KvCachePlan& kv,
int il,
- const std::string& attn_norm,
- int64_t T) {
+ const std::string& attn_norm) {
const std::string p = "blk." + std::to_string(il) + ".";
auto& graph = *e.graph();
@@ -55,10 +54,8 @@ std::string attention(GraphEmitter& e,
const int n_head_kv_l = cfg.layer_n_head_kv(il);
const float kq_scale = cfg.layer_kq_scale(il);
const RopeConfig rope_config_l = cfg.layer_rope_config(il);
- // Shape dimensions are int64_t. Widen before multiplication so malformed metadata cannot
- // overflow the intermediate int expression before it reaches the PartialShape.
+ // Widen before multiplying the reshape dimensions.
const int64_t q_width = static_cast<int64_t>(head_size_l) * cfg.n_head;
- const int64_t kv_width = static_cast<int64_t>(head_size_l) * n_head_kv_l;
// Q/K/V projections: MUL_MAT(w, attn_norm), then conceptual reshape to heads.
// Fused-QKV archs (phi-3, minicpm) carry a single attn_qkv weight; split it into
@@ -82,9 +79,9 @@ std::string attention(GraphEmitter& e,
e.add_weight_from(p + "attn_v.weight", p + "attn_k");
}
}
- auto q = e.add_op("GGML_OP_MUL_MAT", p + "Qcur", {p + "attn_q.weight", attn_norm}, ps({1, 1, T, q_width}), f32);
- auto k = e.add_op("GGML_OP_MUL_MAT", p + "Kcur", {p + "attn_k.weight", attn_norm}, ps({1, 1, T, kv_width}), f32);
- auto v = e.add_op("GGML_OP_MUL_MAT", p + "Vcur", {p + "attn_v.weight", attn_norm}, ps({1, 1, T, kv_width}), f32);
+ auto q = e.add_op("GGML_OP_MUL_MAT", p + "Qcur", {p + "attn_q.weight", attn_norm});
+ auto k = e.add_op("GGML_OP_MUL_MAT", p + "Kcur", {p + "attn_k.weight", attn_norm});
+ auto v = e.add_op("GGML_OP_MUL_MAT", p + "Vcur", {p + "attn_v.weight", attn_norm});
// Q/K/V projection biases (qwen2 / qwen2.5: separate attn_{q,k,v}.bias; phi-3-style
// fused-QKV archs: attn_qkv.bias, already split into attn_{q,k,v}.bias by
@@ -102,9 +99,21 @@ std::string attention(GraphEmitter& e,
}
// reshape Q/K/V to [1, n_tokens, n_head(_kv), head_size]
- q = e.add_op("GGML_OP_RESHAPE", p + "Qcur_r", {q}, ps({1, T, cfg.n_head, head_size_l}), f32, 1);
- k = e.add_op("GGML_OP_RESHAPE", p + "Kcur_r", {k}, ps({1, T, n_head_kv_l, head_size_l}), f32, 1);
- v = e.add_op("GGML_OP_RESHAPE", p + "Vcur_r", {v}, ps({1, T, n_head_kv_l, head_size_l}), f32, 1);
+ q = e.add_op("GGML_OP_RESHAPE",
+ p + "Qcur_r",
+ {q},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{0, -1, cfg.n_head, head_size_l}}, {"special_zero", true}});
+ k = e.add_op("GGML_OP_RESHAPE",
+ p + "Kcur_r",
+ {k},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{0, -1, n_head_kv_l, head_size_l}}, {"special_zero", true}});
+ v = e.add_op("GGML_OP_RESHAPE",
+ p + "Vcur_r",
+ {v},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{0, -1, n_head_kv_l, head_size_l}}, {"special_zero", true}});
// per-head q_norm / k_norm (qwen3, hunyuan, gemma4)
if (cfg.has_qk_norm && !cfg.qk_norm_full && !cfg.qk_norm_after_rope) {
@@ -113,20 +122,15 @@ std::string attention(GraphEmitter& e,
}
// gemma4: V gets a plain RMSNorm (no multiplicative weight, just normalize).
if (cfg.has_v_norm) {
- v = e.add_op("GGML_OP_RMS_NORM",
- p + "Vcur_normed",
- {v},
- ps({1, T, n_head_kv_l, head_size_l}),
- f32,
- 0,
- {{"eps", cfg.rms_eps}});
+ v = e.add_op("GGML_OP_RMS_NORM", p + "Vcur_normed", {v}, 0, {{"eps", cfg.rms_eps}});
}
// RoPE (NEOX). rope_freqs.weight (per-dim frequency factor) is an optional 3rd input.
// For gemma4: global layers use rope_freqs (proportional/NTK scaling), SWA layers don't.
// muse-glimmer ropes ONLY its sliding-window layers; its global layers are NoPE
// (llama.cpp muse-glimmer.cpp: `const bool use_rope = hparams.is_swa(il)`).
- const bool use_rope = !cfg.rope_on_swa_only || is_swa_layer;
+ const bool use_rope =
+ (!cfg.rope_on_swa_only || is_swa_layer) && (cfg.rope_skip_period == 0 || (il + 1) % cfg.rope_skip_period != 0);
const bool use_rope_freqs = cfg.has_rope_freqs && !is_swa_layer;
const std::vector<std::string> q_rope_in = use_rope_freqs
? std::vector<std::string>{q, "inp_pos", "rope_freqs.weight"}
@@ -135,28 +139,36 @@ std::string attention(GraphEmitter& e,
? std::vector<std::string>{k, "inp_pos", "rope_freqs.weight"}
: std::vector<std::string>{k, "inp_pos"};
if (use_rope) {
- q = e.add_op("GGML_OP_ROPE",
- p + "Qcur_rope",
- q_rope_in,
- ps({1, T, cfg.n_head, head_size_l}),
- f32,
- cfg.rope_op_case,
- {{"rope_config", rope_config_l}});
- k = e.add_op("GGML_OP_ROPE",
- p + "Kcur_rope",
- k_rope_in,
- ps({1, T, n_head_kv_l, head_size_l}),
- f32,
- cfg.rope_op_case,
- {{"rope_config", rope_config_l}});
+ q = e.add_op("GGML_OP_ROPE", p + "Qcur_rope", q_rope_in, cfg.rope_op_case, {{"rope_config", rope_config_l}});
+ k = e.add_op("GGML_OP_ROPE", p + "Kcur_rope", k_rope_in, cfg.rope_op_case, {{"rope_config", rope_config_l}});
}
- // Hunyuan differs from Qwen/Gemma: its learned per-head Q/K RMSNorm follows RoPE.
if (cfg.has_qk_norm && !cfg.qk_norm_full && cfg.qk_norm_after_rope) {
q = rms_norm(e, q, p + "attn_q_norm.weight", p + "Qcur_normed", cfg.rms_eps);
k = rms_norm(e, k, p + "attn_k_norm.weight", p + "Kcur_normed", cfg.rms_eps);
}
+ if (cfg.attention_temperature_scale != 0.0f) {
+ auto temp = e.add_op("GGML_OP_CPY", p + "temp_pos", {"inp_pos"}, 0, {{"dst_type", f32}});
+ temp = scale(e, temp, 1.0f / cfg.rope_config.n_ctx_orig, p + "temp_window");
+ // Positions are nonnegative: integer conversion implements floor(position / context).
+ temp = e.add_op("GGML_OP_CPY", p + "temp_floor", {temp}, 0, {{"dst_type", ov::element::i32}});
+ temp = e.add_op("GGML_OP_CPY", p + "temp_float", {temp}, 0, {{"dst_type", f32}});
+ temp = e.add_op("GGML_OP_SCALE", p + "temp_offset", {temp}, 0, {{"bias", 1.0f}});
+ temp = e.add_op("GGML_OP_LOG", p + "temp_log", {temp});
+ temp = e.add_op("GGML_OP_SCALE",
+ p + "temp_scale",
+ {temp},
+ 0,
+ {{"scale", cfg.attention_temperature_scale}, {"bias", 1.0f}});
+ temp = e.add_op("GGML_OP_RESHAPE",
+ p + "temp_broadcast",
+ {temp},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{0, -1, 1, 1}}, {"special_zero", true}});
+ q = e.add_op("GGML_OP_MUL", p + "Qcur_temp_scaled", {q, temp});
+ }
+
// ---- KV cache store ----
// Gemma4: layers with shared_kv_layers have no K/V of their own; they reuse the KV
// from the last layer of the same SWA type that has its own KV cache. SWA layers
@@ -179,22 +191,12 @@ std::string attention(GraphEmitter& e,
e.add_input(kc, ov::element::f16, cache_shape);
e.add_input(vc, ov::element::f16, cache_shape);
}
- e.set_tensor_meta(kc, ps({1, T, n_head_kv_l, head_size_l}), ov::element::f16);
- e.set_tensor_meta(vc, ps({1, T, n_head_kv_l, head_size_l}), ov::element::f16);
// SET_ROWS(cur, idx, cache) -> the cache with this step's rows written in. Lowered by
// the frontend to a stateless ScatterUpdate, or by the caller-registered MakeStateful
// extension to a ReadValue/Concat/Assign OpenVINO state.
- k = e.add_op("GGML_OP_SET_ROWS",
- kc,
- {k, "inp_kv_idx", kc},
- ps({1, T, n_head_kv_l, head_size_l}),
- ov::element::f16);
- v = e.add_op("GGML_OP_SET_ROWS",
- vc,
- {v, "inp_kv_idx", vc},
- ps({1, T, n_head_kv_l, head_size_l}),
- ov::element::f16);
+ k = e.add_op("GGML_OP_SET_ROWS", kc, {k, "inp_kv_idx", kc});
+ v = e.add_op("GGML_OP_SET_ROWS", vc, {v, "inp_kv_idx", vc});
// The written-through caches are model outputs, so the stateless graph returns each
// updated cache as a Result (which MakeStateful, when registered, turns into an Assign
// sink paired with the cache's ReadValue).
@@ -205,31 +207,13 @@ std::string attention(GraphEmitter& e,
// 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
// the last dim, mirroring llama.cpp's ggml_view_4d with n_embd_head_k(il).
- const ov::PartialShape& anchor_kc_shape = e.shape_of_tensor(kc); // [1, T, n_kv, anchor_head]
+ const ov::PartialShape& anchor_kc_shape = e.value(kc).get_partial_shape(); // [1, T, n_kv, anchor_head]
const int64_t anchor_hs = anchor_kc_shape[3].is_static() ? anchor_kc_shape[3].get_length() : cfg.head_size;
if (head_size_l < static_cast<int>(anchor_hs)) {
- // Shrink the last (head-size) axis to head_size_l. This is a plain single-axis shrink
- // at offset 0, which is exactly what the shared VIEW op_case 3 does -- and what the
- // cgraph decoder assigns to llama.cpp's corresponding ggml_view_4d with
- // n_embd_head_k(il) -- so describe it the way that case expects rather than with a
- // builder-only case: "view_slice" = {ov_axis, start, len} plus the input's own shape.
- // No "view_reshape": the sliced shape already is this node's output shape.
- const ov::PartialShape slice_shape = ps({1, T, n_head_kv_l, head_size_l});
+ // Slice the shared cache to this layer's head width.
const std::vector<int64_t> hs_slice{3, 0, int64_t(head_size_l)};
- k = e.add_op("GGML_OP_VIEW",
- p + "k_hslice",
- {kc},
- slice_shape,
- ov::element::f16,
- 3,
- {{"view_slice", hs_slice}, {"input_ggml_shape", e.static_shape_of(kc)}});
- v = e.add_op("GGML_OP_VIEW",
- p + "v_hslice",
- {vc},
- slice_shape,
- ov::element::f16,
- 3,
- {{"view_slice", hs_slice}, {"input_ggml_shape", e.static_shape_of(vc)}});
+ k = e.add_op("GGML_OP_VIEW", p + "k_hslice", {kc}, 3, {{"view_slice", hs_slice}});
+ v = e.add_op("GGML_OP_VIEW", p + "v_hslice", {vc}, 3, {{"view_slice", hs_slice}});
} else {
k = kc;
v = vc;
@@ -259,35 +243,29 @@ std::string attention(GraphEmitter& e,
auto attn = e.add_op("GGML_OP_FLASH_ATTN_EXT",
p + "kqv",
attn_in,
- ps({1, T, cfg.n_head, head_size_l}),
- f32,
100, // builder layout: q/k/v are ggml-natural [1, T, n_head, head_size]
std::move(attn_attrs));
// reshape back to [1, 1, n_tokens, n_head*head_size]
- auto attn_2d = e.add_op("GGML_OP_RESHAPE", p + "kqv_merged", {attn}, ps({1, 1, T, q_width}), f32, 2);
+ auto attn_2d = e.add_op("GGML_OP_RESHAPE",
+ p + "kqv_merged",
+ {attn},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{0, 1, -1, q_width}}, {"special_zero", true}});
// muse-glimmer: sigmoid output gate. The gate is a projection of the PRE-attention
// normed hidden (the same `attn_norm` tensor Q/K/V come from), squashed by sigmoid and
// multiplied elementwise into the merged attention output before the wo projection.
if (cfg.has_attn_gate) {
e.add_weight(p + "attn_gate.weight");
- auto gate = e.add_op("GGML_OP_MUL_MAT",
- p + "attn_gate",
- {p + "attn_gate.weight", attn_norm},
- ps({1, 1, T, q_width}),
- f32);
- gate = e.add_op("GGML_UNARY_OP_SIGMOID", p + "attn_gate_sig", {gate}, e.shape_of_tensor(gate), f32);
- attn_2d = e.add_op("GGML_OP_MUL", p + "kqv_gated", {attn_2d, gate}, e.shape_of_tensor(attn_2d), f32);
+ auto gate = e.add_op("GGML_OP_MUL_MAT", p + "attn_gate", {p + "attn_gate.weight", attn_norm});
+ gate = e.add_op("GGML_UNARY_OP_SIGMOID", p + "attn_gate_sig", {gate});
+ attn_2d = e.add_op("GGML_OP_MUL", p + "kqv_gated", {attn_2d, gate});
}
// output projection (+ optional bias)
e.add_weight(p + "attn_output.weight");
- auto attn_out = e.add_op("GGML_OP_MUL_MAT",
- p + "attn_out",
- {p + "attn_output.weight", attn_2d},
- ps({1, 1, T, cfg.n_embd}),
- f32);
+ auto attn_out = e.add_op("GGML_OP_MUL_MAT", p + "attn_out", {p + "attn_output.weight", attn_2d});
if (cfg.has_attn_out_bias) {
attn_out = add_bias(e, attn_out, p + "attn_output.bias", p + "attn_out_b");
}
diff --git a/src/frontends/gguf/src/builder/blocks/attention.hpp b/src/frontends/gguf/src/builder/blocks/attention.hpp
index 1724d116e0e..0104e05c00c 100644
--- a/src/frontends/gguf/src/builder/blocks/attention.hpp
+++ b/src/frontends/gguf/src/builder/blocks/attention.hpp
@@ -39,8 +39,7 @@ std::string attention(GraphEmitter& e,
const DecoderConfig& cfg,
const KvCachePlan& kv,
int il,
- const std::string& attn_norm,
- int64_t T);
+ const std::string& attn_norm);
} // namespace blocks
} // namespace gguf
diff --git a/src/frontends/gguf/src/builder/blocks/common.cpp b/src/frontends/gguf/src/builder/blocks/common.cpp
index 517a752084b..7430aa141db 100644
--- a/src/frontends/gguf/src/builder/blocks/common.cpp
+++ b/src/frontends/gguf/src/builder/blocks/common.cpp
@@ -15,29 +15,17 @@ std::string rms_norm(GraphEmitter& e,
const std::string& out_prefix,
float eps) {
e.add_weight(weight);
- auto norm = e.add_op("GGML_OP_RMS_NORM",
- out_prefix + ".rms",
- {in},
- e.shape_of_tensor(in),
- ov::element::f32,
- 0,
- {{"eps", eps}});
- return e.add_op("GGML_OP_MUL", out_prefix, {norm, weight}, e.shape_of_tensor(in), ov::element::f32);
+ 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 scale(GraphEmitter& e, const std::string& x, float factor, const std::string& name) {
- return e.add_op("GGML_OP_SCALE",
- name,
- {x},
- e.shape_of_tensor(x),
- ov::element::f32,
- 0,
- {{"scale", factor}, {"bias", 0.0f}});
+ return e.add_op("GGML_OP_SCALE", name, {x}, 0, {{"scale", factor}, {"bias", 0.0f}});
}
std::string add_bias(GraphEmitter& e, const std::string& x, const std::string& bias_weight, const std::string& name) {
e.add_named_weight(bias_weight);
- return e.add_op("GGML_OP_ADD", name, {x, bias_weight}, e.shape_of_tensor(x), ov::element::f32);
+ return e.add_op("GGML_OP_ADD", name, {x, bias_weight});
}
} // namespace blocks
diff --git a/src/frontends/gguf/src/builder/blocks/ffn.cpp b/src/frontends/gguf/src/builder/blocks/ffn.cpp
index 0310ac18230..a9a736712e0 100644
--- a/src/frontends/gguf/src/builder/blocks/ffn.cpp
+++ b/src/frontends/gguf/src/builder/blocks/ffn.cpp
@@ -13,8 +13,6 @@ namespace frontend {
namespace gguf {
namespace blocks {
-using ov::element::f32;
-
namespace {
// "<name>.weight" -> "<name>.bias": every weight tensor in this file follows that naming
@@ -37,122 +35,92 @@ std::string swiglu_gate_up(GraphEmitter& e,
const std::string& gate_w,
const std::string& up_w,
const std::string& ffn_norm,
- int64_t T,
const std::string& gate_name,
const std::string& up_name,
const std::string& glu_name,
bool has_bias) {
e.add_weight(gate_w);
- const int n_ff = static_cast<int>(e.weight_tensor(gate_w).get_shape()[0]);
- auto gate = e.add_op("GGML_OP_MUL_MAT", gate_name, {gate_w, ffn_norm}, ps({1, 1, T, n_ff}), f32);
+ 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}, ps({1, 1, T, n_ff}), f32);
+ 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}, ps({1, 1, T, n_ff}), f32, 0, {{"swapped", false}});
+ return e.add_op("GGML_GLU_OP_SWIGLU", glu_name, {gate, up}, 0, {{"swapped", false}});
}
-std::string geglu_ffn(GraphEmitter& e,
- const DecoderConfig& cfg,
- const std::string& p,
- const std::string& ffn_norm,
- int64_t T) {
+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");
- const int n_ff = static_cast<int>(e.weight_tensor(p + "ffn_gate.weight").get_shape()[0]);
- auto gate =
- e.add_op("GGML_OP_MUL_MAT", p + "ffn_gate", {p + "ffn_gate.weight", ffn_norm}, ps({1, 1, T, n_ff}), f32);
- auto up = e.add_op("GGML_OP_MUL_MAT", p + "ffn_up", {p + "ffn_up.weight", ffn_norm}, ps({1, 1, T, n_ff}), f32);
- auto glu =
- e.add_op("GGML_GLU_OP_GEGLU", p + "ffn_geglu", {gate, up}, ps({1, 1, T, n_ff}), f32, 0, {{"swapped", false}});
- return e.add_op("GGML_OP_MUL_MAT", p + "ffn_out", {p + "ffn_down.weight", glu}, ps({1, 1, T, cfg.n_embd}), f32);
+ 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}});
+ return e.add_op("GGML_OP_MUL_MAT", p + "ffn_out", {p + "ffn_down.weight", glu});
}
-std::string dense_ffn(GraphEmitter& e,
- const DecoderConfig& cfg,
- const std::string& p,
- const std::string& ffn_norm,
- int64_t T) {
+std::string dense_ffn(GraphEmitter& e, const DecoderConfig& cfg, const std::string& p, const std::string& ffn_norm) {
e.add_weight(p + "ffn_up.weight");
e.add_weight(p + "ffn_down.weight");
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) {
- const int up2 = static_cast<int>(e.weight_tensor(p + "ffn_up.weight").get_shape()[0]); // 2*n_ff
- auto up = e.add_op("GGML_OP_MUL_MAT", p + "ffn_up", {p + "ffn_up.weight", ffn_norm}, ps({1, 1, T, up2}), f32);
- glu = e.add_op("GGML_GLU_OP_SWIGLU",
- p + "ffn_swiglu",
- {up},
- ps({1, 1, T, up2 / 2}),
- f32,
- 0,
- {{"swapped", false}});
+ 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 {
glu = swiglu_gate_up(e,
p + "ffn_gate.weight",
p + "ffn_up.weight",
ffn_norm,
- T,
p + "ffn_gate",
p + "ffn_up",
p + "ffn_swiglu",
has_ffn_bias);
}
- auto out = e.add_op("GGML_OP_MUL_MAT", p + "ffn_out", {p + "ffn_down.weight", glu}, ps({1, 1, T, cfg.n_embd}), f32);
+ auto out = e.add_op("GGML_OP_MUL_MAT", p + "ffn_out", {p + "ffn_down.weight", glu});
if (has_ffn_bias) {
out = add_bias(e, out, p + "ffn_down.bias", p + "ffn_out_b");
}
return out;
}
-std::string moe_ffn(GraphEmitter& e,
- const DecoderConfig& cfg,
- const std::string& p,
- const std::string& ffn_norm,
- int64_t T) {
- const int E = cfg.n_expert, K = cfg.n_expert_used;
- const int n_ff = static_cast<int>(e.weight_tensor(p + "ffn_gate_exps.weight").get_shape()[1]);
-
+std::string moe_ffn(GraphEmitter& e, const DecoderConfig& cfg, const std::string& p, const std::string& ffn_norm) {
// --- 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}, ps({1, 1, T, E}), f32);
+ auto logits = e.add_op("GGML_OP_MUL_MAT", p + "moe_logits", {p + "ffn_gate_inp.weight", ffn_norm});
if (cfg.has_moe_gate_bias) {
logits = add_bias(e, logits, p + "ffn_gate_inp.bias", p + "moe_logits_b");
}
- // gating: softmax (OLMoE) or softmax-after-topk (gpt-oss "softmax_weight").
+ // GPT-OSS applies softmax after top-k; other routers use softmax or sigmoid here.
std::string probs = logits;
- if (!cfg.moe_softmax_weight) {
- probs = e.add_op("GGML_OP_SOFT_MAX",
- p + "moe_probs",
- {logits},
- ps({1, 1, T, E}),
- f32,
- 0,
- {{"softmax_axis", int64_t(-1)}});
+ if (cfg.moe_sigmoid_gating) {
+ probs = e.add_op("GGML_UNARY_OP_SIGMOID", p + "moe_probs", {logits});
+ } else if (!cfg.moe_softmax_weight) {
+ probs = e.add_op("GGML_OP_SOFT_MAX", p + "moe_probs", {logits}, 0, {{"softmax_axis", int64_t(-1)}});
}
// top-k expert selection -> indices [1,1,T,K] (i32).
- auto selected = e.add_op("GGML_OP_TOP_K", p + "moe_topk", {probs}, ps({1, 1, T, K}), ov::element::i32);
+ auto selection_probs = probs;
+ if (e.has_weight(p + "exp_probs_b.bias"))
+ selection_probs = add_bias(e, probs, p + "exp_probs_b.bias", p + "moe_selection_probs");
+ auto selected = e.add_op("GGML_OP_TOP_K",
+ p + "moe_topk",
+ {selection_probs},
+ 0,
+ {{"k", int64_t{cfg.n_expert_used}},
+ {"expert_groups", cfg.expert_groups},
+ {"expert_groups_used", cfg.expert_groups_used}});
// weights = gather probs by selected; op_case 10 returns a per-expert column
// [1,T,K,1] (robust to dynamic T). gpt-oss softmaxes over the K (expert) axis.
- auto weights = e.add_op("GGML_OP_GET_ROWS", p + "moe_w", {probs, selected}, ps({1, T, K, 1}), f32, 10);
+ auto weights = e.add_op("GGML_OP_GET_ROWS", p + "moe_w", {probs, selected}, 10);
if (cfg.moe_softmax_weight) {
- weights = e.add_op("GGML_OP_SOFT_MAX",
- p + "moe_w_sm",
- {weights},
- ps({1, T, K, 1}),
- f32,
- 0,
- {{"softmax_axis", int64_t(2)}});
+ weights = e.add_op("GGML_OP_SOFT_MAX", p + "moe_w_sm", {weights}, 0, {{"softmax_axis", int64_t(2)}});
}
// Renormalize the selected top-K gating weights to sum to 1 (llama.cpp build_moe_ffn's
// norm_w path, e.g. qwen3moe/glm4moe/bailingmoe2). On the softmax-before-topk path the
@@ -162,16 +130,14 @@ std::string moe_ffn(GraphEmitter& e,
// clamp away from 0 (matches llama.cpp's 6.1e-5 floor), then DIV back (broadcasts the
// [1,T,1,1] sum over K via repeat_input_to_match).
if (cfg.expert_weights_norm && !cfg.moe_softmax_weight) {
- auto w_tr = e.add_op("GGML_OP_TRANSPOSE", p + "moe_w_tr", {weights}, ps({1, T, 1, K}), f32);
- auto w_sum = e.add_op("GGML_OP_SUM_ROWS", p + "moe_w_sum", {w_tr}, ps({1, T, 1, 1}), f32);
+ auto w_tr = e.add_op("GGML_OP_TRANSPOSE", p + "moe_w_tr", {weights});
+ auto w_sum = e.add_op("GGML_OP_SUM_ROWS", p + "moe_w_sum", {w_tr});
w_sum = e.add_op("GGML_OP_CLAMP",
p + "moe_w_sum_clamped",
{w_sum},
- ps({1, T, 1, 1}),
- f32,
0,
{{"clamp_min", 6.1e-5f}, {"clamp_max", std::numeric_limits<float>::max()}});
- weights = e.add_op("GGML_OP_DIV", p + "moe_w_norm", {weights, w_sum}, ps({1, T, K, 1}), f32);
+ weights = e.add_op("GGML_OP_DIV", p + "moe_w_norm", {weights, w_sum});
}
// gpt-oss expert_weights_scale: optional constant multiplier applied after softmax
@@ -187,99 +153,59 @@ std::string moe_ffn(GraphEmitter& e,
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},
- ps({1, T, K, n_ff}),
- f32);
+ auto 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},
- ps({1, T, K, n_ff}),
- f32);
+ 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},
- ps({1, T, K, n_ff}),
- f32);
+ 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},
- ps({1, T, K, n_ff}),
- f32);
+ gate = e.add_op("GGML_OP_ADD_ID", p + "moe_gate_b", {gate, p + "ffn_gate_exps.bias", selected});
}
std::string act;
if (cfg.moe_swiglu_oai) {
act = e.add_op("GGML_GLU_OP_SWIGLU_OAI",
p + "moe_act",
{gate, up},
- ps({1, T, K, n_ff}),
- f32,
- 0,
- // Attribute names must match the cgraph decoder's (ggml-decoder.cpp), which
- // is the external contract the shared translators read: glu_alpha/glu_limit.
+ 0, // Attribute names must match the cgraph decoder's (ggml-decoder.cpp), which
+ // 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},
- ps({1, T, K, n_ff}),
- f32,
- 0,
- {{"swapped", false}});
+ act = e.add_op("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},
- ps({1, T, K, cfg.n_embd}),
- f32);
+ auto experts = e.add_op("GGML_OP_MUL_MAT_ID", p + "moe_down", {p + "ffn_down_exps.weight", act, selected});
if (eb) {
e.add_named_weight(p + "ffn_down_exps.bias");
- experts = e.add_op("GGML_OP_ADD_ID",
- p + "moe_down_b",
- {experts, p + "ffn_down_exps.bias", selected},
- ps({1, T, K, cfg.n_embd}),
- f32);
+ experts = e.add_op("GGML_OP_ADD_ID", p + "moe_down_b", {experts, p + "ffn_down_exps.bias", selected});
}
// 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]
// RESHAPE (dynamic) -> [1,1,T,n_embd].
- // The reshape is op_case 5: collapse to [1, 1, -1, n_embd], the token axis staying dynamic.
- // That is the case the cgraph decoder would assign to this same reshape too -- ggml ne
- // [1,n_embd,T,1] -> [n_embd,T,1,1] satisfies both of its case-5 predicates -- so the shared
- // case applies as-is and needs no builder-specific numbering.
- auto weighted = e.add_op("GGML_OP_MUL", p + "moe_weighted", {experts, weights}, ps({1, T, K, cfg.n_embd}), f32);
- auto tr = e.add_op("GGML_OP_TRANSPOSE", p + "moe_tr", {weighted}, ps({1, T, cfg.n_embd, K}), f32);
- auto summed = e.add_op("GGML_OP_SUM_ROWS", p + "moe_sum", {tr}, ps({1, T, cfg.n_embd, 1}), f32);
- auto moe_out = e.add_op("GGML_OP_RESHAPE", p + "moe_out", {summed}, ps({1, 1, T, cfg.n_embd}), f32, 5);
-
- // Shared experts (deepseek2-ocr, bailingmoe2, exaone-moe): always-active experts whose
- // output is added to the routed experts' weighted sum. Uses plain SwiGLU dense FFN with
- // ffn_{gate,up,down}_shexp.weight (n_ff_shared = shexp rows). Output added to moe_out.
- if (cfg.n_expert_shared > 0 && e.has_weight(p + "ffn_gate_shexp.weight")) {
+ auto weighted = e.add_op("GGML_OP_MUL", p + "moe_weighted", {experts, weights});
+ auto tr = e.add_op("GGML_OP_TRANSPOSE", p + "moe_tr", {weighted});
+ auto summed = e.add_op("GGML_OP_SUM_ROWS", p + "moe_sum", {tr});
+ auto moe_out = e.add_op("GGML_OP_RESHAPE",
+ p + "moe_out",
+ {summed},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{1, 1, -1, cfg.n_embd}}, {"special_zero", false}});
+
+ // Shared experts are always active; some checkpoints omit expert_shared_count.
+ if (e.has_weight(p + "ffn_gate_shexp.weight")) {
auto s_act = swiglu_gate_up(e,
p + "ffn_gate_shexp.weight",
p + "ffn_up_shexp.weight",
ffn_norm,
- T,
p + "shexp_gate",
p + "shexp_up",
p + "shexp_act",
/*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},
- ps({1, 1, T, cfg.n_embd}),
- f32);
- moe_out = e.add_op("GGML_OP_ADD", p + "moe_shared_out", {moe_out, s_down}, ps({1, 1, T, cfg.n_embd}), f32);
+ auto s_down = e.add_op("GGML_OP_MUL_MAT", p + "shexp_out", {p + "ffn_down_shexp.weight", s_act});
+ moe_out = e.add_op("GGML_OP_ADD", p + "moe_shared_out", {moe_out, s_down});
}
return moe_out;
}
diff --git a/src/frontends/gguf/src/builder/blocks/ffn.hpp b/src/frontends/gguf/src/builder/blocks/ffn.hpp
index 1f9b1a671ae..75e7a75ee57 100644
--- a/src/frontends/gguf/src/builder/blocks/ffn.hpp
+++ b/src/frontends/gguf/src/builder/blocks/ffn.hpp
@@ -16,7 +16,7 @@ namespace blocks {
// Feed-forward sublayers of the decoder block, mirroring llm_graph_context::build_ffn /
// build_moe_ffn. `prefix` is the layer prefix ("blk.<il>."), `ffn_norm` the pre-FFN normed hidden,
-// and `T` the representative static token length. Each returns the sublayer output tensor name,
+// Each returns the sublayer output tensor name,
// before the residual add.
// Dense SwiGLU FFN (llama/qwen/phi3/minicpm). Supports the fused gate+up projection (phi-3, no
@@ -25,25 +25,19 @@ namespace blocks {
std::string dense_ffn(GraphEmitter& e,
const DecoderConfig& cfg,
const std::string& prefix,
- const std::string& ffn_norm,
- int64_t T);
+ const std::string& ffn_norm);
// Dense GeGLU FFN (Gemma/Gemma2). Same layout as SwiGLU but uses GELU activation.
std::string geglu_ffn(GraphEmitter& e,
const DecoderConfig& cfg,
const std::string& prefix,
- const std::string& ffn_norm,
- int64_t T);
+ const std::string& ffn_norm);
// Mixture-of-experts FFN (OLMoE / gpt-oss / qwen3moe), mirroring llm_graph_context::build_moe_ffn.
// 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,
- int64_t T);
+std::string moe_ffn(GraphEmitter& e, const DecoderConfig& cfg, const std::string& prefix, const std::string& ffn_norm);
} // namespace blocks
} // namespace gguf
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 fd6bdfbcad6..d199e5350e5 100644
--- a/src/frontends/gguf/src/builder/blocks/gated_delta_net.cpp
+++ b/src/frontends/gguf/src/builder/blocks/gated_delta_net.cpp
@@ -14,11 +14,7 @@ namespace frontend {
namespace gguf {
namespace blocks {
-std::string gated_delta_net(GraphEmitter& e,
- const DecoderConfig& cfg,
- int il,
- const std::string& attn_norm,
- int64_t T) {
+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) + ".";
auto& graph = *e.graph();
@@ -40,26 +36,33 @@ std::string gated_delta_net(GraphEmitter& e,
// ---- 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}, ps({1, 1, T, conv_dim}), f32);
+ 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}, ps({1, 1, T, value_dim}), f32);
+ auto z = e.add_op("GGML_OP_MUL_MAT", p + "z", {p + "attn_gate.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}, ps({1, 1, T, H_v}), f32);
- beta = e.add_op("GGML_UNARY_OP_SIGMOID", p + "beta_sig", {beta}, ps({1, 1, T, H_v}), f32);
- beta = e.add_op("GGML_OP_RESHAPE", p + "beta_4d", {beta}, ps({1, T, H_v, 1}), f32, 1);
+ 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",
+ {beta},
+ 6,
+ {{"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}, ps({1, 1, T, H_v}), f32);
+ 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"}, ps({1, 1, T, H_v}), f32);
- alpha = e.add_op("GGML_UNARY_OP_SOFTPLUS", p + "alpha_sp", {alpha}, ps({1, 1, T, H_v}), f32);
+ alpha = e.add_op("GGML_OP_ADD", p + "alpha_biased", {alpha, p + "ssm_dt.bias"});
+ 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"}, ps({1, 1, T, H_v}), f32);
- g = e.add_op("GGML_OP_RESHAPE", p + "gate_4d", {g}, ps({1, T, H_v, 1}), f32, 1);
+ auto g = e.add_op("GGML_OP_MUL", p + "gate", {alpha, p + "ssm_a"});
+ g = e.add_op("GGML_OP_RESHAPE",
+ p + "gate_4d",
+ {g},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{0, -1, H_v, 1}}, {"special_zero", true}});
// ---- causal depthwise conv over [conv state | this step's tokens] ----
// conv_state holds the trailing d_conv-1 columns of the previous step's conv input.
@@ -67,52 +70,36 @@ std::string gated_delta_net(GraphEmitter& e,
if (!e.has_model_input(cs)) {
e.add_input(cs, f32, ps({1, 1, conv_dim, d_conv - 1}));
}
- e.set_tensor_meta(cs, ps({1, 1, conv_dim, d_conv - 1}), f32);
// [1,1,T,conv_dim] -> [1,1,conv_dim,T] so the conv window grows along the last axis.
- auto qkv_t = e.add_op("GGML_OP_TRANSPOSE", p + "qkv_t", {qkv}, ps({1, 1, conv_dim, T}), f32);
- auto conv_in = e.add_op("GGML_OP_CONCAT",
- p + "conv_in",
- {cs, qkv_t},
- ps({1, 1, conv_dim, d_conv - 1 + T}),
- f32,
- 0,
- {{"concat_axis", int{0}}});
+ auto qkv_t = e.add_op("GGML_OP_TRANSPOSE", p + "qkv_t", {qkv});
+ auto conv_in = e.add_op("GGML_OP_CONCAT", p + "conv_in", {cs, qkv_t}, 0, {{"concat_axis", int{0}}});
// Next step's state is the trailing d_conv-1 columns of this window.
const std::vector<int64_t> tail_slice{3, -(d_conv - 1), d_conv - 1};
- auto cs_out = e.add_op("GGML_OP_VIEW",
- cs + "_out",
- {conv_in},
- ps({1, 1, conv_dim, d_conv - 1}),
- f32,
- 3,
- {{"view_slice", tail_slice}, {"input_ggml_shape", e.static_shape_of(conv_in)}});
+ auto cs_out = e.add_op("GGML_OP_VIEW", cs + "_out", {conv_in}, 3, {{"view_slice", tail_slice}});
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"}, ps({1, 1, T, conv_dim}), f32);
- conv = e.add_op("GGML_UNARY_OP_SILU", p + "conv_silu", {conv}, ps({1, 1, T, conv_dim}), f32);
+ auto conv = e.add_op("GGML_OP_SSM_CONV", p + "conv_out", {conv_in, p + "ssm_conv1d.weight"});
+ conv = e.add_op("GGML_UNARY_OP_SILU", p + "conv_silu", {conv});
// ---- split the conv output into q | k | v and normalize 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},
- ps({1, 1, T, width}),
- f32,
- 3,
- {{"view_slice", sl}, {"input_ggml_shape", e.static_shape_of(conv)}});
- return e.add_op("GGML_OP_RESHAPE", p + name, {s}, ps({1, T, heads, dim}), f32, 1);
+ auto s = e.add_op("GGML_OP_VIEW", p + name + "_s", {conv}, 3, {{"view_slice", sl}});
+ return e.add_op("GGML_OP_RESHAPE",
+ p + name,
+ {s},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{0, -1, heads, dim}}, {"special_zero", true}});
};
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}, ps({1, T, H_k, S}), f32, 0, {{"eps", cfg.rms_eps}});
- k = e.add_op("GGML_OP_L2_NORM", p + "k_l2", {k}, ps({1, T, H_k, S}), f32, 0, {{"eps", cfg.rms_eps}});
+ 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
@@ -121,34 +108,21 @@ std::string gated_delta_net(GraphEmitter& e,
if (!e.has_model_input(ss)) {
e.add_input(ss, f32, ps({1, H_v, head_v, S}));
}
- e.set_tensor_meta(ss, ps({1, H_v, head_v, S}), f32);
-
- auto gdn = e.add_op("GGML_OP_GATED_DELTA_NET",
- p + "gdn",
- {q, k, v, g, beta, ss},
- ps({1, 1, T + head_v, head_v * H_v}),
- f32,
- 0,
- {{"gdn_state_slots", int64_t{1}}});
-
- // The op packs [attn rows | new-state rows]; op_case 4 slices them apart. The attn view's
- // token axis is marked -1 explicitly rather than left as the representative T: the consumer
- // replaces the FIRST dim equal to the token count, and with T == 1 that would match the
- // leading batch dim and move the tokens into dim 0 for the rest of the model.
+
+ 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},
- ps({1, T, H_v, head_v}),
- f32,
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},
- ps({1, H_v, head_v, S}),
- f32,
4,
{{"gdn_view", state_view}, {"view_reshape", std::vector<int64_t>{1, H_v, head_v, S}}});
graph.model_output_names.push_back(new_state);
@@ -157,17 +131,21 @@ std::string gated_delta_net(GraphEmitter& e,
// ---- gated output norm + projection ----
// build_norm_gated: rms_norm(attn, ssm_norm) * silu(z), normalizing the head_v axis.
auto out = rms_norm(e, attn, p + "ssm_norm.weight", p + "gdn_norm", cfg.rms_eps);
- auto z_4d = e.add_op("GGML_OP_RESHAPE", p + "z_4d", {z}, ps({1, T, H_v, head_v}), f32, 1);
- auto z_silu = e.add_op("GGML_UNARY_OP_SILU", p + "z_silu", {z_4d}, ps({1, T, H_v, head_v}), f32);
- out = e.add_op("GGML_OP_MUL", p + "gdn_gated", {out, z_silu}, ps({1, T, H_v, head_v}), f32);
- out = e.add_op("GGML_OP_RESHAPE", p + "gdn_merged", {out}, ps({1, 1, T, value_dim}), f32, 2);
+ auto z_4d = e.add_op("GGML_OP_RESHAPE",
+ p + "z_4d",
+ {z},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{0, -1, H_v, head_v}}, {"special_zero", true}});
+ auto z_silu = e.add_op("GGML_UNARY_OP_SILU", p + "z_silu", {z_4d});
+ 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}});
e.add_weight(p + "ssm_out.weight");
- return e.add_op("GGML_OP_MUL_MAT",
- p + "linear_attn_out",
- {p + "ssm_out.weight", out},
- ps({1, 1, T, cfg.n_embd}),
- f32);
+ return e.add_op("GGML_OP_MUL_MAT", p + "linear_attn_out", {p + "ssm_out.weight", out});
}
} // namespace blocks
diff --git a/src/frontends/gguf/src/builder/blocks/gated_delta_net.hpp b/src/frontends/gguf/src/builder/blocks/gated_delta_net.hpp
index bd5d45d45c2..308cc4b0f88 100644
--- a/src/frontends/gguf/src/builder/blocks/gated_delta_net.hpp
+++ b/src/frontends/gguf/src/builder/blocks/gated_delta_net.hpp
@@ -23,7 +23,7 @@ namespace blocks {
// builder treats KV caches: the frontend always emits a STATELESS graph and leaves statefulness to
// the consumer. Unlike a KV cache these are OVERWRITTEN, not appended, so they carry no token axis
// and MakeStateful's Concat path does not apply to them.
-std::string gated_delta_net(GraphEmitter& e, const DecoderConfig& cfg, int il, const std::string& attn_norm, int64_t T);
+std::string gated_delta_net(GraphEmitter& e, const DecoderConfig& cfg, int il, const std::string& attn_norm);
} // namespace blocks
} // namespace gguf
diff --git a/src/frontends/gguf/src/builder/blocks/qkv_repack.cpp b/src/frontends/gguf/src/builder/blocks/qkv_repack.cpp
index 99f805f6113..9e6e2c051fc 100644
--- a/src/frontends/gguf/src/builder/blocks/qkv_repack.cpp
+++ b/src/frontends/gguf/src/builder/blocks/qkv_repack.cpp
@@ -19,9 +19,8 @@ void register_fused_qkv(GraphEmitter& e, const DecoderConfig& cfg, int il) {
const size_t n_kv = static_cast<size_t>(cfg.n_head_kv) * cfg.head_size;
auto parts = split_fused_qkv_extracted(p + "attn_qkv", e.weights(), e.qtypes(), n_q, n_kv, n_kv);
const std::array<std::string, 3> names = {p + "attn_q.weight", p + "attn_k.weight", p + "attn_v.weight"};
- const std::array<int64_t, 3> rows = {(int64_t)n_q, (int64_t)n_kv, (int64_t)n_kv};
for (size_t i = 0; i < 3; ++i) {
- e.emit_weight_op(names[i], parts[i].tensors, parts[i].qtype, ps({1, 1, rows[i], cfg.n_embd}));
+ e.emit_weight_op(names[i], parts[i].tensors, parts[i].qtype);
}
// Some fused-QKV archs (e.g. phi-3) also carry a single attn_qkv.bias; split it into
@@ -40,9 +39,8 @@ void register_qwen35_q_gate(GraphEmitter& e, const DecoderConfig& cfg, int il) {
const std::string p = "blk." + std::to_string(il) + ".";
auto parts = split_interleaved_q_gate(p + "attn_q", e.weights(), e.qtypes(), static_cast<size_t>(cfg.head_size));
const std::array<std::string, 2> names = {p + "attn_q.weight", p + "attn_gate.weight"};
- const int64_t rows = static_cast<int64_t>(cfg.n_head) * cfg.head_size;
for (size_t i = 0; i < 2; ++i) {
- e.emit_weight_op(names[i], parts[i].tensors, parts[i].qtype, ps({1, 1, rows, cfg.n_embd}));
+ e.emit_weight_op(names[i], parts[i].tensors, parts[i].qtype);
}
}
diff --git a/src/frontends/gguf/src/builder/decoder_config.cpp b/src/frontends/gguf/src/builder/decoder_config.cpp
index 6965670f34d..887755ddd4e 100644
--- a/src/frontends/gguf/src/builder/decoder_config.cpp
+++ b/src/frontends/gguf/src/builder/decoder_config.cpp
@@ -7,7 +7,7 @@
// Ground truth for each rule is llama.cpp's per-architecture hparam loading
// (src/models/*.cpp::load_arch_hparams) and llm_graph_context.
-#include "decoder_config.hpp"
+#include "builder/decoder_config.hpp"
#include <algorithm>
#include <cmath>
@@ -41,7 +41,9 @@ float cfg_float(const std::map<std::string, GGUFMetaData>& config, const std::st
} // namespace
DecoderConfig::DecoderConfig(const std::map<std::string, GGUFMetaData>& config,
- const std::unordered_map<std::string, ov::Tensor>& weights) {
+ const std::unordered_map<std::string, ov::Tensor>& weights,
+ std::optional<RopeMode> rope,
+ const DecoderOptions& options) {
const auto has = [&weights](const std::string& name) {
return weights.count(name) > 0;
};
@@ -78,14 +80,11 @@ DecoderConfig::DecoderConfig(const std::map<std::string, GGUFMetaData>& config,
const size_t qn = weights.at("blk.0.attn_q_norm.weight").get_shape()[0];
qk_norm_full = (arch != "gemma4") && (qn != static_cast<size_t>(head_size));
}
- // Hunyuan's graph applies RoPE before its learned per-head Q/K RMSNorm. This order is
- // architecture-specific and cannot be inferred from the identical tensor shapes used by
- // Qwen3/Gemma, which normalize before RoPE.
- qk_norm_after_rope = arch == "hunyuan-dense" || arch == "hunyuan-moe";
n_dense_lead = cfg_i("n_layer_dense_lead");
- // Detect MoE from the first non-dense-lead layer (layer 0 may be dense even in MoE models).
+ moe_layer_step = std::max(1, cfg_i("moe_layer_step"));
+ // Inspect the first routed layer, accounting for both dense lead layers and MoE stride.
{
- const int probe = std::max(0, n_dense_lead);
+ 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");
}
@@ -98,42 +97,21 @@ DecoderConfig::DecoderConfig(const std::map<std::string, GGUFMetaData>& config,
has_v_norm = (arch == "gemma4");
n_expert = cfg_i("expert_count");
n_expert_used = cfg_i("expert_used_count");
- n_expert_shared = cfg_i("expert_shared_count");
+ expert_groups = std::max(1, cfg_i("expert_groups"));
+ expert_groups_used = std::max(1, cfg_i("expert_groups_used"));
has_moe_gate_bias = has("blk.0.ffn_gate_inp.bias"); // gpt-oss
has_moe_expert_bias = has("blk.0.ffn_gate_exps.bias"); // gpt-oss
has_sinks = has("blk.0.attn_sinks.weight"); // gpt-oss
- // Gemma2/Gemma4: per-layer post-attention and post-FFN RMSNorm applied after the sublayer
- // output and before the residual add. Detected from the tensor table at layer 0.
- //
- // Key naming ambiguity across architectures:
- // Gemma2/Gemma4: attn_norm (pre-attn) + ffn_norm (pre-FFN)
- // + post_attention_norm (post-attn) + post_ffw_norm (post-FFN)
- // gpt-oss: attn_norm (pre-attn) + post_attention_norm (pre-FFN, no ffn_norm!)
- // exaone4: post_attention_norm (pre-attn!) + post_ffw_norm (pre-FFN!) — no attn_norm
- //
- // Rule: post_attention_norm is a true POST-attn norm only when both attn_norm.weight
- // AND ffn_norm.weight also exist. Same for post_ffw_norm as a true POST-FFN norm.
- {
- const bool has_attn_norm_w = has("blk.0.attn_norm.weight");
- const bool has_ffn_norm_w = has("blk.0.ffn_norm.weight");
- has_attn_post_norm = has("blk.0.post_attention_norm.weight") && has_attn_norm_w && has_ffn_norm_w;
- has_ffn_post_norm = has("blk.0.post_ffw_norm.weight") && has_ffn_norm_w;
-
- // Compute effective pre-attn and pre-FFN norm key suffixes.
- // Standard: "attn_norm.weight" / "ffn_norm.weight".
- // exaone4: "post_attention_norm.weight" / "post_ffw_norm.weight".
- // gpt-oss: "attn_norm.weight" / "post_attention_norm.weight".
- if (!has_attn_norm_w && has("blk.0.post_attention_norm.weight")) {
- attn_norm_key = "post_attention_norm.weight"; // exaone4
- }
- if (!has_ffn_norm_w) {
- if (has("blk.0.post_ffw_norm.weight")) {
- ffn_norm_key = "post_ffw_norm.weight"; // exaone4
- } else if (has("blk.0.post_attention_norm.weight")) {
- ffn_norm_key = "post_attention_norm.weight"; // gpt-oss
- }
- }
- }
+ qk_norm_after_rope =
+ 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") &&
+ (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"));
+ 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;
// gpt-oss uses "softmax-after-topk" gating + the OAI gated activation; OLMoE uses
// softmax-before-topk + plain SwiGLU. Detect by weight-tensor presence so the logic
// extends to future architectures without touching this file.
@@ -157,7 +135,9 @@ 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;
+ rope_on_swa_only = is_muse_glimmer || (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
// ---- qwen35 (Qwen3.5/3.6): hybrid Gated-DeltaNet + full attention ----
@@ -214,7 +194,9 @@ DecoderConfig::DecoderConfig(const std::map<std::string, GGUFMetaData>& config,
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
- expert_weights_norm = cfg_i("expert_weights_norm") != 0;
+ // 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);
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).
@@ -242,12 +224,54 @@ DecoderConfig::DecoderConfig(const std::map<std::string, GGUFMetaData>& config,
rope_config.freq_scale = cfg_f("rope_freq_scale");
rope_config.ext_factor = cfg_f("rope_ext_factor");
rope_config.attn_factor = 1.0f;
- rope_config.beta_fast = 32.0f;
- rope_config.beta_slow = 1.0f;
+ rope_config.beta_fast = cfg_f("rope_yarn_beta_fast");
+ rope_config.beta_slow = cfg_f("rope_yarn_beta_slow");
+ const float yarn_log_mul = cfg_f("rope_yarn_log_mul");
+ if (rope_config.ext_factor != 0.0f && yarn_log_mul != 0.0f && rope_config.freq_scale < 1.0f) {
+ // The RoPE translator already applies YaRN's default magnitude factor.
+ rope_config.attn_factor /= 1.0f + 0.1f * yarn_log_mul * std::log(1.0f / rope_config.freq_scale);
+ }
+ attention_temperature_scale = cfg_f("attention_temperature_scale");
+ OPENVINO_ASSERT(attention_temperature_scale == 0.0f || rope_config.n_ctx_orig > 0,
+ "[GGUF] Attention temperature scaling requires a positive original context length");
// Gemma4: separate rope config for SWA layers (different freq_base and n_dims).
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");
+ if (options.geglu)
+ is_geglu = *options.geglu;
+ if (options.value_norm)
+ has_v_norm = *options.value_norm;
+ if (options.embedding_norm)
+ scaleless_embd_norm = *options.embedding_norm;
+ if (options.rope_on_swa_only)
+ rope_on_swa_only = *options.rope_on_swa_only;
+ if (options.post_norm_epsilon) {
+ OPENVINO_ASSERT(std::isfinite(*options.post_norm_epsilon) && *options.post_norm_epsilon > 0,
+ "[GGUF] post-norm epsilon must be finite and positive");
+ post_norm_eps = *options.post_norm_epsilon;
+ }
+ if (options.swa_rope_frequency_base) {
+ OPENVINO_ASSERT(std::isfinite(*options.swa_rope_frequency_base) && *options.swa_rope_frequency_base > 0,
+ "[GGUF] SWA RoPE frequency base must be finite and positive");
+ rope_freq_base_swa = rope_config_swa.freq_base = *options.swa_rope_frequency_base;
+ }
+ if (options.swa_rope_dimensions) {
+ OPENVINO_ASSERT(*options.swa_rope_dimensions > 0 && *options.swa_rope_dimensions % 2 == 0 &&
+ *options.swa_rope_dimensions <= (head_size_swa > 0 ? head_size_swa : head_size),
+ "[GGUF] SWA RoPE dimensions must be positive, even and fit the attention head");
+ rope_dim_swa = rope_config_swa.n_dims = *options.swa_rope_dimensions;
+ }
+ if (options.sliding_window) {
+ OPENVINO_ASSERT(*options.sliding_window > 0, "[GGUF] sliding window must be positive");
+ swa_window_size = *options.sliding_window;
+ has_swa = true;
+ }
+ if (rope) {
+ rope_op_case = *rope == RopeMode::Interleaved ? ROPE_OP_CASE_IMROPE
+ : *rope == RopeMode::Neox ? ROPE_OP_CASE_NEOX
+ : ROPE_OP_CASE_NORMAL;
+ }
// Per-op sin/cos is required whenever SWA and global layers differ in any rope
// parameter that feeds the shared sin/cos table: n_dims (gemma4) OR freq_base (gemma3,
// whose SWA layers rope at 10000 vs the global 1000000). Without it every layer would
@@ -267,6 +291,10 @@ DecoderConfig::DecoderConfig(const std::map<std::string, GGUFMetaData>& config,
}
}
+bool DecoderConfig::layer_is_moe(int il) const {
+ return is_moe && il >= n_dense_lead && (il + 1) % moe_layer_step == 0;
+}
+
bool DecoderConfig::layer_is_swa(int il) const {
if (!swa_layer_flags.empty()) {
return il < static_cast<int>(swa_layer_flags.size()) && swa_layer_flags[il] != 0;
diff --git a/src/frontends/gguf/src/builder/decoder_config.hpp b/src/frontends/gguf/src/builder/decoder_config.hpp
index 3663e5fcec9..263f73d43f9 100644
--- a/src/frontends/gguf/src/builder/decoder_config.hpp
+++ b/src/frontends/gguf/src/builder/decoder_config.hpp
@@ -4,11 +4,11 @@
#pragma once
-#include <map>
#include <string>
#include <unordered_map>
#include <vector>
+#include "openvino/frontend/gguf/builder/decoder_options.hpp"
#include "openvino/frontend/gguf/decoder.hpp"
#include "openvino/runtime/tensor.hpp"
#include "quant/gguf.hpp"
@@ -17,23 +17,15 @@ namespace ov {
namespace frontend {
namespace gguf {
-// Everything the decoder topology needs to know about ONE model, resolved once up front.
-//
-// This is the GGUF frontend's equivalent of llama.cpp's llama_hparams plus its per-arch
-// load_arch_hparams: a flat, already-decided description of the model, so the topology builder in
-// arch/decoder_builder.cpp never re-derives anything and reads declaratively.
-//
-// Almost every field is DETECTED, not hard-coded per architecture: the presence of a layer-0
-// weight tensor decides whether the model has QK-norm, projection biases, fused QKV, MoE routing,
-// attention sinks, post-norms and so on. That is what lets a new same-family architecture be
-// enabled by adding its name to arch_registry.cpp and writing no code at all. Only a handful of
-// genuinely tensor-table-ambiguous properties (GeGLU vs SwiGLU, gemma4's V-norm) fall back to an
-// architecture-name check; prefer weight presence when adding a new one.
+// Internal configuration resolved from metadata, tensor shapes and architecture semantics.
+// Extensions override ambiguous semantics through DecoderOptions before dependent plans are built.
struct DecoderConfig {
// Resolve the whole description from the parsed metadata (already normalized by
// config_from_meta) and the parser's tensor table.
DecoderConfig(const std::map<std::string, GGUFMetaData>& config,
- const std::unordered_map<std::string, ov::Tensor>& weights);
+ const std::unordered_map<std::string, ov::Tensor>& weights,
+ std::optional<RopeMode> rope = {},
+ const DecoderOptions& options = {});
std::string arch;
@@ -48,8 +40,9 @@ struct DecoderConfig {
// ---- auto-detected per-architecture structure ----
bool has_qk_norm = false;
- bool qk_norm_full = false; // norm width is n_head*head_size (OLMoE) rather than per-head
- bool qk_norm_after_rope = false; // Hunyuan applies learned per-head Q/K norm after RoPE
+ bool qk_norm_after_rope = false;
+ bool post_norm_only = false;
+ bool qk_norm_full = false; // norm width is n_head*head_size (OLMoE) rather than per-head
bool has_qkv_bias = false;
bool has_attn_out_bias = false;
bool has_rope_freqs = false;
@@ -69,8 +62,9 @@ struct DecoderConfig {
// muse-glimmer specifics
bool has_attn_gate = false; // sigmoid gate multiplied into the attention output
bool scaleless_embd_norm = false; // weightless RMSNorm on the token embeddings
- bool rope_on_swa_only = false; // global (non-SWA) layers are NoPE
- float post_norm_eps = 0.0f; // eps for post-attn/post-FFN norms (0 -> rms_eps)
+ int rope_skip_period = 0;
+ bool rope_on_swa_only = false; // global (non-SWA) layers are NoPE
+ float post_norm_eps = 0.0f; // eps for post-attn/post-FFN norms (0 -> rms_eps)
// ---- qwen35 (hybrid Gated-DeltaNet + full attention) ----
bool is_qwen35 = false;
@@ -84,7 +78,7 @@ struct DecoderConfig {
std::vector<int32_t> rope_sections; // M-RoPE per-axis section widths
std::vector<int32_t> recurrent_layer_flags; // explicit per-layer recurrent flags
- // Norm key suffixes; overridden for archs that use non-standard naming (exaone4, gpt-oss).
+ // Pre-norm key suffixes; GPT-OSS uses post_attention_norm for its pre-FFN norm.
std::string attn_norm_key{"attn_norm.weight"};
std::string ffn_norm_key{"ffn_norm.weight"};
@@ -92,11 +86,15 @@ struct DecoderConfig {
int n_expert = 0;
int n_expert_used = 0;
int n_dense_lead = 0;
- int n_expert_shared = 0;
+ int moe_layer_step = 1;
+ bool moe_sigmoid_gating = false;
+ int expert_groups = 1;
+ int expert_groups_used = 1;
float embedding_scale = 1.0f;
float residual_scale = 1.0f;
float logit_scale = 1.0f;
- float attention_scale = 0.0f; // 0 -> 1/sqrt(head_size)
+ float attention_scale = 0.0f; // 0 -> 1/sqrt(head_size)
+ float attention_temperature_scale = 0.0f;
float expert_weights_scale = 0.0f; // 0 -> 1.0 no-op
bool expert_weights_norm = false; // renormalize top-K gate weights to sum to 1 (qwen3moe etc.)
float attn_soft_cap = 0.0f;
@@ -130,6 +128,7 @@ struct DecoderConfig {
// boolean array; gpt-oss/gemma3/smollm3 use a period (il is SWA unless it is the last in each
// period, matching llama.cpp set_swa_pattern(period, dense_first=false)).
bool layer_is_swa(int il) const;
+ bool layer_is_moe(int il) const;
// Head size for layer `il`. gemma4 SWA layers use a smaller head size than global layers.
int layer_head_size(int il) const;
diff --git a/src/frontends/gguf/src/builder/gguf_builder.cpp b/src/frontends/gguf/src/builder/gguf_builder.cpp
index 1628f1fe707..c9855cfc9d7 100644
--- a/src/frontends/gguf/src/builder/gguf_builder.cpp
+++ b/src/frontends/gguf/src/builder/gguf_builder.cpp
@@ -1,35 +1,21 @@
// Copyright (C) 2018-2026 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
-// Entry point of the native GGUF -> GgufGraph path: parse the container, decide which model FAMILY
-// the file holds, and hand it to that family's ModelBuilder. No llama.cpp / gguf dependency.
-//
-// The emitted nodes use the GGML op vocabulary and reproduce llama.cpp's cgraph topology, so the
-// resulting GgufGraph drives the same op translators as the llama.cpp cgraph path.
-//
-// Layering (see docs/adding_an_architecture.md):
-// graph_emitter.hpp arch-agnostic "how do I write a node"
-// blocks/ reusable graph fragments (norm, ffn, attention, gated delta net)
-// decoder_config.hpp all per-architecture detection for the decoder family
-// arch/decoder_builder the decoder family's topology
-// arch_registry.hpp which architectures are accepted, and their RoPE mode
-// model_kind.hpp which family a file belongs to
-//
-// Adding an ARCHITECTURE of an existing family is a name in arch_registry.cpp.
-// Adding a FAMILY (mmproj vision/audio, encoder-decoder) is a new ModelBuilder subclass plus a
-// branch in build_ggml_graph_from_gguf below; nothing existing changes.
+// 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.
#include "gguf_builder.hpp"
#include <memory>
#include <type_traits>
+#include "builder/api/metadata_store.hpp"
#include "builder/arch/decoder_builder.hpp"
#include "builder/arch_registry.hpp"
-#include "builder/model_builder.hpp"
#include "builder/model_kind.hpp"
#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"
@@ -67,37 +53,48 @@ ov::AnyMap extract_tokenizer_config(const std::unordered_map<std::string, GGUFMe
} // namespace
-std::shared_ptr<GgufGraph> build_ggml_graph_from_gguf(const std::string& file) {
- auto [metadata, weights, qtypes, mmap, quant_buf] = get_gguf_data(file);
+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;
- // Decide the family FIRST: the metadata key layout differs per family, so reading any
- // decoder hyperparameter before this point would misreport an mmproj file as a broken LLM.
- const ModelKind kind = detect_model_kind(metadata);
- OPENVINO_ASSERT(kind == ModelKind::DECODER,
- "[GGUF] this file holds a ",
- model_kind_name(kind),
- " model; the native GGUF builder currently implements the decoder family only. "
- "Support is added by implementing a ModelBuilder subclass for that family (see "
- "builder/model_builder.hpp).");
+ const detail::MetadataStore meta_store{metadata};
+ const GgufMetadata meta_view(meta_store);
- auto config = decoder_config_from_meta(metadata);
-
- const std::string arch = std::get<std::string>(config.at("architecture"));
- OPENVINO_ASSERT(supported_archs().count(arch),
- "[GGUF] native GGUF builder does not support architecture '",
- arch,
- "'. See supported_archs() in builder/arch_registry.cpp for the full list.");
- if (experimental_archs().count(arch)) {
- OPENVINO_WARN("[GGUF] architecture '",
- arch,
- "' is experimental: it is built by structural auto-detection but has not been "
- "end-to-end verified against a reference. Validate accuracy before relying on it.");
+ // Built-in and external definitions share selection, construction and postprocessing.
+ // Family detection is only a diagnostic fallback; it must not reject a registered family.
+ const auto definition = registry.find(meta_view);
+ if (!definition) {
+ const auto kind = detect_model_kind(metadata);
+ OPENVINO_ASSERT(kind == ModelKind::DECODER,
+ "[GGUF] no builder for ",
+ model_kind_name(kind),
+ "; the default catalog implements the decoder family. Register an ArchitectureExtension.");
+ OPENVINO_THROW("[GGUF] native GGUF builder does not support architecture '",
+ meta_view.architecture(),
+ "'. Supported: ",
+ registry.describe_supported(),
+ ". Register an ArchitectureExtension.");
}
-
- std::unique_ptr<ModelBuilder> builder = std::make_unique<DecoderBuilder>(config, weights, qtypes);
- auto graph = builder->build();
- graph->tokenizer_config = extract_tokenizer_config(metadata);
- return graph;
+ 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;
+ 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};
+ 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);
+ return graph;
+ };
}
} // namespace gguf
diff --git a/src/frontends/gguf/src/builder/gguf_builder.hpp b/src/frontends/gguf/src/builder/gguf_builder.hpp
index eb5a62209fe..f6dd95a45b4 100644
--- a/src/frontends/gguf/src/builder/gguf_builder.hpp
+++ b/src/frontends/gguf/src/builder/gguf_builder.hpp
@@ -4,20 +4,22 @@
#pragma once
+#include <functional>
#include <memory>
#include <string>
+#include "node_context.hpp"
+
namespace ov {
namespace frontend {
namespace gguf {
struct GgufGraph; // defined in gguf_graph.hpp; only used here as a shared_ptr return type
+class ArchRegistry;
-// Build a GgufGraph natively from a .gguf file (no llama.cpp / gguf dependency).
-// Parses the container, then dispatches to a per-architecture builder that emits nodes in
-// the GGML op vocabulary reproducing llama.cpp's cgraph topology for that architecture.
-// Throws if the architecture is not supported natively.
-std::shared_ptr<GgufGraph> build_ggml_graph_from_gguf(const std::string& file);
+using GraphBuilder = std::function<std::shared_ptr<GgufGraph>(const std::unordered_map<std::string, CreatorFunction>&)>;
+// Parse the file and select a definition; invoke the builder with the converters active at conversion.
+GraphBuilder load_gguf_builder(const std::string& file, const ArchRegistry& registry);
} // namespace gguf
} // namespace frontend
diff --git a/src/frontends/gguf/src/builder/gguf_builder_decoder.cpp b/src/frontends/gguf/src/builder/gguf_builder_decoder.cpp
index 5c75b42011c..16ca7364916 100644
--- a/src/frontends/gguf/src/builder/gguf_builder_decoder.cpp
+++ b/src/frontends/gguf/src/builder/gguf_builder_decoder.cpp
@@ -12,7 +12,9 @@ namespace ov {
namespace frontend {
namespace gguf {
-GgufBuilderDecoder::GgufBuilderDecoder(std::shared_ptr<GgufGraph> graph) : m_graph(std::move(graph)) {}
+GgufBuilderDecoder::GgufBuilderDecoder(std::shared_ptr<GgufGraph> graph, int node_index)
+ : m_graph(std::move(graph)),
+ m_node_idx(node_index) {}
const GgufOp& GgufBuilderDecoder::node() const {
OPENVINO_ASSERT(m_node_idx >= 0 && static_cast<size_t>(m_node_idx) < m_graph->nodes.size(),
@@ -21,39 +23,11 @@ const GgufOp& GgufBuilderDecoder::node() const {
return m_graph->nodes[m_node_idx];
}
-// ---- Per-node typed attribute ----
-//
-// In addition to keys stored in GgufOp::attributes, the following reserved keys are
-// served so external converters can access per-input/output metadata through the public
-// base NodeContext::get_attribute<T>() interface without including internal headers:
-//
-// "input_shape[N]" -> ov::PartialShape for input N (0-based)
-// "input_type[N]" -> ov::element::Type for input N
-// "input_stride[N]" -> std::vector<size_t> for input N
-// "input_view_offset[N]" -> int64_t for input N
-// "output_shape" -> ov::PartialShape of the node output
-// "output_type" -> ov::element::Type of the node output
-// "rope_config" -> RopeConfig (model-scope RoPE config; see get_attribute below)
-// "swa_window_size" -> int (model-scope sliding-window length in tokens; 0 -> not
-// configured in this model's metadata; see get_attribute below)
-
-static bool parse_indexed_key(const std::string& name, const std::string& prefix, size_t& out_idx) {
- if (name.size() <= prefix.size() + 2)
- return false;
- if (name.compare(0, prefix.size(), prefix) != 0)
- return false;
- if (name[prefix.size()] != '[' || name.back() != ']')
- return false;
- try {
- out_idx = static_cast<size_t>(std::stoul(name.substr(prefix.size() + 1, name.size() - prefix.size() - 2)));
- return true;
- } catch (...) {
- return false;
- }
-}
+// Expose operation parameters through the common decoder interface. Native nodes do not
+// carry source shapes; converters infer them from their OpenVINO inputs.
ov::Any GgufBuilderDecoder::get_attribute(const std::string& name) const {
- // RoPE config is queried at model scope (TranslateSession::preprocess, to build the shared
+ // 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
// fall through to the node's own "rope_config" attribute -- the builder stores a per-node
@@ -76,45 +50,9 @@ ov::Any GgufBuilderDecoder::get_attribute(const std::string& name) const {
const auto& n = node();
- // Reserved keys for per-input metadata
- size_t idx = 0;
- if (parse_indexed_key(name, "input_shape", idx)) {
- if (idx < n.input_names.size()) {
- auto it = n.input_shapes.find(n.input_names[idx]);
- if (it != n.input_shapes.end())
- return it->second;
- }
- return {};
- }
- if (parse_indexed_key(name, "input_type", idx)) {
- if (idx < n.input_names.size()) {
- auto it = n.input_types.find(n.input_names[idx]);
- if (it != n.input_types.end())
- return it->second;
- }
- return {};
- }
- if (parse_indexed_key(name, "input_stride", idx)) {
- if (idx < n.input_names.size()) {
- auto it = n.input_strides.find(n.input_names[idx]);
- if (it != n.input_strides.end())
- return it->second;
- }
- return {};
- }
- if (parse_indexed_key(name, "input_view_offset", idx)) {
- if (idx < n.input_names.size()) {
- auto it = n.input_view_offsets.find(n.input_names[idx]);
- return it != n.input_view_offsets.end() ? ov::Any(it->second) : ov::Any(int64_t{0});
- }
- return {};
- }
-
- // Reserved keys for per-output metadata
+ // Legacy source shape metadata is unavailable for native nodes.
if (name == "output_shape")
- return n.output_shape;
- if (name == "output_type")
- return n.output_type;
+ return ov::PartialShape::dynamic();
// Per-node op case (the op translators read it via get_attribute<int>("op_case", 0)).
if (name == "op_case")
@@ -127,20 +65,12 @@ ov::Any GgufBuilderDecoder::get_attribute(const std::string& name) const {
// ---- Per-input metadata ----
-PartialShape GgufBuilderDecoder::get_input_shape(const std::string& name) const {
- const auto& m = node().input_shapes;
- auto it = m.find(name);
- OPENVINO_ASSERT(it != m.end(), "[gguf] no input shape for '", name, "'");
- return it->second;
+PartialShape GgufBuilderDecoder::get_input_shape(const std::string&) const {
+ return ov::PartialShape::dynamic();
}
-int64_t GgufBuilderDecoder::get_input_view_element_offset(const std::string& name) const {
- // The builder does not emit strided VIEW inputs (it materializes slices as explicit ops), so
- // there is no view offset to convert; the stored offsets, when present, are already in
- // elements. Return 0 when the input is not a view.
- const auto& m = node().input_view_offsets;
- auto it = m.find(name);
- return it == m.end() ? 0 : it->second;
+int64_t GgufBuilderDecoder::get_input_view_element_offset(const std::string&) const {
+ return 0;
}
size_t GgufBuilderDecoder::get_input_size() const {
@@ -154,7 +84,7 @@ std::vector<std::string> GgufBuilderDecoder::get_input_names() const {
// ---- Per-node output metadata ----
PartialShape GgufBuilderDecoder::get_output_shape() const {
- return node().output_shape;
+ return ov::PartialShape::dynamic();
}
std::vector<std::string> GgufBuilderDecoder::get_output_names() const {
diff --git a/src/frontends/gguf/src/builder/gguf_builder_decoder.hpp b/src/frontends/gguf/src/builder/gguf_builder_decoder.hpp
index 8252236412e..5ccf4fe2331 100644
--- a/src/frontends/gguf/src/builder/gguf_builder_decoder.hpp
+++ b/src/frontends/gguf/src/builder/gguf_builder_decoder.hpp
@@ -23,7 +23,11 @@ namespace gguf {
// the node it is bound to, so no node index is threaded through the interface.
class GgufBuilderDecoder : public GgufDecoder {
public:
- explicit GgufBuilderDecoder(std::shared_ptr<GgufGraph> graph);
+ explicit GgufBuilderDecoder(std::shared_ptr<GgufGraph> graph, int node_index = -1);
+
+ const std::shared_ptr<TensorMap>& values() const {
+ return m_graph->values;
+ }
// Per-node accessors (bound to the node this decoder instance was cloned for).
ov::Any get_attribute(const std::string& name) const override;
diff --git a/src/frontends/gguf/src/builder/gguf_graph.hpp b/src/frontends/gguf/src/builder/gguf_graph.hpp
index cf910d21486..b36c2fe7757 100644
--- a/src/frontends/gguf/src/builder/gguf_graph.hpp
+++ b/src/frontends/gguf/src/builder/gguf_graph.hpp
@@ -9,6 +9,7 @@
#include <string>
#include <vector>
+#include "node_context.hpp"
#include "openvino/core/any.hpp"
#include "openvino/core/node.hpp"
#include "openvino/core/partial_shape.hpp"
@@ -29,17 +30,8 @@ struct GgufOp {
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
- ov::PartialShape output_shape;
- ov::element::Type output_type = ov::element::dynamic;
int op_case = 0;
- // Per-input shape/stride/type and view-offset, keyed by input name. Populated for the
- // inputs that translators query (shapes for MUL_MAT/RESHAPE, view offsets for VIEW).
- std::map<std::string, ov::PartialShape> input_shapes;
- std::map<std::string, std::vector<size_t>> input_strides;
- std::map<std::string, ov::element::Type> input_types;
- std::map<std::string, int64_t> input_view_offsets;
-
// Typed scalar/struct op attributes consumed by translators via get_attribute<T>
// (e.g. "eps", "scale", "bias", "max_bias", "swapped", "rope_config").
std::map<std::string, ov::Any> attributes;
@@ -50,6 +42,7 @@ struct GgufOp {
// a parsed GGUF file; consumed by GgufBuilderDecoder.
struct GgufGraph {
std::vector<GgufOp> nodes;
+ std::shared_ptr<TensorMap> values = std::make_shared<TensorMap>();
// Model inputs (Parameters) and extra inputs (e.g. attention_size; Parameter or Constant).
// Same semantics as the corresponding GgufDecoder getters. Weights are not here: they are
diff --git a/src/frontends/gguf/src/builder/graph_emitter.cpp b/src/frontends/gguf/src/builder/graph_emitter.cpp
index 0c445eb26cc..1ec2572b955 100644
--- a/src/frontends/gguf/src/builder/graph_emitter.cpp
+++ b/src/frontends/gguf/src/builder/graph_emitter.cpp
@@ -4,8 +4,11 @@
#include "graph_emitter.hpp"
+#include "gguf_builder_decoder.hpp"
+#include "op_table.hpp"
#include "openvino/core/except.hpp"
#include "openvino/op/constant.hpp"
+#include "translate_session.hpp"
namespace ov {
namespace frontend {
@@ -40,11 +43,13 @@ WeightTensors find_weight_tensors(const std::unordered_map<std::string, ov::Tens
GraphEmitter::GraphEmitter(std::unordered_map<std::string, ov::Tensor>& weights,
std::unordered_map<std::string, GgufTensorType>& qtypes,
- std::string arch)
+ std::string arch,
+ const std::unordered_map<std::string, CreatorFunction>* translators)
: m_weights(weights),
m_qtypes(qtypes),
m_arch(std::move(arch)),
- m_graph(std::make_shared<GgufGraph>()) {}
+ m_graph(std::make_shared<GgufGraph>()),
+ m_translators(translators ? *translators : get_supported_ops()) {}
const ov::Tensor& GraphEmitter::weight_tensor(const std::string& name) const {
auto it = m_weights.find(name);
@@ -66,33 +71,15 @@ int64_t GraphEmitter::weight_rows(const std::string& name) const {
return s.empty() ? 1 : static_cast<int64_t>(s[0]);
}
-const ov::PartialShape& GraphEmitter::shape_of_tensor(const std::string& name) const {
- auto it = m_tensor_shapes.find(name);
- OPENVINO_ASSERT(it != m_tensor_shapes.end(), "[GGUF] internal: no shape recorded for '", name, "'");
+const ov::Output<ov::Node>& GraphEmitter::value(const std::string& name) const {
+ const auto it = m_graph->values->find(name);
+ OPENVINO_ASSERT(it != m_graph->values->end(), "[GGUF] unknown value '", name, "'");
return it->second;
}
-ov::Shape GraphEmitter::static_shape_of(const std::string& tensor_name) const {
- const auto& shape = shape_of_tensor(tensor_name);
- OPENVINO_ASSERT(shape.is_static(),
- "[GGUF] internal: shape of '",
- tensor_name,
- "' is dynamic (",
- shape,
- "), cannot be used as a static input shape");
- return shape.to_shape();
-}
-
-void GraphEmitter::set_tensor_meta(const std::string& name, const ov::PartialShape& shape, ov::element::Type type) {
- m_tensor_shapes[name] = shape;
- m_tensor_types[name] = type;
-}
-
std::string GraphEmitter::add_op(const std::string& op_type,
const std::string& name,
const std::vector<std::string>& inputs,
- const ov::PartialShape& out_shape,
- ov::element::Type out_type,
int op_case,
std::map<std::string, ov::Any> attrs) {
GgufOp op;
@@ -100,23 +87,14 @@ std::string GraphEmitter::add_op(const std::string& op_type,
op.name = name;
op.input_names = inputs;
op.output_name = name;
- op.output_shape = out_shape;
- op.output_type = out_type;
op.op_case = op_case;
op.attributes = std::move(attrs);
- // Fill per-input shape/type from known producers so translators that query them
- // (MUL_MAT, RESHAPE) get sane values.
- for (const auto& in : inputs) {
- if (auto it = m_tensor_shapes.find(in); it != m_tensor_shapes.end()) {
- op.input_shapes[in] = it->second;
- }
- if (auto it = m_tensor_types.find(in); it != m_tensor_types.end()) {
- op.input_types[in] = it->second;
- }
- }
- m_tensor_shapes[name] = out_shape;
- m_tensor_types[name] = out_type;
m_graph->nodes.push_back(std::move(op));
+ auto decoder = std::make_shared<GgufBuilderDecoder>(m_graph);
+ prepare_graph_inputs(*m_graph->values, *decoder);
+ translate_node(std::make_shared<GgufBuilderDecoder>(m_graph, static_cast<int>(m_graph->nodes.size() - 1)),
+ m_graph->values,
+ m_translators);
return name;
}
@@ -127,6 +105,7 @@ std::shared_ptr<ov::op::v0::Parameter> GraphEmitter::add_input(const std::string
p->set_friendly_name(name);
p->output(0).set_names({name});
m_graph->model_inputs[name] = p;
+ (*m_graph->values)[name] = p;
return p;
}
@@ -134,42 +113,30 @@ void GraphEmitter::add_extra_input(const std::string& name, int64_t value) {
auto c = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {value});
c->set_friendly_name(name);
m_graph->model_extra_inputs[name] = c;
+ (*m_graph->values)[name] = c;
}
void GraphEmitter::add_extra_input_node(const std::string& name, const std::shared_ptr<ov::Node>& node) {
m_graph->model_extra_inputs[name] = node;
+ (*m_graph->values)[name] = node;
}
-void GraphEmitter::emit_weight_op(const std::string& node_name,
- const WeightTensors& tensors,
- GgufTensorType qtype,
- const ov::PartialShape& shape_4d) {
+void GraphEmitter::emit_weight_op(const std::string& node_name, const WeightTensors& tensors, GgufTensorType qtype) {
if (m_emitted_weights.count(node_name)) {
return;
}
m_emitted_weights.insert(node_name);
- GgufOp op;
- op.op_type = "GGML_OP_NONE";
- op.name = node_name;
- op.output_name = node_name;
- op.output_shape = shape_4d;
- op.output_type = ov::element::f32;
- // translate_weight reads these into a WeightTensors payload:
- // "gguf.blob.<sub>" -> extracted tensor (<sub> in {weight, scales, zp}), and the qtype id.
- op.attributes["gguf_weight"] = true; // marks this GGML_OP_NONE leaf as a weight
- op.attributes["gguf_qtype"] = static_cast<int>(qtype);
- op.attributes["gguf.blob.weight"] = tensors.weight;
+ std::map<std::string, ov::Any> attrs{{"gguf_weight", true},
+ {"gguf_qtype", static_cast<int>(qtype)},
+ {"gguf.blob.weight", tensors.weight}};
if (tensors.scales) {
- op.attributes["gguf.blob.scales"] = tensors.scales;
+ attrs["gguf.blob.scales"] = tensors.scales;
}
if (tensors.zero_point) {
- op.attributes["gguf.blob.zp"] = tensors.zero_point;
+ attrs["gguf.blob.zp"] = tensors.zero_point;
}
- m_graph->nodes.push_back(std::move(op));
-
- m_tensor_shapes[node_name] = shape_4d;
- m_tensor_types[node_name] = ov::element::f32;
+ add_op("GGML_OP_NONE", node_name, {}, 0, std::move(attrs));
}
void GraphEmitter::add_weight(const std::string& ggml_name) {
@@ -184,15 +151,7 @@ void GraphEmitter::add_weight(const std::string& ggml_name) {
qtype = it->second;
}
- // Shape padded to the decoder's rank-4 convention; the extents matter only as the
- // per-input shape/type for translators (MUL_MAT) that index dims [1] and [3].
- int64_t rows = 1, cols = 1;
- if (auto it = m_weights.find(ggml_name); it != m_weights.end()) {
- const auto& s = it->second.get_shape(); // [rows, cols(packed)]
- rows = s.size() >= 1 ? static_cast<int64_t>(s[0]) : 1;
- cols = s.size() >= 2 ? static_cast<int64_t>(s[1]) : 1;
- }
- emit_weight_op(ggml_name, tensors, qtype, ov::PartialShape({1, 1, rows, cols}));
+ emit_weight_op(ggml_name, tensors, qtype);
}
void GraphEmitter::add_weight_from(const std::string& node_name, const std::string& src_base) {
@@ -204,13 +163,7 @@ void GraphEmitter::add_weight_from(const std::string& node_name, const std::stri
if (auto it = m_qtypes.find(src_base + ".qtype"); it != m_qtypes.end()) {
qtype = it->second;
}
- int64_t rows = 1, cols = 1;
- if (auto it = m_weights.find(src_base + ".weight"); it != m_weights.end()) {
- const auto& s = it->second.get_shape();
- rows = s.size() >= 1 ? static_cast<int64_t>(s[0]) : 1;
- cols = s.size() >= 2 ? static_cast<int64_t>(s[1]) : 1;
- }
- emit_weight_op(node_name, tensors, qtype, ov::PartialShape({1, 1, rows, cols}));
+ emit_weight_op(node_name, tensors, qtype);
}
void GraphEmitter::add_named_weight(const std::string& ggml_name) {
@@ -225,12 +178,7 @@ void GraphEmitter::add_named_weight(const std::string& ggml_name) {
GgufTensorType qtype = w.get_element_type() == ov::element::f32 ? GGUF_TYPE_F32
: w.get_element_type() == ov::element::bf16 ? GGUF_TYPE_BF16
: GGUF_TYPE_F16;
- const auto& s = w.get_shape();
- int64_t n = s.empty() ? 1 : static_cast<int64_t>(s[0]);
- // 2-D plain weights (qwen35's ssm_conv1d, OV [conv_dim, d_conv]) keep both extents;
- // 1-D ones (biases, norm scales) are the common case and stay a trailing vector.
- const ov::PartialShape shape = s.size() == 2 ? ps({1, 1, n, static_cast<int64_t>(s[1])}) : ps({1, 1, 1, n});
- emit_weight_op(ggml_name, {w, {}, {}}, qtype, shape);
+ emit_weight_op(ggml_name, {w, {}, {}}, qtype);
}
} // namespace gguf
diff --git a/src/frontends/gguf/src/builder/graph_emitter.hpp b/src/frontends/gguf/src/builder/graph_emitter.hpp
index 9f9f03c0899..4af1cc29895 100644
--- a/src/frontends/gguf/src/builder/graph_emitter.hpp
+++ b/src/frontends/gguf/src/builder/graph_emitter.hpp
@@ -24,26 +24,15 @@ namespace ov {
namespace frontend {
namespace gguf {
-// Appends nodes to a GgufGraph and tracks the shape/type of every tensor emitted so far.
-//
-// This is the whole "how do I write a node" layer, and it knows nothing about transformers,
-// attention or any architecture: it is the GGUF-frontend counterpart of ggml's ggml_context +
-// ggml_build_forward_expand. Everything above it (the block library in blocks/, the per-family
-// topology builders in arch/) is expressed purely in terms of these calls, which is what lets a
-// non-decoder family (mmproj/vision, audio) reuse it verbatim.
-//
-// Owns the emit-time bookkeeping the graph itself does not carry:
-// - tensor shapes/types, so add_op can fill each node's per-input shape/type metadata for the
-// translators that query it (MUL_MAT, RESHAPE, VIEW);
-// - the set of already-emitted weight leaves, so a weight referenced by several ops (or tied,
-// e.g. MQA tie-V) is emitted exactly once.
+// Builds OpenVINO values through the shared GGML converters.
class GraphEmitter {
public:
// `weights` / `qtypes` are the parser's tensor tables; they are referenced, not copied, and
// must outlive the emitter.
GraphEmitter(std::unordered_map<std::string, ov::Tensor>& weights,
std::unordered_map<std::string, GgufTensorType>& qtypes,
- std::string arch);
+ std::string arch,
+ const std::unordered_map<std::string, CreatorFunction>* translators = nullptr);
// ---- graph under construction ----
const std::shared_ptr<GgufGraph>& graph() const {
@@ -71,18 +60,7 @@ public:
return m_qtypes;
}
- // ---- emitted-tensor queries ----
- const ov::PartialShape& shape_of_tensor(const std::string& name) const;
-
- // Static shape of an already-emitted tensor, for ops whose translator needs its input's own
- // layout (VIEW op_case 3's "input_ggml_shape", which it uses to restore that layout before
- // slicing). Per-node shapes are static except for the model-input Parameters, so a dynamic dim
- // here means the caller asked about a tensor this cannot describe.
- ov::Shape static_shape_of(const std::string& tensor_name) const;
-
- // Record a shape/type for a tensor the emitter did not create itself (a model input reused as
- // an op input at a representative token length).
- void set_tensor_meta(const std::string& name, const ov::PartialShape& shape, ov::element::Type type);
+ const ov::Output<ov::Node>& value(const std::string& name) const;
bool has_model_input(const std::string& name) const {
return m_graph->model_inputs.count(name) > 0;
@@ -95,8 +73,6 @@ public:
std::string add_op(const std::string& op_type,
const std::string& name,
const std::vector<std::string>& inputs,
- const ov::PartialShape& out_shape,
- ov::element::Type out_type,
int op_case = 0,
std::map<std::string, ov::Any> attrs = {});
@@ -108,18 +84,8 @@ public:
void add_extra_input_node(const std::string& name, const std::shared_ptr<ov::Node>& node);
- // Emit a weight as a GGML_OP_NONE leaf node carrying the parser's already-extracted tensors
- // (`<base>.weight` [+ `.scales` [+ `.zp`]] + qtype) as node attributes. translate_weight
- // rebuilds a WeightTensors payload from these attributes and calls make_weight_node.
- // Routing weights through GGML_OP_NONE makes that the single weight-loading
- // API, shared with the llama.cpp cgraph decoder (which marks the same leaf with raw ggml bytes
- // instead), and keeps the compressed decompression subgraph -- built lazily in translate_weight
- // during the walk -- rather than materializing an ov::Node eagerly here.
- // `node_name` is the tensor name translators reference (the GGML_OP_NONE output).
- void emit_weight_op(const std::string& node_name,
- const WeightTensors& tensors,
- GgufTensorType qtype,
- const ov::PartialShape& shape_4d);
+ // The shared weight converter constructs the compressed OpenVINO subgraph from parsed tensors.
+ void emit_weight_op(const std::string& node_name, const WeightTensors& tensors, GgufTensorType qtype);
// `ggml_name` is the full tensor name ending in ".weight" (the name translators reference).
void add_weight(const std::string& ggml_name);
@@ -146,8 +112,7 @@ private:
std::string m_arch;
std::shared_ptr<GgufGraph> m_graph;
- std::map<std::string, ov::PartialShape> m_tensor_shapes;
- std::map<std::string, ov::element::Type> m_tensor_types;
+ std::unordered_map<std::string, CreatorFunction> m_translators;
// Names of weights already emitted as GGML_OP_NONE leaves, so a weight referenced by several
// ops (or tied, e.g. MQA tie-V) is emitted once.
std::set<std::string> m_emitted_weights;
diff --git a/src/frontends/gguf/src/builder/model_builder.hpp b/src/frontends/gguf/src/builder/model_builder.hpp
deleted file mode 100644
index 1c1dd9e83e5..00000000000
--- a/src/frontends/gguf/src/builder/model_builder.hpp
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (C) 2018-2026 Intel Corporation
-// SPDX-License-Identifier: Apache-2.0
-//
-
-#pragma once
-
-#include <memory>
-
-#include "builder/gguf_graph.hpp"
-
-namespace ov {
-namespace frontend {
-namespace gguf {
-
-// Base class for a whole-model graph builder: one subclass per MODEL FAMILY, not per architecture.
-//
-// A family is a distinct graph SHAPE with its own inputs, its own block vocabulary and its own
-// notion of a "layer": the causal decoder stack (DecoderBuilder, arch/decoder_builder.hpp) is one;
-// a vision/mmproj encoder or an audio encoder would each be another. Within a family, individual
-// architectures are data, not code -- they are detected from the GGUF tensor table and metadata
-// (see DecoderConfig) and enabled by name in arch_registry.cpp.
-//
-// This mirrors llama.cpp's split between llm_graph_context (LLMs) and clip_graph (mmproj), where
-// each family has its own base and its own build_norm/build_ffn/build_attn vocabulary, rather than
-// one builder growing flags for structurally unrelated models.
-//
-// To add a family: subclass this, implement build(), and dispatch to it from
-// build_ggml_graph_from_gguf() on the detected ModelKind. Nothing in the existing families needs
-// to change, and the arch-agnostic pieces (GraphEmitter, blocks/common) are reused as-is.
-class ModelBuilder {
-public:
- virtual ~ModelBuilder() = default;
-
- // Emit the whole model and return the finished graph.
- virtual std::shared_ptr<GgufGraph> build() = 0;
-};
-
-} // namespace gguf
-} // namespace frontend
-} // namespace ov
diff --git a/src/frontends/gguf/src/extension/architecture.cpp b/src/frontends/gguf/src/extension/architecture.cpp
new file mode 100644
index 00000000000..679acd5a2d5
--- /dev/null
+++ b/src/frontends/gguf/src/extension/architecture.cpp
@@ -0,0 +1,47 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/frontend/gguf/extension/architecture.hpp"
+
+#include "builder/api/metadata_store.hpp"
+#include "builder/arch/decoder_builder.hpp"
+#include "openvino/core/except.hpp"
+
+namespace ov::frontend::gguf {
+
+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 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{};
+ auto config = decoder_config_from_meta(detail::MetadataAccess::get(ctx.metadata).map);
+ return std::make_shared<DecoderBuilder>(config,
+ ctx.weights->weights,
+ ctx.weights->qtypes,
+ rope,
+ overrides,
+ ctx.weights->translators);
+ };
+ return definition;
+}
+
+ArchitectureExtension::ArchitectureExtension(ArchitectureDefinition definition, RegistrationMode mode)
+ : 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() = default;
+
+} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/frontend.cpp b/src/frontends/gguf/src/frontend.cpp
index 3f294c21dc2..b783efb665f 100644
--- a/src/frontends/gguf/src/frontend.cpp
+++ b/src/frontends/gguf/src/frontend.cpp
@@ -7,6 +7,7 @@
#include <filesystem>
#include <fstream>
+#include "builder/arch_registry.hpp"
#include "builder/gguf_builder.hpp"
#include "builder/gguf_builder_decoder.hpp"
#include "input_model.hpp"
@@ -17,6 +18,7 @@
#include "openvino/frontend/extension/decoder_transformation.hpp"
#include "openvino/frontend/extension/telemetry.hpp"
#include "openvino/frontend/gguf/decoder.hpp"
+#include "openvino/frontend/gguf/extension/architecture.hpp"
#include "openvino/frontend/manager.hpp"
#include "translate_session.hpp"
@@ -45,6 +47,8 @@ struct FrontEnd::Impl {
// default (stateless) SetRows lowering for an alternative (e.g. a backend stateful lowering).
std::vector<DecoderTransformationExtension::Ptr> transformation_extensions;
TelemetryExtension::Ptr telemetry;
+ // Per-instance catalog: runtime registrations do not affect other frontends.
+ ArchRegistry arch_registry;
};
namespace {
@@ -82,7 +86,12 @@ std::shared_ptr<Model> FrontEnd::convert(const InputModel::Ptr& model) const {
std::shared_ptr<Model> converted_model;
{
auto ops = merged_ops(m_impl->op_extension_translators);
- TranslateSession translate_session(model, ops, m_impl->transformation_extensions);
+ auto conversion_input = gguf_model;
+ if (gguf_model->m_builder) {
+ 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);
converted_model = translate_session.get_converted_model();
}
return converted_model;
@@ -106,6 +115,8 @@ void FrontEnd::add_extension(const std::shared_ptr<ov::Extension>& extension) {
m_extensions.push_back(so_ext);
} 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)) {
+ m_impl->arch_registry.add_extension(arch_ext);
} else if (const auto& telemetry = std::dynamic_pointer_cast<TelemetryExtension>(extension)) {
m_impl->telemetry = telemetry;
} else if (auto op_base_ext = std::dynamic_pointer_cast<ov::BaseOpExtension>(extension)) {
@@ -149,9 +160,8 @@ InputModel::Ptr FrontEnd::load_impl(const std::vector<ov::Any>& variants) const
FRONT_END_GENERAL_CHECK(model_path.extension() == ".gguf",
"GGUF Frontend file loading expects a .gguf file, got: ",
model_path.string());
- auto graph = build_ggml_graph_from_gguf(model_path.string());
- auto decoder = std::make_shared<GgufBuilderDecoder>(graph);
- return std::make_shared<InputModel>(decoder);
+ return std::make_shared<InputModel>(load_gguf_builder(model_path.string(), m_impl->arch_registry),
+ m_extensions);
}
FRONT_END_GENERAL_CHECK(false,
diff --git a/src/frontends/gguf/src/input_model.cpp b/src/frontends/gguf/src/input_model.cpp
index f6a65289b09..0f113df25d4 100644
--- a/src/frontends/gguf/src/input_model.cpp
+++ b/src/frontends/gguf/src/input_model.cpp
@@ -4,6 +4,7 @@
#include "input_model.hpp"
+#include "openvino/frontend/exception.hpp"
#include "openvino/frontend/gguf/decoder.hpp"
namespace ov {
@@ -13,15 +14,15 @@ namespace gguf {
InputModel::InputModel(const std::shared_ptr<GgufDecoder>& gdecoder) : m_decoder(gdecoder) {}
const std::map<std::string, std::shared_ptr<ov::Node>>& InputModel::get_model_inputs() const {
- return m_decoder->get_model_inputs();
+ return get_model_decoder()->get_model_inputs();
}
std::vector<std::string> InputModel::get_model_output_names() const {
- return m_decoder->get_model_output_names();
+ return get_model_decoder()->get_model_output_names();
}
const std::vector<std::pair<std::string, std::string>>& InputModel::get_recurrent_states() const {
- return m_decoder->get_recurrent_states();
+ return get_model_decoder()->get_recurrent_states();
}
RopeConfig InputModel::get_rope_config() const {
@@ -30,15 +31,16 @@ RopeConfig InputModel::get_rope_config() const {
// (n_dims == 0, "model uses no RoPE") in that case, so TranslateSession::preprocess builds no
// shared rope sin/cos table and the ROPE translator -- if one is even present -- falls back to
// its own per-op sin/cos. This is what makes a separate naive flag unnecessary.
- auto cfg = m_decoder->get_attribute("rope_config");
+ auto cfg = get_model_decoder()->get_attribute("rope_config");
return cfg.empty() ? RopeConfig{} : cfg.as<RopeConfig>();
}
void InputModel::visit_subgraph(const std::function<void(std::shared_ptr<GgufDecoder>)>& node_visitor) const {
- m_decoder->visit_subgraph(node_visitor);
+ get_model_decoder()->visit_subgraph(node_visitor);
}
const std::shared_ptr<GgufDecoder>& InputModel::get_model_decoder() const {
+ FRONT_END_GENERAL_CHECK(m_decoder, "Native GGUF graphs are constructed during convert()");
return m_decoder;
}
diff --git a/src/frontends/gguf/src/input_model.hpp b/src/frontends/gguf/src/input_model.hpp
index c5224c43b54..484860faa8e 100644
--- a/src/frontends/gguf/src/input_model.hpp
+++ b/src/frontends/gguf/src/input_model.hpp
@@ -10,6 +10,7 @@
#include <string>
#include <vector>
+#include "builder/gguf_builder.hpp"
#include "openvino/frontend/gguf/decoder.hpp"
#include "openvino/frontend/gguf/visibility.hpp"
#include "openvino/frontend/input_model.hpp"
@@ -29,6 +30,9 @@ class GGUF_FRONTEND_API InputModel : public ov::frontend::InputModel {
public:
explicit InputModel(const std::shared_ptr<GgufDecoder>& gdecoder);
+ InputModel(GraphBuilder builder, std::vector<ov::Extension::Ptr> extensions)
+ : m_extensions(std::move(extensions)),
+ m_builder(std::move(builder)) {}
// Model-scope topology (forwarded to the underlying decoder's model-scope accessors).
const std::map<std::string, std::shared_ptr<ov::Node>>& get_model_inputs() const;
@@ -44,6 +48,9 @@ public:
private:
std::shared_ptr<GgufDecoder> m_decoder;
+ // Keep the builder library loaded until its factory has been destroyed.
+ std::vector<ov::Extension::Ptr> m_extensions;
+ GraphBuilder m_builder;
};
} // namespace ov::frontend::gguf
diff --git a/src/frontends/gguf/src/node_context.hpp b/src/frontends/gguf/src/node_context.hpp
index 5663fff6f20..7239c0b3a0e 100644
--- a/src/frontends/gguf/src/node_context.hpp
+++ b/src/frontends/gguf/src/node_context.hpp
@@ -33,7 +33,16 @@ public:
}
PartialShape get_input_shape(size_t input_index) const {
- return m_decoder->get_input_shape(m_input_names[input_index]);
+ auto shape = m_decoder->get_input_shape(m_input_names[input_index]);
+ if (shape.rank().is_dynamic()) {
+ shape = get_input(static_cast<int>(input_index)).get_partial_shape();
+ if (shape.rank().is_static() && shape.size() < 4) {
+ std::vector<ov::Dimension> dims(4 - shape.size(), 1);
+ dims.insert(dims.end(), shape.begin(), shape.end());
+ shape = ov::PartialShape(dims);
+ }
+ }
+ return shape;
}
// Element offset of a VIEW input into a larger tensor (0 when not a view). The decoder
@@ -46,16 +55,10 @@ public:
return m_decoder->get_output_shape();
}
- // Convenience typed reads over get_attribute, kept so both the attribute-style op bodies and
- // the accessor-style (op_case / output_type) op bodies compile against one NodeContext.
int get_op_case() const {
return get_attribute<int>("op_case", 0);
}
- ov::element::Type get_output_type() const {
- return get_attribute<ov::element::Type>("output_type");
- }
-
Output<Node> get_input(int idx) const override {
return m_tensor_map->at(m_input_names[idx]);
}
diff --git a/src/frontends/gguf/src/op/add_id.cpp b/src/frontends/gguf/src/op/add_id.cpp
index 0b2b6ee414f..b9db386c6e5 100644
--- a/src/frontends/gguf/src/op/add_id.cpp
+++ b/src/frontends/gguf/src/op/add_id.cpp
@@ -70,10 +70,6 @@ OutputVector translate_add_id(const NodeContext& context) {
}
ov::Output<ov::Node> res = std::make_shared<ov::op::v1::Add>(input, selected_bias);
- const auto output_type = context.get_attribute<ov::element::Type>("output_type");
- if (res.get_element_type() != output_type) {
- 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/argsort.cpp b/src/frontends/gguf/src/op/argsort.cpp
index f1235783d00..fb47dc48395 100644
--- a/src/frontends/gguf/src/op/argsort.cpp
+++ b/src/frontends/gguf/src/op/argsort.cpp
@@ -38,13 +38,12 @@ OutputVector translate_argsort(const NodeContext& context) {
FRONT_END_OP_CONVERSION_CHECK(false, "Unsupported ARGSORT order: ", sort_order);
}
- auto index_type = context.get_attribute<ov::element::Type>("output_type");
// ggml ARGSORT sorts ne[0] == the OV last axis; derive it from the rank (rank-4 keeps axis 3).
const auto& in_ps = input.get_partial_shape();
const int64_t axis = in_ps.rank().is_static() ? in_ps.rank().get_length() - 1 : 3;
auto k = std::make_shared<ov::op::v0::Squeeze>(get_dimensions(input, {(int)axis}),
ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
- auto indices = make_topk_indices(input, k, axis, mode, index_type);
+ auto indices = make_topk_indices(input, k, axis, mode);
return rename_outputs_with_suffix({std::move(indices)}, context.get_name());
}
diff --git a/src/frontends/gguf/src/op/concat.cpp b/src/frontends/gguf/src/op/concat.cpp
index e247422113d..1056f624c6f 100644
--- a/src/frontends/gguf/src/op/concat.cpp
+++ b/src/frontends/gguf/src/op/concat.cpp
@@ -22,8 +22,8 @@ namespace op {
OutputVector translate_concat(const NodeContext& context) {
num_inputs_check(context, 2, 2);
- const auto output_shape = context.get_output_shape();
- FRONT_END_OP_CONVERSION_CHECK(output_shape.rank().is_static(), "CONCAT requires static output rank");
+ const auto output_shape = context.get_input(0).get_partial_shape();
+ FRONT_END_OP_CONVERSION_CHECK(output_shape.rank().is_static(), "CONCAT requires static input rank");
const auto rank = output_shape.rank().get_length();
const int ggml_dim = context.get_attribute<int>("concat_axis");
@@ -31,11 +31,8 @@ OutputVector translate_concat(const NodeContext& context) {
auto input_0 = context.get_input(0);
auto input_1 = context.get_input(1);
- const auto output_type = context.get_attribute<ov::element::Type>("output_type");
+ const auto output_type = input_0.get_element_type();
- if (input_0.get_element_type() != output_type) {
- input_0 = std::make_shared<ov::op::v0::Convert>(input_0, output_type);
- }
if (input_1.get_element_type() != output_type) {
input_1 = std::make_shared<ov::op::v0::Convert>(input_1, output_type);
}
diff --git a/src/frontends/gguf/src/op/cpy.cpp b/src/frontends/gguf/src/op/cpy.cpp
index 61a89be1158..5a283010005 100644
--- a/src/frontends/gguf/src/op/cpy.cpp
+++ b/src/frontends/gguf/src/op/cpy.cpp
@@ -28,6 +28,15 @@ namespace op {
OutputVector translate_cpy(const NodeContext& context) {
const int op_case = context.get_op_case();
+ auto type = context.get_attribute<ov::element::Type>("dst_type", ov::element::dynamic);
+ if (type.is_dynamic() && context.get_input_size() > 1 && context.has_input(context.get_input_names()[1])) {
+ type = context.get_input(1).get_element_type();
+ }
+ if (type.is_dynamic()) {
+ // Older cgraph decoders encode a cast's target in output_type.
+ type = context.get_attribute<ov::element::Type>("output_type", ov::element::dynamic);
+ }
+ FRONT_END_OP_CONVERSION_CHECK(type.is_static(), "CPY requires a destination input or 'dst_type'");
const auto input_shape = context.get_input_shape(0);
const auto output_shape = context.get_output_shape();
@@ -44,8 +53,8 @@ OutputVector translate_cpy(const NodeContext& context) {
ov::op::v0::Constant::create(ov::element::i64, {1}, {INT_MAX}),
ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),
ov::op::v0::Constant::create(ov::element::i64, {1}, {2}));
- if (value.get_element_type() != context.get_output_type()) {
- value = std::make_shared<ov::op::v0::Convert>(value, context.get_output_type());
+ if (value.get_element_type() != type) {
+ value = std::make_shared<ov::op::v0::Convert>(value, type);
}
auto target = ov::op::v0::Constant::create(ov::element::i64, {output_shape.size()}, output_shape.to_shape());
auto res = std::make_shared<ov::op::v1::Reshape>(value, target, false);
@@ -69,8 +78,8 @@ OutputVector translate_cpy(const NodeContext& context) {
const int64_t end_val = begin_val + n_elems;
auto flat_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 1, 1, -1});
src = std::make_shared<ov::op::v1::Reshape>(src, flat_shape, false);
- if (src.get_element_type() != context.get_output_type()) {
- src = std::make_shared<ov::op::v0::Convert>(src, context.get_output_type());
+ if (src.get_element_type() != type) {
+ src = std::make_shared<ov::op::v0::Convert>(src, type);
}
auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});
@@ -138,8 +147,8 @@ OutputVector translate_cpy(const NodeContext& context) {
src = context.get_input(0);
}
- if (src.get_element_type() != context.get_output_type()) {
- src = std::make_shared<ov::op::v0::Convert>(src, context.get_output_type());
+ if (src.get_element_type() != type) {
+ src = std::make_shared<ov::op::v0::Convert>(src, type);
}
auto base = context.get_input(1);
@@ -154,9 +163,7 @@ OutputVector translate_cpy(const NodeContext& context) {
return rename_outputs_with_suffix({std::move(res)}, context.get_name());
}
- ov::Output<ov::Node> res =
- std::make_shared<ov::op::v0::Convert>(context.get_input(0),
- context.get_attribute<ov::element::Type>("output_type"));
+ ov::Output<ov::Node> res = std::make_shared<ov::op::v0::Convert>(context.get_input(0), type);
// A CPY may reinterpret the source layout into its destination's (e.g. qwen3-next's conv-state
// writeback flattens the contiguous [S, F] conv_state_last into the flat [S*F] recurrent cache
diff --git a/src/frontends/gguf/src/op/diag.cpp b/src/frontends/gguf/src/op/diag.cpp
index 34df8905f49..e666d7715a5 100644
--- a/src/frontends/gguf/src/op/diag.cpp
+++ b/src/frontends/gguf/src/op/diag.cpp
@@ -30,8 +30,8 @@ OutputVector translate_diag(const NodeContext& context) {
auto x = context.get_input(0); // OV shape: [ne3, ne2, 1, ne0]
- auto out_shape = context.get_output_shape().to_shape();
- size_t n = out_shape[3]; // ne0
+ const auto shape = x.get_partial_shape();
+ const size_t n = shape[shape.size() - 1].get_length();
// Explicit [1, 1, n, n] identity matrix (1.0 on the diagonal, 0.0 elsewhere).
std::vector<float> identity(n * n, 0.0f);
@@ -39,9 +39,7 @@ OutputVector translate_diag(const NodeContext& context) {
identity[i * n + i] = 1.0f;
}
// Build the mask in the node's own type, or an f16 input gets promoted to f32 by the Multiply.
- auto eye = ov::op::v0::Constant::create(context.get_attribute<ov::element::Type>("output_type"),
- ov::Shape{1, 1, n, n},
- identity);
+ auto eye = ov::op::v0::Constant::create(x.get_element_type(), ov::Shape{1, 1, n, n}, identity);
// Multiply broadcasts the [ne3,ne2,1,ne0] input over the row axis, zeroing off-diagonal entries.
auto res = std::make_shared<ov::op::v1::Multiply>(x, eye);
diff --git a/src/frontends/gguf/src/op/div.cpp b/src/frontends/gguf/src/op/div.cpp
index a85b0d28f4e..b7e16cf53bc 100644
--- a/src/frontends/gguf/src/op/div.cpp
+++ b/src/frontends/gguf/src/op/div.cpp
@@ -119,7 +119,7 @@ OutputVector translate_div(const NodeContext& context) {
auto input_0 = context.get_input(0);
auto input_1 = context.get_input(1);
- const auto output_type = context.get_attribute<ov::element::Type>("output_type");
+ const auto output_type = input_0.get_element_type();
if (is_silu_div_pattern(input_0, input_1)) {
ov::Output<ov::Node> res = std::make_shared<ov::op::v0::Sigmoid>(input_1);
diff --git a/src/frontends/gguf/src/op/fill.cpp b/src/frontends/gguf/src/op/fill.cpp
index 6361c2e12b1..7cc739c851a 100644
--- a/src/frontends/gguf/src/op/fill.cpp
+++ b/src/frontends/gguf/src/op/fill.cpp
@@ -29,9 +29,7 @@ OutputVector translate_fill(const NodeContext& context) {
float fill_value = context.get_attribute<float>("fill_value");
// ggml FILL keeps the tensor's own type (f32 or f16), so do not hardcode f32 here.
- auto val = ov::op::v0::Constant::create(context.get_attribute<ov::element::Type>("output_type"),
- ov::Shape{},
- {fill_value});
+ auto val = ov::op::v0::Constant::create(x.get_element_type(), ov::Shape{}, {fill_value});
auto target_shape = std::make_shared<ov::op::v3::ShapeOf>(x, ov::element::i64);
auto res = std::make_shared<ov::op::v3::Broadcast>(val, target_shape);
diff --git a/src/frontends/gguf/src/op/flash_attn_ext.cpp b/src/frontends/gguf/src/op/flash_attn_ext.cpp
index e4747aa09d5..9abebd743fe 100644
--- a/src/frontends/gguf/src/op/flash_attn_ext.cpp
+++ b/src/frontends/gguf/src/op/flash_attn_ext.cpp
@@ -107,13 +107,10 @@ OutputVector translate_flash_attn_ext(const NodeContext& context) {
return kv;
};
- // Use the static ggml input shapes (get_input_shape), not the live OV node shapes: on the
- // stateful KV-cache path the OV node's batch/seq dims are dynamic (K/V are fed by the cache
- // concat), but the head-count / head-size dims are static ggml facts the decoder knows.
- auto q_shape = context.get_input_shape(0).to_shape();
- auto k_shape = context.get_input_shape(1).to_shape();
- k = tile_kv(q_shape[head_axis], k_shape[head_axis], q_shape[3], k);
- v = tile_kv(q_shape[head_axis], k_shape[head_axis], q_shape[3], v);
+ auto q_shape = context.get_input_shape(0);
+ auto k_shape = context.get_input_shape(1);
+ k = tile_kv(q_shape[head_axis].get_length(), k_shape[head_axis].get_length(), q_shape[3].get_length(), k);
+ v = tile_kv(q_shape[head_axis].get_length(), k_shape[head_axis].get_length(), q_shape[3].get_length(), v);
// 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);
@@ -181,8 +178,9 @@ OutputVector translate_flash_attn_ext(const NodeContext& context) {
auto sink_f16 = sink.get_element_type() != element::f16
? std::make_shared<v0::Convert>(sink, element::f16)->output(0)
: sink;
- auto sink_shape =
- v0::Constant::create(element::i64, {4}, std::vector<int64_t>{1, (int64_t)q_shape[head_axis], 1, 1});
+ 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);
sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(q_t,
k_t,
diff --git a/src/frontends/gguf/src/op/gated_delta_net.cpp b/src/frontends/gguf/src/op/gated_delta_net.cpp
index 6843b84428a..f0212f4e3c6 100644
--- a/src/frontends/gguf/src/op/gated_delta_net.cpp
+++ b/src/frontends/gguf/src/op/gated_delta_net.cpp
@@ -43,14 +43,14 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext& context);
OutputVector translate_gated_delta_net(const NodeContext& context) {
num_inputs_check(context, 6, 6);
- auto v_shape = context.get_input_shape(2).to_shape(); // [B, T, H_v, S_v]
- auto q_shape = context.get_input_shape(0).to_shape(); // [B, T, H_k, S_k]
- auto g_shape = context.get_input_shape(3).to_shape(); // [B, T, H_v, 1 or S_v]
+ auto v_shape = context.get_input_shape(2); // [B, T, H_v, S_v]
+ auto q_shape = context.get_input_shape(0); // [B, T, H_k, S_k]
+ auto g_shape = context.get_input_shape(3); // [B, T, H_v, 1 or S_v]
- const int64_t H_v = v_shape[2];
- const int64_t S_v = v_shape[3];
- const int64_t H_k = q_shape[2];
- const bool kda = (g_shape[3] == (size_t)S_v);
+ const int64_t H_v = v_shape[2].get_length();
+ const int64_t S_v = v_shape[3].get_length();
+ const int64_t H_k = q_shape[2].get_length();
+ const bool kda = (g_shape[3].get_length() == S_v);
// ggml reserves K * S_v * n_seqs state rows for K per-token snapshots (K = 1 + n_rs_seq, > 1 only
// for speculative-decode rollback), while both paths here pack exactly one S_v-row block. Reject
@@ -122,24 +122,19 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext& context) {
auto beta = context.get_input(4);
auto state = context.get_input(5);
- auto v_shape = context.get_input_shape(2).to_shape(); // [B, T, H_v, S_v]
- auto q_shape = context.get_input_shape(0).to_shape(); // [B, T, H_k, S_k]
- auto g_shape = context.get_input_shape(3).to_shape(); // [B, T, H_v, 1 or S_v]
+ auto v_shape = context.get_input_shape(2); // [B, T, H_v, S_v]
+ auto q_shape = context.get_input_shape(0); // [B, T, H_k, S_k]
+ auto g_shape = context.get_input_shape(3); // [B, T, H_v, 1 or S_v]
- const int64_t B = v_shape[0];
- const int64_t T = v_shape[1];
- const int64_t H_v = v_shape[2];
- const int64_t S_v = v_shape[3];
- const int64_t H_k = q_shape[2];
- const bool kda = (g_shape[3] == (size_t)S_v);
+ const int64_t B = v_shape[0].get_length();
+ const int64_t H_v = v_shape[2].get_length();
+ const int64_t S_v = v_shape[3].get_length();
+ const int64_t H_k = q_shape[2].get_length();
+ const bool kda = (g_shape[3].get_length() == S_v);
const int64_t rq1 = H_v / H_k; // GQA head repeat factor
const float scale = 1.0f / std::sqrt((float)S_v);
- // T is dynamic at runtime: T-dependent reshapes use -1 and the Loop trip count is read at
- // runtime, so the convert-time T is only used for the static dims (B/H_v/S_v/H_k).
- (void)T;
-
auto axis_0 = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});
auto axis_1 = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
auto axis_2 = ov::op::v0::Constant::create(ov::element::i64, {1}, {2});
diff --git a/src/frontends/gguf/src/op/get_rows.cpp b/src/frontends/gguf/src/op/get_rows.cpp
index 91c313b54c0..81d2b5a002b 100644
--- a/src/frontends/gguf/src/op/get_rows.cpp
+++ b/src/frontends/gguf/src/op/get_rows.cpp
@@ -28,9 +28,17 @@ OutputVector translate_get_rows(const NodeContext& context) {
Output<Node> res;
auto data = context.get_input(0);
auto indices = context.get_input(1);
+ // GGML gathers integer rows as I32 and all floating/quantized rows as F32.
+ const auto type = data.get_element_type() == ov::element::i32 ? ov::element::i32 : ov::element::f32;
+ const auto convert_rows = [&](ov::Output<Node> rows) {
+ if (rows.get_element_type() != type) {
+ rows = std::make_shared<ov::op::v0::Convert>(rows, type);
+ }
+ return rows;
+ };
if (op_case == 3) {
- return {std::move(data)};
+ return {convert_rows(data)};
}
if (op_case == 4) {
@@ -39,10 +47,7 @@ OutputVector translate_get_rows(const NodeContext& context) {
ov::op::v0::Constant::create(ov::element::i64, {3}, {0, 1, 2}));
auto axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {2});
res = std::make_shared<ov::op::v8::Gather>(data, flat_indices, axis);
- if (res.get_element_type() != context.get_output_type()) {
- res = std::make_shared<ov::op::v0::Convert>(res, context.get_output_type());
- }
- return rename_outputs_with_suffix({std::move(res)}, context.get_name());
+ return rename_outputs_with_suffix({convert_rows(res)}, context.get_name());
}
// MoE gating-weight gather (op_case 10): data = probs [1,1,T,E], indices = selected experts
@@ -53,14 +58,15 @@ OutputVector translate_get_rows(const NodeContext& context) {
// explicit [1,-1,K,1] reshape (K is static, read via PartialShape to avoid .to_shape()
// throwing when T is dynamic) instead of Squeeze+Unsqueeze, which the CPU plugin
// implements as a Reshape internally and mis-infers the static pattern when T=1.
- const int64_t K = context.get_output_shape()[2].get_length();
+ 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]
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}),
false); // [1,T,K,1]
- return rename_outputs_with_suffix({std::move(col)}, context.get_name());
+ return rename_outputs_with_suffix({convert_rows(col)}, context.get_name());
}
if (op_case == 2) {
@@ -90,12 +96,9 @@ OutputVector translate_get_rows(const NodeContext& context) {
res = std::make_shared<ov::op::v8::Gather>(data, indices, axis);
}
- if (res.get_element_type() != context.get_output_type()) {
- res = std::make_shared<ov::op::v0::Convert>(res, context.get_output_type());
- }
// The two Squeezes above dropped the leading axes; restore ggml's rank-4 form.
res = std::make_shared<ov::op::v0::Unsqueeze>(res, ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
- return rename_outputs_with_suffix({std::move(res)}, context.get_name());
+ return rename_outputs_with_suffix({convert_rows(res)}, context.get_name());
}
} // namespace op
diff --git a/src/frontends/gguf/src/op/im2col.cpp b/src/frontends/gguf/src/op/im2col.cpp
index 92281176f9e..0fd63f8dd6d 100644
--- a/src/frontends/gguf/src/op/im2col.cpp
+++ b/src/frontends/gguf/src/op/im2col.cpp
@@ -114,7 +114,11 @@ OutputVector translate_im2col(const NodeContext& context) {
res = std::make_shared<ov::op::v1::Reshape>(res, final_reshape_shape, false);
}
- auto output_type = context.get_attribute<ov::element::Type>("output_type");
+ // 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 (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/mul_mat_id.cpp b/src/frontends/gguf/src/op/mul_mat_id.cpp
index 0caf845554e..13d1baf8cbf 100644
--- a/src/frontends/gguf/src/op/mul_mat_id.cpp
+++ b/src/frontends/gguf/src/op/mul_mat_id.cpp
@@ -102,8 +102,7 @@ ov::Output<ov::Node> activations_per_expert(const ov::Output<ov::Node>& activati
// Packed-MXFP4 MoE path: expert weights arrive as raw u8 blocks of shape
// [1, n_expert, m, k_blocks, 17] (1 e8m0 scale byte + 16 nibble-packed f4e2m1 quants per 32-block).
// The dequant (nibble unpack + LUT + scale) is done on-graph, per selected expert.
-ov::Output<ov::Node> translate_mul_mat_id_mxfp4_packed(const NodeContext& context,
- ov::Output<ov::Node> expert_weights,
+ov::Output<ov::Node> translate_mul_mat_id_mxfp4_packed(ov::Output<ov::Node> expert_weights,
ov::Output<ov::Node> activations,
ov::Output<ov::Node> ids) {
auto packed_shape = expert_weights.get_partial_shape().to_shape();
@@ -189,10 +188,6 @@ ov::Output<ov::Node> translate_mul_mat_id_mxfp4_packed(const NodeContext& contex
0);
result = std::make_shared<ov::op::v1::Reshape>(result, result_target_dims, false);
- const auto output_type = context.get_attribute<ov::element::Type>("output_type");
- if (result.get_element_type() != output_type) {
- result = std::make_shared<ov::op::v0::Convert>(result, output_type);
- }
return result;
}
@@ -213,8 +208,7 @@ ov::Output<ov::Node> translate_mul_mat_id_mxfp4_packed(const NodeContext& contex
// expert_weights (as) : [n_expert, rows, cols] (or reversed rank-4 [1, n_expert, rows, cols])
// activations (b) : [.., T, cols] (gate/up, shared input) or [.., T, K, cols] (down)
// ids : [1, 1, T, K]
-ov::Output<ov::Node> translate_mul_mat_id_gathermatmul(const NodeContext& context,
- ov::Output<ov::Node> expert_weights,
+ov::Output<ov::Node> translate_mul_mat_id_gathermatmul(ov::Output<ov::Node> expert_weights,
ov::Output<ov::Node> activations,
ov::Output<ov::Node> ids) {
// Normalize the expert weights to the rank-3 [n_expert, rows, cols] GatherMatmul expects. The
@@ -284,8 +278,7 @@ ov::Output<ov::Node> translate_mul_mat_id_gathermatmul(const NodeContext& contex
// batched MatMul. Handles non-constant expert weights (e.g. the single-op unit tests) that the CPU
// GatherMatmul node does not support. Expects reversed rank-4 inputs
// (weights [1, n_expert, m, k], activations [1, T, 1_or_K, k], ids [1, 1, T, K]).
-ov::Output<ov::Node> translate_mul_mat_id_generic(const NodeContext& context,
- ov::Output<ov::Node> expert_weights,
+ov::Output<ov::Node> translate_mul_mat_id_generic(ov::Output<ov::Node> expert_weights,
ov::Output<ov::Node> activations,
ov::Output<ov::Node> ids) {
auto expert_weights_shape_4d = std::make_shared<ov::op::v3::ShapeOf>(expert_weights, ov::element::i64);
@@ -306,7 +299,6 @@ ov::Output<ov::Node> translate_mul_mat_id_generic(const NodeContext& context,
auto gather_axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0});
ov::Output<ov::Node> selected_weights = std::make_shared<ov::op::v8::Gather>(expert_weights, ids, gather_axis);
- const auto output_type = context.get_attribute<ov::element::Type>("output_type");
if (selected_weights.get_element_type() != ov::element::f32) {
selected_weights = std::make_shared<ov::op::v0::Convert>(selected_weights, ov::element::f32);
}
@@ -322,11 +314,12 @@ ov::Output<ov::Node> translate_mul_mat_id_generic(const NodeContext& context,
auto activations_expanded = std::make_shared<ov::op::v0::Unsqueeze>(acts_broadcasted, unsqueeze_axes);
auto batch_dim = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
- auto output_shape = context.get_output_shape();
- FRONT_END_OP_CONVERSION_CHECK(output_shape.rank().is_static() && output_shape.rank().get_length() == 4,
- "Unexpected MUL_MAT_ID output rank");
- FRONT_END_OP_CONVERSION_CHECK(output_shape[3].is_static(), "Expected static row dimension for MUL_MAT_ID output");
- auto row_dim = ov::op::v0::Constant::create(ov::element::i64, {1}, {output_shape[3].get_length()});
+ const auto weights_shape = selected_weights.get_partial_shape();
+ FRONT_END_OP_CONVERSION_CHECK(weights_shape.rank().is_static() && weights_shape.size() >= 2,
+ "MUL_MAT_ID requires a known weight rank");
+ const auto rows = weights_shape[weights_shape.size() - 2];
+ FRONT_END_OP_CONVERSION_CHECK(rows.is_static(), "MUL_MAT_ID requires a static row dimension");
+ auto row_dim = ov::op::v0::Constant::create(ov::element::i64, {1}, {rows.get_length()});
ov::Output<ov::Node> result =
std::make_shared<ov::op::v0::MatMul>(activations_expanded, selected_weights, false, true);
@@ -334,9 +327,6 @@ ov::Output<ov::Node> translate_mul_mat_id_generic(const NodeContext& context,
std::make_shared<ov::op::v0::Concat>(ov::OutputVector{batch_dim, get_dimensions(ids_shape, {0, 1}), row_dim},
0);
result = std::make_shared<ov::op::v1::Reshape>(result, result_target_dims, false);
- if (result.get_element_type() != output_type) {
- result = std::make_shared<ov::op::v0::Convert>(result, output_type);
- }
return result;
}
@@ -353,13 +343,15 @@ OutputVector translate_mul_mat_id(const NodeContext& context) {
auto expert_weights = context.get_input(0);
auto activations = context.get_input(1);
+ if (activations.get_element_type() != ov::element::f32) {
+ activations = std::make_shared<ov::op::v0::Convert>(activations, ov::element::f32);
+ }
auto ids = context.get_input(2);
if (expert_weights.get_element_type() == ov::element::u8 && expert_weights.get_partial_shape().rank().is_static() &&
expert_weights.get_partial_shape().rank().get_length() == 5) {
- return rename_outputs_with_suffix(
- {translate_mul_mat_id_mxfp4_packed(context, expert_weights, activations, ids)},
- context.get_name());
+ return rename_outputs_with_suffix({translate_mul_mat_id_mxfp4_packed(expert_weights, activations, ids)},
+ context.get_name());
}
// The CPU GatherMatmul node requires constant-backed weights. Real .gguf models feed a
@@ -368,9 +360,9 @@ OutputVector translate_mul_mat_id(const NodeContext& context) {
// GatherMatmul on CPU, so fall back to the portable Gather + MatMul lowering.
ov::Output<ov::Node> result;
if (ov::op::util::is_on_path<ov::op::v0::Constant>(expert_weights)) {
- result = translate_mul_mat_id_gathermatmul(context, expert_weights, activations, ids);
+ result = translate_mul_mat_id_gathermatmul(expert_weights, activations, ids);
} else {
- result = translate_mul_mat_id_generic(context, expert_weights, activations, ids);
+ result = translate_mul_mat_id_generic(expert_weights, activations, ids);
}
return rename_outputs_with_suffix({std::move(result)}, context.get_name());
}
diff --git a/src/frontends/gguf/src/op/mulmat.cpp b/src/frontends/gguf/src/op/mulmat.cpp
index 7c8b0f7f054..baa893458a2 100644
--- a/src/frontends/gguf/src/op/mulmat.cpp
+++ b/src/frontends/gguf/src/op/mulmat.cpp
@@ -45,18 +45,18 @@ OutputVector translate_mulmat(const NodeContext& context) {
B = process_view_input(context, 0);
A = process_view_input(context, 1);
}
- if (A.get_element_type() != B.get_element_type()) {
- // Convert the reprocessed B, not input(0), to preserve the op_case 2/3 rebinding.
- B = std::make_shared<ov::op::v0::Convert>(B, A.get_element_type());
+ // GGML MUL_MAT produces F32, including when both operands are F16.
+ if (A.get_element_type() != ov::element::f32) {
+ A = std::make_shared<ov::op::v0::Convert>(A, ov::element::f32);
+ }
+ if (B.get_element_type() != ov::element::f32) {
+ B = std::make_shared<ov::op::v0::Convert>(B, ov::element::f32);
}
- // Use the static ggml input shapes (get_input_shape), not the live OV node shapes: on the
- // stateful KV-cache path the OV node's batch/seq dims are dynamic, but the batch/head/feature
- // dims MUL_MAT needs are static ggml facts the decoder knows by construction.
- auto B_shape = context.get_input_shape(0).to_shape();
- auto A_shape = context.get_input_shape(1).to_shape();
- int64_t A_batch = A_shape[1];
- int64_t B_batch = B_shape[1];
+ auto B_shape = context.get_input_shape(0);
+ auto A_shape = context.get_input_shape(1);
+ int64_t A_batch = A_shape[1].get_length();
+ int64_t B_batch = B_shape[1].get_length();
auto A_batch_larger = A_batch > B_batch;
auto batch_large = A_batch_larger ? A_batch : B_batch;
@@ -75,9 +75,10 @@ OutputVector translate_mulmat(const NodeContext& context) {
auto broadcast_shape = ov::op::v0::Constant::create(ov::element::i64,
{5},
{(int64_t)1, (int64_t)1, factor, (int64_t)1, (int64_t)1});
- auto new_Z_shape = ov::op::v0::Constant::create(ov::element::i64,
- {4},
- {(int64_t)0, batch_large, (int64_t)-1, (int64_t)A_shape[3]});
+ auto new_Z_shape =
+ ov::op::v0::Constant::create(ov::element::i64,
+ {4},
+ {(int64_t)0, batch_large, (int64_t)-1, (int64_t)A_shape[3].get_length()});
auto Z_broadcasted = std::make_shared<ov::op::v3::Broadcast>(Z_unsqueezed,
broadcast_shape,
@@ -92,11 +93,6 @@ OutputVector translate_mulmat(const NodeContext& context) {
res = std::make_shared<ov::op::v0::MatMul>(A, B, false, transpose_b);
- const auto output_type = context.get_output_type();
- if (res.get_element_type() != output_type) {
- 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/repeat.cpp b/src/frontends/gguf/src/op/repeat.cpp
index 284dabfee0b..4b74bbac2bf 100644
--- a/src/frontends/gguf/src/op/repeat.cpp
+++ b/src/frontends/gguf/src/op/repeat.cpp
@@ -25,6 +25,11 @@ OutputVector translate_repeat(const NodeContext& context) {
num_inputs_check(context, 1, 2);
auto input = context.get_input(0);
+ const auto repeats = context.get_attribute<std::vector<int64_t>>("repeats", {});
+ if (!repeats.empty()) {
+ auto factors = ov::op::v0::Constant::create(ov::element::i64, {repeats.size()}, repeats);
+ return rename_outputs_with_suffix({std::make_shared<ov::op::v0::Tile>(input, factors)}, context.get_name());
+ }
const auto input_shape = context.get_input_shape(0);
const auto output_shape = context.get_output_shape();
diff --git a/src/frontends/gguf/src/op/reshape.cpp b/src/frontends/gguf/src/op/reshape.cpp
index 73c46434d60..85bb414f45b 100644
--- a/src/frontends/gguf/src/op/reshape.cpp
+++ b/src/frontends/gguf/src/op/reshape.cpp
@@ -16,6 +16,9 @@
#include "openvino/frontend/exception.hpp"
#include "openvino/op/concat.hpp"
#include "openvino/op/constant.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/reduce_prod.hpp"
+#include "openvino/op/shape_of.hpp"
#include "openvino/op/transpose.hpp"
#include "utils.hpp"
@@ -26,7 +29,44 @@ namespace op {
OutputVector translate_reshape(const NodeContext& context) {
num_inputs_check(context, 1, 1);
- if (context.get_input_shape(0) == context.get_output_shape()) {
+ 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);
+ return rename_outputs_with_suffix(
+ {std::make_shared<ov::op::v1::Reshape>(context.get_input(0),
+ pattern,
+ context.get_attribute<bool>("special_zero", false))},
+ context.get_name());
+ }
+ if (context.get_attribute<bool>("merge_heads", false)) {
+ const auto input = context.get_input(0);
+ const auto shape = input.get_partial_shape();
+ FRONT_END_OP_CONVERSION_CHECK(shape.rank() == 4, "Head merging requires a rank-4 input");
+ ov::Output<ov::Node> pattern;
+ if (shape[2].is_static() && shape[3].is_static()) {
+ pattern = ov::op::v0::Constant::create(
+ ov::element::i64,
+ {4},
+ std::vector<int64_t>{0, 1, -1, shape[2].get_length() * shape[3].get_length()});
+ } else {
+ auto dimensions = std::make_shared<ov::op::v3::ShapeOf>(input, ov::element::i64);
+ auto heads =
+ std::make_shared<ov::op::v8::Gather>(dimensions,
+ ov::op::v0::Constant::create(ov::element::i64, {2}, {2, 3}),
+ ov::op::v0::Constant::create(ov::element::i64, {}, {0}));
+ auto width =
+ std::make_shared<ov::op::v1::ReduceProd>(heads,
+ ov::op::v0::Constant::create(ov::element::i64, {1}, {0}),
+ true);
+ pattern = std::make_shared<ov::op::v0::Concat>(
+ ov::OutputVector{ov::op::v0::Constant::create(ov::element::i64, {3}, {0, 1, -1}), width},
+ 0);
+ }
+ return rename_outputs_with_suffix({std::make_shared<ov::op::v1::Reshape>(input, pattern, true)},
+ context.get_name());
+ }
+ if (!context.get_attribute<bool>("preserve_dynamic_layout", false) &&
+ context.get_input_shape(0) == context.get_output_shape()) {
return {context.get_input(0)};
}
diff --git a/src/frontends/gguf/src/op/rope.cpp b/src/frontends/gguf/src/op/rope.cpp
index 3c06fddf23c..a65e7f96c89 100644
--- a/src/frontends/gguf/src/op/rope.cpp
+++ b/src/frontends/gguf/src/op/rope.cpp
@@ -45,7 +45,10 @@ OutputVector translate_rope(const NodeContext& context) {
ov::Output<Node> res;
auto data = context.get_input(0);
- auto output_shape = context.get_output_shape().to_shape();
+ auto output_shape = context.get_output_shape();
+ if (output_shape.rank().is_dynamic()) {
+ output_shape = context.get_input_shape(0);
+ }
auto rope_config = context.get_attribute<RopeConfig>("rope_config");
const int mode = (op_case & 0xFFFF0000) >> 16;
op_case = (op_case & 0x0000FFFF);
@@ -79,17 +82,17 @@ OutputVector translate_rope(const NodeContext& context) {
return ov::op::v0::Constant::create(
ov::element::i64,
{4},
- std::vector<int64_t>{0, -1, (int64_t)output_shape[2], (int64_t)output_shape[3]});
+ std::vector<int64_t>{0, -1, (int64_t)output_shape[2].get_length(), (int64_t)output_shape[3].get_length()});
};
if (op_case == 2) {
// The input comes from a VIEW
- int slice_len = static_cast<int>(output_shape[2] * output_shape[3]);
+ int slice_len = static_cast<int>(output_shape[2].get_length() * output_shape[3].get_length());
data = process_view_input(context, 0, slice_len);
data = std::make_shared<ov::op::v1::Reshape>(data, make_bhsd_shape(), true);
}
- const auto output_type = context.get_output_type();
+ const auto output_type = data.get_element_type();
if (data.get_element_type() != ov::element::f32) {
data = std::make_shared<ov::op::v0::Convert>(data, ov::element::f32);
}
@@ -99,8 +102,8 @@ OutputVector translate_rope(const NodeContext& context) {
// folds this subgraph into ov::op::internal::RoPE → GPU ocl::rope::opt kernel.
// RoPEFusionFlux requires rank-4 x with static last two dims [n_heads, head_size].
// After the VIEW prologue the data is already [B,L,n_heads,head_size].
- const int64_t n_heads = static_cast<int64_t>(output_shape[2]);
- const int64_t head_size = static_cast<int64_t>(output_shape[3]);
+ const int64_t n_heads = static_cast<int64_t>(output_shape[2].get_length());
+ const int64_t head_size = static_cast<int64_t>(output_shape[3].get_length());
const int64_t n_rot = rope_config.n_dims > 0 ? rope_config.n_dims : head_size;
const int64_t half = n_rot / 2;
@@ -160,7 +163,7 @@ OutputVector translate_rope(const NodeContext& context) {
// Partial rotary (ggml n_dims < head_dim): only the first n_dims of every head are
// rotated; the remaining tail is passed through unchanged. cos/sin have width n_dims/2,
// so the rotated block must be exactly n_dims wide.
- const int64_t head_dim = static_cast<int64_t>(output_shape[3]);
+ const int64_t head_dim = static_cast<int64_t>(output_shape[3].get_length());
const int64_t n_rot = rope_config.n_dims > 0 ? rope_config.n_dims : head_dim;
// Split the head into the rotated block [0, n_rot) and the untouched tail [n_rot, head_dim)
@@ -189,8 +192,8 @@ OutputVector translate_rope(const NodeContext& context) {
// the decomposition there, and transpose the result back. The math is unchanged; the
// wrapping Transposes are sunk / cancelled against the adjacent PERMUTE during
// TransposeSinking.
- const int64_t n_head_rope = static_cast<int64_t>(output_shape[2]);
- const int64_t head_size_rope = static_cast<int64_t>(output_shape[3]);
+ const int64_t n_head_rope = static_cast<int64_t>(output_shape[2].get_length());
+ const int64_t head_size_rope = static_cast<int64_t>(output_shape[3].get_length());
const auto perm_bhls = ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3});
// Data reaches this op in inconsistent shapes depending on the layer's upstream rank:
@@ -240,7 +243,7 @@ OutputVector translate_rope(const NodeContext& context) {
// exactly n_rot wide; using the full head here rotates the pass-through tail and corrupts
// every full-attention layer. (Use output_shape, not data.get_shape() which throws
// on a dynamic dim.)
- const int64_t head_dim = static_cast<int64_t>(output_shape[3]);
+ const int64_t head_dim = static_cast<int64_t>(output_shape[3].get_length());
const int64_t n_rot = rope_config.n_dims > 0 ? rope_config.n_dims : head_dim;
Output<Node> rotary_in = data;
diff --git a/src/frontends/gguf/src/op/set.cpp b/src/frontends/gguf/src/op/set.cpp
index 0b88e886bff..0823dc27588 100644
--- a/src/frontends/gguf/src/op/set.cpp
+++ b/src/frontends/gguf/src/op/set.cpp
@@ -33,12 +33,9 @@ OutputVector translate_set(const NodeContext& context) {
ov::Output<ov::Node> dst = context.get_input(0);
ov::Output<ov::Node> src = context.get_input(1);
- // ScatterUpdate requires data and updates to share an element type, so cast both.
- const auto output_type = context.get_attribute<ov::element::Type>("output_type");
+ // ScatterUpdate requires updates to have the destination type.
+ const auto output_type = dst.get_element_type();
src = std::make_shared<ov::op::v0::Convert>(src, output_type);
- if (dst.get_element_type() != output_type) {
- dst = std::make_shared<ov::op::v0::Convert>(dst, output_type);
- }
const int64_t offset_elems = context.get_attribute<int64_t>("set_offset_elems");
diff --git a/src/frontends/gguf/src/op/set_rows.cpp b/src/frontends/gguf/src/op/set_rows.cpp
index ae0049203f8..c819be2026b 100644
--- a/src/frontends/gguf/src/op/set_rows.cpp
+++ b/src/frontends/gguf/src/op/set_rows.cpp
@@ -33,7 +33,7 @@ OutputVector translate_set_rows(const NodeContext& context) {
auto indices = context.get_input(1);
auto dst = context.get_input(2);
- data = std::make_shared<ov::op::v0::Convert>(data, context.get_output_type());
+ data = std::make_shared<ov::op::v0::Convert>(data, dst.get_element_type());
// Row size = the destination cache's innermost dim. Using the dst input (not the SET_ROWS
// output shape) matters for the flattened KV-cache write (gpt-oss cache_v is stored as
diff --git a/src/frontends/gguf/src/op/softmax.cpp b/src/frontends/gguf/src/op/softmax.cpp
index 886b68697fe..7da5ccae3a7 100644
--- a/src/frontends/gguf/src/op/softmax.cpp
+++ b/src/frontends/gguf/src/op/softmax.cpp
@@ -99,7 +99,7 @@ OutputVector translate_soft_max(const NodeContext& context) {
// Disambiguate a 2nd input: it is either the additive mask or (gpt-oss) the attention sinks.
const bool second_input_is_sinks =
context.get_input_size() == 2 &&
- is_attention_sinks_input_shape(context.get_input_shape(1), context.get_output_shape());
+ is_attention_sinks_input_shape(context.get_input_shape(1), context.get_input_shape(0));
const bool has_mask = context.get_input_size() > 1 && !second_input_is_sinks;
const bool has_sinks = second_input_is_sinks || context.get_input_size() > 2;
const int sinks_input_idx = second_input_is_sinks ? 1 : 2;
@@ -124,7 +124,7 @@ OutputVector translate_soft_max(const NodeContext& context) {
mask_node_sliced = std::make_shared<ov::op::v8::Slice>(mask_node, zero, token_len, one, one);
}
- auto output_type = context.get_attribute<ov::element::Type>("output_type");
+ auto output_type = input0.get_element_type();
if (mask_node_sliced.get_element_type() != output_type) {
mask_node_sliced = std::make_shared<ov::op::v0::Convert>(mask_node_sliced, output_type);
}
diff --git a/src/frontends/gguf/src/op/ssm_conv.cpp b/src/frontends/gguf/src/op/ssm_conv.cpp
index fdba04921cc..821d2679200 100644
--- a/src/frontends/gguf/src/op/ssm_conv.cpp
+++ b/src/frontends/gguf/src/op/ssm_conv.cpp
@@ -25,12 +25,12 @@ OutputVector translate_ssm_conv(const NodeContext& context) {
auto sx = context.get_input(0); // conv state + input: OV [1, n_s, d_inner, ncs]
auto c = context.get_input(1); // conv1d weight: OV [1, 1, d_inner, d_conv]
- auto sx_shape = context.get_input_shape(0).to_shape();
- auto c_shape = context.get_input_shape(1).to_shape();
+ auto sx_shape = context.get_input_shape(0);
+ auto c_shape = context.get_input_shape(1);
- int64_t n_s = sx_shape[1];
- int64_t d_inner = sx_shape[2];
- int64_t d_conv = c_shape[3];
+ int64_t n_s = sx_shape[1].get_length();
+ int64_t d_inner = sx_shape[2].get_length();
+ int64_t d_conv = c_shape[3].get_length();
// The conv-window length ncs (= n_t + d_conv - 1) and the token count n_t are token-dependent: the
// stateful model is compiled once and reused across token counts, so keep those axes dynamic (-1)
diff --git a/src/frontends/gguf/src/op/top_k.cpp b/src/frontends/gguf/src/op/top_k.cpp
index 6982592c849..f5d12ae5b10 100644
--- a/src/frontends/gguf/src/op/top_k.cpp
+++ b/src/frontends/gguf/src/op/top_k.cpp
@@ -2,12 +2,21 @@
// SPDX-License-Identifier: Apache-2.0
//
+#include <limits>
+
#include "node_context.hpp"
#include "op_table.hpp"
#include "openvino/core/node_output.hpp"
+#include "openvino/op/broadcast.hpp"
#include "openvino/op/constant.hpp"
+#include "openvino/op/reduce_sum.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/scatter_elements_update.hpp"
+#include "openvino/op/select.hpp"
+#include "openvino/op/shape_of.hpp"
#include "openvino/op/squeeze.hpp"
#include "openvino/op/topk.hpp"
+#include "openvino/op/unsqueeze.hpp"
#include "utils.hpp"
namespace ov {
@@ -15,34 +24,57 @@ namespace frontend {
namespace gguf {
namespace op {
-// ggml_top_k(a, k): the indices of the k largest values along ne[0] (the OV last axis),
-// ordered by descending value, as i32. k is the extent of that axis on the output.
+// ggml_top_k(a, k): the indices of the k largest values along ne[0] (the OV last axis).
+// The caller supplies k; legacy decoders encode it in the output's last dimension.
OutputVector translate_top_k(const NodeContext& context) {
num_inputs_check(context, 1, 1);
auto input = context.get_input(0);
+ const int groups = context.get_attribute<int>("expert_groups", 1);
+ if (groups > 1) {
+ using namespace ov::op;
+ const int used = context.get_attribute<int>("expert_groups_used");
+ const auto shape = input.get_partial_shape();
+ const auto experts = shape[shape.rank().get_length() - 1].get_length();
+ FRONT_END_GENERAL_CHECK(experts % groups == 0 && experts / groups >= 2 && used > 0 && used <= groups,
+ "Invalid grouped expert selection dimensions");
+ const auto grouped_shape =
+ v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{-1, groups, experts / groups});
+ auto grouped = std::make_shared<v1::Reshape>(input, grouped_shape, false);
+ auto two = v0::Constant::create(ov::element::i64, {}, {2});
+ auto best =
+ std::make_shared<v11::TopK>(grouped, two, -1, v11::TopK::Mode::MAX, v11::TopK::SortType::SORT_VALUES);
+ auto axis = v0::Constant::create(ov::element::i64, {}, {-1});
+ // llama.cpp scores each group by its two highest (possibly biased) expert probabilities.
+ auto scores = std::make_shared<v1::ReduceSum>(best->output(0), axis, false);
+ auto selected =
+ make_topk_indices(scores, v0::Constant::create(ov::element::i64, {}, {used}), -1, v11::TopK::Mode::MAX);
+ auto zero = v0::Constant::create(ov::element::boolean, {}, {false});
+ auto one = v0::Constant::create(ov::element::boolean, {}, {true});
+ auto mask = std::make_shared<v3::Broadcast>(zero, std::make_shared<v3::ShapeOf>(scores));
+ auto updates = std::make_shared<v3::Broadcast>(one, std::make_shared<v3::ShapeOf>(selected));
+ auto selected_mask = std::make_shared<v3::ScatterElementsUpdate>(mask, selected, updates, axis);
+ auto expanded = std::make_shared<v0::Unsqueeze>(selected_mask, axis);
+ auto negative = v0::Constant::create(input.get_element_type(), {}, {-std::numeric_limits<float>::infinity()});
+ auto filtered = std::make_shared<v1::Select>(expanded, grouped, negative);
+ input = std::make_shared<v1::Reshape>(filtered, std::make_shared<v3::ShapeOf>(input), false);
+ }
- // k is the output's last-axis extent. Prefer the static value, but fall back to reading it off
- // the output shape at runtime so a dynamic extent converts instead of throwing (ARGSORT derives
- // its k dynamically for the same reason).
- const auto& out_ps = context.get_output_shape();
- const auto rank = out_ps.rank();
- const int64_t axis = rank.is_static() ? rank.get_length() - 1 : -1;
- ov::Output<ov::Node> k_node;
- if (rank.is_static() && out_ps[rank.get_length() - 1].is_static()) {
- k_node =
- ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {out_ps[rank.get_length() - 1].get_length()});
+ const auto k_attribute = context.get_attribute_as_any("k");
+ int64_t k;
+ if (!k_attribute.empty()) {
+ k = k_attribute.as<int64_t>();
} else {
- k_node = std::make_shared<ov::op::v0::Squeeze>(
- get_dimensions(input, {static_cast<int>(rank.is_static() ? rank.get_length() - 1 : 3)}),
- ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
+ const auto shape = context.get_output_shape();
+ const auto rank = shape.rank();
+ FRONT_END_OP_CONVERSION_CHECK(
+ rank.is_static() && rank.get_length() > 0 && shape[rank.get_length() - 1].is_static(),
+ "TOP_K requires 'k' or a static last output dimension");
+ k = shape[rank.get_length() - 1].get_length();
}
- auto indices = make_topk_indices(input,
- k_node,
- axis,
- ov::op::v11::TopK::Mode::MAX,
- context.get_attribute<ov::element::Type>("output_type"));
+ auto k_node = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {k});
+ auto indices = make_topk_indices(input, k_node, -1, ov::op::v11::TopK::Mode::MAX);
return rename_outputs_with_suffix({std::move(indices)}, context.get_name());
}
diff --git a/src/frontends/gguf/src/op/tri.cpp b/src/frontends/gguf/src/op/tri.cpp
index 05079ca40e9..1d9fca139b0 100644
--- a/src/frontends/gguf/src/op/tri.cpp
+++ b/src/frontends/gguf/src/op/tri.cpp
@@ -66,9 +66,7 @@ OutputVector translate_tri(const NodeContext& context) {
}
}
// Build the mask in the node's own type, or an f16 input gets promoted to f32 by the Multiply.
- auto keep_mask = ov::op::v0::Constant::create(context.get_attribute<ov::element::Type>("output_type"),
- ov::Shape{1, 1, n, n},
- mask);
+ auto keep_mask = ov::op::v0::Constant::create(x.get_element_type(), ov::Shape{1, 1, n, n}, mask);
auto res = std::make_shared<ov::op::v1::Multiply>(x, keep_mask);
diff --git a/src/frontends/gguf/src/op/view.cpp b/src/frontends/gguf/src/op/view.cpp
index 2227d111426..f59e694e9c1 100644
--- a/src/frontends/gguf/src/op/view.cpp
+++ b/src/frontends/gguf/src/op/view.cpp
@@ -100,9 +100,9 @@ OutputVector translate_view(const NodeContext& context) {
// Restore the original ggml (base) shape if the OV input was already reshaped, mirroring
// op_case 3. The base is [F, T] (ggml) == OV [.., T, F]; we then split F into G x group_stride.
- auto input_ggml_shape = context.get_attribute<ov::Shape>("input_ggml_shape");
+ auto input_ggml_shape = context.get_attribute<ov::Shape>("input_ggml_shape", {});
auto input_ov_shape = input.get_partial_shape();
- if (input_ov_shape.rank().is_static() &&
+ if (!input_ggml_shape.empty() && input_ov_shape.rank().is_static() &&
static_cast<size_t>(input_ov_shape.rank().get_length()) != input_ggml_shape.size()) {
input = std::make_shared<ov::op::v1::Reshape>(
input,
@@ -184,10 +184,10 @@ OutputVector translate_view(const NodeContext& context) {
if (context.get_attribute<int>("op_case", 0) == 3) {
auto input = context.get_input(0);
auto input_ov_shape = input.get_partial_shape();
- auto input_ggml_shape = context.get_attribute<ov::Shape>("input_ggml_shape");
+ auto input_ggml_shape = context.get_attribute<ov::Shape>("input_ggml_shape", {});
// Input already reshaped: restore the original ggml (base) shape before slicing.
- if (input_ov_shape.rank().is_static() &&
+ if (!input_ggml_shape.empty() && input_ov_shape.rank().is_static() &&
static_cast<size_t>(input_ov_shape.rank().get_length()) != input_ggml_shape.size()) {
input = std::make_shared<ov::op::v1::Reshape>(
input,
@@ -268,7 +268,7 @@ OutputVector translate_view(const NodeContext& context) {
const auto ref_rank = ref.get_partial_shape().rank();
FRONT_END_OP_CONVERSION_CHECK(ref_rank.is_static(),
"VIEW case 104 shape reference must have a static rank");
- const auto d_ps = context.get_output_shape();
+ const auto d_ps = input.get_partial_shape();
const int64_t rank = ref_rank.get_length();
FRONT_END_OP_CONVERSION_CHECK(d_ps.rank().is_static() && d_ps[d_ps.rank().get_length() - 1].is_static(),
"VIEW case 104 requires a static per-layer embedding width");
diff --git a/src/frontends/gguf/src/pass/adapt_to_genai.cpp b/src/frontends/gguf/src/pass/adapt_to_genai.cpp
index 504aa316ccc..0883fc98ccd 100644
--- a/src/frontends/gguf/src/pass/adapt_to_genai.cpp
+++ b/src/frontends/gguf/src/pass/adapt_to_genai.cpp
@@ -190,14 +190,13 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
"[gguf] AdaptToGenAI: only InputMode::IDS_TO_LOGITS is implemented; "
"EMBEDS_TO_LOGITS (VLM language model) is reserved for future work.");
- // The gguf inputs we rewire. inp_tokens/inp_pos/self_kq_mask/token_len_per_seq are
- // required; if they are absent the model is not a gguf-IO model (e.g. already adapted),
- // so this pass is a no-op.
+ // 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.
auto inp_tokens = find_parameter(model, "inp_tokens");
auto inp_pos = find_parameter(model, "inp_pos");
auto self_kq_mask = find_parameter(model, "self_kq_mask");
auto token_len_per_seq = find_parameter(model, "token_len_per_seq");
- if (!inp_tokens || !inp_pos || !self_kq_mask || !token_len_per_seq) {
+ if (!inp_tokens || !inp_pos || !self_kq_mask) {
return false;
}
@@ -233,8 +232,9 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {
// 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);
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); // [1]
- token_len_per_seq->output(0).replace(seq_len->output(0));
+ auto seq_len = make_shared<v1::ReduceProd>(ids_shape, reduce_axis_0, true);
+ if (token_len_per_seq)
+ token_len_per_seq->output(0).replace(seq_len->output(0));
// The two gguf rank-4 input kinds carry the (batch, tokens) pair on different axes, so they get
// different lifts. Both are written so the genai Parameter's own leading dims flow through
diff --git a/src/frontends/gguf/src/quant/gguf.cpp b/src/frontends/gguf/src/quant/gguf.cpp
index e9699b8d1cf..48391e8e736 100644
--- a/src/frontends/gguf/src/quant/gguf.cpp
+++ b/src/frontends/gguf/src/quant/gguf.cpp
@@ -904,6 +904,11 @@ std::map<std::string, GGUFMetaData> decoder_config_from_meta(
const bool is_yarn = metadata.count(arch + ".rope.scaling.type") &&
std::get<std::string>(metadata.at(arch + ".rope.scaling.type")) == "yarn";
config["rope_ext_factor"] = is_yarn ? 1.0f : 0.0f;
+ config["rope_yarn_beta_fast"] = metadata_to_float_or(metadata, arch + ".rope.scaling.yarn_beta_fast", 32.0f);
+ config["rope_yarn_beta_slow"] = metadata_to_float_or(metadata, arch + ".rope.scaling.yarn_beta_slow", 1.0f);
+ config["rope_yarn_log_mul"] = metadata_to_float_or(metadata, arch + ".rope.scaling.yarn_log_multiplier", 0.0f);
+ config["attention_temperature_scale"] =
+ metadata_to_float_or(metadata, arch + ".attention.temperature_scale", 0.0f);
// n_ctx_orig: use rope.scaling.original_context_length when present; fall back to
// context_length (the training context, which is also n_ctx_train in llama.cpp).
@@ -956,7 +961,9 @@ std::map<std::string, GGUFMetaData> decoder_config_from_meta(
const float def_logit_scale = is_minicpm ? 256.0f / static_cast<float>(std::get<int>(config["hidden_size"])) : 1.0f;
config["embedding_scale"] = metadata_to_float_or(metadata, arch + ".embedding_scale", def_embedding_scale);
config["residual_scale"] = metadata_to_float_or(metadata, arch + ".residual_scale", def_residual_scale);
- config["logit_scale"] = metadata_to_float_or(metadata, arch + ".logit_scale", def_logit_scale);
+ const float logit_scale = metadata_to_float_or(metadata, arch + ".logit_scale", def_logit_scale);
+ // MiniCPM shares llama.cpp's Granite graph, which divides logits by this scale.
+ config["logit_scale"] = is_minicpm && logit_scale != 0.0f ? 1.0f / logit_scale : logit_scale;
// Hybrid linear-attention (Gated DeltaNet) parameters: qwen35 / qwen3next / kimi-linear.
// 0 for every non-SSM architecture, which is what the builder tests against.
auto ssm_key = [&](const std::string& k) {
@@ -1007,7 +1014,11 @@ std::map<std::string, GGUFMetaData> decoder_config_from_meta(
// Gemma3 (like gemma/gemma2) uses 1/sqrt(n_embd_head_k); llama.cpp applies it as a
// Qcur pre-scale with build_attn(scale=1.0), which is numerically 1/sqrt(head_size) --
// exactly the default branch here, so gemma3 must NOT force scale=1.0.
- const float def_attention_scale = (arch == "gemma4") ? 1.0f : 0.0f;
+ const float def_attention_scale = arch == "gemma4" ? 1.0f
+ : arch == "gemma2" && std::get<int>(config["layer_num"]) == 46
+ ? 1.0f / std::sqrt(static_cast<float>(std::get<int>(config["hidden_size"]) /
+ std::get<int>(config["head_num"])))
+ : 0.0f;
config["attention_scale"] = metadata_to_float_or(metadata, arch + ".attention.scale", def_attention_scale);
// gpt-oss SWA: separate RoPE frequency base for sliding-window attention layers.
@@ -1029,7 +1040,8 @@ std::map<std::string, GGUFMetaData> decoder_config_from_meta(
// (swa_window_size below): a token at position q may then attend to keys in
// [q - swa_window_size + 1, q], which AdaptToGenAI needs to build a correctly windowed
// self_kq_mask_swa instead of reusing the full causal mask.
- uint32_t swa_window_value = 0;
+ uint32_t swa_window_value =
+ (arch == "gemma2" || (arch == "exaone4" && std::get<int>(config["layer_num"]) == 64)) ? 4096 : 0;
if (metadata.count(arch + ".attention.sliding_window")) {
const auto& t = std::get<ov::Tensor>(metadata.at(arch + ".attention.sliding_window"));
const uint32_t v = *t.data<uint32_t>();
@@ -1070,15 +1082,18 @@ 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 : 2;
+ config["swa_layer_pattern"] = arch == "gemma3" ? 6 : arch == "exaone4" ? 4 : 2;
config["swa_layer_flags"] = std::vector<int32_t>{};
}
// gpt-oss MoE: optional per-expert routing weight scale applied after softmax (0 = 1.0 no-op).
config["expert_weights_scale"] = metadata_to_float_or(metadata, arch + ".expert_weights_scale", 0.0f);
- // qwen3moe/glm4moe/bailingmoe2 MoE: renormalize the selected top-K gate weights to sum to 1
- // (llama.cpp build_moe_ffn's norm_w / "norm_topk_prob"); absent -> no renormalization.
+ // Routing metadata; architecture-required normalization is resolved in DecoderConfig.
+ 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);
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/translate_session.cpp b/src/frontends/gguf/src/translate_session.cpp
index a55e5cc2962..9c763030805 100644
--- a/src/frontends/gguf/src/translate_session.cpp
+++ b/src/frontends/gguf/src/translate_session.cpp
@@ -12,6 +12,7 @@
#include <set>
#include <unordered_set>
+#include "builder/gguf_builder_decoder.hpp"
#include "input_model.hpp"
#include "node_context.hpp"
#include "openvino/core/graph_util.hpp"
@@ -61,7 +62,7 @@ void add_sliced_mask(TensorMap& tensor_map) {
// Publish the decoder's runtime-sized attention mask under the shared name
// consumed by the attention translators.
auto create_sliced_mask = [&](const std::string& mask_name, const std::string& sliced_name) {
- if (tensor_map.find(mask_name) != tensor_map.end()) {
+ if (tensor_map.count(mask_name) && !tensor_map.count(sliced_name)) {
auto mask = tensor_map.at(mask_name).get_node_shared_ptr();
// The decoder binds the mask with its current runtime shape, so its
// token axis already is the active token window.
@@ -86,7 +87,7 @@ void add_rope_sin_cos(TensorMap& tensor_map, GgufDecoder& gguf_model_decoder) {
const auto& rope_config = rope_config_any.as<RopeConfig>();
// n_dims == 0 means the model uses no RoPE; per_op means each ROPE op builds its own sin/cos
// (e.g. gemma4 where SWA and global layers differ), so skip the shared table entirely.
- if (tensor_map.find("inp_pos") == tensor_map.end() || rope_config.n_dims == 0 || rope_config.per_op) {
+ if (tensor_map.count("rope_cos") || !tensor_map.count("inp_pos") || rope_config.n_dims == 0 || rope_config.per_op) {
return;
}
auto inp_pos = tensor_map.at("inp_pos").get_node_shared_ptr();
@@ -105,13 +106,56 @@ void add_rope_sin_cos(TensorMap& tensor_map, GgufDecoder& gguf_model_decoder) {
tensor_map.insert({"rope_sin", sin_theta});
}
-// Create common patterns
-void preprocess(TensorMap& tensor_map, GgufDecoder& gguf_model_decoder) {
+} // namespace
+
+void prepare_graph_inputs(TensorMap& tensor_map, GgufDecoder& gguf_model_decoder) {
add_sliced_mask(tensor_map);
add_rope_sin_cos(tensor_map, gguf_model_decoder);
}
-} // namespace
+void translate_node(const std::shared_ptr<GgufDecoder>& decoder,
+ std::shared_ptr<TensorMap>& tensor_map,
+ const std::unordered_map<std::string, CreatorFunction>& translators) {
+ const auto& operation_type = decoder->get_op_type();
+ if (operation_type == "GGML_OP_NONE") {
+ // A GGML_OP_NONE leaf is a weight if the decoder marks it as one: either the native
+ // builder's pre-extracted payload (bool "gguf_weight") or the cgraph decoder's raw
+ // bytes ("data"). Otherwise it is a model-input leaf (already seeded as a Parameter
+ // above) and there is nothing to translate.
+ const bool is_builder_weight =
+ decoder->get_attribute("gguf_weight").is<bool>() && decoder->get_attribute("gguf_weight").as<bool>();
+ const bool is_cgraph_weight = decoder->get_attribute("data").is<ov::Tensor>();
+ if (!is_builder_weight && !is_cgraph_weight) {
+ return;
+ }
+ }
+
+ ov::OutputVector converted_outputs;
+ auto it = translators.find(operation_type);
+ FRONT_END_OP_CONVERSION_CHECK(it != translators.end(),
+ "Translation for operation type ",
+ operation_type,
+ " is not implemented.");
+ NodeContext node_context(decoder, tensor_map);
+ converted_outputs = it->second(node_context);
+
+ const auto& node_output_names = decoder->get_output_names();
+ FRONT_END_OP_CONVERSION_CHECK(node_output_names.size() == converted_outputs.size(),
+ "Number of ",
+ operation_type,
+ " outputs greater than number of converted outputs, which are ",
+ node_output_names.size(),
+ " and ",
+ converted_outputs.size(),
+ " respectively.");
+
+ for (size_t i = 0; i < node_output_names.size(); ++i) {
+ const auto& output_name = node_output_names[i];
+ if (i < converted_outputs.size() && converted_outputs[i].get_node_shared_ptr() != nullptr) {
+ (*tensor_map)[output_name] = converted_outputs[i];
+ }
+ }
+}
TranslateSession::TranslateSession(const frontend::InputModel::Ptr& input_model,
const std::unordered_map<std::string, CreatorFunction>& translator_map,
@@ -175,45 +219,7 @@ std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputMo
// lazy (never materialized to f32) and keeps one weight-loading path for both ingest paths.
auto node_visitor = [&](std::shared_ptr<GgufDecoder> decoder) {
- const auto& operation_type = decoder->get_op_type();
- if (operation_type == "GGML_OP_NONE") {
- // A GGML_OP_NONE leaf is a weight if the decoder marks it as one: either the native
- // builder's pre-extracted payload (bool "gguf_weight") or the cgraph decoder's raw
- // bytes ("data"). Otherwise it is a model-input leaf (already seeded as a Parameter
- // above) and there is nothing to translate.
- const bool is_builder_weight =
- decoder->get_attribute("gguf_weight").is<bool>() && decoder->get_attribute("gguf_weight").as<bool>();
- const bool is_cgraph_weight = decoder->get_attribute("data").is<ov::Tensor>();
- if (!is_builder_weight && !is_cgraph_weight) {
- return;
- }
- }
-
- ov::OutputVector converted_outputs;
- auto it = m_translator_map.find(operation_type);
- FRONT_END_OP_CONVERSION_CHECK(it != m_translator_map.end(),
- "Translation for operation type ",
- operation_type,
- " is not implemented.");
- NodeContext node_context(decoder, tensor_map);
- converted_outputs = it->second(node_context);
-
- const auto& node_output_names = decoder->get_output_names();
- FRONT_END_OP_CONVERSION_CHECK(node_output_names.size() == converted_outputs.size(),
- "Number of ",
- operation_type,
- " outputs greater than number of converted outputs, which are ",
- node_output_names.size(),
- " and ",
- converted_outputs.size(),
- " respectively.");
-
- for (size_t i = 0; i < node_output_names.size(); ++i) {
- const auto& output_name = node_output_names[i];
- if (i < converted_outputs.size() && converted_outputs[i].get_node_shared_ptr() != nullptr) {
- (*tensor_map)[output_name] = converted_outputs[i];
- }
- }
+ translate_node(decoder, tensor_map, m_translator_map);
};
// Build the shared LLM scaffolding (sliced attention mask + rope sin/cos table) once, so all
@@ -222,8 +228,13 @@ std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputMo
// the model uses a shared rope table (n_dims != 0, not per-op). For a bare op / small cgraph
// (no rope_config -> default n_dims == 0, no mask/pos inputs) both no-op, and the ROPE/attention
// translators fall back to building their own -- so there is no separate "naive" mode.
- preprocess(*tensor_map, *gguf_model_decoder);
- gguf_model_decoder->visit_subgraph(node_visitor);
+ const auto builder = std::dynamic_pointer_cast<GgufBuilderDecoder>(gguf_model_decoder);
+ if (builder) {
+ tensor_map = builder->values();
+ } else {
+ prepare_graph_inputs(*tensor_map, *gguf_model_decoder);
+ gguf_model_decoder->visit_subgraph(node_visitor);
+ }
for (const auto& name : gguf_model_decoder->get_model_output_names()) {
FRONT_END_GENERAL_CHECK(tensor_map->find(name) != tensor_map->end(),
@@ -281,6 +292,9 @@ std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputMo
}
}
+ if (builder) {
+ resulting_model = resulting_model->clone();
+ }
resulting_model = apply_transformations(resulting_model);
// Auxiliary Parameters are kept through normalization in case a transformation extension
diff --git a/src/frontends/gguf/src/translate_session.hpp b/src/frontends/gguf/src/translate_session.hpp
index cb4f60c56f0..354bb389a21 100644
--- a/src/frontends/gguf/src/translate_session.hpp
+++ b/src/frontends/gguf/src/translate_session.hpp
@@ -10,6 +10,11 @@
namespace ov::frontend::gguf {
+void prepare_graph_inputs(TensorMap& values, GgufDecoder& decoder);
+void translate_node(const std::shared_ptr<GgufDecoder>& decoder,
+ std::shared_ptr<TensorMap>& values,
+ const std::unordered_map<std::string, CreatorFunction>& translators);
+
class TranslateSession {
public:
TranslateSession(const frontend::InputModel::Ptr& input_model,
diff --git a/src/frontends/gguf/src/utils.cpp b/src/frontends/gguf/src/utils.cpp
index c0142b1d226..b33457bd9f4 100644
--- a/src/frontends/gguf/src/utils.cpp
+++ b/src/frontends/gguf/src/utils.cpp
@@ -87,14 +87,13 @@ ov::Output<ov::Node> make_topk_indices(const ov::Output<ov::Node>& input,
const ov::Output<ov::Node>& k,
int64_t axis,
ov::op::v11::TopK::Mode mode,
- const ov::element::Type& index_type,
bool stable) {
auto topk = std::make_shared<ov::op::v11::TopK>(input,
k,
axis,
mode,
ov::op::v11::TopK::SortType::SORT_VALUES,
- index_type,
+ ov::element::i32,
stable);
return topk->output(1); // indices
}
diff --git a/src/frontends/gguf/src/utils.hpp b/src/frontends/gguf/src/utils.hpp
index 6923bb28aa6..b95263c9937 100644
--- a/src/frontends/gguf/src/utils.hpp
+++ b/src/frontends/gguf/src/utils.hpp
@@ -54,24 +54,11 @@ std::shared_ptr<ov::Node> get_dimensions(const ov::Output<ov::Node>& output, con
// then return the same vector without an extra copy.
OutputVector rename_outputs_with_suffix(OutputVector outputs, const std::string& suffix);
-/// \brief Build a TopK over `axis` and return its INDICES port.
-///
-/// Shared by the ARGSORT and TOP_K translators. Both want ggml's "indices that sort/select along
-/// ne[0]" semantics, which in OpenVINO is output(1) of a TopK whose index element type follows the
-/// decoder's "output_type" attribute. Keeping that contract in one place stops the two call sites
-/// from drifting apart.
-///
-/// \param input tensor to sort/select over
-/// \param k number of elements to keep along `axis` (may be a dynamic value)
-/// \param axis axis to operate on
-/// \param mode MAX for descending, MIN for ascending
-/// \param index_type element type of the returned indices
-/// \param stable whether ties keep their input order
+// GGML TOP_K and ARGSORT return I32 indices, which are OpenVINO TopK's second output.
ov::Output<ov::Node> make_topk_indices(const ov::Output<ov::Node>& input,
const ov::Output<ov::Node>& k,
int64_t axis,
ov::op::v11::TopK::Mode mode,
- const ov::element::Type& index_type,
bool stable = false);
std::pair<ov::Output<Node>, ov::Output<Node>> make_sin_cos(const RopeConfig& rope_config,
diff --git a/src/frontends/gguf/tests/CMakeLists.txt b/src/frontends/gguf/tests/CMakeLists.txt
index cd06713194f..413f1cede22 100644
--- a/src/frontends/gguf/tests/CMakeLists.txt
+++ b/src/frontends/gguf/tests/CMakeLists.txt
@@ -37,6 +37,10 @@ set(FRONTEND_SRCS
"${FE_SRC_DIR}/builder/arch_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}/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/blocks/attention.cpp"
"${FE_SRC_DIR}/builder/blocks/common.cpp"
@@ -89,6 +93,9 @@ set(FRONTEND_SRCS
set(TEST_SRCS
"${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"
+ "${CMAKE_CURRENT_SOURCE_DIR}/test_architecture_extension.cpp"
+ "${CMAKE_CURRENT_SOURCE_DIR}/test_builder_api.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/test_dequant_vs_ggml.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/test_extensions.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/test_op_coverage.cpp"
@@ -112,6 +119,7 @@ ov_add_test_target(
INCLUDES
"${CMAKE_CURRENT_SOURCE_DIR}/../src"
"${CMAKE_CURRENT_SOURCE_DIR}/../include"
+ "${CMAKE_CURRENT_SOURCE_DIR}/../dev_api"
# frontend.cpp (compiled into the self-contained test binary) includes the native
# .gguf load path (get_path_from_any in openvino/frontend/common/path_util.hpp).
"${OpenVINO_SOURCE_DIR}/src/frontends/common/include"
@@ -136,6 +144,7 @@ install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/test_data"
EXCLUDE_FROM_ALL
FILES_MATCHING
PATTERN "*.npy"
+ PATTERN "*.npz"
PATTERN "manifest.txt")
# Sources compiled into the binary: resolve the visibility macros to local definitions, not dllimport.
@@ -155,3 +164,26 @@ target_compile_definitions(${TARGET_NAME} PRIVATE
)
ov_build_target_faster(${TARGET_NAME} PCH)
+
+# Test loading an independently compiled architecture module using only builder API headers.
+set(ARCH_EXAMPLE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../examples/architecture_extension")
+add_library(gguf_projector_extension MODULE
+ "${ARCH_EXAMPLE_DIR}/projector.cpp" "${ARCH_EXAMPLE_DIR}/extension.cpp")
+target_link_libraries(gguf_projector_extension PRIVATE openvino::frontend::gguf)
+target_compile_features(gguf_projector_extension PRIVATE cxx_std_17)
+install(TARGETS gguf_projector_extension LIBRARY DESTINATION tests RUNTIME DESTINATION tests
+ COMPONENT tests EXCLUDE_FROM_ALL)
+
+ov_add_test_target(
+ NAME ov_gguf_architecture_library_tests
+ SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/test_architecture_library.cpp" "${ARCH_EXAMPLE_DIR}/projector.cpp"
+ LINK_LIBRARIES gtest gtest_main common_test_utils openvino::runtime openvino::frontend::gguf
+ INCLUDES "${ARCH_EXAMPLE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}"
+ LABELS OV UNIT GGUF_FE)
+target_compile_definitions(ov_gguf_architecture_library_tests PRIVATE
+ ARCH_EXTENSION_LIBRARY="$<TARGET_FILE_NAME:gguf_projector_extension>")
+add_dependencies(ov_gguf_architecture_library_tests gguf_projector_extension)
+
+# The same definition can be seeded into the native catalog without the plugin entry point.
+target_sources(${TARGET_NAME} PRIVATE "${ARCH_EXAMPLE_DIR}/projector.cpp")
+target_include_directories(${TARGET_NAME} PRIVATE "${ARCH_EXAMPLE_DIR}")
diff --git a/src/frontends/gguf/tests/architecture_oracle.cpp b/src/frontends/gguf/tests/architecture_oracle.cpp
new file mode 100644
index 00000000000..3602f9d457d
--- /dev/null
+++ b/src/frontends/gguf/tests/architecture_oracle.cpp
@@ -0,0 +1,79 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+// Build against a CPU-only llama.cpp. See gen_arch_accuracy.py.
+#include <algorithm>
+#include <cstdint>
+#include <fstream>
+#include <stdexcept>
+#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};
+ if (!devices[0])
+ throw std::runtime_error("The architecture oracle requires the ggml CPU backend");
+ auto mp = llama_model_default_params();
+ mp.devices = devices;
+ mp.n_gpu_layers = 0;
+ auto* model = llama_model_load_from_file(argv[1], mp);
+ if (!model)
+ return 3;
+ auto cp = llama_context_default_params();
+ cp.n_ctx = 128;
+ cp.n_batch = 64;
+ cp.n_ubatch = 64;
+ cp.n_threads = cp.n_threads_batch = 4;
+ cp.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_DISABLED;
+ auto* ctx = llama_init_from_model(model, cp);
+ if (!ctx)
+ return 4;
+ const int32_t vocab = llama_vocab_n_tokens(llama_model_get_vocab(model));
+ std::ofstream out(argv[2], std::ios::binary);
+ out.write(reinterpret_cast<const char*>(&vocab), sizeof(vocab));
+ const auto* vocabulary = llama_model_get_vocab(model);
+ const bool generation = argc == 4;
+ std::vector<llama_token> tokens{1, 2, 3};
+ if (generation) {
+ const std::string prompt = argv[3];
+ tokens.resize(64);
+ const auto count = llama_tokenize(vocabulary,
+ prompt.data(),
+ static_cast<int32_t>(prompt.size()),
+ tokens.data(),
+ 64,
+ true,
+ false);
+ if (count <= 0)
+ return 7;
+ tokens.resize(count);
+ }
+ std::ofstream schedule(std::string(argv[2]) + ".tokens");
+ for (int step = 0; step < (generation ? 13 : 3); ++step) {
+ schedule << tokens.size();
+ for (auto token : tokens)
+ schedule << ' ' << token;
+ schedule << '\n';
+ auto batch = llama_batch_get_one(tokens.data(), static_cast<int32_t>(tokens.size()));
+ if (llama_decode(ctx, batch))
+ return 5;
+ const auto* logits = llama_get_logits_ith(ctx, -1);
+ out.write(reinterpret_cast<const char*>(logits), vocab * sizeof(float));
+ tokens =
+ generation
+ ? std::vector<llama_token>{static_cast<llama_token>(std::max_element(logits, logits + vocab) - logits)}
+ : step == 0 ? std::vector<llama_token>{4}
+ : std::vector<llama_token>{5, 6};
+ }
+ llama_free(ctx);
+ llama_model_free(model);
+ llama_backend_free();
+ return out ? 0 : 6;
+}
diff --git a/src/frontends/gguf/tests/gen_arch_accuracy.py b/src/frontends/gguf/tests/gen_arch_accuracy.py
new file mode 100644
index 00000000000..aa0ad9496a6
--- /dev/null
+++ b/src/frontends/gguf/tests/gen_arch_accuracy.py
@@ -0,0 +1,179 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+#
+
+"""Generate small GGUF models and logits from real llama.cpp CPU, never from OpenVINO.
+
+Usage: PYTHONPATH=<llama.cpp>/gguf-py python gen_arch_accuracy.py --oracle <architecture_oracle>
+Build architecture_oracle.cpp against a CPU-only llama.cpp (include/, ggml/include/,
+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
+
+import gguf
+import numpy as np
+
+CASES = {
+ "llama": {}, "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},
+ "gemma": {"mqa": True, "tied": True},
+ "gemma2": {"post": True, "swa": True, "tied": True, "softcap": True},
+ "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,
+ "selection_bias": True, "shared": True, "sigmoid": True},
+ "maincoder": {"qk": True}, "mistral3": {}, "smollm3": {"layers": 4},
+ "mellum": {"qk": True, "moe": True},
+ "muse-glimmer": {"qk": True, "post": True, "swa": True, "gate": True},
+ "deepseek2-ocr": {"moe": True, "lead": 1, "shared": True},
+ "devstral-small": {"architecture": "llama", "embedding": 40},
+ "devstral-small2": {"architecture": "mistral3", "embedding": 40, "yarn": 48.0,
+ "yarn_log_mul": 1.0, "temperature": 0.1, "original_context": 2},
+ "devstral2": {"architecture": "mistral3", "yarn": 64.0, "yarn_beta_fast": 4.0,
+ "yarn_log_mul": 0.0, "original_context": 128},
+}
+
+
+def write_model(path, arch, opts):
+ arch = opts.get("architecture", arch)
+ w = gguf.GGUFWriter(path, arch)
+ d, heads, head, ff, vocab = opts.get("embedding", 32), 4, 8, 48, 32
+ kv = 1 if opts.get("mqa") else heads if opts.get("full_qk") or arch == "deepseek2-ocr" else 2
+ layers = opts.get("layers", 2)
+ w.add_context_length(128)
+ w.add_embedding_length(d)
+ w.add_block_count(layers)
+ 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_freq_base(10000.0 if arch == "deepseek2-ocr" else 100.0)
+ w.add_layer_norm_rms_eps(1e-5)
+ w.add_vocab_size(vocab)
+ w.add_tokenizer_model("none")
+ if opts.get("yarn"):
+ w.add_rope_scaling_type(gguf.RopeScalingType.YARN)
+ w.add_rope_scaling_factor(opts["yarn"])
+ w.add_rope_scaling_orig_ctx_len(opts["original_context"])
+ w.add_rope_scaling_yarn_beta_fast(opts.get("yarn_beta_fast", 32.0))
+ w.add_rope_scaling_yarn_beta_slow(1.0)
+ w.add_rope_scaling_yarn_log_mul(opts["yarn_log_mul"])
+ w.add_attn_temperature_scale(opts.get("temperature", 0.0))
+ if opts.get("swa"):
+ w.add_sliding_window(2)
+ w.add_sliding_window_pattern(2)
+ if opts.get("softcap"):
+ w.add_attn_logit_softcapping(2.0)
+ w.add_final_logit_softcapping(3.0)
+ if arch == "muse-glimmer":
+ w.add_logit_scale(1.0)
+ if opts.get("moe"):
+ w.add_expert_count(4)
+ w.add_expert_used_count(2)
+ w.add_expert_feed_forward_length(ff)
+ w.add_leading_dense_block_count(opts.get("lead", 0))
+ if arch != "ernie4_5-moe":
+ 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"):
+ w.add_expert_weights_norm(arch != "olmoe")
+ if arch == "bailingmoe2":
+ w.add_expert_group_count(2)
+ w.add_expert_group_used_count(1)
+ 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("token_embd.weight", (vocab, d))
+ tensor("output_norm.weight", (d,), True)
+ 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"):
+ tensor(p + name + ".weight", (d,), True)
+ if opts.get("post") or opts.get("post_only"):
+ for name in ("post_attention_norm", "post_ffw_norm"):
+ tensor(p + name + ".weight", (d,), True)
+ if opts.get("fused"):
+ tensor(p + "attn_qkv.weight", ((heads + 2 * kv) * head, d))
+ else:
+ for name, width in (("q", heads * head), ("k", kv * head), ("v", kv * head)):
+ tensor(p + f"attn_{name}.weight", (width, d))
+ if opts.get("bias"):
+ tensor(p + f"attn_{name}.bias", (width,))
+ tensor(p + "attn_output.weight", (d, heads * head))
+ 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)
+ if opts.get("gate"):
+ tensor(p + "attn_gate.weight", (heads * head, d))
+ if opts.get("moe") and layer >= opts.get("lead", 0):
+ tensor(p + "ffn_gate_inp.weight", (4, d))
+ for name, shape in (("gate", (4, ff, d)), ("up", (4, ff, d)), ("down", (4, d, ff))):
+ tensor(p + f"ffn_{name}_exps.weight", shape)
+ if opts.get("selection_bias"):
+ tensor(p + "exp_probs_b.bias", (4,))
+ 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("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()
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--oracle", required=True)
+ 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()
+ 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)
+ if result.returncode:
+ raise RuntimeError(f"{arch}: oracle failed\n{result.stderr.decode()}")
+ 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())
+ print(f"{arch}: {model.stat().st_size} bytes, reference logits {logits.shape}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/frontends/gguf/tests/gguf_writer.hpp b/src/frontends/gguf/tests/gguf_writer.hpp
new file mode 100644
index 00000000000..c9122d59a48
--- /dev/null
+++ b/src/frontends/gguf/tests/gguf_writer.hpp
@@ -0,0 +1,132 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+// Minimal GGUF writer for synthetic decoder and non-decoder fixtures.
+// Tensor data is F32, optionally initialized with supplied values.
+
+#pragma once
+
+#include <cstdint>
+#include <cstring>
+#include <fstream>
+#include <stdexcept>
+#include <string>
+#include <vector>
+
+namespace ov_gguf_test {
+
+// GGUF metadata value types (gguf.h GGUF_VALUE_TYPE_*).
+enum : uint32_t {
+ GGUF_TYPE_UINT32 = 4,
+ GGUF_TYPE_FLOAT32 = 6,
+ GGUF_TYPE_BOOL = 7,
+ GGUF_TYPE_STRING = 8,
+};
+
+// ggml tensor type F32 (ggml.h GGML_TYPE_F32).
+constexpr uint32_t GGML_TYPE_F32 = 0;
+
+class GgufWriter {
+public:
+ void kv_u32(const std::string& key, uint32_t v) {
+ kv_key(key, GGUF_TYPE_UINT32);
+ put(v);
+ }
+ void kv_f32(const std::string& key, float v) {
+ kv_key(key, GGUF_TYPE_FLOAT32);
+ put(v);
+ }
+ void kv_bool(const std::string& key, bool v) {
+ kv_key(key, GGUF_TYPE_BOOL);
+ m_kv.push_back(static_cast<char>(v ? 1 : 0));
+ }
+ void kv_str(const std::string& key, const std::string& v) {
+ kv_key(key, GGUF_TYPE_STRING);
+ put(static_cast<uint64_t>(v.size()));
+ m_kv.insert(m_kv.end(), v.begin(), v.end());
+ }
+
+ // 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 = {}) {
+ put_str(m_ti, name);
+ put(m_ti, static_cast<uint32_t>(dims.size()));
+ for (auto d : dims) {
+ put(m_ti, d);
+ }
+ put(m_ti, GGML_TYPE_F32);
+ put(m_ti, m_data_size);
+
+ uint64_t n = 1;
+ for (auto d : dims) {
+ n *= d;
+ }
+ uint64_t bytes = n * sizeof(float);
+ // Every tensor starts at an aligned offset within the data section.
+ if (const uint64_t rem = bytes % kAlignment) {
+ bytes += kAlignment - rem;
+ }
+ if (!values.empty() && values.size() != n)
+ throw std::invalid_argument("tensor payload size mismatch");
+ const auto offset = m_data.size();
+ m_data.resize(offset + bytes, 0);
+ if (!values.empty())
+ std::memcpy(m_data.data() + offset, values.data(), n * sizeof(float));
+ m_data_size += bytes;
+ ++m_n_tensors;
+ }
+
+ bool write(const std::string& path) const {
+ std::ofstream out(path, std::ios::binary);
+ if (!out) {
+ return false;
+ }
+ std::vector<char> head;
+ put(head, static_cast<uint32_t>(0x46554747)); // "GGUF"
+ put(head, static_cast<uint32_t>(3)); // version
+ put(head, m_n_tensors);
+ put(head, m_n_kv);
+ out.write(head.data(), static_cast<std::streamsize>(head.size()));
+ out.write(m_kv.data(), static_cast<std::streamsize>(m_kv.size()));
+ out.write(m_ti.data(), static_cast<std::streamsize>(m_ti.size()));
+
+ // Tensor data starts at the next aligned offset after the info section.
+ uint64_t off = head.size() + m_kv.size() + m_ti.size();
+ if (const uint64_t rem = off % kAlignment) {
+ const std::vector<char> pad(kAlignment - rem, 0);
+ out.write(pad.data(), static_cast<std::streamsize>(pad.size()));
+ }
+ out.write(m_data.data(), static_cast<std::streamsize>(m_data.size()));
+ return static_cast<bool>(out);
+ }
+
+private:
+ static constexpr uint64_t kAlignment = 32;
+
+ template <typename T>
+ static void put(std::vector<char>& buf, const T& v) {
+ const auto* p = reinterpret_cast<const char*>(&v);
+ buf.insert(buf.end(), p, p + sizeof(T));
+ }
+ static void put_str(std::vector<char>& buf, const std::string& s) {
+ put(buf, static_cast<uint64_t>(s.size()));
+ buf.insert(buf.end(), s.begin(), s.end());
+ }
+ template <typename T>
+ void put(const T& v) {
+ put(m_kv, v);
+ }
+ void kv_key(const std::string& key, uint32_t type) {
+ put_str(m_kv, key);
+ put(m_kv, type);
+ ++m_n_kv;
+ }
+
+ std::vector<char> m_kv;
+ std::vector<char> m_ti;
+ std::vector<char> m_data;
+ uint64_t m_n_kv = 0;
+ uint64_t m_n_tensors = 0;
+ uint64_t m_data_size = 0;
+};
+
+} // 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 6440af6e0ed..338e4efbd1d 100644
--- a/src/frontends/gguf/tests/test_adapt_to_genai.cpp
+++ b/src/frontends/gguf/tests/test_adapt_to_genai.cpp
@@ -159,6 +159,22 @@ TEST(GGUFAdaptToGenAI, RewritesIOContract) {
EXPECT_EQ(m.model->get_results()[0]->get_output_partial_shape(0).rank().get_length(), 3);
}
+TEST(GGUFAdaptToGenAI, AcceptsPrunedTokenCountInput) {
+ auto m = build_minimal_gguf_model();
+ auto count = find_parameter(m.model, "token_len_per_seq");
+ ASSERT_NE(count, nullptr);
+ ASSERT_TRUE(count->output(0).get_target_inputs().empty());
+ m.model->remove_parameter(count);
+
+ ASSERT_TRUE(AdaptToGenAI().run_on_model(m.model));
+ EXPECT_NE(find_parameter(m.model, "input_ids"), nullptr);
+ EXPECT_NE(find_parameter(m.model, "attention_mask"), nullptr);
+ EXPECT_NE(find_parameter(m.model, "position_ids"), nullptr);
+ EXPECT_EQ(m.model->get_results().size(), 1);
+ EXPECT_EQ(m.model->output().get_partial_shape().rank().get_length(), 3);
+ EXPECT_FALSE(AdaptToGenAI().run_on_model(m.model));
+}
+
// Without the required gguf inputs present, the pass is a no-op (e.g. a model already adapted, or
// not a gguf-IO model at all).
TEST(GGUFAdaptToGenAI, NoOpWithoutGgufInputs) {
diff --git a/src/frontends/gguf/tests/test_arch_accuracy.cpp b/src/frontends/gguf/tests/test_arch_accuracy.cpp
new file mode 100644
index 00000000000..3db31a63553
--- /dev/null
+++ b/src/frontends/gguf/tests/test_arch_accuracy.cpp
@@ -0,0 +1,190 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <algorithm>
+#include <cmath>
+#include <cstdlib>
+#include <filesystem>
+#include <fstream>
+
+#include "cnpy.h"
+#include "common_test_utils/common_utils.hpp"
+#include "gtest/gtest.h"
+#include "op_test_utils.hpp"
+#include "openvino/frontend/extension/decoder_transformation.hpp"
+#include "openvino/frontend/gguf/adapt_to_genai.hpp"
+#include "openvino/frontend/gguf/frontend.hpp"
+#include "openvino/frontend/gguf/make_stateful.hpp"
+#include "openvino/openvino.hpp"
+
+namespace {
+class GGUFArchitectureAccuracy : public ::testing::TestWithParam<const char*> {};
+
+TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {
+ const char* override_dir = std::getenv("OV_GGUF_ACCURACY_DATA");
+ const auto directory = override_dir ? std::filesystem::path(override_dir)
+ : std::filesystem::path(ov_gguf_test::test_data_dir()) / "arch_accuracy";
+ ASSERT_TRUE(std::filesystem::exists(directory)) << "Missing architecture reference data: " << directory;
+ const auto base = directory / GetParam();
+ std::vector<std::vector<int64_t>> schedule{{1, 2, 3}, {4}, {5, 6}};
+ 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;
+ if (override_dir) {
+ std::ifstream file(base.string() + ".bin", std::ios::binary);
+ ASSERT_TRUE(file) << base;
+ file.read(reinterpret_cast<char*>(&vocab), sizeof(vocab));
+ ASSERT_GT(vocab, 6);
+ ASSERT_LT(vocab, 1000000);
+ std::ifstream token_file(base.string() + ".bin.tokens");
+ if (token_file) {
+ schedule.clear();
+ size_t count = 0;
+ while (token_file >> count) {
+ ASSERT_GT(count, 0);
+ ASSERT_LE(count, 64);
+ std::vector<int64_t> ids(count);
+ for (auto& token : ids)
+ ASSERT_TRUE(token_file >> token);
+ schedule.push_back(std::move(ids));
+ }
+ }
+ ASSERT_FALSE(schedule.empty());
+ reference.resize(schedule.size() * vocab);
+ file.read(reinterpret_cast<char*>(reference.data()), reference.size() * sizeof(float));
+ ASSERT_TRUE(file);
+ } 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;
+ };
+ const auto& logits = array("logits");
+ ASSERT_EQ(logits.shape.size(), 2);
+ ASSERT_EQ(logits.shape[0], 3);
+ 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);
+ }
+ 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()));
+ auto model = fe.convert(fe.load(model_path));
+ 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 request = compiled.create_infer_request();
+ size_t past = 0;
+ size_t step = 0;
+ size_t matching_tokens = 0;
+ for (const auto& tokens : schedule) {
+ const auto count = tokens.size();
+ SCOPED_TRACE("past=" + std::to_string(past) + ", tokens=" + std::to_string(count));
+ ov::Tensor ids(ov::element::i64, {1, count});
+ ov::Tensor positions(ov::element::i64, {1, count});
+ ov::Tensor mask(ov::element::i64, {1, past + count});
+ ov::Tensor beam(ov::element::i32, {1});
+ *beam.data<int32_t>() = 0;
+ for (size_t i = 0; i < count; ++i) {
+ ids.data<int64_t>()[i] = tokens[i];
+ positions.data<int64_t>()[i] = static_cast<int64_t>(past + i);
+ }
+ std::fill_n(mask.data<int64_t>(), mask.get_size(), 1);
+ request.set_tensor("input_ids", ids);
+ request.set_tensor("position_ids", positions);
+ request.set_tensor("attention_mask", mask);
+ if (std::any_of(compiled.inputs().begin(), compiled.inputs().end(), [](const ov::Output<const ov::Node>& p) {
+ return p.get_names().count("beam_idx");
+ }))
+ request.set_tensor("beam_idx", beam);
+ request.infer();
+ const auto result = request.get_output_tensor();
+ ASSERT_EQ(result.get_element_type(), ov::element::f32);
+ 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;
+ double error = 0, norm = 0;
+ for (int32_t i = 0; i < vocab; ++i) {
+ ASSERT_TRUE(std::isfinite(actual[i]));
+ const double difference = actual[i] - expected[i];
+ error += difference * difference;
+ norm += expected[i] * expected[i];
+ }
+ ASSERT_GT(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 / norm));
+ if (override_dir) {
+ // Real quantized checkpoints use lossy weight conversions. Check the first prediction
+ // and continuation agreement; keep their full-logit metrics in the XML report.
+ if (step == 1) {
+ EXPECT_EQ(predicted, wanted);
+ }
+ } else {
+ EXPECT_LT(error / norm, 1e-5) << "Normalized MSE against llama.cpp CPU";
+ }
+ past += count;
+ }
+ if (override_dir) {
+ EXPECT_GE(matching_tokens * 10, schedule.size() * 9) << "Fewer than 90% of greedy choices match";
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(Architectures,
+ GGUFArchitectureAccuracy,
+ ::testing::Values("llama",
+ "qwen2",
+ "qwen3",
+ "phi3",
+ "minicpm",
+ "olmoe",
+ "hunyuan-dense",
+ "hunyuan-moe",
+ "qwen3moe",
+ "gemma",
+ "gemma2",
+ "exaone4",
+ "ernie4_5-moe",
+ "bailingmoe2",
+ "maincoder",
+ "mistral3",
+ "smollm3",
+ "mellum",
+ "muse-glimmer",
+ "deepseek2-ocr",
+ "devstral-small",
+ "devstral-small2",
+ "devstral2"),
+ [](const ::testing::TestParamInfo<const char*>& info) {
+ std::string name = info.param;
+ std::replace(name.begin(), name.end(), '-', '_');
+ return name;
+ });
+} // namespace
diff --git a/src/frontends/gguf/tests/test_arch_conversion.cpp b/src/frontends/gguf/tests/test_arch_conversion.cpp
index 2ce0f29f5db..704450e4c7a 100644
--- a/src/frontends/gguf/tests/test_arch_conversion.cpp
+++ b/src/frontends/gguf/tests/test_arch_conversion.cpp
@@ -180,17 +180,17 @@ struct Fingerprint {
const std::map<std::string, Fingerprint>& fingerprints() {
static const std::map<std::string, Fingerprint> fp{
- {"bailingmoe2-moe.gguf.hdr", {473, 10}}, {"ernie4_5-moe-moe.gguf.hdr", {447, 10}},
- {"exaone4-dense.gguf.hdr", {418, 11}}, {"gemma-dense.gguf.hdr", {365, 10}},
+ {"bailingmoe2-moe.gguf.hdr", {473, 10}}, {"ernie4_5-moe-moe.gguf.hdr", {455, 10}},
+ {"exaone4-dense.gguf.hdr", {417, 11}}, {"gemma-dense.gguf.hdr", {365, 10}},
{"gemma2-dense.gguf.hdr", {415, 11}}, {"glm4moe-moe.gguf.hdr", {485, 10}},
{"gpt-oss-moe.gguf.hdr", {574, 11}}, {"hunyuan-dense-dense.gguf.hdr", {416, 10}},
- {"hunyuan-moe-moe.gguf.hdr", {534, 10}}, {"llama-dense.gguf.hdr", {400, 10}},
+ {"hunyuan-moe-moe.gguf.hdr", {554, 10}}, {"llama-dense.gguf.hdr", {400, 10}},
{"llama-moe.gguf.hdr", {506, 10}}, {"maincoder-dense.gguf.hdr", {432, 10}},
{"minicpm-dense.gguf.hdr", {398, 10}}, {"minicpm-moe.gguf.hdr", {504, 10}},
{"minimax-m2-moe.gguf.hdr", {534, 10}}, {"mistral3-dense.gguf.hdr", {400, 10}},
{"mistral3-moe.gguf.hdr", {506, 10}}, {"olmoe-moe.gguf.hdr", {534, 10}},
{"phi3-dense.gguf.hdr", {380, 10}}, {"qwen2-dense.gguf.hdr", {368, 10}},
- {"qwen3-dense.gguf.hdr", {416, 10}}, {"qwen3moe-moe.gguf.hdr", {550, 10}},
+ {"qwen3-dense.gguf.hdr", {416, 10}}, {"qwen3moe-moe.gguf.hdr", {546, 10}},
{"qwen35-dense.gguf.hdr", {395, 10}}, {"smollm3-dense.gguf.hdr", {384, 10}},
};
return fp;
diff --git a/src/frontends/gguf/tests/test_architecture_extension.cpp b/src/frontends/gguf/tests/test_architecture_extension.cpp
new file mode 100644
index 00000000000..324e0291c4d
--- /dev/null
+++ b/src/frontends/gguf/tests/test_architecture_extension.cpp
@@ -0,0 +1,549 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+// Runtime registration, shared decoder blocks, and non-decoder architecture construction.
+
+#include <algorithm>
+#include <cmath>
+#include <cstdint>
+#include <filesystem>
+#include <map>
+#include <memory>
+#include <numeric>
+#include <string>
+#include <vector>
+
+#include "common_test_utils/common_utils.hpp"
+#include "common_test_utils/file_utils.hpp"
+#include "common_test_utils/test_assertions.hpp"
+#include "gguf_writer.hpp"
+#include "gtest/gtest.h"
+#include "openvino/frontend/extension/conversion.hpp"
+#include "openvino/frontend/extension/decoder_transformation.hpp"
+#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/frontend.hpp"
+#include "openvino/frontend/gguf/make_stateful.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/openvino.hpp"
+#include "openvino/util/file_util.hpp"
+
+using namespace ov_gguf_test;
+using ov::frontend::gguf::ArchitectureDefinition;
+using ov::frontend::gguf::ArchitectureExtension;
+using ov::frontend::gguf::BuildContext;
+using ov::frontend::gguf::DecoderOptions;
+using ov::frontend::gguf::GgufGraph;
+using ov::frontend::gguf::GgufGraphContext;
+using ov::frontend::gguf::GgufMetadata;
+using ov::frontend::gguf::make_decoder_architecture;
+using ov::frontend::gguf::ModelBuilder;
+using ov::frontend::gguf::RegistrationMode;
+using ov::frontend::gguf::RopeMode;
+
+namespace {
+
+// Remove the generated files even when a test fails.
+class ScratchDir {
+public:
+ ScratchDir() : m_path(ov::test::utils::generateTestFilePrefix() + "_gguf_arch_ext") {
+ ov::util::create_directory_recursive(std::filesystem::path(m_path));
+ }
+ ~ScratchDir() {
+ std::error_code ec;
+ std::filesystem::remove_all(std::filesystem::path(m_path), ec);
+ }
+ const std::string& path() const {
+ return m_path;
+ }
+
+private:
+ std::string m_path;
+};
+
+// Small nonzero fixture shared by registration, structure, and stateful numerical tests.
+std::string write_decoder_gguf(const std::string& dir, const std::string& arch = "qwen3", uint32_t layers = 2) {
+ const auto path = ov::util::path_join({dir, arch + ".gguf"}).string();
+ GgufWriter writer;
+ writer.kv_str("general.architecture", arch);
+ writer.kv_u32(arch + ".block_count", layers);
+ writer.kv_u32(arch + ".embedding_length", 8);
+ writer.kv_u32(arch + ".attention.head_count", 2);
+ writer.kv_u32(arch + ".attention.head_count_kv", 1);
+ writer.kv_u32(arch + ".rope.dimension_count", 4);
+ writer.kv_u32(arch + ".context_length", 32);
+ writer.kv_f32(arch + ".attention.layer_norm_rms_epsilon", 1e-5f);
+ writer.kv_f32(arch + ".rope.scaling.factor", 4.f);
+ 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);
+ };
+ weight("token_embd.weight", {8, 16});
+ weight("output_norm.weight", {8}, true);
+ for (uint32_t layer = 0; layer < layers; ++layer) {
+ const auto prefix = "blk." + std::to_string(layer) + ".";
+ weight(prefix + "attn_norm.weight", {8}, true);
+ weight(prefix + "attn_q.weight", {8, 8});
+ weight(prefix + "attn_k.weight", {8, 4});
+ weight(prefix + "attn_v.weight", {8, 4});
+ weight(prefix + "attn_output.weight", {8, 8});
+ weight(prefix + "attn_q_norm.weight", {4}, true);
+ weight(prefix + "attn_k_norm.weight", {4}, true);
+ weight(prefix + "ffn_norm.weight", {8}, true);
+ weight(prefix + "ffn_gate.weight", {8, 12});
+ weight(prefix + "ffn_up.weight", {8, 12});
+ weight(prefix + "ffn_down.weight", {12, 8});
+ }
+ return writer.write(path) ? path : std::string{};
+}
+
+constexpr const char* kUnknownArch = "my-qwen3";
+
+std::shared_ptr<ov::Model> convert_with(const std::string& path,
+ const std::vector<ov::Extension::Ptr>& extensions = {}) {
+ ov::frontend::gguf::FrontEnd frontend;
+ for (const auto& extension : extensions)
+ frontend.add_extension(extension);
+ return frontend.convert(frontend.load(path));
+}
+
+std::map<std::string, size_t> op_histogram(const std::shared_ptr<ov::Model>& model) {
+ std::map<std::string, size_t> hist;
+ for (const auto& node : model->get_ops()) {
+ ++hist[node->get_type_info().name];
+ }
+ return hist;
+}
+
+} // namespace
+
+TEST(GGUFArchitectureExtension, UnknownArchitectureIsRejectedWithoutAnExtension) {
+ ScratchDir scratch;
+ const auto path = write_decoder_gguf(scratch.path(), kUnknownArch);
+ ASSERT_FALSE(path.empty());
+
+ OV_EXPECT_THROW(convert_with(path),
+ ov::Exception,
+ testing::AllOf(testing::HasSubstr("does not support architecture"),
+ testing::HasSubstr("ArchitectureExtension")));
+}
+
+TEST(GGUFArchitectureExtension, DecoderDefinitionMatchesBuiltInGraph) {
+ ScratchDir scratch;
+
+ const auto ref_path = write_decoder_gguf(scratch.path());
+ ASSERT_FALSE(ref_path.empty());
+ const auto reference = convert_with(ref_path, {});
+ ASSERT_TRUE(reference);
+ const auto expected_hist = op_histogram(reference);
+
+ // Enable the identical topology under an unrecognized architecture name.
+ ScratchDir scratch2;
+ const auto path = write_decoder_gguf(scratch2.path(), kUnknownArch);
+ ASSERT_FALSE(path.empty());
+ const auto ext = std::make_shared<ArchitectureExtension>(kUnknownArch, RopeMode::Neox);
+
+ const auto model = convert_with(path, {ext});
+ ASSERT_TRUE(model);
+
+ EXPECT_EQ(model->get_ops().size(), reference->get_ops().size());
+ EXPECT_EQ(model->inputs().size(), reference->inputs().size());
+ EXPECT_EQ(op_histogram(model), expected_hist)
+ << "an architecture enabled by extension must build the same graph as the built-in path";
+}
+
+TEST(GGUFArchitectureExtension, DecoderRopeModeReachesTheBuilder) {
+ ScratchDir scratch;
+ const auto path = write_decoder_gguf(scratch.path(), kUnknownArch);
+ ASSERT_FALSE(path.empty());
+
+ const auto neox = convert_with(path, {std::make_shared<ArchitectureExtension>(kUnknownArch, RopeMode::Neox)});
+ ASSERT_TRUE(neox);
+
+ const auto normal = convert_with(path, {std::make_shared<ArchitectureExtension>(kUnknownArch, RopeMode::Normal)});
+ ASSERT_TRUE(normal);
+
+ // NORMAL and NEOX lower to different rotation subgraphs, so the two graphs must differ.
+ EXPECT_NE(op_histogram(neox), op_histogram(normal))
+ << "the registered RoPE mode did not affect the graph, so it is not reaching the builder";
+}
+
+TEST(GGUFArchitectureExtension, DecoderOptionsSelectTheActivation) {
+ ScratchDir scratch;
+ const auto path = write_decoder_gguf(scratch.path(), kUnknownArch);
+ ASSERT_FALSE(path.empty());
+
+ const auto plain = convert_with(path, {std::make_shared<ArchitectureExtension>(kUnknownArch, RopeMode::Neox)});
+ ASSERT_TRUE(plain);
+
+ // SwiGLU and GeGLU use the same tensor layout; the option must select the activation.
+ auto hooked_ext = std::make_shared<ArchitectureExtension>(
+ make_decoder_architecture(kUnknownArch, RopeMode::Neox, [](const GgufMetadata&) {
+ DecoderOptions options;
+ options.geglu = true;
+ return options;
+ }));
+ const auto hooked = convert_with(path, {hooked_ext});
+ ASSERT_TRUE(hooked);
+
+ EXPECT_NE(op_histogram(plain), op_histogram(hooked)) << "decoder options did not change the activation";
+}
+
+namespace {
+
+// Custom topology reuses the very same decoder blocks as the built-in family.
+class Qwen3Builder : public ModelBuilder {
+public:
+ explicit Qwen3Builder(const BuildContext& ctx) : m_ctx(ctx) {}
+ std::shared_ptr<GgufGraph> build() override {
+ GgufGraphContext ctx(m_ctx);
+ const auto dimensions = ctx.configure_decoder(RopeMode::Neox);
+ auto tensors = ctx.tensors();
+ auto cur = ctx.build_inp_embd(tensors.require("token_embd.weight"));
+ ctx.build_inp_pos();
+ ctx.build_attn_inp_kv();
+ for (int layer = 0; layer < dimensions.layers; ++layer) {
+ auto norm = ctx.build_norm(cur, tensors.layer(layer, "attn_norm.weight"), dimensions.norm_epsilon);
+ cur = ctx.node("GGML_OP_ADD", {ctx.decoder_attention(layer, norm), cur});
+ norm = ctx.build_norm(cur, tensors.layer(layer, "ffn_norm.weight"), dimensions.norm_epsilon);
+ cur = ctx.node("GGML_OP_ADD", {ctx.decoder_ffn(layer, norm), cur});
+ }
+ cur = ctx.build_norm(cur, tensors.require("output_norm.weight"), dimensions.norm_epsilon);
+ auto output = tensors("output.weight");
+ if (!output)
+ output = tensors.require("token_embd.weight");
+ ctx.set_output(ctx.node("GGML_OP_MUL_MAT", {output, cur}));
+ return ctx.finish();
+ }
+
+private:
+ BuildContext m_ctx;
+};
+
+constexpr uint32_t kVisEmbd = 32;
+constexpr uint32_t kVisLayers = 2;
+constexpr uint32_t kVisHeads = 4;
+constexpr uint32_t kVisPatches = 16;
+constexpr uint32_t kVisFF = 64;
+constexpr uint32_t kVisProjDim = 48;
+
+// Vision and audio files share architecture "clip"; metadata distinguishes them.
+std::string write_vision_gguf(const std::string& dir) {
+ GgufWriter w;
+ w.kv_str("general.architecture", "clip");
+ w.kv_bool("clip.has_vision_encoder", true);
+ w.kv_u32("clip.vision.embedding_length", kVisEmbd);
+ w.kv_u32("clip.vision.block_count", kVisLayers);
+ w.kv_u32("clip.vision.attention.head_count", kVisHeads);
+ w.kv_u32("clip.vision.feed_forward_length", kVisFF);
+ w.kv_u32("clip.vision.projection_dim", kVisProjDim);
+ w.kv_f32("clip.vision.attention.layer_norm_epsilon", 1e-5f);
+
+ // Dims are in GGUF on-disk order (fastest-varying first).
+ w.tensor("v.position_embd.weight", {kVisEmbd, kVisPatches});
+ for (uint32_t il = 0; il < kVisLayers; ++il) {
+ const std::string p = "v.blk." + std::to_string(il) + ".";
+ w.tensor(p + "ln1.weight", {kVisEmbd});
+ w.tensor(p + "attn_q.weight", {kVisEmbd, kVisEmbd});
+ w.tensor(p + "attn_k.weight", {kVisEmbd, kVisEmbd});
+ w.tensor(p + "attn_v.weight", {kVisEmbd, kVisEmbd});
+ w.tensor(p + "attn_out.weight", {kVisEmbd, kVisEmbd});
+ w.tensor(p + "ln2.weight", {kVisEmbd});
+ w.tensor(p + "ffn_up.weight", {kVisEmbd, kVisFF});
+ w.tensor(p + "ffn_down.weight", {kVisFF, kVisEmbd});
+ }
+ w.tensor("v.post_ln.weight", {kVisEmbd});
+ w.tensor("mm.0.weight", {kVisEmbd, kVisProjDim});
+
+ const std::string path = ov::util::path_join({dir, "mmproj-vision.gguf"}).string();
+ return w.write(path) ? path : std::string{};
+}
+
+// Patch embeddings -> non-causal transformer blocks -> projector. No decoder configuration or KV cache.
+class VisionEncoderBuilder : public ModelBuilder {
+public:
+ explicit VisionEncoderBuilder(const BuildContext& ctx) : m_ctx(ctx) {}
+
+ std::shared_ptr<GgufGraph> build() override {
+ GgufGraphContext ctx(m_ctx);
+ const auto& meta = ctx.metadata();
+ auto tensors = ctx.tensors();
+
+ const int64_t n_embd = meta.get_int("clip.vision.embedding_length").value_or(0);
+ const int n_layer = static_cast<int>(meta.get_int("clip.vision.block_count").value_or(0));
+ const int64_t n_head = meta.get_int("clip.vision.attention.head_count").value_or(0);
+ const float eps = static_cast<float>(meta.get_float("clip.vision.attention.layer_norm_epsilon").value_or(1e-5));
+ const int64_t n_patches = kVisPatches;
+ const int64_t head_size = n_embd / n_head;
+
+ // One embedding per image patch.
+ auto cur = ctx.add_input("inp_patches", ov::element::f32, ov::PartialShape({1, 1, n_patches, n_embd}));
+ cur = ctx.node("GGML_OP_ADD", {cur, tensors.require("v.position_embd.weight")});
+
+ for (int il = 0; il < n_layer; ++il) {
+ const std::string p = "v.blk." + std::to_string(il) + ".";
+ auto residual = cur;
+
+ cur = ctx.build_norm(cur, tensors.require(p + "ln1.weight"), eps);
+
+ // Non-causal attention: softmax(Q @ K^T / sqrt(head_size)) @ V.
+ auto q = ctx.node("GGML_OP_MUL_MAT", {tensors.require(p + "attn_q.weight"), cur});
+ auto k = ctx.node("GGML_OP_MUL_MAT", {tensors.require(p + "attn_k.weight"), cur});
+ auto v = ctx.node("GGML_OP_MUL_MAT", {tensors.require(p + "attn_v.weight"), cur});
+
+ for (auto* value : {&q, &k, &v}) {
+ *value = ctx.node("GGML_OP_RESHAPE",
+ {*value},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{1, n_patches, n_head, head_size}}});
+ }
+ // Q/K contract over head_size; V contracts over patches.
+ q = ctx.node("GGML_OP_PERMUTE", {q}, 1, {{"perm", std::vector<int64_t>{0, 2, 1, 3}}});
+ k = ctx.node("GGML_OP_PERMUTE", {k}, 1, {{"perm", std::vector<int64_t>{0, 2, 1, 3}}});
+ v = ctx.node("GGML_OP_PERMUTE", {v}, 1, {{"perm", std::vector<int64_t>{0, 2, 3, 1}}});
+
+ auto kq = ctx.node("GGML_OP_MUL_MAT", {k, q});
+ kq = ctx.node("GGML_OP_SCALE",
+ {kq},
+ 0,
+ {{"scale", 1.0f / std::sqrt(static_cast<float>(head_size))}, {"bias", 0.0f}});
+ kq = ctx.node("GGML_OP_SOFT_MAX", {kq});
+ auto kqv = ctx.node("GGML_OP_MUL_MAT", {v, kq});
+
+ cur = ctx.node("GGML_OP_PERMUTE", {kqv}, 1, {{"perm", std::vector<int64_t>{0, 2, 1, 3}}});
+ cur = ctx.node("GGML_OP_RESHAPE",
+ {ctx.node("GGML_OP_CONT", {cur}, 1)},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{1, 1, n_patches, n_embd}}});
+ cur = ctx.node("GGML_OP_MUL_MAT", {tensors.require(p + "attn_out.weight"), cur});
+ cur = ctx.node("GGML_OP_ADD", {cur, residual});
+
+ residual = cur;
+ cur = ctx.build_norm(cur, tensors.require(p + "ln2.weight"), eps);
+ cur = ctx.node("GGML_OP_MUL_MAT", {tensors.require(p + "ffn_up.weight"), cur});
+ cur = ctx.node("GGML_UNARY_OP_GELU", {cur});
+ cur = ctx.node("GGML_OP_MUL_MAT", {tensors.require(p + "ffn_down.weight"), cur});
+ cur = ctx.node("GGML_OP_ADD", {cur, residual});
+ }
+
+ cur = ctx.build_norm(cur, tensors.require("v.post_ln.weight"), eps);
+ cur = ctx.node("GGML_OP_MUL_MAT", {tensors.require("mm.0.weight"), cur});
+ ctx.set_output(cur);
+ return ctx.finish();
+ }
+
+private:
+ BuildContext m_ctx;
+};
+
+} // namespace
+
+TEST(GGUFArchitectureExtension, NonDecoderFileIsRejectedWithoutAnExtension) {
+ ScratchDir scratch;
+ const auto path = write_vision_gguf(scratch.path());
+ ASSERT_FALSE(path.empty());
+
+ OV_EXPECT_THROW(convert_with(path),
+ ov::Exception,
+ testing::AllOf(testing::HasSubstr("decoder family"), testing::HasSubstr("ArchitectureExtension")));
+}
+
+TEST(GGUFArchitectureExtension, NonDecoderFamilyConvertsEndToEnd) {
+ ScratchDir scratch;
+ const auto path = write_vision_gguf(scratch.path());
+ ASSERT_FALSE(path.empty());
+
+ // Match both architecture "clip" and its vision flag.
+ auto ext = std::make_shared<ArchitectureExtension>(
+ ArchitectureDefinition{"clip.vision",
+ "clip",
+ [](const BuildContext& c) {
+ return std::make_shared<VisionEncoderBuilder>(c);
+ },
+ [](const GgufMetadata& m) {
+ return m.get_bool("clip.has_vision_encoder").value_or(false);
+ }});
+
+ const auto model = convert_with(path, {ext});
+ ASSERT_TRUE(model);
+
+ EXPECT_EQ(model->inputs().size(), 1u) << "a vision encoder takes patches and nothing else -- "
+ << "no tokens, no positions, no KV caches";
+ EXPECT_EQ(model->inputs()[0].get_any_name(), "inp_patches");
+ EXPECT_EQ(model->outputs().size(), 1u) << "no KV caches means no cache outputs";
+
+ auto hist = op_histogram(model);
+ EXPECT_EQ(hist["Softmax"], kVisLayers) << "one non-causal attention softmax per encoder block";
+ EXPECT_GT(hist["MatMul"], 0u);
+ EXPECT_EQ(hist["Parameter"], 1u);
+}
+
+TEST(GGUFArchitectureExtension, AmbiguousClaimIsReportedNotGuessed) {
+ ScratchDir scratch;
+ const auto path = write_vision_gguf(scratch.path());
+ ASSERT_FALSE(path.empty());
+
+ const auto claim_everything = [](const GgufMetadata&) {
+ return true;
+ };
+ const auto factory = [](const BuildContext& c) {
+ return std::make_shared<VisionEncoderBuilder>(c);
+ };
+ auto first = std::make_shared<ArchitectureExtension>(
+ ArchitectureDefinition{"first-claimant", "clip", factory, claim_everything});
+ auto second = std::make_shared<ArchitectureExtension>(
+ ArchitectureDefinition{"second-claimant", "clip", factory, claim_everything});
+
+ OV_EXPECT_THROW(convert_with(path, {first, second}),
+ ov::Exception,
+ testing::AllOf(testing::HasSubstr("first-claimant"), testing::HasSubstr("second-claimant")));
+}
+
+TEST(GGUFArchitectureExtension, SharedDecoderBlocksMatchNumericallyAcrossPrefillAndDecode) {
+ ScratchDir scratch;
+ const auto path = write_decoder_gguf(scratch.path(), "qwen3");
+ ASSERT_FALSE(path.empty());
+ const auto load = [&](bool custom) {
+ ov::frontend::gguf::FrontEnd frontend;
+ if (custom) {
+ frontend.add_extension(std::make_shared<ArchitectureExtension>(
+ ArchitectureDefinition{"qwen3",
+ "qwen3",
+ [](const BuildContext& ctx) {
+ return std::make_shared<Qwen3Builder>(ctx);
+ }},
+ 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()));
+ return frontend.convert(frontend.load(path));
+ };
+ auto builtin = load(false);
+ auto custom = load(true);
+ ASSERT_EQ(builtin->get_variables().size(), 4);
+ ASSERT_EQ(custom->get_variables().size(), 4);
+ ov::Core core;
+ const auto request = [&](const std::shared_ptr<ov::Model>& model) {
+ return 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))
+ .create_infer_request();
+ };
+ auto reference = request(builtin);
+ auto extension = request(custom);
+ size_t past = 0;
+ for (size_t tokens : {3u, 1u, 2u}) {
+ ov::Tensor ids(ov::element::i64, {1, tokens});
+ ov::Tensor pos(ov::element::i64, {1, tokens});
+ for (size_t i = 0; i < tokens; ++i) {
+ ids.data<int64_t>()[i] = static_cast<int64_t>((past + i + 1) % 16);
+ pos.data<int64_t>()[i] = static_cast<int64_t>(past + i);
+ }
+ ov::Tensor mask(ov::element::i64, {1, past + tokens});
+ std::fill_n(mask.data<int64_t>(), mask.get_size(), 1);
+ ov::Tensor beam(ov::element::i32, {1});
+ *beam.data<int32_t>() = 0;
+ for (auto* infer : {&reference, &extension}) {
+ infer->set_tensor("input_ids", ids);
+ infer->set_tensor("position_ids", pos);
+ infer->set_tensor("attention_mask", mask);
+ infer->set_tensor("beam_idx", beam);
+ infer->infer();
+ const auto states = infer->query_state();
+ ASSERT_EQ(states.size(), 4);
+ for (const auto& state : states)
+ EXPECT_EQ(state.get_state().get_size(), (past + tokens) * 4);
+ }
+ auto a = reference.get_output_tensor();
+ auto b = extension.get_output_tensor();
+ ASSERT_GE(a.get_size(), 16);
+ ASSERT_GE(b.get_size(), 16);
+ const auto* last_a = a.data<float>() + a.get_size() - 16;
+ const auto* last_b = b.data<float>() + b.get_size() - 16;
+ for (size_t i = 0; i < 16; ++i) {
+ ASSERT_TRUE(std::isfinite(last_a[i]));
+ EXPECT_NEAR(last_a[i], last_b[i], 1e-5f);
+ }
+ past += tokens;
+ }
+}
+
+namespace {
+class CustomOpBuilder : public ModelBuilder {
+public:
+ explicit CustomOpBuilder(const BuildContext& context) : m_context(context) {}
+
+ std::shared_ptr<GgufGraph> build() override {
+ GgufGraphContext graph(m_context);
+ auto input = graph.add_input("features", ov::element::f32, {1, 1, -1, 4});
+ auto expanded = graph.node("TEST_EXPAND_FEATURES", {input});
+ // The following operation can query the converter's inferred width immediately.
+ graph.set_output(graph.node("GGML_OP_RESHAPE",
+ {expanded},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{1, 1, -1, expanded.ne(0)}}}));
+ return graph.finish();
+ }
+
+private:
+ BuildContext m_context;
+};
+} // namespace
+
+TEST(GGUFArchitectureExtension, ConverterRegisteredAfterLoadInfersBuilderValues) {
+ ScratchDir scratch;
+ const auto path = write_decoder_gguf(scratch.path(), kUnknownArch);
+ ASSERT_FALSE(path.empty());
+ ov::frontend::gguf::FrontEnd frontend;
+ frontend.add_extension(std::make_shared<ArchitectureExtension>(
+ ArchitectureDefinition{kUnknownArch, kUnknownArch, [](const BuildContext& context) {
+ return std::make_shared<CustomOpBuilder>(context);
+ }}));
+ auto input_model = frontend.load(path);
+ size_t calls = 0;
+ const auto register_converter = [&](size_t copies) {
+ frontend.add_extension(std::make_shared<ov::frontend::ConversionExtension>(
+ "TEST_EXPAND_FEATURES",
+ [&, copies](const ov::frontend::NodeContext& context) {
+ ++calls;
+ return ov::OutputVector{
+ std::make_shared<ov::op::v0::Concat>(ov::OutputVector(copies, context.get_input(0)), 3)};
+ }));
+ };
+ register_converter(2);
+ auto first = frontend.convert(input_model);
+ EXPECT_EQ(calls, 1);
+ EXPECT_EQ(first->output().get_partial_shape(), (ov::PartialShape{1, 1, -1, 8}));
+ register_converter(3);
+ auto second = frontend.convert(input_model);
+ EXPECT_EQ(calls, 2);
+ EXPECT_EQ(second->output().get_partial_shape(), (ov::PartialShape{1, 1, -1, 12}));
+ EXPECT_EQ(first->output().get_partial_shape(), (ov::PartialShape{1, 1, -1, 8}));
+ for (size_t tokens : {1u, 3u}) {
+ ov::Tensor data(ov::element::f32, {1, 1, tokens, 4});
+ std::iota(data.data<float>(), data.data<float>() + data.get_size(), 0.f);
+ ov::TensorVector result{ov::Tensor(ov::element::f32, {1, 1, tokens, 12})};
+ ASSERT_TRUE(second->evaluate(result, {data}));
+ EXPECT_EQ(result[0].get_shape(), (ov::Shape{1, 1, tokens, 12}));
+ for (size_t t = 0; t < tokens; ++t) {
+ for (size_t i = 0; i < 12; ++i) {
+ EXPECT_EQ(result[0].data<float>()[12 * t + i], data.data<float>()[4 * t + i % 4]);
+ }
+ }
+ }
+}
diff --git a/src/frontends/gguf/tests/test_architecture_library.cpp b/src/frontends/gguf/tests/test_architecture_library.cpp
new file mode 100644
index 00000000000..daba0e552c6
--- /dev/null
+++ b/src/frontends/gguf/tests/test_architecture_library.cpp
@@ -0,0 +1,56 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <filesystem>
+#include <numeric>
+
+#include "common_test_utils/file_utils.hpp"
+#include "gguf_writer.hpp"
+#include "gtest/gtest.h"
+#include "openvino/frontend/gguf/frontend.hpp"
+#include "projector.hpp"
+
+// Link the actual frontend library to exercise the builder API and module-loading boundary.
+TEST(GGUFArchitectureLibrary, ExternalModuleMatchesDirectRegistrationAcrossTokenCounts) {
+ const auto path =
+ std::filesystem::temp_directory_path() / (ov::test::utils::generateTestFilePrefix() + "_projector.gguf");
+ struct RemoveFile {
+ std::filesystem::path path;
+ ~RemoveFile() {
+ std::error_code error;
+ std::filesystem::remove(path, error);
+ }
+ } cleanup{path};
+ ov_gguf_test::GgufWriter writer;
+ writer.kv_str("general.architecture", "example-projector");
+ writer.tensor("projection.weight", {2, 3}, {1, 2, 3, 4, 5, 6});
+ ASSERT_TRUE(writer.write(path.string()));
+
+ std::shared_ptr<ov::Model> from_library;
+ {
+ ov::frontend::gguf::FrontEnd frontend;
+ const auto library = std::filesystem::path(ov::test::utils::getExecutableDirectory()) / ARCH_EXTENSION_LIBRARY;
+ static_cast<ov::frontend::FrontEnd&>(frontend).add_extension(library.string());
+ from_library = frontend.convert(frontend.load(path.string()));
+ }
+ ov::frontend::gguf::FrontEnd direct;
+ direct.add_extension(
+ std::make_shared<ov::frontend::gguf::ArchitectureExtension>(example::projector_architecture()));
+ auto from_definition = direct.convert(direct.load(path.string()));
+ for (size_t tokens : {1u, 3u, 7u}) {
+ ov::Tensor data(ov::element::f32, {1, 1, tokens, 2});
+ std::iota(data.data<float>(), data.data<float>() + data.get_size(), 1.0f);
+ ov::TensorVector a{ov::Tensor(ov::element::f32, {1, 1, tokens, 3})};
+ ov::TensorVector b{ov::Tensor(ov::element::f32, {1, 1, tokens, 3})};
+ ASSERT_TRUE(from_library->evaluate(a, {data}));
+ ASSERT_TRUE(from_definition->evaluate(b, {data}));
+ for (size_t t = 0; t < tokens; ++t) {
+ for (size_t channel = 0; channel < 3; ++channel) {
+ const auto expected = float((2 * t + 1) * (2 * channel + 1) + (2 * t + 2) * (2 * channel + 2));
+ EXPECT_FLOAT_EQ(a[0].data<float>()[t * 3 + channel], expected);
+ EXPECT_FLOAT_EQ(b[0].data<float>()[t * 3 + channel], expected);
+ }
+ }
+ }
+}
diff --git a/src/frontends/gguf/tests/test_builder_api.cpp b/src/frontends/gguf/tests/test_builder_api.cpp
new file mode 100644
index 00000000000..86686726c48
--- /dev/null
+++ b/src/frontends/gguf/tests/test_builder_api.cpp
@@ -0,0 +1,736 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <cmath>
+#include <limits>
+#include <numeric>
+
+#include "builder/api/metadata_store.hpp"
+#include "builder/arch_registry.hpp"
+#include "builder/decoder_config.hpp"
+#include "builder/gguf_builder_decoder.hpp"
+#include "builder/gguf_graph.hpp"
+#include "gtest/gtest.h"
+#include "openvino/core/type/float16.hpp"
+#include "openvino/frontend/gguf/builder/graph_context.hpp"
+#include "openvino/frontend/gguf/frontend.hpp"
+#include "openvino/frontend/gguf/make_stateful.hpp"
+#include "openvino/op/assign.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/pass/manager.hpp"
+#include "projector.hpp"
+
+using namespace ov::frontend::gguf;
+
+namespace {
+struct Environment {
+ std::unordered_map<std::string, GGUFMetaData> metadata;
+ std::unordered_map<std::string, ov::Tensor> weights;
+ std::unordered_map<std::string, GgufTensorType> qtypes;
+ detail::MetadataStore store{metadata};
+ detail::WeightStore tensors{weights, qtypes};
+ BuildContext context{GgufMetadata(store), "test", &tensors};
+
+ Environment() {
+ metadata["general.architecture"] = std::string("test");
+ }
+ void integer(const std::string& key, uint32_t value) {
+ ov::Tensor t(ov::element::u32, {});
+ *t.data<uint32_t>() = value;
+ metadata[key] = t;
+ }
+ void real(const std::string& key, float value) {
+ ov::Tensor t(ov::element::f32, {});
+ *t.data<float>() = value;
+ metadata[key] = t;
+ }
+ void architecture(const std::string& name) {
+ std::unordered_map<std::string, GGUFMetaData> renamed;
+ for (const auto& entry : metadata)
+ renamed[entry.first.rfind("test.", 0) == 0 ? name + entry.first.substr(4) : entry.first] = entry.second;
+ metadata = std::move(renamed);
+ metadata["general.architecture"] = name;
+ }
+
+ void decoder() {
+ integer("test.block_count", 2);
+ integer("test.embedding_length", 32);
+ integer("test.attention.head_count", 4);
+ real("test.attention.layer_norm_rms_epsilon", 1e-5f);
+ }
+};
+
+std::shared_ptr<ov::Model> convert(const std::shared_ptr<GgufGraph>& graph) {
+ FrontEnd frontend;
+ std::shared_ptr<GgufDecoder> decoder = std::make_shared<GgufBuilderDecoder>(graph);
+ return frontend.convert(frontend.load(decoder));
+}
+
+ArchitectureDefinition handler(const std::string& id, ArchitectureDefinition::MatchFn match = {}) {
+ return {id,
+ "test",
+ [](const BuildContext&) -> std::shared_ptr<ModelBuilder> {
+ return {};
+ },
+ std::move(match)};
+}
+} // namespace
+
+TEST(GGUFBuilderAPI, MetadataReadsReuseNumericConversionAcrossWidths) {
+ Environment env;
+ const auto& metadata = env.context.metadata;
+ const auto store = [&](const std::string& key, const ov::op::v0::Constant& value) {
+ ov::TensorVector output;
+ ASSERT_TRUE(value.evaluate(output, {}));
+ env.metadata[key] = output.front();
+ };
+ for (auto type : {ov::element::boolean,
+ ov::element::i8,
+ ov::element::u8,
+ ov::element::i16,
+ ov::element::u16,
+ ov::element::i32,
+ ov::element::u32,
+ ov::element::i64,
+ ov::element::u64,
+ ov::element::f32,
+ ov::element::f64}) {
+ SCOPED_TRACE(type.get_type_name());
+ store("scalar", ov::op::v0::Constant(type, {}, 1));
+ store("array", ov::op::v0::Constant(type, {3}, 1));
+ EXPECT_EQ(metadata.get_float("scalar"), 1.0);
+ EXPECT_EQ(metadata.get_float_array("array"), (std::vector<double>{1, 1, 1}));
+ EXPECT_FALSE(metadata.get_float("array"));
+ if (type.is_real()) {
+ EXPECT_FALSE(metadata.get_int("scalar"));
+ EXPECT_TRUE(metadata.get_int_array("array").empty());
+ } else {
+ EXPECT_EQ(metadata.get_int("scalar"), 1);
+ EXPECT_EQ(metadata.get_bool("scalar"), true);
+ EXPECT_EQ(metadata.get_int_array("array"), (std::vector<int64_t>{1, 1, 1}));
+ }
+ }
+ store("signed", ov::op::v0::Constant(ov::element::i64, {}, -7));
+ EXPECT_EQ(metadata.get_int("signed"), -7);
+ store("unsigned", ov::op::v0::Constant(ov::element::u64, {}, uint64_t{1} << 63));
+ EXPECT_EQ(metadata.get_float("unsigned"), double(uint64_t{1} << 63));
+}
+
+TEST(GGUFBuilderAPI, MetadataMissingAndIncompatibleValuesRemainOptional) {
+ Environment env;
+ const auto& metadata = env.context.metadata;
+ env.metadata["string"] = std::string("value");
+ env.metadata["strings"] = std::vector<std::string>{"a", "b"};
+ env.metadata["integers"] = std::vector<int32_t>{-2, 3};
+ env.metadata["integer"] = 7;
+ env.metadata["float"] = 0.5f;
+ for (const auto* key : {"missing", "string", "strings"}) {
+ EXPECT_FALSE(metadata.get_int(key));
+ EXPECT_FALSE(metadata.get_float(key));
+ EXPECT_FALSE(metadata.get_bool(key));
+ EXPECT_TRUE(metadata.get_int_array(key).empty());
+ EXPECT_TRUE(metadata.get_float_array(key).empty());
+ }
+ EXPECT_FALSE(metadata.has("missing"));
+ EXPECT_TRUE(metadata.has("string"));
+ EXPECT_EQ(metadata.get_str("string"), "value");
+ EXPECT_EQ(metadata.get_str("missing").value_or("fallback"), "fallback");
+ EXPECT_EQ(metadata.get_str_array("strings"), (std::vector<std::string>{"a", "b"}));
+ EXPECT_EQ(metadata.get_int_array("integers"), (std::vector<int64_t>{-2, 3}));
+ EXPECT_EQ(metadata.get_int("integer"), 7);
+ EXPECT_EQ(metadata.get_float("float"), 0.5);
+ for (float value : {0.5f, std::numeric_limits<float>::infinity(), std::numeric_limits<float>::quiet_NaN()}) {
+ env.metadata["float"] = value;
+ EXPECT_FALSE(metadata.get_int("float"));
+ EXPECT_FALSE(metadata.get_bool("float"));
+ }
+}
+
+TEST(GGUFBuilderAPI, RejectsValuesFromAnotherGraphWithMatchingNames) {
+ Environment env;
+ GgufGraphContext graph(env.context), other(env.context);
+ auto local = graph.add_input("state", ov::element::f32, {1, 1, 1, 4});
+ auto foreign = other.add_input("state", ov::element::f32, {1, 1, 1, 4});
+ EXPECT_THROW(graph.node("GGML_OP_ADD", {local, foreign}), ov::Exception);
+ EXPECT_THROW(graph.build_norm(foreign, {}, 1e-5f), ov::Exception);
+ EXPECT_THROW(graph.build_norm(local, foreign, 1e-5f), ov::Exception);
+ EXPECT_THROW(graph.set_output(foreign), ov::Exception);
+ EXPECT_THROW(graph.add_recurrent_state(local, foreign), ov::Exception);
+ EXPECT_THROW(graph.add_recurrent_state(foreign, local), ov::Exception);
+ graph.set_output(local);
+ EXPECT_NO_THROW(convert(graph.finish()));
+}
+
+TEST(GGUFBuilderAPI, GeneratedNamesDoNotOverwriteInputs) {
+ Environment env;
+ GgufGraphContext graph(env.context);
+ auto input = graph.add_input("GGML_OP_SCALE_0", ov::element::f32, {1, 1, 1, 4});
+ auto output = graph.node("GGML_OP_SCALE", {input}, 0, {{"scale", 2.f}});
+ EXPECT_NE(output.name(), input.name());
+ EXPECT_THROW(graph.add_input(output.name(), ov::element::f32, input.shape()), ov::Exception);
+ graph.set_output(input);
+ graph.set_output(output);
+ auto model = convert(graph.finish());
+ auto data = ov::op::v0::Constant::create(ov::element::f32, {1, 1, 1, 4}, {1, 2, 3, 4});
+ ov::TensorVector inputs;
+ ov::TensorVector outputs{ov::Tensor(ov::element::f32, {1, 1, 1, 4}), ov::Tensor(ov::element::f32, {1, 1, 1, 4})};
+ ASSERT_TRUE(data->evaluate(inputs, {}));
+ ASSERT_TRUE(model->evaluate(outputs, inputs));
+ for (size_t i = 0; i < 4; ++i) {
+ EXPECT_EQ(outputs[0].data<float>()[i], float(i + 1));
+ EXPECT_EQ(outputs[1].data<float>()[i], float(2 * (i + 1)));
+ }
+}
+
+TEST(GGUFBuilderAPI, NormalizationPreservesInputNamesAndAcceptsGraphValues) {
+ Environment env;
+ GgufGraphContext graph(env.context);
+ auto input = graph.add_input("norm_0.rms", ov::element::f32, {1, 1, 1, 4});
+ auto output = graph.build_norm(input, input, 0.f);
+ graph.set_output(input);
+ graph.set_output(output);
+ auto model = convert(graph.finish());
+ auto data = ov::op::v0::Constant::create(ov::element::f32, {1, 1, 1, 4}, {1, 2, 3, 4});
+ ov::TensorVector inputs;
+ ov::TensorVector outputs{ov::Tensor(ov::element::f32, {1, 1, 1, 4}), ov::Tensor(ov::element::f32, {1, 1, 1, 4})};
+ ASSERT_TRUE(data->evaluate(inputs, {}));
+ ASSERT_TRUE(model->evaluate(outputs, inputs));
+ for (size_t i = 0; i < 4; ++i) {
+ EXPECT_EQ(outputs[0].data<float>()[i], float(i + 1));
+ EXPECT_NEAR(outputs[1].data<float>()[i], float((i + 1) * (i + 1)) / std::sqrt(7.5f), 1e-6f);
+ }
+}
+
+TEST(GGUFBuilderAPI, LogicalWeightDimensionsPreserveVectorsAndExpertAxes) {
+ GgufValue empty;
+ EXPECT_TRUE(empty.shape().rank().is_dynamic());
+ EXPECT_EQ(empty.type(), ov::element::dynamic);
+ EXPECT_EQ(empty.ne(0), -1);
+ Environment env;
+ env.weights["norm.weight"] = ov::Tensor(ov::element::f32, {32});
+ env.weights["experts.weight"] = ov::Tensor(ov::element::f32, {2, 3, 4});
+ GgufGraphContext graph(env.context);
+ auto vector = graph.tensors().require("norm.weight");
+ EXPECT_EQ(vector.ne(0), 32);
+ EXPECT_EQ(vector.ne(1), 1);
+ auto experts = graph.tensors().require("experts.weight");
+ EXPECT_EQ(experts.ne(0), 4);
+ EXPECT_EQ(experts.ne(1), 3);
+ EXPECT_EQ(experts.ne(2), 2);
+ EXPECT_THROW(graph.node("GGML_OP_ADD", {empty, vector}), ov::Exception);
+}
+
+TEST(GGUFBuilderAPI, GeneralReshapeDoesNotCopyTheAttentionBatchAxis) {
+ Environment env;
+ GgufGraphContext graph(env.context);
+ auto input = graph.add_input("x", ov::element::f32, {2, 3, 4, 5});
+ graph.set_output(
+ graph.node("GGML_OP_RESHAPE", {input}, 6, {{"reshape_target", std::vector<int64_t>{1, 4, 3, 10}}}));
+ auto model = convert(graph.finish());
+ EXPECT_EQ(model->output().get_shape(), (ov::Shape{1, 4, 3, 10}));
+ ov::Tensor data(ov::element::f32, {2, 3, 4, 5});
+ std::iota(data.data<float>(), data.data<float>() + data.get_size(), 0.0f);
+ ov::TensorVector output{ov::Tensor(ov::element::f32, {1, 4, 3, 10})};
+ ASSERT_TRUE(model->evaluate(output, {data}));
+ for (size_t i = 0; i < data.get_size(); ++i)
+ EXPECT_EQ(output[0].data<float>()[i], float(i));
+}
+
+TEST(GGUFBuilderAPI, ExplicitInferredReshapeRemainsDynamicAcrossTokenCounts) {
+ Environment env;
+ GgufGraphContext graph(env.context);
+ auto input = graph.add_input("x", ov::element::f32, {1, 1, -1, 8});
+ graph.set_output(
+ graph.node("GGML_OP_RESHAPE", {input}, 6, {{"reshape_target", std::vector<int64_t>{1, -1, 2, 4}}}));
+ auto model = convert(graph.finish());
+ for (size_t tokens : {1u, 3u, 7u}) {
+ ov::Tensor data(ov::element::f32, {1, 1, tokens, 8});
+ std::iota(data.data<float>(), data.data<float>() + data.get_size(), 1.0f);
+ ov::TensorVector output{ov::Tensor(ov::element::f32, {1, tokens, 2, 4})};
+ ASSERT_TRUE(model->evaluate(output, {data}));
+ EXPECT_EQ(output[0].get_shape(), (ov::Shape{1, tokens, 2, 4}));
+ for (size_t i = 0; i < data.get_size(); ++i)
+ EXPECT_EQ(output[0].data<float>()[i], float(i + 1));
+ }
+}
+
+TEST(GGUFBuilderAPI, DecoderOptionsAreResolvedBeforeRopePlans) {
+ Environment env;
+ env.decoder();
+ env.real("test.rope.scaling.factor", 4.0f);
+ DecoderOptions options;
+ options.sliding_window = 16;
+ options.swa_rope_frequency_base = 2000.f;
+ options.swa_rope_dimensions = 4;
+ GgufGraphContext graph(env.context);
+ auto dimensions = graph.configure_decoder(RopeMode::Neox, options);
+ EXPECT_EQ(dimensions.embedding, 32);
+ const auto layer = graph.decoder_layer_parameters(0);
+ EXPECT_EQ(layer.kv_heads, 4);
+ EXPECT_EQ(layer.rope.n_dims, 4);
+ EXPECT_FLOAT_EQ(layer.rope.freq_base, 2000.f);
+ auto input = graph.add_input("x", ov::element::f32, {1, 1, 1, 32});
+ graph.set_output(input);
+ auto built = graph.finish();
+ EXPECT_FLOAT_EQ(built->rope_config.freq_scale, 0.25f);
+ EXPECT_TRUE(built->use_per_op_rope);
+ EXPECT_EQ(built->swa_window_size, 16);
+ DecoderOptions invalid;
+ invalid.swa_rope_dimensions = 33;
+ GgufGraphContext other(env.context);
+ EXPECT_THROW(other.configure_decoder(RopeMode::Neox, invalid), ov::Exception);
+}
+
+TEST(GGUFBuilderAPI, RecurrentStateDeclarationReachesMakeStateful) {
+ Environment env;
+ GgufGraphContext graph(env.context);
+ auto state = graph.add_input("state", ov::element::f32, {1, 1, 1, 4});
+ auto input = graph.add_input("x", ov::element::f32, {1, 1, 1, 4});
+ auto update = graph.node("GGML_OP_ADD", {state, input});
+ graph.add_recurrent_state(state, update);
+ graph.set_output(graph.node("GGML_OP_SCALE", {update}, 0, {{"scale", float{2}}, {"bias", 0.0f}}));
+ auto model = convert(graph.finish());
+ ASSERT_TRUE(model->get_rt_info().count(pass::gguf_recurrent_states_key()));
+ ov::pass::Manager passes;
+ passes.register_pass<pass::GGUFMakeStateful>();
+ passes.run_passes(model);
+ EXPECT_EQ(model->inputs().size(), 1);
+ EXPECT_EQ(model->outputs().size(), 1);
+ EXPECT_EQ(model->get_sinks().size(), 1);
+}
+
+TEST(GGUFBuilderAPI, SlidingWindowDeclarationSurvivesConversion) {
+ Environment env;
+ GgufGraphContext graph(env.context);
+ graph.set_sliding_window(32);
+ graph.set_output(graph.add_input("x", ov::element::f32, {1, 1, 1, 4}));
+ auto model = convert(graph.finish());
+ EXPECT_EQ(model->get_rt_info().at(pass::gguf_swa_window_key()).as<int64_t>(), 32);
+ EXPECT_THROW(graph.set_sliding_window(64), ov::Exception);
+ EXPECT_THROW(graph.finish(), ov::Exception);
+}
+
+TEST(GGUFArchitectureRegistry, DisjointHandlersForTheSameArchitectureCoexist) {
+ Environment env;
+ env.integer("modality", 1);
+ ArchRegistry registry({handler("vision",
+ [](const GgufMetadata& m) {
+ return m.get_int("modality") == 1;
+ }),
+ handler("audio", [](const GgufMetadata& m) {
+ return m.get_int("modality") == 2;
+ })});
+ ASSERT_TRUE(registry.find(env.context.metadata));
+ EXPECT_EQ(registry.find(env.context.metadata)->id, "vision");
+ env.integer("modality", 2);
+ EXPECT_EQ(registry.find(env.context.metadata)->id, "audio");
+ env.metadata["general.architecture"] = std::string("unrelated");
+ EXPECT_FALSE(registry.find(env.context.metadata));
+}
+
+TEST(GGUFArchitectureRegistry, ReplacementIsExplicitAndInstancesAreIsolated) {
+ Environment env;
+ ArchRegistry first({handler("test")});
+ ArchRegistry second({handler("test")});
+ EXPECT_THROW(first.add(handler("test")), ov::Exception);
+ auto replacement = handler("test");
+ replacement.maturity = Maturity::Verified;
+ 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_THROW(first.add(handler("missing"), RegistrationMode::Replace), ov::Exception);
+ auto invalid = handler("invalid");
+ invalid.factory = {};
+ EXPECT_THROW(first.add(invalid), ov::Exception);
+}
+
+// Promotion changes only where the definition is registered, including its custom builder.
+TEST(GGUFArchitectureRegistry, PromotedDefinitionUsesTheSameBuilderAndDispatch) {
+ Environment env;
+ env.metadata["general.architecture"] = std::string("example-projector");
+ env.context.arch = "example-projector";
+ env.weights["projection.weight"] = ov::Tensor(ov::element::f32, {3, 2});
+ const auto definition = example::projector_architecture();
+ ArchRegistry native({definition});
+ ArchRegistry external(std::vector<ArchitectureDefinition>{});
+ external.add_extension(std::make_shared<ArchitectureExtension>(definition));
+ auto first = native.find(env.context.metadata)->factory(env.context)->build();
+ auto second = external.find(env.context.metadata)->factory(env.context)->build();
+ ASSERT_EQ(first->nodes.size(), second->nodes.size());
+ EXPECT_EQ(first->model_output_names, second->model_output_names);
+ for (size_t i = 0; i < first->nodes.size(); ++i) {
+ EXPECT_EQ(first->nodes[i].op_type, second->nodes[i].op_type);
+ EXPECT_EQ(first->values->at(first->nodes[i].output_name).get_partial_shape(),
+ second->values->at(second->nodes[i].output_name).get_partial_shape());
+ }
+}
+
+TEST(GGUFBuilderAPI, SingleHeadSplitPreservesDynamicTokens) {
+ Environment env;
+ GgufGraphContext graph(env.context);
+ auto input = graph.add_input("x", ov::element::f32, {1, 1, -1, 8});
+ auto heads = graph.node("GGML_OP_RESHAPE",
+ {input},
+ 6,
+ {{"reshape_target", std::vector<int64_t>{0, -1, 1, 8}}, {"special_zero", true}});
+ graph.set_output(heads);
+ graph.set_output(graph.node("GGML_OP_RESHAPE", {heads}, 2, {{"merge_heads", true}}));
+ auto model = convert(graph.finish());
+ ov::Tensor data(ov::element::f32, {1, 1, 3, 8});
+ std::iota(data.data<float>(), data.data<float>() + data.get_size(), 1.0f);
+ ov::TensorVector results{ov::Tensor(ov::element::f32, {1, 3, 1, 8}), ov::Tensor(ov::element::f32, {1, 1, 3, 8})};
+ ASSERT_TRUE(model->evaluate(results, {data}));
+ EXPECT_EQ(results[0].get_shape(), (ov::Shape{1, 3, 1, 8}));
+ EXPECT_EQ(results[1].get_shape(), data.get_shape());
+}
+
+TEST(GGUFBuilderAPI, Gemma2DefaultsIncludeSlidingWindowAnd27BAttentionScale) {
+ Environment env;
+ env.decoder();
+ env.integer("test.block_count", 46);
+ env.integer("test.embedding_length", 4608);
+ env.integer("test.attention.head_count", 32);
+ env.integer("test.attention.key_length", 128);
+ env.architecture("gemma2");
+ DecoderConfig config(decoder_config_from_meta(env.metadata), env.weights);
+ EXPECT_EQ(config.swa_window_size, 4096);
+ EXPECT_TRUE(config.layer_is_swa(0));
+ EXPECT_FALSE(config.layer_is_swa(1));
+ EXPECT_FLOAT_EQ(config.layer_kq_scale(0), 1.f / 12.f);
+}
+
+TEST(GGUFBuilderAPI, Gemma2RejectsZeroAttentionHeadsWithOrWithoutKeyLength) {
+ for (bool explicit_key_length : {false, true}) {
+ SCOPED_TRACE(explicit_key_length);
+ Environment env;
+ env.decoder();
+ env.integer("test.block_count", 46);
+ env.integer("test.attention.head_count", 0);
+ if (explicit_key_length) {
+ env.integer("test.attention.key_length", 128);
+ }
+ env.architecture("gemma2");
+ EXPECT_THROW(decoder_config_from_meta(env.metadata), ov::Exception);
+ }
+}
+
+TEST(GGUFBuilderAPI, ErnieInterleavesDenseAndExpertLayers) {
+ Environment env;
+ env.decoder();
+ env.integer("test.block_count", 4);
+ env.integer("test.interleave_moe_layer_step", 2);
+ env.integer("test.expert_count", 4);
+ env.integer("test.expert_used_count", 2);
+ for (int layer = 0; layer < 4; ++layer) {
+ const auto prefix = "blk." + std::to_string(layer) + ".";
+ if (layer % 2 == 0) {
+ env.weights[prefix + "ffn_gate.weight"] = ov::Tensor(ov::element::f32, {48, 32});
+ env.weights[prefix + "ffn_up.weight"] = ov::Tensor(ov::element::f32, {48, 32});
+ env.weights[prefix + "ffn_down.weight"] = ov::Tensor(ov::element::f32, {32, 48});
+ } else {
+ env.weights[prefix + "ffn_gate_inp.weight"] = ov::Tensor(ov::element::f32, {4, 32});
+ env.weights[prefix + "ffn_gate_exps.weight"] = ov::Tensor(ov::element::f32, {4, 48, 32});
+ env.weights[prefix + "ffn_up_exps.weight"] = ov::Tensor(ov::element::f32, {4, 48, 32});
+ env.weights[prefix + "ffn_down_exps.weight"] = ov::Tensor(ov::element::f32, {4, 32, 48});
+ }
+ }
+ env.architecture("ernie4_5-moe");
+ for (uint32_t dense_lead : {0u, 1u}) {
+ SCOPED_TRACE(dense_lead);
+ env.integer("ernie4_5-moe.leading_dense_block_count", dense_lead);
+ DecoderConfig config(decoder_config_from_meta(env.metadata), env.weights);
+ EXPECT_FALSE(config.layer_is_moe(0));
+ EXPECT_TRUE(config.layer_is_moe(1));
+ EXPECT_FALSE(config.layer_is_moe(2));
+ EXPECT_TRUE(config.layer_is_moe(3));
+ EXPECT_TRUE(config.expert_weights_norm);
+ GgufGraphContext graph(env.context);
+ graph.configure_decoder(RopeMode::Neox);
+ auto value = graph.add_input("x", ov::element::f32, {1, 1, -1, 32});
+ for (int layer = 0; layer < 4; ++layer) {
+ value = graph.decoder_ffn(layer, value);
+ }
+ graph.set_output(value);
+ auto model = convert(graph.finish());
+ EXPECT_EQ(model->output().get_partial_shape(), (ov::PartialShape{1, 1, -1, 32}));
+ }
+}
+
+TEST(GGUFBuilderAPI, Exaone64LayerDefaultsIncludeLocalRopeAndSlidingWindow) {
+ Environment env;
+ env.decoder();
+ env.integer("test.block_count", 64);
+ env.architecture("exaone4");
+ DecoderConfig config(decoder_config_from_meta(env.metadata), env.weights);
+ EXPECT_TRUE(config.post_norm_only);
+ EXPECT_TRUE(config.rope_on_swa_only);
+ EXPECT_EQ(config.swa_window_size, 4096);
+ EXPECT_TRUE(config.layer_is_swa(0));
+ EXPECT_TRUE(config.layer_is_swa(2));
+ EXPECT_FALSE(config.layer_is_swa(3));
+ EXPECT_TRUE(config.layer_is_swa(4));
+}
+
+TEST(GGUFBuilderAPI, ArchitectureOptionsOverrideAmbiguousTensorSemantics) {
+ Environment env;
+ env.decoder();
+ DecoderOptions options;
+ options.qk_norm_after_rope = true;
+ options.post_norm_only = true;
+ options.normalize_expert_weights = true;
+ options.rope_skip_period = 4;
+ DecoderConfig config(decoder_config_from_meta(env.metadata), env.weights, RopeMode::Neox, options);
+ EXPECT_TRUE(config.qk_norm_after_rope);
+ EXPECT_TRUE(config.post_norm_only);
+ EXPECT_TRUE(config.expert_weights_norm);
+ EXPECT_EQ(config.rope_skip_period, 4);
+ options.rope_skip_period = -1;
+ EXPECT_THROW(DecoderConfig(decoder_config_from_meta(env.metadata), env.weights, RopeMode::Neox, options),
+ ov::Exception);
+}
+
+TEST(GGUFBuilderAPI, DevstralReadsYarnAndAttentionTemperatureMetadata) {
+ Environment env;
+ env.decoder();
+ env.metadata["test.rope.scaling.type"] = std::string("yarn");
+ env.real("test.rope.scaling.factor", 48.0f);
+ env.real("test.rope.scaling.yarn_beta_fast", 4.0f);
+ env.real("test.rope.scaling.yarn_beta_slow", 1.0f);
+ env.real("test.rope.scaling.yarn_log_multiplier", 1.0f);
+ env.integer("test.rope.scaling.original_context_length", 8192);
+ env.real("test.attention.temperature_scale", 0.1f);
+ env.architecture("mistral3");
+ DecoderConfig config(decoder_config_from_meta(env.metadata), env.weights);
+ EXPECT_FLOAT_EQ(config.rope_config.beta_fast, 4.0f);
+ EXPECT_FLOAT_EQ(config.rope_config.beta_slow, 1.0f);
+ EXPECT_FLOAT_EQ(config.rope_config.attn_factor, 1.0f / (1.0f + 0.1f * std::log(48.0f)));
+ EXPECT_FLOAT_EQ(config.attention_temperature_scale, 0.1f);
+ env.integer("mistral3.rope.scaling.original_context_length", 0);
+ EXPECT_THROW(DecoderConfig(decoder_config_from_meta(env.metadata), env.weights), ov::Exception);
+}
+
+TEST(GGUFBuilderAPI, BroadcastAndConcatShapesComeFromOpenVINO) {
+ Environment env;
+ GgufGraphContext graph(env.context);
+ auto a = graph.add_input("a", ov::element::f32, {2, 1, -1, 4});
+ auto b = graph.add_input("b", ov::element::f32, {1, 3, 1, 4});
+ auto sum = graph.node("GGML_OP_ADD", {a, b});
+ EXPECT_EQ(sum.shape(), (ov::PartialShape{2, 3, -1, 4}));
+ auto joined = graph.node("GGML_OP_CONCAT", {sum, sum}, 0, {{"concat_axis", 0}});
+ EXPECT_EQ(joined.shape(), (ov::PartialShape{2, 3, -1, 8}));
+ auto output = graph.node("GGML_OP_TRANSPOSE", {joined});
+ EXPECT_EQ(output.shape(), (ov::PartialShape{2, 3, 8, -1}));
+ graph.set_output(output);
+ auto model = convert(graph.finish());
+ for (size_t tokens : {1u, 3u}) {
+ ov::Tensor input_a(ov::element::f32, {2, 1, tokens, 4});
+ ov::Tensor input_b(ov::element::f32, {1, 3, 1, 4});
+ std::fill_n(input_a.data<float>(), input_a.get_size(), 2.f);
+ std::fill_n(input_b.data<float>(), input_b.get_size(), 3.f);
+ ov::TensorVector results{ov::Tensor(ov::element::f32, {2, 3, 8, tokens})};
+ ASSERT_TRUE(model->evaluate(results, {input_a, input_b}));
+ EXPECT_EQ(results[0].get_shape(), (ov::Shape{2, 3, 8, tokens}));
+ for (size_t i = 0; i < results[0].get_size(); ++i) {
+ EXPECT_EQ(results[0].data<float>()[i], 5.f);
+ }
+ }
+}
+
+TEST(GGUFBuilderAPI, GenericNodesNeedOnlySemanticAttributes) {
+ Environment env;
+ GgufGraphContext graph(env.context);
+ auto input = graph.add_input("x", ov::element::f32, {1, 1, -1, 5});
+ auto selected = graph.node("GGML_OP_TOP_K", {input}, 0, {{"k", int64_t{2}}});
+ EXPECT_EQ(selected.shape(), (ov::PartialShape{1, 1, -1, 2}));
+ EXPECT_EQ(selected.type(), ov::element::i32);
+ auto repeated = graph.node("GGML_OP_REPEAT", {selected}, 0, {{"repeats", std::vector<int64_t>{1, 2, 1, 3}}});
+ EXPECT_EQ(repeated.shape(), (ov::PartialShape{1, 2, -1, 6}));
+ graph.set_output(repeated);
+ auto model = convert(graph.finish());
+ EXPECT_EQ(model->output().get_partial_shape(), repeated.shape());
+}
+
+TEST(GGUFBuilderAPI, MergeHeadsAcceptsRuntimeTokenAndHeadDimensions) {
+ Environment env;
+ GgufGraphContext graph(env.context);
+ auto input = graph.add_input("x", ov::element::f32, {2, -1, 3, -1});
+ auto merged = graph.node("GGML_OP_RESHAPE", {input}, 2, {{"merge_heads", true}});
+ EXPECT_EQ(merged.shape(), (ov::PartialShape{2, 1, -1, -1}));
+ graph.set_output(merged);
+ auto model = convert(graph.finish());
+ for (const ov::Shape& shape : {ov::Shape{2, 1, 3, 4}, ov::Shape{2, 5, 3, 2}}) {
+ ov::Tensor input_data(ov::element::f32, shape);
+ std::iota(input_data.data<float>(), input_data.data<float>() + input_data.get_size(), 0.f);
+ ov::TensorVector result{ov::Tensor(ov::element::f32, {2, 1, shape[1], 3 * shape[3]})};
+ ASSERT_TRUE(model->evaluate(result, {input_data}));
+ EXPECT_EQ(result[0].get_shape(), (ov::Shape{2, 1, shape[1], 3 * shape[3]}));
+ for (size_t i = 0; i < input_data.get_size(); ++i) {
+ EXPECT_EQ(result[0].data<float>()[i], input_data.data<float>()[i]);
+ }
+ }
+}
+
+TEST(GGUFBuilderAPI, GenericNodesValidateAttributesThroughConverters) {
+ for (const auto& invalid : std::vector<std::pair<std::string, std::map<std::string, ov::Any>>>{
+ {"GGML_OP_RESHAPE", {{"reshape_target", std::vector<int64_t>{1, -1, -1, 4}}}},
+ {"GGML_OP_PERMUTE", {{"perm", std::vector<int64_t>{0, 1, 1, 3}}}},
+ {"GGML_OP_CONCAT", {{"concat_axis", 4}}}}) {
+ SCOPED_TRACE(invalid.first);
+ Environment env;
+ GgufGraphContext graph(env.context);
+ auto input = graph.add_input("x", ov::element::f32, {1, 1, 2, 4});
+ const auto inputs =
+ invalid.first == "GGML_OP_CONCAT" ? std::vector<GgufValue>{input, input} : std::vector<GgufValue>{input};
+ const int op_case = invalid.first == "GGML_OP_PERMUTE" ? 1 : 0;
+ EXPECT_THROW(graph.node(invalid.first, inputs, op_case, invalid.second), ov::Exception);
+ }
+}
+
+TEST(GGUFBuilderAPI, GenericRopeNodesPreserveModelPositionContract) {
+ for (bool multimodal : {false, true}) {
+ for (bool per_op : {false, true}) {
+ SCOPED_TRACE(testing::Message() << "multimodal=" << multimodal << ", per_op=" << per_op);
+ Environment env;
+ GgufGraphContext graph(env.context);
+ RopeConfig config;
+ config.n_dims = 4;
+ config.n_ctx_orig = 128;
+ config.freq_base = 10000.f;
+ config.freq_scale = config.attn_factor = 1.f;
+ config.beta_fast = 32.f;
+ config.beta_slow = 1.f;
+ config.per_op = per_op;
+ config.is_imrope = multimodal;
+ graph.configure_rope(config);
+ auto input = graph.add_input("x", ov::element::f32, {1, -1, 2, 4});
+ auto positions = graph.build_inp_pos();
+ auto rotated =
+ graph.node("GGML_OP_ROPE", {input, positions}, (multimodal ? 2 : 1) << 16, {{"rope_config", config}});
+ EXPECT_EQ(rotated.shape(), input.shape());
+ graph.set_output(rotated);
+ auto built = graph.finish();
+ EXPECT_EQ(built->values->count("rope_cos"), per_op ? 0u : 1u);
+ auto model = convert(built);
+ EXPECT_EQ(model->get_rt_info().count(pass::gguf_imrope_key()), multimodal ? 1u : 0u);
+ EXPECT_EQ(model->inputs().size(), 2u);
+ EXPECT_EQ(model->output().get_partial_shape(), input.shape());
+ }
+ }
+}
+
+TEST(GGUFBuilderAPI, MatmulProducesF32FromF16Operands) {
+ Environment env;
+ GgufGraphContext graph(env.context);
+ auto weights = graph.add_input("w", ov::element::f16, {1, 1, 2, 2});
+ auto input = graph.add_input("x", ov::element::f16, {1, 1, -1, 2});
+ auto product = graph.node("GGML_OP_MUL_MAT", {weights, input});
+ EXPECT_EQ(product.type(), ov::element::f32);
+ graph.set_output(product);
+ auto model = convert(graph.finish());
+ ov::Tensor w(ov::element::f16, {1, 1, 2, 2});
+ const std::vector<ov::float16> values{256.f, 256.f, 1.f, -1.f};
+ std::copy(values.begin(), values.end(), w.data<ov::float16>());
+ for (size_t tokens : {1u, 3u}) {
+ ov::Tensor x(ov::element::f16, {1, 1, tokens, 2});
+ std::fill_n(x.data<ov::float16>(), x.get_size(), ov::float16(256.f));
+ ov::TensorVector result{ov::Tensor(ov::element::f32, {1, 1, tokens, 2})};
+ ASSERT_TRUE(model->evaluate(result, {w, x}));
+ for (size_t t = 0; t < tokens; ++t) {
+ // Converting an F16 MatMul result afterward would already have overflowed.
+ EXPECT_EQ(result[0].data<float>()[2 * t], 131072.f);
+ EXPECT_EQ(result[0].data<float>()[2 * t + 1], 0.f);
+ }
+ }
+}
+
+TEST(GGUFBuilderAPI, GetRowsDerivesFloatingAndIntegerResultTypes) {
+ for (auto type : {ov::element::f16, ov::element::i32}) {
+ SCOPED_TRACE(type);
+ Environment env;
+ GgufGraphContext graph(env.context);
+ auto data = graph.add_input("data", type, {1, 1, 3, 2});
+ auto indices = graph.add_input("indices", ov::element::i32, {1, 1, 1, 2});
+ auto rows = graph.node("GGML_OP_GET_ROWS", {data, indices});
+ const auto expected_type = type == ov::element::i32 ? ov::element::i32 : ov::element::f32;
+ EXPECT_EQ(rows.type(), expected_type);
+ graph.set_output(rows);
+ auto model = convert(graph.finish());
+ ov::Tensor input(type, {1, 1, 3, 2});
+ for (size_t i = 0; i < input.get_size(); ++i) {
+ if (type == ov::element::i32) {
+ input.data<int32_t>()[i] = static_cast<int32_t>(i);
+ } else {
+ input.data<ov::float16>()[i] = ov::float16(static_cast<float>(i));
+ }
+ }
+ ov::Tensor ids(ov::element::i32, {1, 1, 1, 2});
+ ids.data<int32_t>()[0] = 2;
+ ids.data<int32_t>()[1] = 0;
+ ov::TensorVector result{ov::Tensor(expected_type, {1, 1, 2, 2})};
+ ASSERT_TRUE(model->evaluate(result, {input, ids}));
+ const std::vector<int32_t> expected{4, 5, 0, 1};
+ for (size_t i = 0; i < expected.size(); ++i) {
+ if (type == ov::element::i32) {
+ EXPECT_EQ(result[0].data<int32_t>()[i], expected[i]);
+ } else {
+ EXPECT_EQ(result[0].data<float>()[i], expected[i]);
+ }
+ }
+ }
+}
+
+TEST(GGUFBuilderAPI, ElementwiseNodesPreserveF16) {
+ Environment env;
+ GgufGraphContext graph(env.context);
+ auto input = graph.add_input("x", ov::element::f16, {1, 1, 1, 4});
+ auto sum = graph.node("GGML_OP_ADD", {input, input});
+ auto ratio = graph.node("GGML_OP_DIV", {sum, input});
+ auto joined = graph.node("GGML_OP_CONCAT", {ratio, ratio}, 0, {{"concat_axis", 0}});
+ auto output = graph.node("GGML_OP_FILL", {joined}, 0, {{"fill_value", 3.f}});
+ for (const auto& value : {sum, ratio, joined, output}) {
+ EXPECT_EQ(value.type(), ov::element::f16);
+ }
+ graph.set_output(output);
+ auto model = convert(graph.finish());
+ EXPECT_EQ(model->output().get_element_type(), ov::element::f16);
+}
+
+TEST(GGUFBuilderAPI, CopyAndStateWritesUseDestinationType) {
+ Environment env;
+ GgufGraphContext graph(env.context);
+ auto destination = graph.add_input("dst", ov::element::f16, {1, 1, 1, 4});
+ auto indices = graph.add_input("ids", ov::element::i32, {1, 1, 1, 1});
+ auto source = graph.add_input("src", ov::element::f32, {1, 1, 1, 4});
+ auto copy = graph.node("GGML_OP_CPY", {source, destination});
+ auto set = graph.node("GGML_OP_SET", {destination, source}, 0, {{"set_offset_elems", int64_t{0}}});
+ auto rows = graph.node("GGML_OP_SET_ROWS", {source, indices, destination});
+ for (const auto& value : {copy, set, rows}) {
+ EXPECT_EQ(value.type(), ov::element::f16);
+ graph.set_output(value);
+ }
+ auto model = convert(graph.finish());
+ for (const auto& output : model->outputs()) {
+ EXPECT_EQ(output.get_element_type(), ov::element::f16);
+ }
+}
+
+TEST(GGUFBuilderAPI, CastAndIm2colRequireExplicitDestinationType) {
+ for (bool cast : {true, false}) {
+ Environment env;
+ GgufGraphContext graph(env.context);
+ auto input = graph.add_input("x", ov::element::f32, {1, 1, 1, 3});
+ const auto op = cast ? "GGML_OP_CPY" : "GGML_OP_IM2COL";
+ auto inputs = std::vector<GgufValue>{input};
+ std::map<std::string, ov::Any> attrs;
+ if (!cast) {
+ auto kernel = graph.add_input("kernel", ov::element::f32, {1, 1, 1, 2});
+ inputs = {kernel, input};
+ attrs["im2col_params"] = std::vector<int32_t>{1, 0, 0, 0, 1, 0, 0};
+ }
+ EXPECT_THROW(graph.node(op, inputs, 0, attrs), ov::Exception);
+ attrs["dst_type"] = ov::element::f16;
+ auto output = graph.node(op, inputs, 0, attrs);
+ EXPECT_EQ(output.type(), ov::element::f16);
+ }
+}
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/README.md b/src/frontends/gguf/tests/test_data/arch_accuracy/README.md
new file mode 100644
index 00000000000..fc951eb95cf
--- /dev/null
+++ b/src/frontends/gguf/tests/test_data/arch_accuracy/README.md
@@ -0,0 +1,49 @@
+# Native architecture accuracy references
+
+Each 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.
+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 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.
+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.
+
+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
+boundaries at positions 2 and 4 to exercise attention temperature; Devstral 2 uses non-default
+YaRN correction parameters. Each runs through the native frontend. Devstral 2's real
+123B checkpoint and full-context workloads are not verified by these small fixtures.
+
+`GGUFArchitectureAccuracy` compiles the native frontend graph on CPU with F32 inference,
+F16 KV state and dynamic activation quantization disabled. It checks every logit using
+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
+`GGML_OPENVINO=OFF`. Run from `src/frontends/gguf/tests`, with `LLAMA_SRC` and
+`LLAMA_BUILD` pointing to that checkout and its build directory:
+
+```sh
+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
+PYTHONPATH="$LLAMA_SRC/gguf-py" python3 gen_arch_accuracy.py \
+ --oracle ./architecture_oracle
+```
+
+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.
+This performs prefill plus twelve reference-token decode steps, requires the same first
+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.
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/bailingmoe2.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/bailingmoe2.npz
new file mode 100644
index 00000000000..a0f8984a0bd
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/bailingmoe2.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/deepseek2-ocr.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/deepseek2-ocr.npz
new file mode 100644
index 00000000000..9cb4e3f8b93
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/deepseek2-ocr.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/devstral-small.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/devstral-small.npz
new file mode 100644
index 00000000000..ff8d6ca394b
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/devstral-small.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/devstral-small2.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/devstral-small2.npz
new file mode 100644
index 00000000000..c61c02873ef
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/devstral-small2.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/devstral2.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/devstral2.npz
new file mode 100644
index 00000000000..529d8e7477f
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/devstral2.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/ernie4_5-moe.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/ernie4_5-moe.npz
new file mode 100644
index 00000000000..a9004ec28f8
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/ernie4_5-moe.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/exaone4.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/exaone4.npz
new file mode 100644
index 00000000000..44b3dbfa1d6
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/exaone4.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/gemma.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/gemma.npz
new file mode 100644
index 00000000000..fafeefb58e7
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/gemma.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/gemma2.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/gemma2.npz
new file mode 100644
index 00000000000..6ad69cc0e97
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/gemma2.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/hunyuan-dense.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/hunyuan-dense.npz
new file mode 100644
index 00000000000..a68c0f86e69
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/hunyuan-dense.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
new file mode 100644
index 00000000000..3c4f51b084e
Binary files /dev/null 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/llama.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/llama.npz
new file mode 100644
index 00000000000..cb6eed9b72a
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/llama.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/maincoder.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/maincoder.npz
new file mode 100644
index 00000000000..1bbf8fd8bb0
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/maincoder.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/mellum.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/mellum.npz
new file mode 100644
index 00000000000..4abe150170d
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/mellum.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/minicpm.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/minicpm.npz
new file mode 100644
index 00000000000..1f87fa3f178
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/minicpm.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/mistral3.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/mistral3.npz
new file mode 100644
index 00000000000..50ffc5f497e
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/mistral3.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/muse-glimmer.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/muse-glimmer.npz
new file mode 100644
index 00000000000..97654a66d40
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/muse-glimmer.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/olmoe.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/olmoe.npz
new file mode 100644
index 00000000000..31b860bea26
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/olmoe.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/phi3.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/phi3.npz
new file mode 100644
index 00000000000..d77d55c0621
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/phi3.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/qwen2.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen2.npz
new file mode 100644
index 00000000000..3cd1a24a76f
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen2.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3.npz
new file mode 100644
index 00000000000..ef94d1121af
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3moe.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3moe.npz
new file mode 100644
index 00000000000..5ed71e86a57
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/qwen3moe.npz differ
diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/smollm3.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/smollm3.npz
new file mode 100644
index 00000000000..1da8d4eb04a
Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/smollm3.npz differ
diff --git a/src/frontends/gguf/tests/test_ops.cpp b/src/frontends/gguf/tests/test_ops.cpp
index 66cb471aefd..ec66229ab49 100644
--- a/src/frontends/gguf/tests/test_ops.cpp
+++ b/src/frontends/gguf/tests/test_ops.cpp
@@ -496,21 +496,19 @@ TEST(GGUFOps, Norm) {
expect_near(out, expected, 1e-4f);
}
-// The index type comes from the decoder, not a hardcoded i32: an i64 TOP_K output must produce
-// an i64 tensor, otherwise the model signature and the actual tensor disagree.
-TEST(GGUFOps, TopKIndexTypeFollowsOutput) {
+TEST(GGUFOps, TopKIndexTypeComesFromOperation) {
auto model = SingleOpBuilder()
.op("GGML_OP_TOP_K")
.input("x", ov::element::f32, {1, 1, 2, 4})
- .output("out", ov::element::i64, {1, 1, 2, 2})
+ .output("out", ov::element::dynamic, {1, 1, 2, 2})
.build();
std::vector<float> x{4, 1, 3, 2, 10, 40, 20, 30};
auto out = run_on_cpu(model, {{"x", make_f32_tensor({1, 1, 2, 4}, x)}});
- ASSERT_EQ(out.get_element_type(), ov::element::i64);
- const int64_t* a = out.data<int64_t>();
- std::vector<int64_t> expected{0, 2, 1, 3};
+ ASSERT_EQ(out.get_element_type(), ov::element::i32);
+ const int32_t* a = out.data<int32_t>();
+ std::vector<int32_t> expected{0, 2, 1, 3};
for (size_t i = 0; i < expected.size(); ++i)
EXPECT_EQ(a[i], expected[i]) << "mismatch at index " << i;
}
@@ -627,7 +625,7 @@ TEST(GGUFOps, Argsort) {
auto model = SingleOpBuilder()
.op("GGML_OP_ARGSORT")
.input("x", ov::element::f32, {1, 1, 2, 4})
- .output("out", ov::element::i32, {1, 1, 2, 4})
+ .output("out", ov::element::dynamic, {1, 1, 2, 4})
.attr<int>("sort_order", 0) // ascending
.build();
@@ -807,6 +805,46 @@ TEST(GGUFOps, TopK) {
EXPECT_EQ(row1, (std::vector<int32_t>{0, 2, 4}));
}
+TEST(GGUFOps, TopKExplicitKInfersOutputShape) {
+ const std::vector<float> values{1, 9, 3, 7, 5, 50, 10, 40, 20, 30};
+ // Sorted index sets from ggml_top_k on llama.cpp CPU, revision 03fa73cb27.
+ const std::vector<std::vector<int32_t>> expected_one{{1}, {0}};
+ const std::vector<std::vector<int32_t>> expected_three{{1, 3, 4}, {0, 2, 4}};
+ for (int64_t k : {1, 3}) {
+ SCOPED_TRACE(k);
+ auto model = SingleOpBuilder()
+ .op("GGML_OP_TOP_K")
+ .input("x", ov::element::f32, {1, 1, -1, 5})
+ .output("out", ov::element::i32, ov::PartialShape::dynamic())
+ .attr<int64_t>("k", k)
+ .build();
+ EXPECT_EQ(model->output().get_partial_shape(), (ov::PartialShape{1, 1, -1, k}));
+ const auto& expected = k == 1 ? expected_one : expected_three;
+ for (size_t rows : {1u, 2u}) {
+ SCOPED_TRACE(rows);
+ const std::vector<float> data(values.begin(), values.begin() + rows * 5);
+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({1, 1, rows, 5}, data)}});
+ ASSERT_EQ(out.get_shape(), (ov::Shape{1, 1, rows, static_cast<size_t>(k)}));
+ const auto* indices = out.data<int32_t>();
+ for (size_t row = 0; row < rows; ++row) {
+ std::vector<int32_t> selected(indices + row * k, indices + (row + 1) * k);
+ std::sort(selected.begin(), selected.end());
+ EXPECT_EQ(selected, expected[row]);
+ }
+ }
+ }
+}
+
+TEST(GGUFOps, TopKRejectsUnknownK) {
+ for (const auto& shape : {ov::PartialShape::dynamic(), ov::PartialShape{1, 1, 2, -1}}) {
+ auto builder = SingleOpBuilder()
+ .op("GGML_OP_TOP_K")
+ .input("x", ov::element::f32, {1, 1, 2, 5})
+ .output("out", ov::element::i32, shape);
+ EXPECT_THROW(builder.build(), ov::Exception);
+ }
+}
+
// Repeat: tile src to fill the output shape (integer multiples per axis).
TEST(GGUFOps, Repeat) {
auto model = SingleOpBuilder()
@@ -1206,6 +1244,7 @@ TEST(GGUFOps, ReshapeCase1SplitHeadsIsLayoutPolymorphic) {
.op("GGML_OP_RESHAPE")
.input("x", ov::element::f32, {1, 1, tokens, heads * head_size})
.output("out", ov::element::f32, {1, tokens, heads, head_size})
+ .attr<std::vector<int64_t>>("reshape_target", {1, tokens, heads, head_size})
.op_case(1)
.build();
auto sdpa_out = run_on_cpu(sdpa, {{"x", make_f32_tensor({1, 1, (size_t)tokens, (size_t)(heads * head_size)}, x)}});
@@ -1217,6 +1256,7 @@ TEST(GGUFOps, ReshapeCase1SplitHeadsIsLayoutPolymorphic) {
.op("GGML_OP_RESHAPE")
.input("x", ov::element::f32, {tokens, 1, 1, heads * head_size})
.output("out", ov::element::f32, {1, tokens, heads, head_size})
+ .attr<std::vector<int64_t>>("reshape_target", {1, tokens, heads, head_size})
.op_case(1)
.build();
auto pa_out = run_on_cpu(pa, {{"x", make_f32_tensor({(size_t)tokens, 1, 1, (size_t)(heads * head_size)}, x)}});
@@ -1236,6 +1276,7 @@ TEST(GGUFOps, ReshapeCase2MergeHeadsIsLayoutPolymorphic) {
.op("GGML_OP_RESHAPE")
.input("x", ov::element::f32, {1, tokens, heads, head_size})
.output("out", ov::element::f32, {1, 1, tokens, heads * head_size})
+ .attr<std::vector<int64_t>>("reshape_target", {1, 1, tokens, heads * head_size})
.op_case(2)
.build();
auto sdpa_out =
@@ -1247,6 +1288,7 @@ TEST(GGUFOps, ReshapeCase2MergeHeadsIsLayoutPolymorphic) {
.op("GGML_OP_RESHAPE")
.input("x", ov::element::f32, {tokens, 1, heads, head_size})
.output("out", ov::element::f32, {1, 1, tokens, heads * head_size})
+ .attr<std::vector<int64_t>>("reshape_target", {1, 1, tokens, heads * head_size})
.op_case(2)
.build();
auto pa_out = run_on_cpu(pa, {{"x", make_f32_tensor({(size_t)tokens, 1, (size_t)heads, (size_t)head_size}, x)}});
@@ -1746,7 +1788,7 @@ TEST(GGUFOps, MulMat) {
.op("GGML_OP_MUL_MAT")
.input("b", ov::element::f32, {1, 1, 2, 3})
.input("a", ov::element::f32, {1, 1, 2, 3})
- .output("out", ov::element::f32, {1, 1, 2, 2})
+ .output("out", ov::element::dynamic, {1, 1, 2, 2})
.build();
std::vector<float> b{1, 2, 3, 4, 5, 6}; // rows n0=[1,2,3], n1=[4,5,6]
diff --git a/tests/model_hub_tests/gguf/gguf_models_nightly b/tests/model_hub_tests/gguf/gguf_models_nightly
index 2c565ef3567..01254a27d58 100644
--- a/tests/model_hub_tests/gguf/gguf_models_nightly
+++ b/tests/model_hub_tests/gguf/gguf_models_nightly
@@ -21,6 +21,8 @@ qwen35-bonsai,prism-ml/Ternary-Bonsai-27B-gguf,Ternary-Bonsai-27B-Q2_g64.gguf
ernie4_5-moe,bartowski/baidu_ERNIE-4.5-21B-A3B-PT-GGUF,baidu_ERNIE-4.5-21B-A3B-PT-Q4_K_M.gguf
bailingmoe2,bartowski/inclusionAI_Ling-mini-2.0-GGUF,inclusionAI_Ling-mini-2.0-Q4_K_M.gguf
mellum,bartowski/Mellum2-12B-A2.5B-Instruct-GGUF,Mellum2-12B-A2.5B-Instruct-Q4_K_M.gguf
+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)"