OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[GGUF] Enable Mamba 2 and dense Nemotron-H models (#38168)
Maxim Vafin6b5b70ae9919
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.hppindex 83a21df40ff..50ee5fc8b9c 100644--- a/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/graph_context.hpp+++ b/src/frontends/gguf/dev_api/openvino/frontend/gguf/builder/graph_context.hpp@@ -52,6 +52,7 @@ public:// 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);+ GgufValue add_constant(const std::string& name, const ov::Tensor& value);// Invoke a registered converter; its OpenVINO outputs supply shape/type inference.GgufValue node(const std::string& op_type,@@ -71,6 +72,8 @@ public:// Outputs and statevoid set_output(const GgufValue& logits);+ // Put the data output before auxiliary cache outputs registered by decoder blocks.+ void set_primary_output(const GgufValue& value);// Record the sliding window for normalization passes.void set_sliding_window(int64_t tokens);// Registers an overwritten state, automatically marking the update as a model output.diff --git a/src/frontends/gguf/docs/internal_ops.md b/src/frontends/gguf/docs/internal_ops.mdindex d3a0e82b533..4a8de472000 100644--- a/src/frontends/gguf/docs/internal_ops.md+++ b/src/frontends/gguf/docs/internal_ops.md@@ -58,6 +58,7 @@ serializable — see the example below.| Op | GGML op | Path | Fallback ||---|---|---|---|+| `ov::op::internal::SelectiveSSM` | `GGML_OP_SSM_SCAN` | `translate_ssm_scan` (Mamba 2 scalar decay) | No frontend decomposition || `ov::op::internal::GatedDeltaNet` | `GGML_OP_GATED_DELTA_NET` | `translate_gated_delta_net` (scalar gate) | `translate_gated_delta_net_ref` — a serializable `Loop` scan, used for per-key-dimension gating (`kda`) and as a portable fallback |See [`src/op/gated_delta_net.cpp`](../src/op/gated_delta_net.cpp).diff --git a/src/frontends/gguf/docs/porting_a_llama_cpp_model.md b/src/frontends/gguf/docs/porting_a_llama_cpp_model.mdindex 05d99881d9a..b54c4d18263 100644--- a/src/frontends/gguf/docs/porting_a_llama_cpp_model.md+++ b/src/frontends/gguf/docs/porting_a_llama_cpp_model.md@@ -435,8 +435,9 @@ Graph nodes alone do not describe how consumers should maintain state or form ma- `add_recurrent_state(input, update)` declares an overwritten state and marks the update as anoutput. `GGUFMakeStateful` consumes this relationship. Its existing batch/beam restrictions stillapply.-- `set_output(value)` declares other outputs. `finish()` validates references and outputs and seals- the context against further emission.+- `set_output(value)` appends an output. `set_primary_output(value)` puts the data output+ before auxiliary outputs already registered by decoder blocks (for example, logits before KV+ caches). `finish()` validates references and outputs and seals the context against further emission.These declarations are passed through the same `GgufGraph` and `TranslateSession` pipeline as thebuilt-in decoder. A consumer selects `GGUFMakeStateful` and `AdaptToGenAI` through transformationdiff --git a/src/frontends/gguf/docs/supported_models.md b/src/frontends/gguf/docs/supported_models.mdindex 7f2507a755c..75cd494e879 100644--- a/src/frontends/gguf/docs/supported_models.md+++ b/src/frontends/gguf/docs/supported_models.md@@ -54,7 +54,7 @@ The native architecture catalog is defined inWithout additional architecture registrations, names outside this catalog are rejected at loadtime. External definitions and custom-family catalog entries extend the same registry.-### Verified — 23 architectures+### Verified — 25 architectures| Architecture | Notes ||---|---|@@ -70,10 +70,12 @@ time. External definitions and custom-family catalog entries extend the same reg| `hunyuan-dense` | learned QK-norm after RoPE || `llama` | llama-2 / llama-3 || `maincoder` | NORMAL RoPE; learned QK-norm after RoPE |+| `mamba2` | Mamba 2 mixer, tied or separate output embeddings; stateful greedy decoding with one sequence || `mellum` | MoE with normalized expert weights || `minicpm` | NORMAL RoPE; embedding/residual scales and inverse logit scale || `mistral3` | dense decoder, NORMAL RoPE || `muse-glimmer` | RoPE on SWA layers, attention output gate, pre/post norms |+| `nemotron_h` | dense hybrid Mamba 2 / attention / ReLU-squared FFN; stateful greedy decoding with one sequence || `olmoe` | full-width QK-norm and MoE || `phi3` | fused QKV || `qwen2` | qwen2 / qwen2.5 |@@ -96,8 +98,8 @@ time. External definitions and custom-family catalog entries extend the same reg### Numerical regression coverage-[`GGUFArchitectureAccuracy`](../tests/test_arch_accuracy.cpp) contains 23 small, nonzero F32-fixtures covering 19 verified architecture identifiers and experimental `hunyuan-moe`.+[`GGUFArchitectureAccuracy`](../tests/test_arch_accuracy.cpp) contains 26 small, nonzero F32+fixtures covering 21 verified architecture identifiers and experimental `hunyuan-moe`.Additional model variants exercise YaRN and position-dependent attention scaling under`llama` and `mistral3`. The suite does not cover `gemma3`, `gemma4`, `gpt-oss` or `qwen35`.@@ -112,6 +114,20 @@ sliding-window boundaries, SmolLM3's fourth NoPE layer, ERNIE shared experts witcover Gemma2-27B's attention scale, EXAONE4's 64-layer SWA defaults and ERNIE's interleaveddense/MoE schedule. Zero-weight conversion fingerprints provide structural smoke coverage.+### Mamba 2 execution++`GGML_OP_SSM_SCAN` uses the existing `SelectiveSSM` operation. `GGUFMakeStateful` normalizes+convolution caches for OpenVINO's recurrent fusions. Stateful execution supports greedy+decoding with one sequence and resettable convolution/SSM caches.++CPU tests cover prefill, decode and state reset through the stateful frontend path.+GenAI paged integration is not included. Beam search and prefix-cache reuse are not verified.+Mamba 1 and `nemotron_h_moe` are not supported.++Regenerate the Mamba references with `gen_arch_accuracy.py --oracle <oracle>+--architectures mamba2 mamba2-tied nemotron_h`, using+`architecture_oracle.cpp` built against llama.cpp `476c01efe88aad7880a8132d5d3a415f2ca75139`.+### Reference-checked checkpointsThe following checkpoint comparisons use the prompt `The capital of France is`, native@@ -132,10 +148,12 @@ choices across prefill and those twelve steps. Q4_K checks use| `hunyuan-dense` | Hunyuan-0.5B-Instruct Q8_0 | 13/13 || `llama` | Devstral Small 2507, 24B Q4_K_M | 13/13 || `maincoder` | Maincoder-1B Q4_K_M | 13/13 |+| `mamba2` | Mamba2-2.7B Q8_0 | 12/13 || `mellum` | Mellum2-12B-A2.5B-Instruct Q4_K_M | 12/13 || `mistral3` | Devstral Small 2, 24B Q4_K_M (text) | 13/13 || `mistral3` | Ministral-3-3B-Instruct-2512 Q4_K_M | 13/13 || `muse-glimmer` | Muse-Glimmer-30B Q4_0 | 13/13 |+| `nemotron_h` | NVIDIA Nemotron-H-8B-Reasoning-128K Q4_K_M | 12/13 || `qwen3moe` | Qwen3-0.9B-A0.6B Q4_K_M | 13/13 || `smollm3` | SmolLM3-3B Q4_K_M | 12/13 |@@ -145,6 +163,16 @@ lossy weight conversions. This is bounded decoder validation, not a quality bencor a guarantee for every checkpoint, context length, quantization or device. In particular,default integer-zero-point Q4_K and U8 KV-cache approximations can change output.+Native Q8_0 preserves weight codes and scales. These comparisons disable OpenVINO's dynamic+activation quantization (`DYNAMIC_QUANTIZATION_GROUP_SIZE=0`) and use F32 inference.+llama.cpp's Q8 CPU path quantizes activations. Running llama.cpp with F32 arithmetic on+the same decoded weights, while keeping OpenVINO's settings unchanged, gives 13/13 matching+choices for Mamba2-130M and Mamba2-2.7B. The 130M checkpoint has model-hub smoke coverage but+falls below the agreement threshold against Q8 CPU arithmetic with OpenVINO dynamic+quantization disabled (11/13). Enabling it with group size 32 gives 13/13 matching choices+for both checkpoints against llama.cpp Q8 CPU in stateful execution. Full logits still+differ; their mean normalized error increases despite the improved token agreement.+See [reference generation and reproduction instructions](../tests/test_data/arch_accuracy/README.md).These references are shipped with the frontend tests; no model download or llama.cppbuild is needed in the regular test run. Real-model hub tests separately exercisediff --git a/src/frontends/gguf/src/builder/api/graph_context.cpp b/src/frontends/gguf/src/builder/api/graph_context.cppindex 8d451a7ff44..58c34a95aaa 100644--- a/src/frontends/gguf/src/builder/api/graph_context.cpp+++ b/src/frontends/gguf/src/builder/api/graph_context.cpp@@ -12,6 +12,7 @@#include "builder/api/graph_context_impl.hpp"#include "builder/blocks/ffn.hpp"#include "builder/blocks/gated_delta_net.hpp"+#include "openvino/op/constant.hpp"namespace ov {namespace frontend {@@ -119,6 +120,17 @@ GgufValue GgufGraphContext::add_input(const std::string& name, ov::element::Typereturn GgufValue(name, e.value(name));}+GgufValue GgufGraphContext::add_constant(const std::string& name, const ov::Tensor& value) {+ m_impl->check_open();+ auto& emitter = m_impl->emitter;+ OPENVINO_ASSERT(+ !emitter.graph()->values->count(name) && !emitter.has_weight(name) && !emitter.has_model_input(name),+ "[GGUF] constant name is already used: ",+ name);+ emitter.add_extra_input_node(name, std::make_shared<ov::op::v0::Constant>(value));+ return GgufValue(name, emitter.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}));@@ -188,6 +200,12 @@ void GgufGraphContext::set_output(const GgufValue& logits) {m_impl->emitter.graph()->model_output_names.push_back(m_impl->value_name(logits));}+void GgufGraphContext::set_primary_output(const GgufValue& value) {+ m_impl->check_open();+ auto& outputs = m_impl->emitter.graph()->model_output_names;+ outputs.insert(outputs.begin(), m_impl->value_name(value));+}+void GgufGraphContext::set_sliding_window(int64_t tokens) {m_impl->check_open();OPENVINO_ASSERT(tokens > 0 && tokens <= std::numeric_limits<int>::max(),diff --git a/src/frontends/gguf/src/builder/arch/mamba_builder.cpp b/src/frontends/gguf/src/builder/arch/mamba_builder.cppnew file mode 100644index 00000000000..3b43e187d71--- /dev/null+++ b/src/frontends/gguf/src/builder/arch/mamba_builder.cpp@@ -0,0 +1,158 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "mamba_builder.hpp"++#include <cmath>+#include <limits>++#include "openvino/frontend/gguf/builder/graph_context.hpp"++namespace ov::frontend::gguf {+namespace {++// Mamba2 has a norm/mixer/residual stack, without attention or a feed-forward sublayer.+// Dense Nemotron-H interleaves those mixers with attention and ReLU-squared FFN layers.+// Reference: llama.cpp models/mamba.cpp and mamba-base.cpp::build_mamba2_layer.+class Mamba2Builder : public ModelBuilder {+public:+ explicit Mamba2Builder(const BuildContext& context) : g(context) {}++ std::shared_ptr<GgufGraph> build() override {+ const auto positive = [&](const std::string& suffix) {+ const auto key = g.arch() + "." + suffix;+ const auto value = g.metadata().get_int(key);+ OPENVINO_ASSERT(value && *value > 0 && *value <= std::numeric_limits<int>::max(),+ "[GGUF] Mamba2 requires positive metadata '",+ key,+ "'");+ return *value;+ };+ const auto layers = positive("block_count");+ const auto inner = positive("ssm.inner_size");+ const auto heads = positive("ssm.time_step_rank");+ const auto groups = positive("ssm.group_count");+ const auto state_size = positive("ssm.state_size");+ const auto kernel = positive("ssm.conv_kernel");+ OPENVINO_ASSERT(inner % heads == 0 && heads % groups == 0 && kernel > 1,+ "[GGUF] Mamba2 requires inner_size divisible by heads, heads divisible by groups, "+ "and conv_kernel > 1");+ const auto head_dim = inner / heads;+ const auto conv_dim = inner + 2 * groups * state_size;+ const auto eps_value = g.metadata().get_float(g.arch() + ".attention.layer_norm_rms_epsilon");+ OPENVINO_ASSERT(eps_value && std::isfinite(*eps_value) && *eps_value > 0,+ "[GGUF] Mamba2 requires a positive RMS normalization epsilon");+ const auto eps = static_cast<float>(*eps_value);+ auto weights = g.tensors();+ const bool hybrid = g.arch() == "nemotron_h";+ if (hybrid) {+ OPENVINO_ASSERT(g.metadata().get_int(g.arch() + ".expert_count").value_or(0) == 0,+ "[GGUF] Nemotron-H MoE is not supported by the dense builder");+ DecoderOptions options;+ options.rope_skip_period = 1; // Nemotron-H attention has no positional embedding.+ g.configure_decoder(RopeMode::Normal, options);+ g.build_attn_inp_kv();+ }+ auto cur = g.build_inp_embd(weights.require("token_embd.weight"));+ const auto out_ids = g.build_inp_out_ids();+ ov::Tensor ids_tensor(ov::element::i32, {1, 1, 1, 1});+ ids_tensor.data<int32_t>()[0] = 0;+ const auto ids = g.add_constant("ssm_sequence_ids", ids_tensor);++ for (int64_t layer = 0; layer < layers; ++layer) {+ const auto prefix = "blk." + std::to_string(layer) + ".";+ const auto w = [&](const std::string& name) {+ return weights.require(prefix + name);+ };+ auto residual = cur;+ cur = g.build_norm(cur, w("attn_norm.weight"), eps);+ if (hybrid && !weights.has(prefix + "ssm_in.weight")) {+ if (weights.has(prefix + "attn_q.weight") || weights.has(prefix + "attn_qkv.weight")) {+ cur = g.decoder_attention(static_cast<int>(layer), cur);+ } else {+ cur = g.node("GGML_OP_MUL_MAT", {w("ffn_up.weight"), cur});+ if (weights.has(prefix + "ffn_up.bias"))+ cur = g.node("GGML_OP_ADD", {cur, w("ffn_up.bias")});+ cur = g.node("GGML_OP_SQR", {g.node("GGML_UNARY_OP_RELU", {cur})});+ cur = g.node("GGML_OP_MUL_MAT", {w("ffn_down.weight"), cur});+ if (weights.has(prefix + "ffn_down.bias"))+ cur = g.node("GGML_OP_ADD", {cur, w("ffn_down.bias")});+ }+ } else {+ auto projected = g.node("GGML_OP_MUL_MAT", {w("ssm_in.weight"), cur});+ const auto z = reshape(slice(projected, 0, inner), {0, -1, heads, head_dim});+ auto xbc = slice(projected, inner, conv_dim);+ const auto xbc_layout = xbc;+ auto dt = slice(projected, inner + conv_dim, heads);+ dt = g.node("GGML_OP_ADD", {dt, w("ssm_dt.bias")});++ const auto conv_state =+ g.add_input("conv_state_l" + std::to_string(layer), ov::element::f32, {1, 1, conv_dim, kernel - 1});+ const auto window =+ g.node("GGML_OP_CONCAT", {conv_state, g.node("GGML_OP_TRANSPOSE", {xbc})}, 0, {{"concat_axis", 0}});+ g.add_recurrent_state(conv_state, slice(window, -(kernel - 1), kernel - 1));+ xbc = g.node("GGML_OP_SSM_CONV", {window, w("ssm_conv1d.weight")});+ if (weights.has(prefix + "ssm_conv1d.bias"))+ xbc = g.node("GGML_OP_ADD", {xbc, w("ssm_conv1d.bias")});+ xbc = g.node("GGML_UNARY_OP_SILU", {xbc});+ xbc = g.node("GGML_OP_VIEW", {xbc, xbc_layout}, 3);+ const auto x = reshape(slice(xbc, 0, inner), {0, -1, heads, head_dim});+ const auto b = reshape(slice(xbc, inner, groups * state_size), {0, -1, groups, state_size});+ const auto c =+ reshape(slice(xbc, inner + groups * state_size, groups * state_size), {0, -1, groups, state_size});+ const auto state = g.add_input("ssm_state_l" + std::to_string(layer),+ ov::element::f32,+ {1, heads, head_dim, state_size});+ const auto scan = g.node("GGML_OP_SSM_SCAN", {state, x, dt, w("ssm_a"), b, c, ids});+ const auto state_elements = inner * state_size;+ g.add_recurrent_state(+ state,+ reshape(slice(scan, -state_elements, state_elements), {1, heads, head_dim, state_size}));+ auto y =+ g.node("GGML_OP_VIEW", {scan, x}, 3, {{"view_slice", std::vector<int64_t>{3, 0, -state_elements}}});+ y = g.node("GGML_OP_ADD", {y, g.node("GGML_OP_MUL", {x, w("ssm_d")})});+ y = g.node("GGML_OP_MUL", {y, g.node("GGML_UNARY_OP_SILU", {z})});+ y = reshape(y, {0, -1, groups, inner / groups});+ y = g.build_norm(y, w("ssm_norm.weight"), eps);+ y = reshape(y, {0, 1, -1, inner});+ cur = g.node("GGML_OP_MUL_MAT", {w("ssm_out.weight"), y});+ }+ if (layer == layers - 1) {+ cur = g.node("GGML_OP_GET_ROWS", {cur, out_ids});+ residual = g.node("GGML_OP_GET_ROWS", {residual, out_ids});+ }+ cur = g.node("GGML_OP_ADD", {cur, residual});+ }+ cur = g.build_norm(cur, weights.require("output_norm.weight"), eps);+ const auto output =+ weights.has("output.weight") ? weights.require("output.weight") : weights.require("token_embd.weight");+ g.set_primary_output(g.node("GGML_OP_MUL_MAT", {output, cur}));+ return g.finish();+ }++private:+ GgufValue reshape(const GgufValue& value, const std::vector<int64_t>& shape) {+ return g.node("GGML_OP_RESHAPE", {value}, 6, {{"reshape_target", shape}, {"special_zero", true}});+ }++ GgufValue slice(const GgufValue& value, int64_t start, int64_t length) {+ return g.node("GGML_OP_VIEW", {value}, 3, {{"view_slice", std::vector<int64_t>{3, start, length}}});+ }++ GgufGraphContext g;+};++} // namespace++ArchitectureDefinition mamba2_architecture(const std::string& architecture) {+ return {architecture,+ architecture,+ [](const BuildContext& context) {+ return std::make_shared<Mamba2Builder>(context);+ },+ {},+ Maturity::Verified};+}++} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/builder/arch/mamba_builder.hpp b/src/frontends/gguf/src/builder/arch/mamba_builder.hppnew file mode 100644index 00000000000..b196e2eb16c--- /dev/null+++ b/src/frontends/gguf/src/builder/arch/mamba_builder.hpp@@ -0,0 +1,10 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+#pragma once++#include "openvino/frontend/gguf/extension/architecture.hpp"++namespace ov::frontend::gguf {+ArchitectureDefinition mamba2_architecture(const std::string& architecture);+} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/builder/arch_registry.cpp b/src/frontends/gguf/src/builder/arch_registry.cppindex 5a22493a60c..129e75b3a5a 100644--- a/src/frontends/gguf/src/builder/arch_registry.cpp+++ b/src/frontends/gguf/src/builder/arch_registry.cpp@@ -4,6 +4,7 @@#include "arch_registry.hpp"+#include "builder/arch/mamba_builder.hpp"#include "openvino/core/except.hpp"namespace ov::frontend::gguf {@@ -38,7 +39,8 @@ std::vector<ArchitectureDefinition> builtin_architectures() {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.+ definitions.push_back(mamba2_architecture("mamba2"));+ definitions.push_back(mamba2_architecture("nemotron_h"));return definitions;}@@ -53,9 +55,9 @@ bool arch_uses_neox_rope(const std::string& arch) {const std::set<std::string>& verified_archs() {static const auto names = [] {std::set<std::string> result;- for (const auto& entry : decoders)- if (entry.maturity == Maturity::Verified)- result.insert(entry.name);+ for (const auto& definition : builtin_architectures())+ if (definition.maturity == Maturity::Verified)+ result.insert(definition.architecture);return result;}();return names;@@ -64,9 +66,9 @@ const std::set<std::string>& verified_archs() {const std::set<std::string>& experimental_archs() {static const auto names = [] {std::set<std::string> result;- for (const auto& entry : decoders)- if (entry.maturity == Maturity::Experimental)- result.insert(entry.name);+ for (const auto& definition : builtin_architectures())+ if (definition.maturity == Maturity::Experimental)+ result.insert(definition.architecture);return result;}();return names;diff --git a/src/frontends/gguf/src/builder/blocks/attention.cpp b/src/frontends/gguf/src/builder/blocks/attention.cppindex 18248880570..231382e6390 100644--- a/src/frontends/gguf/src/builder/blocks/attention.cpp+++ b/src/frontends/gguf/src/builder/blocks/attention.cpp@@ -64,7 +64,7 @@ std::string attention(GraphEmitter& e,register_qwen35_q_gate(e, cfg, il);e.add_weight(p + "attn_k.weight");e.add_weight(p + "attn_v.weight");- } else if (cfg.has_fused_qkv) {+ } else if (e.has_weight(p + "attn_qkv.weight")) {register_fused_qkv(e, cfg, il);} else {e.add_weight(p + "attn_q.weight");@@ -86,7 +86,8 @@ std::string attention(GraphEmitter& e,// 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// register_fused_qkv above).- if (cfg.has_qkv_bias) {+ // Qwen35 repacks a joint Q/gate projection; retain its separate bias policy.+ if (cfg.is_qwen35 ? cfg.has_qkv_bias : e.has_weight(p + "attn_q.bias")) {q = add_bias(e, q, p + "attn_q.bias", p + "Qcur_b");k = add_bias(e, k, p + "attn_k.bias", p + "Kcur_b");v = add_bias(e, v, p + "attn_v.bias", p + "Vcur_b");@@ -266,7 +267,7 @@ std::string attention(GraphEmitter& e,// 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});- if (cfg.has_attn_out_bias) {+ if (cfg.is_qwen35 ? cfg.has_attn_out_bias : e.has_weight(p + "attn_output.bias")) {attn_out = add_bias(e, attn_out, p + "attn_output.bias", p + "attn_out_b");}return attn_out;diff --git a/src/frontends/gguf/src/op/ssm_scan.cpp b/src/frontends/gguf/src/op/ssm_scan.cppnew file mode 100644index 00000000000..0bca43a430b--- /dev/null+++ b/src/frontends/gguf/src/op/ssm_scan.cpp@@ -0,0 +1,52 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "node_context.hpp"+#include "op_table.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/selective_ssm.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/softplus.hpp"+#include "utils.hpp"++namespace ov::frontend::gguf::op {++OutputVector translate_ssm_scan(const NodeContext& context) {+ num_inputs_check(context, 7, 7);+ using namespace ov::op;++ // ggml: s [slots,H,D,S], x [B,T,H,D], dt [1,B,T,H], A [1,1,H,1],+ // B/C [B,T,G,S], ids [1,1,1,B]. Only Mamba2 has scalar decay per head.+ const auto a_shape = context.get_input_shape(3);+ FRONT_END_OP_CONVERSION_CHECK(a_shape.rank() == 4 && a_shape[0] == 1 && a_shape[1] == 1 && a_shape[3] == 1,+ "SSM_SCAN: SelectiveSSM requires Mamba2 scalar decay per head; "+ "Mamba1 state-wise decay is not supported");+ const auto flat = v0::Constant::create(element::i64, {1}, {-1});+ const auto axis0 = v0::Constant::create(element::i64, {}, {0});+ const auto ids = std::make_shared<v1::Reshape>(context.get_input(6), flat, false);+ const auto state = std::make_shared<v8::Gather>(context.get_input(0), ids, axis0);+ const auto a = std::make_shared<v1::Reshape>(context.get_input(3), flat, false);+ const auto dt_shape = std::make_shared<v8::Gather>(std::make_shared<v3::ShapeOf>(context.get_input(1)),+ v0::Constant::create(element::i64, {3}, {0, 1, 2}),+ axis0);+ const auto dt =+ std::make_shared<v4::SoftPlus>(std::make_shared<v1::Reshape>(context.get_input(2), dt_shape, false));+ const auto ssm = std::make_shared<internal::SelectiveSSM>(a,+ dt,+ context.get_input(4),+ context.get_input(1),+ context.get_input(5),+ state);+ // Pack directly in GGUF layout so whole-part views can select either Concat input.+ const auto packed_shape = v0::Constant::create(element::i64, {4}, {1, 1, 1, -1});+ const auto y = std::make_shared<v1::Reshape>(ssm->output(0), packed_shape, false);+ const auto s = std::make_shared<v1::Reshape>(ssm->output(1), packed_shape, false);+ const auto result = std::make_shared<v0::Concat>(OutputVector{y, s}, 3);+ return rename_outputs_with_suffix({result}, context.get_name());+}++} // namespace ov::frontend::gguf::opdiff --git a/src/frontends/gguf/src/op/view.cpp b/src/frontends/gguf/src/op/view.cppindex f59e694e9c1..ff4effb3c61 100644--- a/src/frontends/gguf/src/op/view.cpp+++ b/src/frontends/gguf/src/op/view.cpp@@ -61,9 +61,9 @@ void place_dynamic_token_axis(std::vector<int64_t>& tgt, const ov::PartialShape&// Cases 2-5 are shared by both ingest paths: the llama.cpp cgraph decoder classifies a ggml view// into them (see ggml-decoder.cpp::compute_op_case) and the native .gguf builder describes its own-// views the same way. Case 104 is builder-only: it takes a second (shape-reference) input the-// cgraph path does not supply, so it has a different arity than the shared cases. See its comment-// below, and docs/frontend_design.md for the other two builder-only cases in the frontend.+// views the same way. The native builder can supply an optional second shape-reference input+// for case 3 to preserve the runtime token layout. Builder-only case 104 also uses that input.+// See its comment below and docs/frontend_design.md for the builder-only cases.OutputVector translate_view(const NodeContext& context) {num_inputs_check(context, 1, 2);@@ -201,7 +201,24 @@ OutputVector translate_view(const NodeContext& context) {// ggml strides.auto slice = context.get_attribute<std::vector<int64_t>>("view_slice", {});ov::Output<ov::Node> result = input;- if (slice.size() == 3) {+ bool whole_concat_input = false;+ // Selecting a complete Concat input needs no packing or copy. This also keeps+ // SSM token outputs independent of the final state when converting to paged execution.+ const auto concat = ov::as_type_ptr<ov::op::v0::Concat>(input.get_node_shared_ptr());+ if (slice.size() == 3 && concat && concat->get_input_size() == 2 && concat->get_axis() == slice[0] &&+ slice[0] >= 0 && concat->get_input_partial_shape(1).rank().is_static()) {+ const auto& tail = concat->get_input_partial_shape(1)[slice[0]];+ if (tail.is_static() && tail.get_length() > 0) {+ const auto count = tail.get_length();+ const bool prefix = slice[1] == 0 && slice[2] == -count;+ const bool suffix = slice[1] == -count && slice[2] == count;+ if (prefix || suffix) {+ result = concat->input_value(suffix ? 1 : 0);+ whole_concat_input = true;+ }+ }+ }+ if (!whole_concat_input && slice.size() == 3) {const int64_t axis = slice[0], start = slice[1], len = slice[2];if (axis >= 0 && static_cast<size_t>(axis) < input_ggml_shape.size() &&start >= static_cast<int64_t>(input_ggml_shape[axis])) {@@ -236,10 +253,15 @@ OutputVector translate_view(const NodeContext& context) {false);result.get_node_shared_ptr()->set_friendly_name("view_reshape_" + context.get_name());}- // A view that neither restores rank, slices nor reshapes is a pass-through: the value is- // still the producer's output, so renaming it here would rename a node owned by another- // ggml tensor (and the suffix compounds, since the helper appends).- if (result == context.get_input(0)) {+ // A second operand provides the runtime layout for a view of a packed recurrent+ // output. This preserves token placement when paged execution flattens the batch.+ if (context.get_input_size() == 2) {+ result = std::make_shared<ov::op::v1::Reshape>(result,+ std::make_shared<ov::op::v3::ShapeOf>(context.get_input(1)),+ false);+ }+ // Preserve producer names when the view reuses an existing value.+ if (result == context.get_input(0) || (whole_concat_input && tgt.empty() && context.get_input_size() == 1)) {return {std::move(result)};}return rename_outputs_with_suffix({std::move(result)}, context.get_name());diff --git a/src/frontends/gguf/src/op_table.cpp b/src/frontends/gguf/src/op_table.cppindex cd971924288..8eebff5b267 100644--- a/src/frontends/gguf/src/op_table.cpp+++ b/src/frontends/gguf/src/op_table.cpp@@ -70,6 +70,7 @@ std::unordered_map<std::string, CreatorFunction> get_supported_ops() {{"GGML_OP_SQR", op::translate_sqr},{"GGML_OP_SQRT", op::translate_sqrt},{"GGML_OP_SSM_CONV", op::translate_ssm_conv},+ {"GGML_OP_SSM_SCAN", op::translate_ssm_scan},{"GGML_OP_SUB", op::translate_1to1_match_2_inputs<v1::Subtract>},{"GGML_OP_SUM_ROWS", op::translate_sum_rows},{"GGML_OP_TOP_K", op::translate_top_k},diff --git a/src/frontends/gguf/src/op_table.hpp b/src/frontends/gguf/src/op_table.hppindex a0bec47af3c..52ef1d169e7 100644--- a/src/frontends/gguf/src/op_table.hpp+++ b/src/frontends/gguf/src/op_table.hpp@@ -81,6 +81,7 @@ GGUF_OP_CONVERTER(translate_fill);GGUF_OP_CONVERTER(translate_im2col);GGUF_OP_CONVERTER(translate_pad);GGUF_OP_CONVERTER(translate_ssm_conv);+GGUF_OP_CONVERTER(translate_ssm_scan);GGUF_OP_CONVERTER(translate_gated_delta_net);GGUF_OP_CONVERTER(translate_weight);diff --git a/src/frontends/gguf/src/pass/adapt_to_genai.cpp b/src/frontends/gguf/src/pass/adapt_to_genai.cppindex 0883fc98ccd..a25779faac0 100644--- a/src/frontends/gguf/src/pass/adapt_to_genai.cpp+++ b/src/frontends/gguf/src/pass/adapt_to_genai.cpp@@ -196,7 +196,9 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {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) {+ const bool has_recurrent_states = model->get_rt_info().count(gguf_recurrent_states_key()) != 0;+ const bool recurrent_only = !inp_pos && !self_kq_mask && has_recurrent_states;+ if (!inp_tokens || (!recurrent_only && !self_kq_mask)) {return false;}@@ -208,7 +210,10 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {self_correcting_axis_manager.run_passes(model);// ---- new genai inputs: input_ids / attention_mask / position_ids [b, seq] i64 ----- auto input_ids = make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});+ // Recurrent state buffers currently hold one sequence. Keep that constraint explicit.+ auto input_ids =+ make_shared<v0::Parameter>(ov::element::i64,+ has_recurrent_states ? ov::PartialShape{1, -1} : ov::PartialShape{-1, -1});name_output(input_ids, "input_ids");auto attention_mask = make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});name_output(attention_mask, "attention_mask");@@ -219,10 +224,17 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {// sets it via set_tensor("beam_idx"). Keep that Parameter so its wiring is preserved. Its absence// means the model is not stateful, which the genai contract requires.auto beam_idx = find_parameter(model, "beam_idx");- OPENVINO_ASSERT(beam_idx,+ OPENVINO_ASSERT(beam_idx || (recurrent_only && !model->get_variables().empty()),"[gguf] AdaptToGenAI: model has no 'beam_idx' input, so it is not stateful. ""Register a make-stateful transformation extension (e.g. ""ov::frontend::gguf::pass::MakeStateful) before converting.");+ if (!beam_idx) {+ // GenAI sets beam_idx even for greedy decoding. Pure recurrent models have+ // one fixed state slot, so keep the single-element input as part of the API.+ beam_idx = make_shared<v0::Parameter>(ov::element::i32, ov::PartialShape{1});+ name_output(beam_idx, "beam_idx");+ model->add_parameters({beam_idx});+ }// ---- token_len_per_seq = number of tokens in input_ids -> [1] ----// The token count is the ELEMENT COUNT of input_ids, not any single dimension of it. genai feeds@@ -271,7 +283,8 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {pos_i32 = make_shared<v0::Tile>(pos_i32, tile_repeats);}auto pos_4d = make_shared<v1::Reshape>(pos_i32, shape_keep0_1_1_rest, true);- inp_pos->output(0).replace(pos_4d->output(0));+ if (inp_pos)+ inp_pos->output(0).replace(pos_4d->output(0));// ---- self_kq_mask [1,1,seq,kv_len] f32: 0 where attended, -inf above causal ----// kv_len = attention_mask length (= past + seq). query absolute positions = position_ids[0].@@ -311,7 +324,8 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {auto allowed = make_shared<v1::LessEqual>(k_row, q_pos_col); // [seq, kv_len] boolauto mask_4d = to_mask_4d(allowed);- self_kq_mask->output(0).replace(mask_4d->output(0));+ if (self_kq_mask)+ self_kq_mask->output(0).replace(mask_4d->output(0));// Sliding-window mask: for prompts within the window this equals the full causal mask, but// once the context (prompt + generated tokens) exceeds it, reusing the causal mask woulddiff --git a/src/frontends/gguf/src/pass/make_stateful.cpp b/src/frontends/gguf/src/pass/make_stateful.cppindex c664a309fc1..8b2ac5c938c 100644--- a/src/frontends/gguf/src/pass/make_stateful.cpp+++ b/src/frontends/gguf/src/pass/make_stateful.cpp@@ -4,20 +4,25 @@#include "openvino/frontend/gguf/make_stateful.hpp"+#include <limits>#include <memory>#include <string>#include <vector>#include "openvino/core/graph_util.hpp"+#include "openvino/core/rt_info.hpp"#include "openvino/frontend/gguf/set_rows_op.hpp"#include "openvino/op/assign.hpp"#include "openvino/op/concat.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/gather.hpp"+#include "openvino/op/group_conv.hpp"#include "openvino/op/parameter.hpp"#include "openvino/op/read_value.hpp"#include "openvino/op/reshape.hpp"#include "openvino/op/result.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/op/transpose.hpp"#include "openvino/op/util/variable.hpp"#include "utils.hpp"@@ -77,6 +82,75 @@ int64_t resolve_append_axis(const ov::PartialShape& ps, const std::string& cachereturn axis;}+// ggml keeps K-1 convolution samples in [1, B, C, K-1]. Normalize the private state+// to Optimum's [B, C, K] convention before creating its Variable, so the existing+// PagedCausalConv1DFusion can consume it. Keeping one extra sample produces one extra+// convolution output, which is discarded; the remaining outputs are unchanged.+void normalize_causal_conv_state(const std::shared_ptr<ov::op::v0::Parameter>& state,+ const std::shared_ptr<ov::op::v0::Result>& state_result) {+ using namespace ov::op;+ const auto shape = state->get_partial_shape();+ if (shape.size() != 4 || shape[0] != 1 || shape[3] == 0 || state->output(0).get_target_inputs().size() != 1)+ return;+ const auto update = ov::as_type_ptr<v8::Slice>(state_result->get_input_node_shared_ptr(0));+ if (!update || update->get_input_size() != 5 || update->output(0).get_target_inputs().size() != 1)+ return;+ const auto constant_is = [](const ov::Output<ov::Node>& value, int64_t expected) {+ const auto constant = ov::as_type_ptr<v0::Constant>(value.get_node_shared_ptr());+ return constant && constant->cast_vector<int64_t>() == std::vector<int64_t>{expected};+ };+ if (!constant_is(update->input_value(1), -shape[3].get_length()) ||+ !constant_is(update->input_value(2), std::numeric_limits<int64_t>::max()) ||+ !constant_is(update->input_value(3), 1) || !constant_is(update->input_value(4), 3))+ return;+ const auto window = ov::as_type_ptr<v0::Concat>(update->get_input_node_shared_ptr(0));+ if (!window || window->get_axis() != 3 || window->get_input_size() != 2 ||+ window->input_value(0) != state->output(0) || window->output(0).get_target_inputs().size() != 2)+ return;+ std::shared_ptr<v1::GroupConvolution> conv;+ for (const auto& input : window->output(0).get_target_inputs()) {+ const auto reshape = ov::as_type_ptr<v1::Reshape>(input.get_node()->shared_from_this());+ if (!reshape || reshape->output(0).get_target_inputs().size() != 1)+ continue;+ const auto consumer = *reshape->output(0).get_target_inputs().begin();+ conv = ov::as_type_ptr<v1::GroupConvolution>(consumer.get_node()->shared_from_this());+ }+ const auto kernel = shape[3].get_length() + 1;+ if (!conv || !conv->get_input_partial_shape(0).compatible(ov::PartialShape({shape[1], shape[2], -1})) ||+ conv->get_input_partial_shape(1) != ov::PartialShape({shape[2], 1, 1, kernel}) ||+ conv->get_strides() != ov::Strides{1} || conv->get_dilations() != ov::Strides{1} ||+ conv->get_pads_begin() != ov::CoordinateDiff{0} || conv->get_pads_end() != ov::CoordinateDiff{0} ||+ conv->get_auto_pad() != ov::op::PadType::EXPLICIT)+ return;++ // Paged conversion moves tokens from axis 3 to axis 0 of the ggml window.+ // Restore token-major order before collapsing axes, then expose [B, C, T].+ const auto token_major = std::make_shared<v1::Transpose>(window->input_value(1),+ v0::Constant::create(ov::element::i64, {4}, {0, 1, 3, 2}));+ const auto pattern = v0::Constant::create(ov::element::i64,+ {3},+ std::vector<int64_t>{shape[1].get_length(), -1, shape[2].get_length()});+ const auto token_rows = std::make_shared<v1::Reshape>(token_major, pattern, false);+ const auto tokens =+ std::make_shared<v1::Transpose>(token_rows, v0::Constant::create(ov::element::i64, {3}, {0, 2, 1}));+ state->set_partial_shape(ov::PartialShape{shape[1], shape[2], kernel});+ state->validate_and_infer_types();+ const auto concat = std::make_shared<v0::Concat>(ov::OutputVector{state, tokens}, -1);+ const auto convolution = conv->clone_with_new_inputs({concat, conv->input_value(1)});+ const auto end = v0::Constant::create(ov::element::i64, {1}, {std::numeric_limits<int64_t>::max()});+ const auto step = v0::Constant::create(ov::element::i64, {1}, {1});+ const auto axis = v0::Constant::create(ov::element::i64, {1}, {2});+ const auto output = std::make_shared<v8::Slice>(convolution, step, end, step, axis);+ const auto tail = v0::Constant::create(ov::element::i64, {1}, {-kernel});+ const auto new_state = std::make_shared<v8::Slice>(concat, tail, end, step, axis);+ output->set_friendly_name(conv->get_friendly_name());+ new_state->set_friendly_name(update->get_friendly_name());+ ov::copy_runtime_info({state, window, conv, update},+ {token_major, token_rows, tokens, concat, convolution, output, new_state});+ ov::replace_node(conv, output);+ state_result->input(0).replace_source_output(new_state);+}+} // namespaceconst std::string& gguf_recurrent_states_key() {@@ -127,12 +201,11 @@ static bool make_recurrent_states_stateful(const std::shared_ptr<ov::Model>& modif (!param) {continue; // already rewritten (a second run of this pass)}- const auto& ps = param->get_partial_shape();- OPENVINO_ASSERT(ps.is_static(),+ OPENVINO_ASSERT(param->get_partial_shape().is_static(),"[GGUF] GGUFMakeStateful: recurrent state '",in_name,"' must have a fully static shape, got ",- ps);+ param->get_partial_shape());// The Result holding this state's new value: the one whose producing node carries the// state's output name. The builder names that node after the state (see the VIEW cases),@@ -147,6 +220,8 @@ static bool make_recurrent_states_stateful(const std::shared_ptr<ov::Model>& mod}OPENVINO_ASSERT(state_result, "[GGUF] GGUFMakeStateful: no Result produces recurrent state '", out_name, "'");+ normalize_causal_conv_state(param, state_result);+ const auto& ps = param->get_partial_shape();const auto et = param->get_element_type();auto var = std::make_shared<ov::op::util::Variable>(ov::op::util::VariableInfo{ps, et, in_name});auto init = v0::Constant::create(et, ps.to_shape(), std::vector<float>(1, 0.0f));diff --git a/src/frontends/gguf/tests/CMakeLists.txt b/src/frontends/gguf/tests/CMakeLists.txtindex 413f1cede22..1d66ed5008d 100644--- a/src/frontends/gguf/tests/CMakeLists.txt+++ b/src/frontends/gguf/tests/CMakeLists.txt@@ -42,6 +42,7 @@ set(FRONTEND_SRCS"${FE_SRC_DIR}/builder/api/metadata.cpp""${FE_SRC_DIR}/builder/api/tensor_table.cpp""${FE_SRC_DIR}/builder/arch/decoder_builder.cpp"+ "${FE_SRC_DIR}/builder/arch/mamba_builder.cpp""${FE_SRC_DIR}/builder/blocks/attention.cpp""${FE_SRC_DIR}/builder/blocks/common.cpp""${FE_SRC_DIR}/builder/blocks/ffn.cpp"@@ -79,6 +80,7 @@ set(FRONTEND_SRCS"${FE_SRC_DIR}/op/softmax.cpp""${FE_SRC_DIR}/op/sqr.cpp""${FE_SRC_DIR}/op/ssm_conv.cpp"+ "${FE_SRC_DIR}/op/ssm_scan.cpp""${FE_SRC_DIR}/op/top_k.cpp""${FE_SRC_DIR}/op/tri.cpp""${FE_SRC_DIR}/op/sum_rows.cpp"diff --git a/src/frontends/gguf/tests/gen_arch_accuracy.py b/src/frontends/gguf/tests/gen_arch_accuracy.pyindex aa0ad9496a6..d04303374a3 100644--- a/src/frontends/gguf/tests/gen_arch_accuracy.py+++ b/src/frontends/gguf/tests/gen_arch_accuracy.py@@ -19,6 +19,8 @@ import ggufimport numpy as npCASES = {+ "nemotron_h": {},+ "mamba2": {}, "mamba2-tied": {"architecture": "mamba2", "tied": True},"llama": {}, "qwen2": {"bias": True}, "qwen3": {"qk": True},"phi3": {"fused": True, "fused_ffn": True}, "minicpm": {},"olmoe": {"moe": True, "full_qk": True},@@ -42,8 +44,70 @@ CASES = {}+def write_mamba2_model(path, opts, arch="mamba2"):+ w = gguf.GGUFWriter(path, arch)+ hybrid = arch == "nemotron_h"+ d, inner, heads, groups, state, kernel, vocab = 32, 64, 4, 2, 8, 4, 32+ w.add_context_length(128)+ w.add_embedding_length(d)+ w.add_block_count(4 if hybrid else 2)+ w.add_head_count(4 if hybrid else 0)+ if hybrid:+ w.add_head_count_kv([0, 2, 0, 0])+ w.add_feed_forward_length([0, 0, 48, 0])+ w.add_key_length(8)+ w.add_value_length(8)+ w.add_layer_norm_rms_eps(1e-5)+ w.add_vocab_size(vocab)+ w.add_tokenizer_model("none")+ for key, value in {"inner_size": inner, "time_step_rank": heads, "group_count": groups,+ "state_size": state, "conv_kernel": kernel}.items():+ w.add_uint32(arch + ".ssm." + key, value)+ rng = np.random.default_rng(20260915)++ def tensor(name, shape, norm=False):+ values = rng.uniform(-1, 1, shape).astype(np.float32)+ w.add_tensor(name, 1 + values * .3 if norm else values * .2)++ tensor("token_embd.weight", (vocab, d))+ tensor("output_norm.weight", (d,), True)+ if not opts.get("tied"):+ tensor("output.weight", (vocab, d))+ conv_dim = inner + 2 * groups * state+ for layer in range(4 if hybrid else 2):+ p = f"blk.{layer}."+ tensor(p + "attn_norm.weight", (d,), True)+ if hybrid and layer == 1:+ for name, width in (("q", 32), ("k", 16), ("v", 16)):+ tensor(p + f"attn_{name}.weight", (width, d))+ tensor(p + f"attn_{name}.bias", (width,))+ tensor(p + "attn_output.weight", (d, 32))+ tensor(p + "attn_output.bias", (d,))+ continue+ if hybrid and layer == 2:+ tensor(p + "ffn_up.weight", (48, d))+ tensor(p + "ffn_up.bias", (48,))+ tensor(p + "ffn_down.weight", (d, 48))+ tensor(p + "ffn_down.bias", (d,))+ continue+ tensor(p + "ssm_in.weight", (inner + conv_dim + heads, d))+ tensor(p + "ssm_conv1d.weight", (conv_dim, kernel))+ tensor(p + "ssm_conv1d.bias", (conv_dim,))+ tensor(p + "ssm_dt.bias", (heads,))+ w.add_tensor(p + "ssm_a", -rng.uniform(.1, 1, (heads, 1)).astype(np.float32))+ tensor(p + "ssm_d", (heads, 1))+ tensor(p + "ssm_norm.weight", (groups, inner // groups), True)+ tensor(p + "ssm_out.weight", (d, inner))+ w.write_header_to_file()+ w.write_kv_data_to_file()+ w.write_tensors_to_file()+ w.close()++def write_model(path, arch, opts):arch = opts.get("architecture", arch)+ if arch in ("mamba2", "nemotron_h"):+ return write_mamba2_model(path, opts, arch)w = gguf.GGUFWriter(path, arch)d, heads, head, ff, vocab = opts.get("embedding", 32), 4, 8, 48, 32kv = 1 if opts.get("mqa") else heads if opts.get("full_qk") or arch == "deepseek2-ocr" else 2diff --git a/src/frontends/gguf/tests/op_test_utils.hpp b/src/frontends/gguf/tests/op_test_utils.hppindex 9b1020eac28..ab179c50f66 100644--- a/src/frontends/gguf/tests/op_test_utils.hpp+++ b/src/frontends/gguf/tests/op_test_utils.hpp@@ -230,10 +230,8 @@ inline ov::Tensor make_f32_tensor(const ov::Shape& shape, const std::vector<floa// Compile on CPU and run one inference with the given named inputs; return the single output.//// Inference precision is requested as f32: these tests validate the converted graph against an fp32-// reference, not the plugin's reduced-precision arithmetic, so wherever fp32 inference is available we-// want it regardless of the plugin's performance-mode default (e.g. bf16 on avx512_core_bf16 hosts).-// Where fp32 is not supported (ARM, which always infers in fp16) the request is silently ignored, and-// the wider tolerance below covers the resulting rounding error.+// reference, so request fp32 regardless of the plugin's performance-mode default+// (e.g. bf16 on avx512_core_bf16 hosts or fp16 on ARM).inline ov::Tensor run_on_cpu(const std::shared_ptr<ov::Model>& model, const std::map<std::string, ov::Tensor>& inputs) {ov::Core core;auto compiled = core.compile_model(model, "CPU", ov::hint::inference_precision(ov::element::f32));@@ -245,14 +243,8 @@ inline ov::Tensor run_on_cpu(const std::shared_ptr<ov::Model>& model, const std:return req.get_output_tensor(0);}-// Default relative tolerance, per inference precision the CPU plugin actually uses.-//-// On ARM the f32 request above cannot be honored (the plugin always infers in fp16), so rounding-// error accumulates through long op chains such as rope; the measured worst case needs ~3e-3.-//-// Everywhere else the f32 request holds and the measured worst case across this suite is ~1.4e-6,-// so the bound stays near fp32 precision — tight enough that a real conversion error cannot hide-// inside it.+// Default relative tolerance accounts for differences in platform-specific FP32 math kernels.+// ARM approximations can accumulate error through op chains such as rope.#if defined(OPENVINO_ARCH_ARM) || defined(OPENVINO_ARCH_ARM64)# define OV_GGUF_TEST_DEFAULT_RTOL 1e-2f#else@@ -261,8 +253,7 @@ inline ov::Tensor run_on_cpu(const std::shared_ptr<ov::Model>& model, const std:// Compare against an fp32 reference with a combined absolute + relative tolerance:// |actual - expected| <= atol + rtol * |expected|-// The relative term matters on hardware that runs the graph in fp16 (e.g. ARM CPU), where the-// rounding error grows with the magnitude of the value.+// The relative term accounts for error that grows with the magnitude of the value.inline void expect_near(const ov::Tensor& actual,const std::vector<float>& expected,float atol = 1e-4f,diff --git a/src/frontends/gguf/tests/ssm_scan_oracle.c b/src/frontends/gguf/tests/ssm_scan_oracle.cnew file mode 100644index 00000000000..b7c08a2c3f7--- /dev/null+++ b/src/frontends/gguf/tests/ssm_scan_oracle.c@@ -0,0 +1,61 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// Generate SSM_SCAN output with real ggml CPU. Build with ggml/include and link+// ggml, ggml-base and ggml-cpu. Usage: ssm_scan_oracle <tokens> <output.f32>.+// The deterministic inputs are also used by GGUFOps.SSMScanMamba2.+#include <stdio.h>+#include <stdlib.h>++#include "ggml-backend.h"+#include "ggml-cpu.h"+#include "ggml.h"++int main(int argc, char** argv) {+ if (argc != 3)+ return 2;+ const int nt = atoi(argv[1]);+ struct ggml_init_params ip = {16 * 1024 * 1024, NULL, true};+ struct ggml_context* ctx = ggml_init(ip);+ struct ggml_tensor* s = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 8, 3, 4, 3);+ struct ggml_tensor* x = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 3, 4, nt, 2);+ struct ggml_tensor* dt = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, 4, nt, 2);+ struct ggml_tensor* a = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 1, 4);+ struct ggml_tensor* b = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 8, 2, nt, 2);+ struct ggml_tensor* c = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 8, 2, nt, 2);+ struct ggml_tensor* ids = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 2);+ struct ggml_tensor* out = ggml_ssm_scan(ctx, s, x, dt, a, b, c, ids);+ struct ggml_cgraph* graph = ggml_new_graph(ctx);+ ggml_build_forward_expand(graph, out);+ ggml_backend_t backend = ggml_backend_cpu_init();+ ggml_backend_buffer_t buffer = ggml_backend_alloc_ctx_tensors(ctx, backend);+ struct ggml_tensor* inputs[] = {s, x, dt, a, b, c};+ for (int j = 0; j < 6; ++j) {+ const int64_t count = ggml_nelements(inputs[j]);+ float* values = malloc(count * sizeof(float));+ for (int64_t i = 0; i < count; ++i)+ values[i] = j == 3 ? -.1f * (i + 1) : ((i * (j + 3) + j) % 29 - 14) * .07f;+ if (j == 2) {+ values[0] = -25.f;+ values[1] = 25.f;+ }+ ggml_backend_tensor_set(inputs[j], values, 0, count * sizeof(float));+ free(values);+ }+ const int32_t indices[] = {2, 0};+ ggml_backend_tensor_set(ids, indices, 0, sizeof(indices));+ if (ggml_backend_graph_compute(backend, graph) != GGML_STATUS_SUCCESS)+ return 3;+ const size_t bytes = ggml_nbytes(out);+ void* output = malloc(bytes);+ ggml_backend_tensor_get(out, output, 0, bytes);+ FILE* file = fopen(argv[2], "wb");+ if (!file || fwrite(output, 1, bytes, file) != bytes)+ return 4;+ fclose(file);+ free(output);+ ggml_backend_buffer_free(buffer);+ ggml_backend_free(backend);+ ggml_free(ctx);+ return 0;+}diff --git a/src/frontends/gguf/tests/test_arch_accuracy.cpp b/src/frontends/gguf/tests/test_arch_accuracy.cppindex 3db31a63553..4e5c848bf6d 100644--- a/src/frontends/gguf/tests/test_arch_accuracy.cpp+++ b/src/frontends/gguf/tests/test_arch_accuracy.cpp@@ -23,10 +23,12 @@ class GGUFArchitectureAccuracy : public ::testing::TestWithParam<const char*> {}TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {const char* override_dir = std::getenv("OV_GGUF_ACCURACY_DATA");+ const bool mamba = std::string(GetParam()).find("mamba2") == 0 || std::string(GetParam()) == "nemotron_h";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();+ const bool real_checkpoint = override_dir && !std::filesystem::exists(base.string() + ".npz");std::vector<std::vector<int64_t>> schedule{{1, 2, 3}, {4}, {5, 6}};std::vector<float> reference;int32_t vocab = 0;@@ -38,7 +40,7 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {std::filesystem::remove(path);}} temporary;- if (override_dir) {+ if (real_checkpoint) {std::ifstream file(base.string() + ".bin", std::ios::binary);ASSERT_TRUE(file) << base;file.read(reinterpret_cast<char*>(&vocab), sizeof(vocab));@@ -90,6 +92,10 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {fe.add_extension(std::make_shared<ov::frontend::DecoderTransformationExtension>(ov::frontend::gguf::pass::AdaptToGenAI()));auto model = fe.convert(fe.load(model_path));+ if (mamba) {+ EXPECT_EQ(model->input("input_ids").get_partial_shape(), (ov::PartialShape{1, -1}));+ EXPECT_NO_THROW(model->input("beam_idx"));+ }ov::Core core;auto compiled = core.compile_model(model,"CPU",@@ -99,14 +105,10 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {ov::hint::dynamic_quantization_group_size(0),ov::hint::kv_cache_precision(ov::element::f16));auto request = compiled.create_infer_request();- size_t past = 0;- size_t step = 0;- size_t matching_tokens = 0;- for (const auto& tokens : schedule) {+ const auto infer = [&](const std::vector<int64_t>& tokens, size_t past) {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 positions(ov::element::i64, ids.get_shape());ov::Tensor mask(ov::element::i64, {1, past + count});ov::Tensor beam(ov::element::i32, {1});*beam.data<int32_t>() = 0;@@ -123,43 +125,71 @@ TEST_P(GGUFArchitectureAccuracy, PrefillAndCachedDecodeMatchLlamaCPU) {}))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;+ return request.get_output_tensor();+ };+ const auto nmse = [vocab](const float* actual, const float* expected) {double error = 0, norm = 0;for (int32_t i = 0; i < vocab; ++i) {- ASSERT_TRUE(std::isfinite(actual[i]));+ EXPECT_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";+ EXPECT_GT(norm, 1e-12) << "Reference must contain nonzero logits";+ return error / norm;+ };+ size_t past = 0;+ size_t step = 0;+ size_t matching_tokens = 0;+ for (const auto& tokens : schedule) {+ SCOPED_TRACE("past=" + std::to_string(past) + ", tokens=" + std::to_string(tokens.size()));+ const auto result = infer(tokens, past);+ 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;+ const auto error = nmse(actual, expected);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+ RecordProperty("nmse_step_" + std::to_string(step), std::to_string(error));+ if (real_checkpoint) {+ // Real checkpoints can use different quantization arithmetic. Check the first prediction// and continuation agreement; keep their full-logit metrics in the XML report.if (step == 1) {EXPECT_EQ(predicted, wanted);}} else {- EXPECT_LT(error / norm, 1e-5) << "Normalized MSE against llama.cpp CPU";+ EXPECT_LT(error, 1e-5) << "Normalized MSE against llama.cpp CPU";}- past += count;+ past += tokens.size();+ }+ if (mamba) {+ const auto states = request.query_state();+ ASSERT_FALSE(states.empty());+ for (auto state : states)+ state.reset();+ const auto logits = infer(schedule.front(), 0);+ const auto* actual = logits.data<const float>() + logits.get_size() - vocab;+ const auto error = nmse(actual, reference.data());+ if (real_checkpoint)+ EXPECT_EQ(std::max_element(actual, actual + vocab) - actual,+ std::max_element(reference.begin(), reference.begin() + vocab) - reference.begin());+ else+ EXPECT_LT(error, 1e-5) << "Fresh prefill after resetting recurrent states";}- if (override_dir) {+ if (real_checkpoint) {EXPECT_GE(matching_tokens * 10, schedule.size() * 9) << "Fewer than 90% of greedy choices match";}}INSTANTIATE_TEST_SUITE_P(Architectures,GGUFArchitectureAccuracy,- ::testing::Values("llama",+ ::testing::Values("nemotron_h",+ "mamba2",+ "mamba2-tied",+ "llama","qwen2","qwen3","phi3",diff --git a/src/frontends/gguf/tests/test_arch_conversion.cpp b/src/frontends/gguf/tests/test_arch_conversion.cppindex 704450e4c7a..89561f5f6fe 100644--- a/src/frontends/gguf/tests/test_arch_conversion.cpp+++ b/src/frontends/gguf/tests/test_arch_conversion.cpp@@ -180,6 +180,7 @@ struct Fingerprint {const std::map<std::string, Fingerprint>& fingerprints() {static const std::map<std::string, Fingerprint> fp{+ {"mamba2-dense.gguf.hdr", {293, 6}}, {"nemotron_h-dense.gguf.hdr", {280, 8}},{"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}},diff --git a/src/frontends/gguf/tests/test_builder_api.cpp b/src/frontends/gguf/tests/test_builder_api.cppindex 86686726c48..9618315beaa 100644--- a/src/frontends/gguf/tests/test_builder_api.cpp+++ b/src/frontends/gguf/tests/test_builder_api.cpp@@ -289,8 +289,11 @@ TEST(GGUFBuilderAPI, RecurrentStateDeclarationReachesMakeStateful) {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());+ const auto output = graph.node("GGML_OP_SCALE", {update}, 0, {{"scale", float{2}}, {"bias", 0.0f}});+ graph.set_primary_output(output);+ const auto built = graph.finish();+ ASSERT_EQ(built->model_output_names.front(), output.name());+ auto model = convert(built);ASSERT_TRUE(model->get_rt_info().count(pass::gguf_recurrent_states_key()));ov::pass::Manager passes;passes.register_pass<pass::GGUFMakeStateful>();@@ -571,6 +574,25 @@ TEST(GGUFBuilderAPI, MergeHeadsAcceptsRuntimeTokenAndHeadDimensions) {}}+TEST(GGUFBuilderAPI, ViewReusesWholeConcatInputsAndPreservesNames) {+ Environment env;+ GgufGraphContext graph(env.context);+ auto prefix = graph.add_input("prefix", ov::element::f32, {1, 2, 1, -1});+ auto suffix = graph.add_input("suffix", ov::element::f32, {1, 2, 1, 3});+ auto packed = graph.node("GGML_OP_CONCAT", {prefix, suffix}, 0, {{"concat_axis", 0}});+ for (const auto& slice : std::vector<std::vector<int64_t>>{{3, 0, -3}, {3, -3, 3}, {3, 0, -2}})+ graph.set_output(graph.node("GGML_OP_VIEW", {packed}, 3, {{"view_slice", slice}}));+ auto model = convert(graph.finish());+ EXPECT_EQ(model->get_results()[0]->input_value(0), model->input("prefix"));+ EXPECT_EQ(model->get_results()[1]->input_value(0), model->input("suffix"));+ // A view spanning part of the suffix still needs the concatenated tensor.+ const auto partial = model->get_results()[2]->get_input_node_shared_ptr(0);+ EXPECT_STREQ(partial->get_type_name(), "Slice");+ EXPECT_STREQ(partial->get_input_node_shared_ptr(0)->get_type_name(), "Concat");+ EXPECT_EQ(model->input("prefix").get_node()->get_friendly_name(), "prefix");+ EXPECT_EQ(model->input("suffix").get_node()->get_friendly_name(), "suffix");+}+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}}}},diff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/mamba2-tied.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/mamba2-tied.npznew file mode 100644index 00000000000..a86ea23ed76Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/mamba2-tied.npz differdiff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/mamba2.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/mamba2.npznew file mode 100644index 00000000000..f5b53150bfbBinary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/mamba2.npz differdiff --git a/src/frontends/gguf/tests/test_data/arch_accuracy/nemotron_h.npz b/src/frontends/gguf/tests/test_data/arch_accuracy/nemotron_h.npznew file mode 100644index 00000000000..39d3eba4606Binary files /dev/null and b/src/frontends/gguf/tests/test_data/arch_accuracy/nemotron_h.npz differdiff --git a/src/frontends/gguf/tests/test_data/arch_fixtures/manifest.txt b/src/frontends/gguf/tests/test_data/arch_fixtures/manifest.txtindex 7ba44736506..d407aed9bef 100644--- a/src/frontends/gguf/tests/test_data/arch_fixtures/manifest.txt+++ b/src/frontends/gguf/tests/test_data/arch_fixtures/manifest.txt@@ -69,7 +69,7 @@ llama-moe.gguf.hdr 7096448 convertllama4-moe.gguf.hdr 13921664 rejectmaincoder-dense.gguf.hdr 4732800 convertmamba-dense.gguf.hdr 5029120 reject-mamba2-dense.gguf.hdr 4509120 reject+mamba2-dense.gguf.hdr 4509120 convertminicpm-dense.gguf.hdr 4741248 convertminicpm-moe.gguf.hdr 7096448 convertminicpm3-dense.gguf.hdr 7616512 reject@@ -79,7 +79,7 @@ mistral3-moe.gguf.hdr 7096448 convertmistral4-moe.gguf.hdr 4403296 rejectmpt-dense.gguf.hdr 4094464 rejectnemotron-dense.gguf.hdr 3956480 reject-nemotron_h-dense.gguf.hdr 4230240 reject+nemotron_h-dense.gguf.hdr 4230240 convertnemotron_h_moe-dense.gguf.hdr 4230240 rejectolmo-dense.gguf.hdr 4725632 rejectolmoe-moe.gguf.hdr 7098240 convertdiff --git a/src/frontends/gguf/tests/test_data/ssm_scan_t1_expected.npy b/src/frontends/gguf/tests/test_data/ssm_scan_t1_expected.npynew file mode 100644index 00000000000..5c8660e6003Binary files /dev/null and b/src/frontends/gguf/tests/test_data/ssm_scan_t1_expected.npy differdiff --git a/src/frontends/gguf/tests/test_data/ssm_scan_t3_expected.npy b/src/frontends/gguf/tests/test_data/ssm_scan_t3_expected.npynew file mode 100644index 00000000000..2359a4ad341Binary files /dev/null and b/src/frontends/gguf/tests/test_data/ssm_scan_t3_expected.npy differdiff --git a/src/frontends/gguf/tests/test_extensions.cpp b/src/frontends/gguf/tests/test_extensions.cppindex 50600539fd6..b1c9e2ecb82 100644--- a/src/frontends/gguf/tests/test_extensions.cpp+++ b/src/frontends/gguf/tests/test_extensions.cpp@@ -18,12 +18,14 @@// default stateless lowering ever sees them.#include <algorithm>+#include <limits>#include <set>#include <stdexcept>#include "common_test_utils/node_builders/constant.hpp"#include "common_test_utils/ov_test_utils.hpp"#include "op_test_utils.hpp"+#include "openvino/core/graph_util.hpp"#include "openvino/frontend/extension/conversion.hpp"#include "openvino/frontend/extension/decoder_transformation.hpp"#include "openvino/frontend/gguf/make_stateful.hpp"@@ -38,6 +40,7 @@#include "openvino/op/read_value.hpp"#include "openvino/op/result.hpp"#include "openvino/op/scatter_update.hpp"+#include "openvino/op/slice.hpp"using namespace ov_gguf_test;@@ -452,3 +455,69 @@ TEST(GGUFExtensions, GGUFMakeStatefulRecurrentRewriteIsIdempotent) {EXPECT_EQ(model->get_variables().size(), 1);EXPECT_EQ(model->get_sinks().size(), 1);}++TEST(GGUFExtensions, GGUFMakeStatefulNormalizesCausalConvCache) {+ using namespace ov::op;+ // Use the real SSM_CONV translator, with its ggml window and recurrent-state update.+ auto model = SingleOpBuilder()+ .op("GGML_OP_SSM_CONV")+ .input("sx", ov::element::f32, {1, 1, 3, -1})+ .input("c", ov::element::f32, {1, 1, 3, 4})+ .output("out", ov::element::f32, {1, 1, -1, 3})+ .build();+ const auto sx = ov::as_type_ptr<v0::Parameter>(model->input("sx").get_node_shared_ptr());+ const auto c = ov::as_type_ptr<v0::Parameter>(model->input("c").get_node_shared_ptr());+ const auto state = ov::test::utils::make_param(ov::element::f32, ov::Shape{1, 1, 3, 3}, "conv_state");+ const auto tokens = ov::test::utils::make_param(ov::element::f32, ov::PartialShape{1, 1, 3, -1}, "tokens");+ const auto window = std::make_shared<v0::Concat>(ov::OutputVector{state, tokens}, 3);+ ov::replace_node(sx, window);+ ov::replace_node(c,+ v0::Constant::create(ov::element::f32,+ {1, 1, 3, 4},+ {0.5f, 0.25f, 0.125f, 0.0625f, 1.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 1.f}));+ model->remove_parameter(sx);+ model->remove_parameter(c);+ model->add_parameters({state, tokens});+ const auto update =+ std::make_shared<v8::Slice>(window,+ v0::Constant::create(ov::element::i64, {1}, {-3}),+ v0::Constant::create(ov::element::i64, {1}, {std::numeric_limits<int64_t>::max()}),+ v0::Constant::create(ov::element::i64, {1}, {1}),+ v0::Constant::create(ov::element::i64, {1}, {3}));+ update->set_friendly_name("conv_state_out");+ model->add_results({std::make_shared<v0::Result>(update)});+ model->get_rt_info()[pass::gguf_recurrent_states_key()] = std::vector<std::string>{"conv_state", "conv_state_out"};++ pass::GGUFMakeStateful normalize;+ ASSERT_TRUE(normalize.run_on_model(model));+ EXPECT_FALSE(normalize.run_on_model(model));+ model->validate_nodes_and_infer_types();+ ov::Core core;+ auto compiled = core.compile_model(model, "CPU", ov::hint::inference_precision(ov::element::f32));+ auto request = compiled.create_infer_request();+ auto states = request.query_state();+ ASSERT_EQ(states.size(), 1);+ EXPECT_EQ(states[0].get_state().get_shape(), (ov::Shape{1, 3, 4}));+ // The extra oldest sample must not affect output, even when nonzero.+ states[0].set_state(make_f32_tensor({1, 3, 4}, {-1000, 1, 2, 3, -2000, 11, 12, 13, -3000, 21, 22, 23}));++ // Real ggml CPU oracle: ssm_conv_oracle.c with n_t=8 and sxd[3*11].+ const std::vector<float> expected{1.625f, 11, 24, 2.5625f, 12, 25, 3.5f, 13, 26, 4.4375f, 14, 27,+ 5.375f, 15, 28, 6.3125f, 16, 29, 7.25f, 17, 30, 8.1875f, 18, 31};+ size_t past = 0;+ for (const size_t count : {5, 1, 2}) {+ std::vector<float> values(3 * count);+ for (size_t channel = 0; channel < 3; ++channel)+ for (size_t token = 0; token < count; ++token)+ values[channel * count + token] = static_cast<float>(channel * 10 + past + token + 4);+ request.set_tensor("tokens", make_f32_tensor({1, 1, 3, count}, values));+ request.infer();+ expect_near(request.get_output_tensor(),+ std::vector<float>(expected.begin() + past * 3, expected.begin() + (past + count) * 3),+ 1e-5f);+ past += count;+ }+ expect_near(states[0].get_state(), {8, 9, 10, 11, 18, 19, 20, 21, 28, 29, 30, 31});+ states[0].reset();+ expect_near(states[0].get_state(), std::vector<float>(12, 0));+}diff --git a/src/frontends/gguf/tests/test_ops.cpp b/src/frontends/gguf/tests/test_ops.cppindex ec66229ab49..fb90b83a251 100644--- a/src/frontends/gguf/tests/test_ops.cpp+++ b/src/frontends/gguf/tests/test_ops.cpp@@ -13,6 +13,7 @@#include <functional>#include "op_test_utils.hpp"+#include "openvino/op/selective_ssm.hpp"#include "openvino/op/topk.hpp"#include "utils.hpp"@@ -1078,6 +1079,78 @@ TEST(GGUFOps, GetRowsMoeWeights) {expect_near(out, expected, 1e-5f);}+TEST(GGUFOps, SSMScanMamba2) {+ // Compile once with dynamic batch/token axes. Oracle: ssm_scan_oracle.c, real ggml CPU,+ // two groups, four heads, unequal head/state widths and state slot permutation {2,0}.+ auto model = SingleOpBuilder()+ .op("GGML_OP_SSM_SCAN")+ .input("s", ov::element::f32, {-1, 4, 3, 8})+ .input("x", ov::element::f32, {-1, -1, 4, 3})+ .input("dt", ov::element::f32, {1, -1, -1, 4})+ .input("a", ov::element::f32, {1, 1, 4, 1})+ .input("b", ov::element::f32, {-1, -1, 2, 8})+ .input("c", ov::element::f32, {-1, -1, 2, 8})+ .input("ids", ov::element::i32, {1, 1, 1, -1})+ .output("out", ov::element::f32, {1, 1, 1, -1})+ .build();+ size_t fused = 0;+ for (const auto& node : model->get_ops())+ fused += ov::is_type<ov::op::internal::SelectiveSSM>(node);+ ASSERT_EQ(fused, 1);+ ov::Core core;+ auto compiled = core.compile_model(model, "CPU", ov::hint::inference_precision(ov::element::f32));+ auto request = compiled.create_infer_request();+ for (size_t tokens : {3, 1}) {+ const std::vector<std::string> names{"s", "x", "dt", "a", "b", "c"};+ const std::vector<ov::Shape> shapes{{3, 4, 3, 8},+ {2, tokens, 4, 3},+ {1, 2, tokens, 4},+ {1, 1, 4, 1},+ {2, tokens, 2, 8},+ {2, tokens, 2, 8}};+ for (int j = 0; j < 6; ++j) {+ ov::Tensor input(ov::element::f32, shapes[j]);+ for (size_t i = 0; i < input.get_size(); ++i)+ input.data<float>()[i] =+ j == 3 ? -.1f * (i + 1) : (static_cast<int>((i * (j + 3) + j) % 29) - 14) * .07f;+ if (j == 2) {+ input.data<float>()[0] = -25.f;+ input.data<float>()[1] = 25.f;+ }+ request.set_tensor(names[j], input);+ }+ ov::Tensor ids(ov::element::i32, {1, 1, 1, 2});+ ids.data<int32_t>()[0] = 2;+ ids.data<int32_t>()[1] = 0;+ request.set_tensor("ids", ids);+ request.infer();+ const auto out = request.get_output_tensor();+ const auto expected = load_npy<float>("ssm_scan_t" + std::to_string(tokens) + "_expected");+#if defined(OPENVINO_ARCH_ARM) || defined(OPENVINO_ARCH_ARM64)+ // ARM's FP32 SoftPlus approximation produces up to 8e-4 absolute error through the scan.+ // A relative tolerance alone cannot cover the resulting near-zero state values.+ expect_near(out, expected, 1e-3f);+#else+ expect_near(out, expected);+#endif+ }+}++TEST(GGUFOps, SSMScanRejectsMamba1Decay) {+ EXPECT_THROW(SingleOpBuilder()+ .op("GGML_OP_SSM_SCAN")+ .input("s", ov::element::f32, {1, 4, 1, 8})+ .input("x", ov::element::f32, {1, 2, 4, 1})+ .input("dt", ov::element::f32, {1, 1, 2, 4})+ .input("a", ov::element::f32, {1, 1, 4, 8})+ .input("b", ov::element::f32, {1, 2, 1, 8})+ .input("c", ov::element::f32, {1, 2, 1, 8})+ .input("ids", ov::element::i32, {1, 1, 1, 1})+ .output("out", ov::element::f32, {1, 1, 1, 40})+ .build(),+ ov::Exception);+}+// SsmConv: depthwise causal 1D conv. sx [1, n_s=1, d_inner=2, ncs=4], weight [1,1,2,d_conv=3]// -> out [1, 1, n_t=2, 2].TEST(GGUFOps, SsmConv) {diff --git a/tests/model_hub_tests/gguf/gguf_models_nightly b/tests/model_hub_tests/gguf/gguf_models_nightlyindex 01254a27d58..f218800e274 100644--- a/tests/model_hub_tests/gguf/gguf_models_nightly+++ b/tests/model_hub_tests/gguf/gguf_models_nightly@@ -30,3 +30,5 @@ glm4moe,,,skip,"Smallest checkpoint (GLM-4.5-Air) is ~40 GiB, impractical even fexaone-moe,,,skip,"Smallest checkpoint is ~9 GiB / 32B, not currently validated (see supported_models.md)"minimax-m2,,,skip,"Smallest checkpoint is ~78 GiB, impractical even for nightly"jais2,,,skip,"No small checkpoint publicly available (see supported_models.md)"+nemotron_h,bartowski/nvidia_Nemotron-H-8B-Reasoning-128K-GGUF,nvidia_Nemotron-H-8B-Reasoning-128K-Q4_K_M.gguf+mamba2-2.7b,Nicholas55555/mamba2-2.7b-Q8_0-GGUF,mamba2-2.7b-q8_0.ggufdiff --git a/tests/model_hub_tests/gguf/gguf_models_precommit b/tests/model_hub_tests/gguf/gguf_models_precommitindex 40b45c875df..159f18ef395 100644--- a/tests/model_hub_tests/gguf/gguf_models_precommit+++ b/tests/model_hub_tests/gguf/gguf_models_precommit@@ -33,3 +33,4 @@ smollm3,bartowski/HuggingFaceTB_SmolLM3-3B-GGUF,HuggingFaceTB_SmolLM3-3B-Q4_K_M.maincoder,mradermacher/Maincoder-1B-GGUF,Maincoder-1B.Q4_K_M.ggufmistral3,mradermacher/Ministral-3b-instruct-GGUF,Ministral-3b-instruct.Q4_K_M.ggufqwen35,ggml-org/Qwen3.5-0.8B-GGUF,Qwen3.5-0.8B-Q4_0.gguf+mamba2,rpatel622/mamba2-130m-hf-Q8_0-GGUF,mamba2-130m-q8_0.ggufdiff --git a/tests/model_hub_tests/gguf/utils.py b/tests/model_hub_tests/gguf/utils.pyindex f24fa5e09fe..af0a4216338 100644--- a/tests/model_hub_tests/gguf/utils.py+++ b/tests/model_hub_tests/gguf/utils.py@@ -138,7 +138,7 @@ def convert_gguf_model(path: str) -> ov.Model:return fe.convert(fe.load(path))-def _state_outputs(compiled_model, outputs) -> dict[str, np.ndarray]:+def _state_outputs(compiled_model, outputs, recurrent_states: dict[str, str]) -> dict[str, np.ndarray]:"""Copy state outputs and map them back to their corresponding input names."""data_input_names = {"beam_idx",@@ -158,6 +158,7 @@ def _state_outputs(compiled_model, outputs) -> dict[str, np.ndarray]:state = {}for port, value in outputs.items():state_name = port.get_node().get_friendly_name()+ state_name = recurrent_states.get(state_name, state_name)if state_name.endswith("_1"):state_name = state_name[:-2]if state_name.endswith("_out"):@@ -169,22 +170,21 @@ def _state_outputs(compiled_model, outputs) -> dict[str, np.ndarray]:return state-def _assert_valid_kv_cache(state: dict[str, np.ndarray]):- kv_tensors = {name: value for name, value in state.items() if name.startswith(("cache_k_", "cache_v_"))}- assert kv_tensors, "GGUF model exposes no K/V cache tensors"- for name, value in kv_tensors.items():+def _assert_valid_state(state: dict[str, np.ndarray]):+ assert state, "GGUF model exposes no cache or recurrent state tensors"+ for name, value in state.items():assert value.size > 0, f"{name} is empty"assert np.isfinite(value).all(), f"{name} contains NaN/Inf"assert np.any(value != 0), f"{name} was not populated"-def _run_two_steps(compiled_model, is_imrope: bool) -> np.ndarray:+def _run_two_steps(compiled_model, is_imrope: bool, recurrent_states: dict[str, str] | None = None) -> np.ndarray:request = compiled_model.create_infer_request()first_feed = build_single_token_inputs(compiled_model, token_id=1, is_imrope=is_imrope)first_outputs = request.infer(first_feed)- first_state = _state_outputs(compiled_model, first_outputs)- _assert_valid_kv_cache(first_state)+ first_state = _state_outputs(compiled_model, first_outputs, recurrent_states or {})+ _assert_valid_state(first_state)second_feed = build_single_token_inputs(compiled_model,@@ -195,8 +195,8 @@ def _run_two_steps(compiled_model, is_imrope: bool) -> np.ndarray:kv_cache_length=2,)second_outputs = request.infer(second_feed)- second_state = _state_outputs(compiled_model, second_outputs)- _assert_valid_kv_cache(second_state)+ second_state = _state_outputs(compiled_model, second_outputs, recurrent_states or {})+ _assert_valid_state(second_state)kv_names = [name for name in first_state if name.startswith(("cache_k_", "cache_v_"))]for name in kv_names:@@ -206,6 +206,10 @@ def _run_two_steps(compiled_model, is_imrope: bool) -> np.ndarray:)assert np.any(second_state[name][:, 1, ...] != 0), f"{name} did not populate the second cache slot"+ for name in first_state.keys() - set(kv_names):+ assert first_state[name].shape == second_state[name].shape, f"{name} changed recurrent state shape"+ assert not np.array_equal(first_state[name], second_state[name]), f"{name} did not update on decode"+return second_outputs[compiled_model.output(0)]@@ -223,7 +227,11 @@ def run_gguf_model(repo_id: str, filename: str, device: str = "CPU"):if "gguf_is_imrope" in model.get_rt_info():is_imrope = bool(model.get_rt_info(["gguf_is_imrope"]).get())compiled_model = core.compile_model(model, device)- return _run_two_steps(compiled_model, is_imrope)+ recurrent_states = {}+ if "gguf_recurrent_states" in model.get_rt_info():+ pairs = model.get_rt_info(["gguf_recurrent_states"]).get()+ recurrent_states = dict(zip(pairs[1::2], pairs[::2]))+ return _run_two_steps(compiled_model, is_imrope, recurrent_states)def assert_valid_logits(logits: np.ndarray):