Skip to content

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

[NPUW] Model builder: add linear attention hybrid architecture support (#35286)

Dylan Neve808143a48880
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp
index c0202f1dba1..90c8751476b 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp
@@ -654,7 +654,12 @@ ov::Output<ov::Node> ModelBuilder::setup_position_ids(LLMConfig& config, const o
}
// config.rope set without position_ids means RoPE was pre-built with position_ids baked in
if (position_ids_output.get_node() && !config.rope) {
- config.rope = HalfRotationRoPE(config.head_dim, config.precision, position_ids_output);
+ if (config.rotary_dim > 0 && config.rotary_dim < config.head_dim) {
+ config.rope =
+ PartialRotationRoPE(config.head_dim, config.rotary_dim, config.precision, position_ids_output);
+ } else {
+ config.rope = HalfRotationRoPE(config.head_dim, config.precision, position_ids_output);
+ }
}
return position_ids_output;
@@ -674,6 +679,8 @@ std::shared_ptr<ov::Model> ModelBuilder::build_llm(const LLMConfig& config_in) {
clear();
LLMConfig config = config_in;
+ OPENVINO_ASSERT(!config.is_linear_layer || config.use_kv_cache,
+ "Hybrid models require use_kv_cache — SSM/conv states are inherently stateful");
if (!config.norm)
config.norm = LayerNorm(config.hidden_size, config.precision);
if (!config.ffn) {
@@ -778,8 +785,11 @@ std::shared_ptr<ov::Model> ModelBuilder::build_llm(const LLMConfig& config_in) {
attn.rope_fn = config.rope;
attn.sdpa_mask = default_mask;
attn.shared_broadcast_shape = shared_broadcast;
+ attn.output_gate = config.attn_output_gate;
- if (config.use_kv_cache) {
+ // Non-hybrid: standard past_key_values naming. Hybrid full-attention layers get
+ // per-attn-layer cache_params naming (set below inside build_full_attn_layer).
+ if (config.use_kv_cache && !config.is_linear_layer) {
attn.kv_cache_fn = [&](const ov::Output<ov::Node>& k,
const ov::Output<ov::Node>& v,
size_t layer) -> std::pair<ov::Output<ov::Node>, ov::Output<ov::Node>> {
@@ -804,35 +814,68 @@ std::shared_ptr<ov::Model> ModelBuilder::build_llm(const LLMConfig& config_in) {
};
}
+ // Wire linear-mixer runtime inputs once — all layers share the same graph plumbing.
+ if (config.is_linear_layer) {
+ OPENVINO_ASSERT(config.linear_mixer, "Hybrid models require config.linear_mixer to be set");
+ config.linear_mixer->seq_source = seq_source;
+ config.linear_mixer->beam_idx = beam_idx_output;
+ }
+
+ size_t linear_layer_count = 0;
+ size_t attn_layer_count = 0;
+
+ auto build_full_attn_layer = [&](const ov::Output<ov::Node>& input, const std::string& prefix, size_t layer) {
+ // Local copy so per-layer kv_cache_fn wiring never mutates the shared `attn`.
+ Attention layer_attn = attn;
+ if (config.use_kv_cache && config.is_linear_layer) {
+ // Hybrid attention layers use per-attn-layer cache_params naming (separate from conv/ssm).
+ auto attn_idx = attn_layer_count;
+ layer_attn.kv_cache_fn = [&, attn_idx](const ov::Output<ov::Node>& k_proj,
+ const ov::Output<ov::Node>& v_proj,
+ size_t /*layer*/) {
+ auto idx_str = std::to_string(attn_idx);
+ auto k_cache = make_kv_cache_concat(k_proj, seq_source, beam_idx_output, kv_heads, config.head_dim,
+ make_cache_params_var_id("key", idx_str), prec);
+ auto v_cache = make_kv_cache_concat(v_proj, seq_source, beam_idx_output, kv_heads, config.head_dim,
+ make_cache_params_var_id("value", idx_str), prec);
+ m_sinks.push_back(std::dynamic_pointer_cast<ov::op::Sink>(k_cache.assign));
+ m_sinks.push_back(std::dynamic_pointer_cast<ov::op::Sink>(v_cache.assign));
+ return std::pair{k_cache.concatenated, v_cache.concatenated};
+ };
+ }
+ ++attn_layer_count;
+ auto fn = [&](const ov::Output<ov::Node>& normed, const std::string& pfx) {
+ return layer_attn(normed, {}, pfx, layer);
+ };
+ return config.pre_norm ? make_pre_norm_layer(input, config.norm, fn, config.ffn, prefix)
+ : make_post_norm_layer(input, config.norm, fn, config.ffn, prefix);
+ };
+
+ auto build_linear_layer = [&](const ov::Output<ov::Node>& input, const std::string& prefix, size_t /*layer*/) {
+ auto lin_idx = linear_layer_count++;
+ auto fn = [&, lin_idx](const ov::Output<ov::Node>& normed, const std::string& pfx) {
+ MixerResult r = config.linear_mixer->build(normed, pfx, lin_idx);
+ m_sinks.insert(m_sinks.end(), r.sinks.begin(), r.sinks.end());
+ return r.output;
+ };
+ return config.pre_norm ? make_pre_norm_layer(input, config.norm, fn, config.ffn, prefix)
+ : make_post_norm_layer(input, config.norm, fn, config.ffn, prefix);
+ };
+
auto current =
make_transformer_layers(hidden_states,
config.num_layers,
"model.layers.",
[&](const ov::Output<ov::Node>& input, const std::string& prefix, size_t layer) {
+ if (config.is_linear_layer && config.is_linear_layer(layer)) {
+ return build_linear_layer(input, prefix, layer);
+ }
// Per-layer mask: N sliding layers then 1 full, repeating.
if (has_sliding && config.sliding_to_full_ratio > 0) {
const size_t cycle = config.sliding_to_full_ratio + 1;
attn.sdpa_mask = (layer % cycle == cycle - 1) ? full_mask : sliding_mask;
}
- if (config.pre_norm) {
- return make_pre_norm_layer(
- input,
- config.norm,
- [&](const ov::Output<ov::Node>& normed, const std::string& pfx) {
- return attn(normed, {}, pfx, layer);
- },
- config.ffn,
- prefix);
- } else {
- return make_post_norm_layer(
- input,
- config.norm,
- [&](const ov::Output<ov::Node>& inp, const std::string& pfx) {
- return attn(inp, {}, pfx, layer);
- },
- config.ffn,
- prefix);
- }
+ return build_full_attn_layer(input, prefix, layer);
});
auto final_norm = config.norm(current, "model.norm");
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hpp
index 9a494f7a617..937cb50cf21 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hpp
@@ -176,6 +176,14 @@ struct LLMConfig : public BaseModelConfig {
bool pre_norm = true;
bool force_gqa_broadcast = false; ///< force 5-input SDPA (needed for SDPA isolation pattern matching)
+ /// Qwen3.5-style gated attention: q_proj is 2x wide ([q | gate] per head) and
+ /// Sigmoid(gate) scales the flattened SDPA output before o_proj.
+ bool attn_output_gate = false;
+
+ /// Partial RoPE: rotate only the first rotary_dim of each head (0 = full head_dim).
+ /// Only applies when build_llm auto-creates the RoPE functor.
+ size_t rotary_dim = 0;
+
// MoE configuration (num_experts=0 means dense, no MoE)
size_t num_experts = 0; ///< Total experts. 0 = dense model.
size_t num_experts_per_tok = 0; ///< Top-K. 0 = default to 2.
@@ -188,6 +196,14 @@ struct LLMConfig : public BaseModelConfig {
size_t sliding_to_full_ratio = 0;
bool use_token_type_ids = false; ///< Gemma 3 VLM: token_type_ids param (0=text/causal, 1=image/bidir)
SlidingMaskFn sliding_mask_fn; ///< Empty = default float SWA (matches no NPUW pass; set make_sliding_window_mask_phi3 for Phi-3/Gemma-2/Gemma-3).
+
+ /// Hybrid scheduling. Empty predicate (or null linear_mixer) = pure attention. Layers where it
+ /// returns true use linear_mixer, the rest use full SDPA. Hybrid models require use_kv_cache = true.
+ std::function<bool(size_t /*layer_idx*/)> is_linear_layer;
+
+ /// Token mixer for linear layers (e.g. GatedDeltaNetMixer or ShortConvMixer). build_llm wires
+ /// its seq_source/beam_idx. A new mixer type needs no build_llm change.
+ std::shared_ptr<LinearMixer> linear_mixer;
};
struct WhisperConfig : public BaseModelConfig {
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_attention.cpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_attention.cpp
index 8f1511e235a..79bae1cbf6a 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_attention.cpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_attention.cpp
@@ -4,10 +4,16 @@
#include "model_builder_attention.hpp"
+#include <algorithm>
#include <cmath>
+#include <cstdint>
+#include <utility>
#include <vector>
#include "model_builder.hpp"
+#include "model_builder_internal.hpp"
+#include "model_builder_norm.hpp"
+#include "openvino/op/loop.hpp"
#include "openvino/op/ops.hpp"
#include "openvino/op/util/variable.hpp"
#include "openvino/opsets/opset11.hpp"
@@ -16,6 +22,14 @@ namespace ov {
namespace test {
namespace npuw {
+namespace {
+// Transpose perm {0, 2, 1}: swap the last two axes of a 3D tensor (e.g. [B,seq,C] <-> [B,C,seq]).
+// Reused across the conv/SSM layout swaps below.
+std::shared_ptr<ov::Node> swap_last_two_axes_perm() {
+ return ov::opset11::Constant::create(ov::element::i64, ov::Shape{3}, {0, 2, 1});
+}
+} // namespace
+
ov::Output<ov::Node> make_multihead_reshape(const ov::Output<ov::Node>& input,
size_t num_heads,
size_t head_dim,
@@ -240,19 +254,30 @@ ov::Output<ov::Node> make_sdpa(const ov::Output<ov::Node>& q,
ov::Output<ov::Node> make_attention_output(const ov::Output<ov::Node>& sdpa_output,
size_t hidden_size,
+ size_t attn_dim,
const std::string& name,
ov::element::Type precision,
const WeightFn& weight_fn,
- const WeightFn& bias_fn) {
+ const WeightFn& bias_fn,
+ const ov::Output<ov::Node>& output_gate) {
auto attn_trans = make_attention_transpose(sdpa_output, name + "_transpose");
auto reshape_shape = ov::opset11::Constant::create(ov::element::i64,
ov::Shape{3},
- std::vector<int64_t>{0, -1, static_cast<int64_t>(hidden_size)});
+ std::vector<int64_t>{0, -1, static_cast<int64_t>(attn_dim)});
auto attn_reshaped = std::make_shared<ov::opset11::Reshape>(attn_trans, reshape_shape, true);
attn_reshaped->set_friendly_name(name + "_reshape");
- return make_linear(attn_reshaped->output(0), hidden_size, hidden_size, name, precision, weight_fn, bias_fn);
+ ov::Output<ov::Node> o_proj_in = attn_reshaped->output(0);
+ if (output_gate.get_node()) {
+ auto sig = std::make_shared<ov::opset11::Sigmoid>(output_gate);
+ sig->set_friendly_name(name + "_gate_sigmoid");
+ auto gated = std::make_shared<ov::opset11::Multiply>(o_proj_in, sig);
+ gated->set_friendly_name(name + "_gated");
+ o_proj_in = gated->output(0);
+ }
+
+ return make_linear(o_proj_in, attn_dim, hidden_size, name, precision, weight_fn, bias_fn);
}
ov::Output<ov::Node> Attention::operator()(const ov::Output<ov::Node>& q,
@@ -260,7 +285,32 @@ ov::Output<ov::Node> Attention::operator()(const ov::Output<ov::Node>& q,
const ov::Output<ov::Node>& v,
const std::string& prefix,
size_t layer_idx) const {
- auto q_reshaped = make_multihead_reshape(q, num_heads, head_dim, prefix + attn_prefix + "q_reshape");
+ // Gated attention (Qwen3.5): q carries [q | gate] per head — reshape to
+ // [B, S, H, 2D], split into the attention half and the flat output gate.
+ ov::Output<ov::Node> q_reshaped;
+ ov::Output<ov::Node> gate_flat;
+ if (output_gate) {
+ auto qg = make_multihead_reshape(q, num_heads, 2 * head_dim, prefix + attn_prefix + "q_gate_reshape");
+ auto split_lens = ov::opset11::Constant::create(ov::element::i64,
+ ov::Shape{2},
+ std::vector<int64_t>(2, static_cast<int64_t>(head_dim)));
+ auto qg_split = std::make_shared<ov::opset11::VariadicSplit>(
+ qg,
+ ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {-1}),
+ split_lens);
+ qg_split->set_friendly_name(prefix + attn_prefix + "q_gate_split");
+ q_reshaped = qg_split->output(0);
+
+ auto gate_shape =
+ ov::opset11::Constant::create(ov::element::i64,
+ ov::Shape{3},
+ std::vector<int64_t>{0, 0, static_cast<int64_t>(num_heads * head_dim)});
+ auto gate_reshaped = std::make_shared<ov::opset11::Reshape>(qg_split->output(1), gate_shape, true);
+ gate_reshaped->set_friendly_name(prefix + attn_prefix + "gate_flat");
+ gate_flat = gate_reshaped->output(0);
+ } else {
+ q_reshaped = make_multihead_reshape(q, num_heads, head_dim, prefix + attn_prefix + "q_reshape");
+ }
auto k_reshaped = make_multihead_reshape(k, num_kv_heads, head_dim, prefix + attn_prefix + "k_reshape");
auto v_reshaped = make_multihead_reshape(v, num_kv_heads, head_dim, prefix + attn_prefix + "v_reshape");
@@ -299,7 +349,14 @@ ov::Output<ov::Node> Attention::operator()(const ov::Output<ov::Node>& q,
auto attn_output =
make_sdpa(q_roped, k_expanded, v_expanded, prefix + attn_prefix + "attn", sdpa_mask, sdpa_scale_dim);
- return make_attention_output(attn_output, hidden_size, prefix + o_proj_name, precision, weight_fn, bias_fn);
+ return make_attention_output(attn_output,
+ hidden_size,
+ num_heads * head_dim,
+ prefix + o_proj_name,
+ precision,
+ weight_fn,
+ bias_fn,
+ gate_flat);
}
ov::Output<ov::Node> Attention::operator()(const ov::Output<ov::Node>& input,
@@ -307,14 +364,514 @@ ov::Output<ov::Node> Attention::operator()(const ov::Output<ov::Node>& input,
const std::string& prefix,
size_t layer_idx) const {
auto kv_src = kv_input.get_node() ? kv_input : input;
+ size_t q_dim = (output_gate ? 2 : 1) * num_heads * head_dim;
size_t kv_dim = num_kv_heads * head_dim;
- auto q =
- make_linear(input, hidden_size, hidden_size, prefix + attn_prefix + "q_proj", precision, weight_fn, bias_fn);
+ auto q = make_linear(input, hidden_size, q_dim, prefix + attn_prefix + "q_proj", precision, weight_fn, bias_fn);
auto k = make_linear(kv_src, hidden_size, kv_dim, prefix + attn_prefix + "k_proj", precision, weight_fn, bias_fn);
auto v = make_linear(kv_src, hidden_size, kv_dim, prefix + attn_prefix + "v_proj", precision, weight_fn, bias_fn);
return (*this)(q, k, v, prefix, layer_idx);
}
+FixedStateResult make_fixed_state(const ov::Output<ov::Node>& batch_source,
+ const std::vector<int64_t>& state_dims,
+ const std::string& name,
+ ov::element::Type precision,
+ const ov::Output<ov::Node>& beam_idx) {
+ std::vector<int64_t> var_shape_vec = {-1};
+ var_shape_vec.insert(var_shape_vec.end(), state_dims.begin(), state_dims.end());
+ auto var_shape = ov::PartialShape(var_shape_vec);
+ auto variable = std::make_shared<ov::op::util::Variable>(ov::op::util::VariableInfo{var_shape, precision, name});
+
+ auto shape_of = std::make_shared<ov::opset11::ShapeOf>(batch_source, ov::element::i64);
+ shape_of->set_friendly_name(name + "_shapeof");
+ auto zero_idx = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {0});
+ auto gather_axis = ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {0});
+ auto batch_dim = std::make_shared<ov::opset11::Gather>(shape_of, zero_idx, gather_axis);
+ batch_dim->set_friendly_name(name + "_batch_dim");
+
+ auto dims_const = ov::opset11::Constant::create(ov::element::i64, ov::Shape{state_dims.size()}, state_dims);
+ auto init_shape =
+ std::make_shared<ov::opset11::Concat>(ov::OutputVector{batch_dim->output(0), dims_const->output(0)}, 0);
+ init_shape->set_friendly_name(name + "_init_shape");
+
+ auto zero_scalar = ov::opset11::Constant::create(precision, ov::Shape{}, {0.0f});
+ auto init_value = std::make_shared<ov::opset11::Broadcast>(zero_scalar, init_shape);
+ init_value->set_friendly_name(name + "_init");
+
+ auto read_value = std::make_shared<ov::op::v6::ReadValue>(init_value, variable);
+ read_value->set_friendly_name(name + "_read");
+
+ ov::Output<ov::Node> output = read_value->output(0);
+ if (beam_idx.get_node()) {
+ auto beam_gather = std::make_shared<ov::opset11::Gather>(
+ output, beam_idx, ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {0}));
+ beam_gather->set_friendly_name(name + "_beam_gather");
+ output = beam_gather->output(0);
+ }
+
+ return {variable, output};
+}
+
+namespace {
+// Depthwise conv weight [channels, 1, 1, kernel], in the requested topology.
+// PlainFloat: Const(prec)→(Convert) — matches LFM2's f16→f32 conv weight.
+// U8Decompress: u8→Convert→Subtract(zp)→Multiply(scale) — matches the Qwen3.5/DCOFF path.
+ov::Output<ov::Node> make_conv_weight(size_t channels,
+ size_t kernel_size,
+ const std::string& w_name,
+ ov::element::Type prec,
+ ConvWeightMode mode) {
+ const ov::Shape w_shape{channels, 1, 1, kernel_size};
+
+ if (mode == ConvWeightMode::PlainFloat) {
+ // f16 storage Const -> Convert(compute precision), mirroring LFM2's exported conv weight.
+ uint32_t state = seed_from_name(w_name);
+ std::vector<float> vals(channels * kernel_size);
+ for (auto& v : vals) {
+ v = 0.05f + 0.01f * static_cast<float>(xorshift32(state) % 1000u) / 1000.0f;
+ }
+ auto w_const = ov::opset11::Constant::create(ov::element::f16, w_shape, vals);
+ w_const->set_friendly_name(w_name);
+ if (prec == ov::element::f16) {
+ return w_const->output(0);
+ }
+ auto w_cvt = std::make_shared<ov::opset11::Convert>(w_const, prec);
+ w_cvt->set_friendly_name(w_name + "/convert");
+ return w_cvt->output(0);
+ }
+
+ // Decompression math stays in f16 (as exported), with a trailing Convert when the
+ // compute precision differs — real chain: u8 -> f16 -> Sub -> Mul -> Convert(f32).
+ const auto dec_prec = ov::element::f16;
+ const ov::Shape zs_shape{channels, 1, 1, 1};
+ uint32_t w_state = seed_from_name(w_name);
+ std::vector<uint8_t> w_u8(channels * kernel_size);
+ for (auto& w : w_u8) {
+ w = static_cast<uint8_t>(128 + (xorshift32(w_state) % 32u));
+ }
+ auto w_const = ov::opset11::Constant::create(ov::element::u8, w_shape, w_u8);
+ w_const->set_friendly_name(w_name);
+ auto w_cvt = std::make_shared<ov::opset11::Convert>(w_const, dec_prec);
+ w_cvt->set_friendly_name(w_name + "/convert");
+
+ std::vector<uint8_t> zp_u8(channels, static_cast<uint8_t>(128));
+ auto zp_const = ov::opset11::Constant::create(ov::element::u8, zs_shape, zp_u8);
+ zp_const->set_friendly_name(w_name + "/zero_point");
+ auto zp_cvt = std::make_shared<ov::opset11::Convert>(zp_const, dec_prec);
+ zp_cvt->set_friendly_name(w_name + "/zero_point/convert");
+
+ auto w_sub = std::make_shared<ov::opset11::Subtract>(w_cvt, zp_cvt);
+ w_sub->set_friendly_name(w_name + "/subtract");
+
+ uint32_t s_state = seed_from_name(w_name + "_scale");
+ std::vector<float> sc_vals(channels);
+ for (auto& s : sc_vals) {
+ s = 0.05f + 0.01f * static_cast<float>(xorshift32(s_state) % 1000u) / 1000.0f;
+ }
+ auto sc_const = ov::opset11::Constant::create(dec_prec, zs_shape, sc_vals);
+ sc_const->set_friendly_name(w_name + "/scale");
+ auto weight = std::make_shared<ov::opset11::Multiply>(w_sub, sc_const);
+ weight->set_friendly_name(w_name + "/decompress");
+ if (prec == dec_prec) {
+ return weight->output(0);
+ }
+ auto out_cvt = std::make_shared<ov::opset11::Convert>(weight, prec);
+ out_cvt->set_friendly_name(w_name + "/decompress/convert");
+ return out_cvt->output(0);
+}
+} // namespace
+
+CausalConvResult make_causal_conv(const ov::Output<ov::Node>& input,
+ const ov::Output<ov::Node>& seq_source,
+ const ov::Output<ov::Node>& beam_idx,
+ const std::string& state_name,
+ const std::string& prefix,
+ const CausalConvConfig& cfg) {
+ const auto channels = cfg.channels;
+ const auto kernel_size = cfg.kernel_size;
+
+ // GDN feeds [batch, seq, C] and transposes here; LFM2 transposes before its B/C/x
+ // split, so its input is already channel-first.
+ ov::Output<ov::Node> input_cf = input;
+ if (!cfg.channel_first) {
+ auto input_t = std::make_shared<ov::opset11::Transpose>(input, swap_last_two_axes_perm());
+ input_t->set_friendly_name(prefix + "transpose_in");
+ input_cf = input_t->output(0);
+ }
+
+ auto state = make_fixed_state(seq_source,
+ {static_cast<int64_t>(channels), static_cast<int64_t>(kernel_size)},
+ state_name,
+ cfg.precision,
+ beam_idx);
+
+ auto cat = std::make_shared<ov::opset11::Concat>(ov::OutputVector{state.read_value, input_cf}, 2);
+ cat->set_friendly_name(prefix + "concat");
+
+ // State update: keep last kernel_size positions.
+ auto new_state = std::make_shared<ov::op::v8::Slice>(
+ cat,
+ ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {-static_cast<int64_t>(kernel_size)}),
+ ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {INT64_MAX}),
+ ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {1}),
+ ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {2}));
+ new_state->set_friendly_name(prefix + "new_state");
+ auto assign = std::make_shared<ov::op::v6::Assign>(new_state, state.variable);
+ assign->set_friendly_name(state_name + "_assign");
+
+ auto weight = make_conv_weight(channels, kernel_size, prefix + "conv_weight", cfg.precision, cfg.weight_mode);
+
+ auto conv = std::make_shared<ov::opset11::GroupConvolution>(cat->output(0),
+ weight,
+ ov::Strides{1},
+ ov::CoordinateDiff{0},
+ ov::CoordinateDiff{0},
+ ov::Strides{1});
+ conv->set_friendly_name(prefix + "group_conv");
+
+ // Keep the last seq_len outputs. Exports compute the start as -seq_len at runtime
+ // (vs an equivalent static 1) — mirror that so the Slice subgraph shape matches.
+ auto in_shape = std::make_shared<ov::opset11::ShapeOf>(input_cf, ov::element::i64);
+ in_shape->set_friendly_name(prefix + "shapeof");
+ auto seq_dim =
+ std::make_shared<ov::opset11::Gather>(in_shape,
+ ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {2}),
+ ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {0}));
+ seq_dim->set_friendly_name(prefix + "seq_dim");
+ auto neg_seq =
+ std::make_shared<ov::opset11::Multiply>(seq_dim,
+ ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {-1}));
+ neg_seq->set_friendly_name(prefix + "neg_seq");
+
+ auto sliced =
+ std::make_shared<ov::op::v8::Slice>(conv,
+ neg_seq,
+ ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {INT64_MAX}),
+ ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {1}),
+ ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {2}));
+ sliced->set_friendly_name(prefix + "sliced");
+
+ ov::Output<ov::Node> conv_out = sliced->output(0);
+ if (cfg.activation == ConvActivation::SiLU) {
+ auto activated = std::make_shared<ov::opset11::Swish>(sliced);
+ activated->set_friendly_name(prefix + "silu");
+ conv_out = activated->output(0);
+ }
+
+ if (!cfg.channel_first) {
+ auto output = std::make_shared<ov::opset11::Transpose>(conv_out, swap_last_two_axes_perm());
+ output->set_friendly_name(prefix + "transpose_out");
+ conv_out = output->output(0);
+ }
+
+ CausalConvResult result;
+ result.output = conv_out;
+ result.assign = assign;
+ return result;
+}
+
+// GatedDeltaNet delta rule, one timestep per Loop iteration (replicates the Qwen3.5
+// export's Loop body op-for-op):
+// gated_state = h_prev * exp(gate); delta = v - sum(gated_state * k, -2)
+// h_new = gated_state + k * (delta * beta); output = sum(h_new * q, -2)
+static std::shared_ptr<ov::Model> build_ssm_loop_body(ov::element::Type prec,
+ int64_t H,
+ int64_t Dk,
+ int64_t Dv,
+ ov::ParameterVector& params,
+ ov::ResultVector& results) {
+ auto P = [&](ov::element::Type t, ov::PartialShape s) {
+ return params.emplace_back(std::make_shared<ov::op::v0::Parameter>(t, s));
+ };
+ auto iter = P(ov::element::i32, ov::PartialShape{});
+ auto q = P(prec, {-1, H, 1, Dk});
+ auto k = P(prec, {-1, H, 1, Dk});
+ auto v = P(prec, {-1, H, 1, Dv});
+ auto gate = P(prec, {-1, H, 1});
+ auto beta = P(prec, {-1, H, 1});
+ auto h = P(prec, {-1, H, Dk, Dv});
+ auto out_buf = P(prec, {-1, H, -1, Dv});
+
+ auto axis_1d = [](int64_t val) {
+ return ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {val});
+ };
+
+ auto gate_exp = std::make_shared<ov::opset11::Exp>(gate);
+ auto gate_bc = std::make_shared<ov::opset11::Unsqueeze>(gate_exp, axis_1d(-1));
+ auto gated_state = std::make_shared<ov::opset11::Multiply>(h, gate_bc);
+
+ auto k_sq = std::make_shared<ov::opset11::Squeeze>(k, axis_1d(2));
+ auto k_u = std::make_shared<ov::opset11::Unsqueeze>(k_sq, axis_1d(-1));
+
+ auto proj_mul = std::make_shared<ov::opset11::Multiply>(gated_state, k_u);
+ auto proj_sum = std::make_shared<ov::opset11::ReduceSum>(proj_mul, axis_1d(-2), false);
+
+ auto v_sq = std::make_shared<ov::opset11::Squeeze>(v, axis_1d(2));
+ auto delta = std::make_shared<ov::opset11::Subtract>(v_sq, proj_sum);
+
+ auto scaled_delta = std::make_shared<ov::opset11::Multiply>(delta, beta);
+ auto sd_u = std::make_shared<ov::opset11::Unsqueeze>(scaled_delta, axis_1d(-2));
+ auto outer_update = std::make_shared<ov::opset11::Multiply>(k_u, sd_u);
+
+ auto h_new = std::make_shared<ov::opset11::Add>(gated_state, outer_update);
+
+ auto q_sq = std::make_shared<ov::opset11::Squeeze>(q, axis_1d(2));
+ auto q_u = std::make_shared<ov::opset11::Unsqueeze>(q_sq, axis_1d(-1));
+ auto out_mul = std::make_shared<ov::opset11::Multiply>(h_new, q_u);
+ auto y = std::make_shared<ov::opset11::ReduceSum>(out_mul, axis_1d(-2), true);
+
+ // Scatter y into out_buf at seq position = iter.
+ auto iter_idx = std::make_shared<ov::opset11::Unsqueeze>(iter, axis_1d(0));
+ auto scatter_axis = ov::opset11::Constant::create(ov::element::i32, ov::Shape{}, {2});
+ auto out_new = std::make_shared<ov::opset11::ScatterUpdate>(out_buf, iter_idx, y, scatter_axis);
+
+ results = {
+ std::make_shared<ov::op::v0::Result>(
+ ov::opset11::Constant::create(ov::element::boolean, ov::Shape{}, {true})),
+ std::make_shared<ov::op::v0::Result>(h_new),
+ std::make_shared<ov::op::v0::Result>(out_new),
+ };
+ return std::make_shared<ov::Model>(results, params);
+}
+
+RecurrentStateResult make_recurrent_state(const RecurrentStateInputs& inputs,
+ const RecurrentStateDims& dims,
+ const ov::Output<ov::Node>& seq_source,
+ const ov::Output<ov::Node>& beam_idx,
+ const std::string& state_name,
+ const std::string& prefix,
+ ov::element::Type prec) {
+ const auto H = static_cast<int64_t>(dims.num_heads);
+ const auto Dk = static_cast<int64_t>(dims.key_head_dim);
+ const auto Dv = static_cast<int64_t>(dims.value_head_dim);
+
+ auto state = make_fixed_state(seq_source, {H, Dk, Dv}, state_name, prec, beam_idx);
+
+ // q/k/v arrive per-head [batch, seq, H, D] (q/k already L2-normed by the caller,
+ // as in the real export) — only the [B,H,seq,D] loop layout transpose happens here.
+ auto q_t = make_attention_transpose(inputs.query, prefix + "q_mh");
+ auto k_mh = make_attention_transpose(inputs.key, prefix + "k_mh");
+ auto v_mh = make_attention_transpose(inputs.value, prefix + "v_mh");
+
+ // q is scaled by key_head_dim^-0.5 before entering the Loop. The export computes
+ // sqrt(head_dim) dynamically: ShapeOf -> Gather(3) -> Convert -> Power(0.5) -> Divide.
+ auto q_shape = std::make_shared<ov::opset11::ShapeOf>(q_t, ov::element::i64);
+ q_shape->set_friendly_name(prefix + "q_shapeof");
+ auto q_head_dim =
+ std::make_shared<ov::opset11::Gather>(q_shape,
+ ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {3}),
+ ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {0}));
+ q_head_dim->set_friendly_name(prefix + "q_head_dim");
+ auto q_head_dim_f = std::make_shared<ov::opset11::Convert>(q_head_dim, prec);
+ q_head_dim_f->set_friendly_name(prefix + "q_head_dim_f");
+ auto sqrt_head_dim =
+ std::make_shared<ov::opset11::Power>(q_head_dim_f, ov::opset11::Constant::create(prec, ov::Shape{}, {0.5f}));
+ sqrt_head_dim->set_friendly_name(prefix + "sqrt_head_dim");
+ auto q_mh = std::make_shared<ov::opset11::Divide>(q_t, sqrt_head_dim)->output(0);
+ q_mh.get_node()->set_friendly_name(prefix + "q_scaled");
+
+ // gate/beta: [batch, seq, H] -> [batch, H, seq]
+ auto gate_mh = std::make_shared<ov::opset11::Transpose>(inputs.gate, swap_last_two_axes_perm());
+ auto beta_mh = std::make_shared<ov::opset11::Transpose>(inputs.beta, swap_last_two_axes_perm());
+
+ auto seq_len = std::make_shared<ov::opset11::Gather>(
+ std::make_shared<ov::opset11::ShapeOf>(q_mh, ov::element::i64),
+ ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {2}),
+ ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {0}));
+
+ ov::ParameterVector bp;
+ ov::ResultVector br;
+ auto body = build_ssm_loop_body(prec, H, Dk, Dv, bp, br);
+ // bp: [iter, q, k, v, gate, beta, h, out_buf] br: [cond, h_new, out_new]
+
+ auto loop = std::make_shared<ov::op::v5::Loop>(
+ seq_len, ov::opset11::Constant::create(ov::element::boolean, ov::Shape{}, {true}));
+ loop->set_function(body);
+ loop->set_special_body_ports({0, 0});
+
+ auto v_shape = std::make_shared<ov::opset11::ShapeOf>(v_mh, ov::element::i64);
+ auto zero_scalar = ov::opset11::Constant::create(prec, ov::Shape{}, {0.0f});
+ auto out_init = std::make_shared<ov::op::v3::Broadcast>(zero_scalar, v_shape);
+ out_init->set_friendly_name(prefix + "out_init");
+
+ ov::OutputVector sliced_srcs = {q_mh, k_mh, v_mh, gate_mh, beta_mh};
+ for (size_t i = 0; i < sliced_srcs.size(); ++i)
+ loop->set_sliced_input(bp[i + 1], sliced_srcs[i], 0, 1, 1, -1, 2);
+
+ loop->set_merged_input(bp[6], state.read_value, br[1]); // h back-edge
+ loop->set_merged_input(bp[7], out_init, br[2]); // out_buf back-edge
+
+ auto output = loop->get_iter_value(br[2], -1); // [batch, H, seq, Dv]
+ auto final_h = loop->get_iter_value(br[1], -1); // [batch, H, Dk, Dv]
+ loop->set_friendly_name(prefix + "loop");
+
+ auto assign = std::make_shared<ov::op::v6::Assign>(final_h, state.variable);
+ assign->set_friendly_name(state_name + "_assign");
+
+ auto out_t = make_attention_transpose(output, prefix + "output");
+
+ RecurrentStateResult result;
+ result.output = out_t;
+ result.assign = assign;
+ return result;
+}
+
+std::function<bool(size_t)> make_mamba_schedule(size_t mamba_ratio) {
+ if (mamba_ratio == 0)
+ return {};
+ return [mamba_ratio](size_t layer_idx) {
+ return (layer_idx % (mamba_ratio + 1)) < mamba_ratio;
+ };
+}
+
+std::function<bool(size_t)> make_schedule_with_attention_at(std::vector<size_t> attn_layers) {
+ return [attn = std::move(attn_layers)](size_t layer_idx) {
+ return std::find(attn.begin(), attn.end(), layer_idx) == attn.end();
+ };
+}
+
+// B, C, x — the three equal-width gates an LFM2 in_proj splits into.
+static constexpr size_t kShortConvGates = 3;
+
+MixerResult ShortConvMixer::build(const ov::Output<ov::Node>& input,
+ const std::string& prefix,
+ size_t linear_layer_idx) const {
+ auto layer_str = std::to_string(linear_layer_idx);
+ auto ap = prefix + "conv.";
+ const auto cd = static_cast<int64_t>(conv_dim);
+
+ // in_proj: hidden -> 3*conv_dim. The export transposes to channel-first FIRST and
+ // splits B, C, x on the channel axis — all gating then happens in [B, C, seq].
+ auto in_proj = make_linear(input, hidden_size, kShortConvGates * conv_dim, ap + "in_proj", precision, weight_fn);
+ auto in_proj_t = std::make_shared<ov::opset11::Transpose>(in_proj, swap_last_two_axes_perm());
+ in_proj_t->set_friendly_name(ap + "transpose_in");
+ auto split_lens = ov::opset11::Constant::create(ov::element::i64,
+ ov::Shape{kShortConvGates},
+ std::vector<int64_t>(kShortConvGates, cd));
+ auto bcx =
+ std::make_shared<ov::opset11::VariadicSplit>(in_proj_t,
+ ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {1}),
+ split_lens);
+ bcx->set_friendly_name(ap + "split");
+
+ // Bx = B * x, then causal conv (no activation — gating is external), then C * conv.
+ auto bx = std::make_shared<ov::opset11::Multiply>(bcx->output(0), bcx->output(2));
+ bx->set_friendly_name(ap + "B_mul_x");
+
+ CausalConvConfig conv_cfg;
+ conv_cfg.channels = conv_dim;
+ conv_cfg.kernel_size = conv_kernel;
+ conv_cfg.precision = precision;
+ conv_cfg.activation = ConvActivation::None;
+ conv_cfg.weight_mode = ConvWeightMode::PlainFloat; // LFM2 conv weight is f16 Const -> Convert.
+ conv_cfg.channel_first = true;
+ auto conv = make_causal_conv(bx, seq_source, beam_idx, make_cache_params_var_id("conv", layer_str), ap, conv_cfg);
+
+ auto gated = std::make_shared<ov::opset11::Multiply>(bcx->output(1), conv.output);
+ gated->set_friendly_name(ap + "C_mul_conv");
+
+ // The export folds the [B, C, seq] -> [B, seq, C] layout swap into out_proj via
+ // transpose_a=true — there is no output Transpose op.
+ auto out_w = weight_fn(ap + "out_proj.weight", ov::Shape{hidden_size, conv_dim}, precision);
+ auto output = std::make_shared<ov::opset11::MatMul>(gated, out_w, true, true);
+ output->set_friendly_name(ap + "out_proj");
+ return {output->output(0), {std::dynamic_pointer_cast<ov::op::Sink>(conv.assign)}};
+}
+
+MixerResult GatedDeltaNetMixer::build(const ov::Output<ov::Node>& input,
+ const std::string& prefix,
+ size_t linear_layer_idx) const {
+ const auto kd = key_dim();
+ const auto vd = value_dim();
+ const auto cd = conv_dim();
+ auto layer_str = std::to_string(linear_layer_idx);
+ auto ap = prefix + "linear_attn.";
+
+ auto qkv = make_linear(input, hidden_size, cd, ap + "in_proj_qkv", precision, weight_fn);
+ auto a_proj = make_linear(input, hidden_size, num_heads, ap + "in_proj_a", precision, weight_fn);
+ auto a_bias = weight_fn(ap + "in_proj_a.bias", ov::Shape{1, 1, num_heads}, precision);
+ auto a_biased = std::make_shared<ov::opset11::Add>(a_proj, a_bias);
+ a_biased->set_friendly_name(ap + "in_proj_a_biased");
+ auto b_proj = make_linear(input, hidden_size, num_heads, ap + "in_proj_b", precision, weight_fn);
+ auto z_proj = make_linear(input, hidden_size, vd, ap + "in_proj_z", precision, weight_fn);
+
+ CausalConvConfig conv_cfg;
+ conv_cfg.channels = cd;
+ conv_cfg.kernel_size = conv_kernel;
+ conv_cfg.precision = precision;
+ conv_cfg.activation = ConvActivation::SiLU;
+ conv_cfg.weight_mode = ConvWeightMode::U8Decompress;
+ auto conv =
+ make_causal_conv(qkv, seq_source, beam_idx, make_cache_params_var_id("conv", layer_str), ap + "conv.", conv_cfg);
+
+ // QKV split: [batch, seq, conv_dim] -> Q[key_dim], K[key_dim], V[value_dim].
+ OPENVINO_ASSERT(2 * kd + vd == cd, "GatedDeltaNet conv_dim must equal 2*key_dim + value_dim");
+ auto split_lens = ov::opset11::Constant::create(
+ ov::element::i64,
+ ov::Shape{3},
+ std::vector<int64_t>{static_cast<int64_t>(kd), static_cast<int64_t>(kd), static_cast<int64_t>(vd)});
+ auto qkv_split = std::make_shared<ov::opset11::VariadicSplit>(
+ conv.output, ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {-1}), split_lens);
+ qkv_split->set_friendly_name(ap + "qkv_split");
+
+ // Per-head reshape happens BEFORE the q/k norm — the export L2-normalizes each
+ // head's key_head_dim slice, not the flat key_dim.
+ auto q_heads = make_multihead_reshape(qkv_split->output(0), num_heads, key_head_dim, ap + "q_rs");
+ auto k_heads = make_multihead_reshape(qkv_split->output(1), num_heads, key_head_dim, ap + "k_rs");
+ auto v_heads = make_multihead_reshape(qkv_split->output(2), num_heads, value_head_dim, ap + "v_rs");
+
+ NormFn qk = qk_norm ? qk_norm : NormFn(L2Norm(precision));
+ auto q = qk(q_heads, ap + "q_l2norm");
+ auto k = qk(k_heads, ap + "k_l2norm");
+
+ // Gate: -exp(A_log) * SoftPlus(a + dt_bias) — per-head decay. The -exp(A_log)
+ // factor is a folded per-head Const in the export (per-timestep Exp lives in the
+ // Loop body). Negative magnitudes stand in for the folded values.
+ auto sp = std::make_shared<ov::opset11::SoftPlus>(a_biased);
+ sp->set_friendly_name(ap + "softplus");
+ uint32_t a_state = seed_from_name(ap + "a_log");
+ std::vector<float> a_decay(num_heads);
+ for (auto& a : a_decay) {
+ a = -(0.5f + static_cast<float>(xorshift32(a_state) % 1000u) / 1000.0f);
+ }
+ auto a_decay_const = ov::opset11::Constant::create(precision, ov::Shape{num_heads}, a_decay);
+ a_decay_const->set_friendly_name(ap + "neg_exp_a_log");
+ auto gdn_gate = std::make_shared<ov::opset11::Multiply>(a_decay_const, sp);
+ gdn_gate->set_friendly_name(ap + "gate");
+
+ // Beta: Sigmoid(b) — delta scaling.
+ auto gdn_beta = std::make_shared<ov::opset11::Sigmoid>(b_proj);
+ gdn_beta->set_friendly_name(ap + "beta");
+
+ RecurrentStateInputs ssm_inputs{q, k, v_heads, gdn_gate->output(0), gdn_beta->output(0)};
+ RecurrentStateDims ssm_dims{num_heads, key_head_dim, value_head_dim};
+ auto ssm = make_recurrent_state(ssm_inputs, ssm_dims, seq_source, beam_idx,
+ make_cache_params_var_id("ssm", layer_str), ap + "ssm.", precision);
+
+ // Flatten heads: [batch, seq, num_heads, value_head_dim] -> [batch, seq, value_dim].
+ auto flat = std::make_shared<ov::opset11::Reshape>(
+ ssm.output,
+ ov::opset11::Constant::create(ov::element::i64,
+ ov::Shape{3},
+ std::vector<int64_t>{0, 0, static_cast<int64_t>(vd)}),
+ true);
+ flat->set_friendly_name(ap + "flat");
+
+ // Output gating: Swish(z) * Norm(output). out_norm defaults to RMSNorm over value_dim.
+ NormFn norm = out_norm ? out_norm : NormFn(RMSNorm(vd, precision));
+ auto normed = norm(flat->output(0), ap + "norm");
+ auto z_gate = std::make_shared<ov::opset11::Swish>(z_proj);
+ z_gate->set_friendly_name(ap + "z_gate");
+ auto out_gated = std::make_shared<ov::opset11::Multiply>(z_gate, normed);
+ out_gated->set_friendly_name(ap + "out_gated");
+
+ auto output = make_linear(out_gated->output(0), vd, hidden_size, ap + "out_proj", precision, weight_fn);
+
+ return {output,
+ {std::dynamic_pointer_cast<ov::op::Sink>(conv.assign),
+ std::dynamic_pointer_cast<ov::op::Sink>(ssm.assign)}};
+}
+
} // namespace npuw
} // namespace test
} // namespace ov
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_attention.hpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_attention.hpp
index 7de2409082a..33f641d7939 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_attention.hpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_attention.hpp
@@ -4,11 +4,16 @@
#pragma once
+#include <functional>
+#include <memory>
#include <string>
+#include <vector>
#include "model_builder_types.hpp"
#include "openvino/core/node.hpp"
#include "openvino/core/type/element_type.hpp"
+#include "openvino/op/sink.hpp"
+#include "openvino/op/util/variable.hpp"
namespace ov {
namespace test {
@@ -65,12 +70,17 @@ ov::Output<ov::Node> make_sdpa(const ov::Output<ov::Node>& q,
const ov::Output<ov::Node>& attention_mask = ov::Output<ov::Node>(),
size_t head_dim_for_scale = 0);
+/// `attn_dim = num_heads * head_dim`. May differ from `hidden_size` for rectangular projections.
+/// `output_gate` (flat [batch, seq, attn_dim]) applies Sigmoid-gating between the flatten
+/// and the O projection, as in the Qwen3.5 gated-attention export.
ov::Output<ov::Node> make_attention_output(const ov::Output<ov::Node>& sdpa_output,
size_t hidden_size,
+ size_t attn_dim,
const std::string& name,
ov::element::Type precision,
const WeightFn& weight_fn,
- const WeightFn& bias_fn = {});
+ const WeightFn& bias_fn = {},
+ const ov::Output<ov::Node>& output_gate = {});
/// Takes pre-projected Q, K, V. Handles reshape, QK-norm, RoPE, KV cache, GQA, SDPA, O proj.
struct Attention {
@@ -85,6 +95,10 @@ struct Attention {
ov::Output<ov::Node> sdpa_mask;
ov::Output<ov::Node> shared_broadcast_shape;
+ /// Qwen3.5-style gated attention: q_proj carries [q | gate] per head (2x width),
+ /// split after the per-head reshape; Sigmoid(gate) scales the flattened SDPA output.
+ bool output_gate = false;
+
std::string o_proj_name = "self_attn.o_proj";
std::string attn_prefix = "self_attn.";
@@ -101,6 +115,150 @@ struct Attention {
size_t layer_idx = 0) const;
};
+/// Fixed-size state variable (recurrent/conv states — no sequence growth, optional beam reorder).
+struct FixedStateResult {
+ std::shared_ptr<ov::op::util::Variable> variable;
+ ov::Output<ov::Node> read_value;
+};
+
+FixedStateResult make_fixed_state(const ov::Output<ov::Node>& batch_source,
+ const std::vector<int64_t>& state_dims,
+ const std::string& name,
+ ov::element::Type precision = ov::element::f32,
+ const ov::Output<ov::Node>& beam_idx = {});
+
+/// Post-convolution activation. SiLU matches GatedDeltaNet exports; None matches LFM2 (gated externally).
+enum class ConvActivation { None, SiLU };
+
+/// Depthwise conv weight topology. PlainFloat (Const→Convert) matches LFM2; U8Decompress
+/// (u8→Convert→Subtract(zp)→Multiply(scale) in f16, then Convert) matches the Qwen3.5 export path.
+enum class ConvWeightMode { PlainFloat, U8Decompress };
+
+/// Causal depthwise convolution with sliding-window state.
+/// Input/output: [batch, seq, channels] ([batch, channels, seq] when channel_first).
+/// State: [batch, channels, kernel].
+struct CausalConvResult {
+ ov::Output<ov::Node> output; ///< same layout as input (post-activation)
+ std::shared_ptr<ov::Node> assign; ///< state update Assign
+};
+
+struct CausalConvConfig {
+ size_t channels = 0;
+ size_t kernel_size = 0;
+ ov::element::Type precision = ov::element::f32;
+ ConvActivation activation = ConvActivation::SiLU;
+ ConvWeightMode weight_mode = ConvWeightMode::U8Decompress;
+ /// Input/output already [batch, channels, seq] — skip the internal layout transposes.
+ /// LFM2 transposes before its B/C/x split; GDN feeds [batch, seq, channels].
+ bool channel_first = false;
+};
+
+CausalConvResult make_causal_conv(const ov::Output<ov::Node>& input,
+ const ov::Output<ov::Node>& seq_source,
+ const ov::Output<ov::Node>& beam_idx,
+ const std::string& state_name,
+ const std::string& prefix,
+ const CausalConvConfig& cfg);
+
+/// Recurrent SSM state via OV Loop. Body replicates the GDN delta rule of the
+/// Qwen3.5 export (op-for-op, including Loop port order and back-edges).
+struct RecurrentStateResult {
+ ov::Output<ov::Node> output; ///< [batch, seq, num_heads, value_head_dim]
+ std::shared_ptr<ov::Node> assign; ///< state update Assign
+};
+
+/// Per-timestep SSM inputs — grouped so callers can't transpose same-typed args.
+/// query/key: [batch, seq, H, key_head_dim] (already L2-normed per head);
+/// value: [batch, seq, H, value_head_dim]; gate/beta: [batch, seq, H].
+struct RecurrentStateInputs {
+ ov::Output<ov::Node> query;
+ ov::Output<ov::Node> key;
+ ov::Output<ov::Node> value;
+ ov::Output<ov::Node> gate;
+ ov::Output<ov::Node> beta;
+};
+
+struct RecurrentStateDims {
+ size_t num_heads = 0;
+ size_t key_head_dim = 0;
+ size_t value_head_dim = 0;
+};
+
+RecurrentStateResult make_recurrent_state(const RecurrentStateInputs& inputs,
+ const RecurrentStateDims& dims,
+ const ov::Output<ov::Node>& seq_source,
+ const ov::Output<ov::Node>& beam_idx,
+ const std::string& state_name,
+ const std::string& prefix,
+ ov::element::Type prec);
+
+/// Uniform result for any linear-token mixer. `sinks` already holds the state Assign nodes —
+/// the builder appends them with no knowledge of how many a given mixer produces.
+struct MixerResult {
+ ov::Output<ov::Node> output;
+ ov::SinkVector sinks;
+};
+
+/// Common runtime plumbing every linear mixer needs, wired once by build_llm.
+struct LinearMixer {
+ size_t hidden_size = 0;
+ ov::element::Type precision = ov::element::f32;
+ WeightFn weight_fn;
+
+ // Wired by the builder once for all layers.
+ ov::Output<ov::Node> seq_source;
+ ov::Output<ov::Node> beam_idx;
+
+ virtual ~LinearMixer() = default;
+
+ virtual MixerResult build(const ov::Output<ov::Node>& input,
+ const std::string& prefix,
+ size_t linear_layer_idx) const = 0;
+};
+
+/// GatedDeltaNet (Qwen3.5-style): causal conv + L2-normed Q/K + recurrent SSM + output gating.
+struct GatedDeltaNetMixer : LinearMixer {
+ size_t num_heads = 0;
+ size_t key_head_dim = 0;
+ size_t value_head_dim = 0;
+ size_t conv_kernel = 4;
+ NormFn qk_norm; ///< empty → L2Norm
+ NormFn out_norm; ///< empty → RMSNorm over value_dim()
+
+ size_t key_dim() const {
+ return num_heads * key_head_dim;
+ }
+ size_t value_dim() const {
+ return num_heads * value_head_dim;
+ }
+ size_t conv_dim() const {
+ return 2 * key_dim() + value_dim();
+ }
+
+ MixerResult build(const ov::Output<ov::Node>& input,
+ const std::string& prefix,
+ size_t linear_layer_idx) const override;
+};
+
+/// LFM2-style gated short convolution (no recurrence, conv state only):
+/// in_proj(h → 3*conv_dim) → split(B, C, x) → B*x → causal conv → C*conv → out_proj.
+struct ShortConvMixer : LinearMixer {
+ size_t conv_dim = 0; ///< mixer width (LFM2-1.2B: 2048)
+ size_t conv_kernel = 3;
+
+ MixerResult build(const ov::Output<ov::Node>& input,
+ const std::string& prefix,
+ size_t linear_layer_idx) const override;
+};
+
+/// `mamba_ratio` linear-mixer layers per 1 full-attention layer (0 → empty = pure attention).
+std::function<bool(size_t)> make_mamba_schedule(size_t mamba_ratio);
+
+/// Schedule from an explicit attention-layer index list — full attention at those indices,
+/// linear everywhere else. Mirrors how LFM2/hybrid configs declare per-layer `layer_types`
+/// (e.g. LFM2-1.2B attention at {2, 5, 8, 10, 12, 14}); no closed-form ratio fits.
+std::function<bool(size_t)> make_schedule_with_attention_at(std::vector<size_t> attn_layers);
+
} // namespace npuw
} // namespace test
} // namespace ov
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_internal.hpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_internal.hpp
index 95f07774d6d..1558da718a1 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_internal.hpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_internal.hpp
@@ -49,6 +49,12 @@ inline std::string make_kv_var_id(const std::string& layer,
return "past_key_values." + layer + infix + kv_type + "present." + layer + infix + kv_type;
}
+/// Hybrid model state id: cache_params.past.{type}.{N}cache_params.present.{type}.{N}
+/// Missing separator between past+present halves is intentional — matches StatefulToStateless.
+inline std::string make_cache_params_var_id(const std::string& type, const std::string& idx) {
+ return "cache_params.past." + type + "." + idx + "cache_params.present." + type + "." + idx;
+}
+
} // namespace npuw
} // namespace test
} // namespace ov
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_norm.cpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_norm.cpp
index d2a1caad7d2..273ad6b076c 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_norm.cpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_norm.cpp
@@ -42,7 +42,8 @@ ov::Output<ov::Node> RMSNorm::operator()(const ov::Output<ov::Node>& input, cons
ov::opset11::Constant::create(precision, ov::Shape{hidden_size}, std::vector<float>(hidden_size, w_val));
weight->set_friendly_name(name + ".weight");
- auto squared = std::make_shared<ov::opset11::Multiply>(input, input);
+ auto two = ov::opset11::Constant::create(precision, ov::Shape{}, {2.0f});
+ auto squared = std::make_shared<ov::opset11::Power>(input, two);
auto axes = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {-1});
@@ -52,16 +53,46 @@ ov::Output<ov::Node> RMSNorm::operator()(const ov::Output<ov::Node>& input, cons
auto mean_eps = std::make_shared<ov::opset11::Add>(mean, eps_const);
- auto rsqrt = std::make_shared<ov::opset11::Sqrt>(mean_eps);
+ auto sqrt = std::make_shared<ov::opset11::Sqrt>(mean_eps);
+
+ // rsqrt-style apply (Divide(1, Sqrt) -> Multiply(x) -> Multiply(weight)), as exported.
+ // When x is a residual Add this hits NPUW's strongest compute pattern (RMSNorm,
+ // which also isolates the weight Multiply); the direct-Divide form only hit RMSNorm4.
+ auto one = ov::opset11::Constant::create(precision, ov::Shape{}, {1.0f});
+ auto rsqrt = std::make_shared<ov::opset11::Divide>(one, sqrt);
+ rsqrt->set_friendly_name(name + "/rsqrt");
- auto normalized = std::make_shared<ov::opset11::Divide>(input, rsqrt);
+ auto normalized = std::make_shared<ov::opset11::Multiply>(input, rsqrt);
- auto scaled = std::make_shared<ov::opset11::Multiply>(normalized, weight);
+ auto scaled = std::make_shared<ov::opset11::Multiply>(weight, normalized);
scaled->set_friendly_name(name);
return scaled->output(0);
}
+ov::Output<ov::Node> L2Norm::operator()(const ov::Output<ov::Node>& input, const std::string& name) const {
+ // Mirrors the exported GDN q/k norm: square via self-Multiply (not Power), then
+ // rsqrt-style apply — Divide(1, Sqrt) followed by Multiply with the input.
+ auto squared = std::make_shared<ov::opset11::Multiply>(input, input);
+ squared->set_friendly_name(name + "/square");
+
+ auto axes = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {-1});
+ auto sum = std::make_shared<ov::opset11::ReduceSum>(squared, axes, true);
+
+ auto eps_const = ov::opset11::Constant::create(precision, ov::Shape{}, {eps});
+ auto sum_eps = std::make_shared<ov::opset11::Add>(sum, eps_const);
+
+ auto norm = std::make_shared<ov::opset11::Sqrt>(sum_eps);
+
+ auto one = ov::opset11::Constant::create(precision, ov::Shape{}, {1.0f});
+ auto rsqrt = std::make_shared<ov::opset11::Divide>(one, norm);
+ rsqrt->set_friendly_name(name + "/rsqrt");
+
+ auto out = std::make_shared<ov::opset11::Multiply>(input, rsqrt);
+ out->set_friendly_name(name);
+ return out->output(0);
+}
+
} // namespace npuw
} // namespace test
} // namespace ov
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_norm.hpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_norm.hpp
index bfacf8a4c1a..1fe496374a1 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_norm.hpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_norm.hpp
@@ -39,6 +39,16 @@ struct RMSNorm {
ov::Output<ov::Node> operator()(const ov::Output<ov::Node>& input, const std::string& name) const;
};
+/// L2 normalization on last dimension: x / sqrt(sum(x^2) + eps).
+struct L2Norm {
+ ov::element::Type precision;
+ float eps;
+
+ L2Norm(ov::element::Type prec = ov::element::f32, float e = 1e-6f) : precision(prec), eps(e) {}
+
+ ov::Output<ov::Node> operator()(const ov::Output<ov::Node>& input, const std::string& name) const;
+};
+
} // namespace npuw
} // namespace test
} // namespace ov
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_rope.cpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_rope.cpp
index 8c116610c9d..98c01af6819 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_rope.cpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_rope.cpp
@@ -211,6 +211,36 @@ ov::Output<ov::Node> InterleavedRoPE::operator()(const ov::Output<ov::Node>& inp
return output->output(0);
}
+PartialRotationRoPE::PartialRotationRoPE(size_t hd,
+ size_t rd,
+ ov::element::Type precision,
+ const ov::Output<ov::Node>& position_ids,
+ const ov::Output<ov::Node>& shape_source)
+ : head_dim(hd),
+ rotary_dim(rd),
+ inner(rd, precision, position_ids, shape_source) {}
+
+ov::Output<ov::Node> PartialRotationRoPE::operator()(const ov::Output<ov::Node>& input, const std::string& name) const {
+ auto zero = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {0});
+ auto rot_const = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {static_cast<int64_t>(rotary_dim)});
+ auto full_const = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {static_cast<int64_t>(head_dim)});
+ auto step = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {1});
+ auto last_axis = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {-1});
+
+ auto rot_part = std::make_shared<ov::op::v8::Slice>(input, zero, rot_const, step, last_axis);
+ rot_part->set_friendly_name(name + "_rot_part");
+
+ auto pass_part = std::make_shared<ov::op::v8::Slice>(input, rot_const, full_const, step, last_axis);
+ pass_part->set_friendly_name(name + "_pass_part");
+
+ auto roped = inner(rot_part->output(0), name);
+
+ auto output = std::make_shared<ov::opset11::Concat>(ov::OutputVector{roped, pass_part->output(0)}, -1);
+ output->set_friendly_name(name + "_partial_concat");
+
+ return output->output(0);
+}
+
ov::Output<ov::Node> make_position_ids_2d() {
auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});
param->set_friendly_name("position_ids");
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_rope.hpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_rope.hpp
index 2b0d2bfbba6..f9481a3b272 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_rope.hpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_rope.hpp
@@ -40,6 +40,23 @@ struct InterleavedRoPE {
ov::Output<ov::Node> operator()(const ov::Output<ov::Node>& input, const std::string& name) const;
};
+/// Partial RoPE (Qwen3.5-style): only the first rotary_dim of each head is rotated
+/// (half-rotation), the remaining head_dim - rotary_dim passes through, then both are
+/// re-concatenated. cos/sin are built over rotary_dim.
+struct PartialRotationRoPE {
+ size_t head_dim;
+ size_t rotary_dim;
+ HalfRotationRoPE inner; ///< rotation over the rotary_dim prefix
+
+ PartialRotationRoPE(size_t head_dim,
+ size_t rotary_dim,
+ ov::element::Type precision,
+ const ov::Output<ov::Node>& position_ids,
+ const ov::Output<ov::Node>& shape_source = {});
+
+ ov::Output<ov::Node> operator()(const ov::Output<ov::Node>& input, const std::string& name) const;
+};
+
/// [batch, seq] position_ids Parameter.
ov::Output<ov::Node> make_position_ids_2d();
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_weights.cpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_weights.cpp
index 1456d49d37d..0f9b47ce032 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_weights.cpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_weights.cpp
@@ -4,6 +4,7 @@
#include "model_builder_weights.hpp"
+#include <cmath>
#include <cstdint>
#include <vector>
@@ -20,15 +21,22 @@ ov::Output<ov::Node> FloatWeight::operator()(const std::string& name,
ov::element::Type compute_precision) const {
// Deterministic pseudo-random fill: each element gets a unique value derived
// from the tensor name via xorshift32. Same name always produces the same
- // weights, but values look random and span a wide enough range ([-0.5, 0.5))
- // to survive FP16 quantisation through NPUW. This prevents CSE from merging
- // same-shape projections and produces diverse logits in the LM head.
+ // weights, but values look random. This prevents CSE from merging same-shape
+ // projections and produces diverse logits in the LM head.
+ //
+ // Values are fan-in scaled (Xavier-style, base range [-0.5, 0.5) / sqrt(fan_in))
+ // so activation magnitudes stay realistic through depth. Unscaled weights gave
+ // each projection a ~sqrt(fan_in)/sqrt(12) gain — attention scores reached ~3e2
+ // (hyper-peaked softmax, exp overflow territory), which real trained models
+ // never produce and which amplified kernel-level rounding into visible
+ // prefill-vs-decode logit divergence.
uint32_t state = seed_from_name(name);
size_t total = ov::shape_size(shape);
+ const float fan_in_scale = shape.size() >= 2 ? 1.0f / std::sqrt(static_cast<float>(shape.back())) : 1.0f;
std::vector<float> data(total);
for (size_t i = 0; i < total; ++i) {
uint32_t r = xorshift32(state);
- data[i] = static_cast<float>(r % 10000u) / 10000.0f - 0.5f; // [-0.5, 0.5)
+ data[i] = (static_cast<float>(r % 10000u) / 10000.0f - 0.5f) * fan_in_scale;
}
auto weight = ov::opset11::Constant::create(storage_type, shape, data);
weight->set_friendly_name(name);
diff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_graph_options_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_graph_options_test.cpp
index 0de86160d97..3fac67a5b7e 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_graph_options_test.cpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_graph_options_test.cpp
@@ -14,6 +14,7 @@
#include "llm_test_helpers.hpp"
#include "openvino/op/slice.hpp"
+#include "openvino/pass/stateful_to_stateless.hpp"
namespace {
using ov::test::npuw::CompileCall;
@@ -229,4 +230,53 @@ TEST_F(LLMCompiledModelGraphOptionsTest, GeneratePyramidBuildsTwoStaticGenerateV
::testing::UnorderedElementsAre(ov::Shape({1, 1152}), ov::Shape({1, 2176})));
}
+TEST(HybridModelBuilderTest, HybridLinearAttnModelBuilds) {
+ std::shared_ptr<ov::Model> model;
+ ASSERT_NO_THROW(model = ov::test::npuw::build_hybrid_llm_test_model());
+ ASSERT_NE(model, nullptr);
+
+ // Hybrid model must have sinks (conv + SSM + KV cache state assigns)
+ EXPECT_GT(model->get_sinks().size(), 0u);
+
+ // Validate the model is well-formed
+ EXPECT_TRUE(model->get_results().size() > 0u);
+}
+
+// LFM2-style gated short conv: conv state only (no SSM), key/value on attention layers.
+// StatefulToStateless is the pass NPUW actually runs to consume cache_params.* states.
+TEST(HybridModelBuilderTest, LFM2ModelConvertsToStateless) {
+ auto model = ov::test::npuw::build_lfm2_llm_test_model();
+ ASSERT_NE(model, nullptr);
+
+ // 2 short-conv layers x conv + 2 attn layers x (key + value) = 6 states.
+ ASSERT_EQ(model->get_sinks().size(), 6u);
+ ASSERT_EQ(model->get_variables().size(), 6u);
+
+ ASSERT_NO_THROW(ov::pass::StatefulToStateless().run_on_model(model));
+
+ auto has_input = [&](const std::string& n) {
+ for (const auto& p : model->inputs())
+ if (p.get_names().count(n))
+ return true;
+ return false;
+ };
+ auto has_output = [&](const std::string& n) {
+ for (const auto& r : model->outputs())
+ if (r.get_names().count(n))
+ return true;
+ return false;
+ };
+
+ for (size_t lin = 0; lin < 2; ++lin) {
+ const auto idx = std::to_string(lin);
+ EXPECT_TRUE(has_input("cache_params.past.conv." + idx));
+ EXPECT_TRUE(has_output("cache_params.present.conv." + idx));
+ }
+ for (size_t att = 0; att < 2; ++att) {
+ const auto idx = std::to_string(att);
+ EXPECT_TRUE(has_input("past_key_values." + idx + ".key"));
+ EXPECT_TRUE(has_output("present." + idx + ".key"));
+ }
+}
+
} // namespace
diff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp b/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp
index 6c4097bbef7..26fc8652b14 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp
@@ -128,6 +128,43 @@ inline std::shared_ptr<ov::Model> build_llm_test_model_with_kv_fake_convert(cons
return model;
}
+/// Hybrid LLM: alternating linear-attention / full-attention layers.
+/// 4 layers → layers 0,2 linear; layers 1,3 full attention.
+/// Attention layers are Qwen3.5-style: output-gated, partial RoPE.
+inline std::shared_ptr<ov::Model> build_hybrid_llm_test_model() {
+ auto cfg = make_test_model_config();
+ cfg.num_layers = 4;
+ cfg.attn_output_gate = true;
+ cfg.rotary_dim = cfg.head_dim / 4;
+ cfg.is_linear_layer = make_mamba_schedule(1);
+ auto mixer = std::make_shared<GatedDeltaNetMixer>();
+ mixer->hidden_size = cfg.hidden_size;
+ mixer->precision = cfg.precision;
+ mixer->weight_fn = cfg.weight;
+ mixer->num_heads = cfg.num_heads;
+ mixer->key_head_dim = cfg.head_dim;
+ mixer->value_head_dim = cfg.head_dim;
+ cfg.linear_mixer = mixer;
+ ModelBuilder mb;
+ return mb.build_llm(cfg);
+}
+
+/// LFM2-style hybrid: gated short-conv mixer layers interleaved with full attention.
+/// 4 layers → layers 0,2 short-conv; layers 1,3 full attention.
+inline std::shared_ptr<ov::Model> build_lfm2_llm_test_model() {
+ auto cfg = make_test_model_config();
+ cfg.num_layers = 4;
+ cfg.is_linear_layer = make_mamba_schedule(1);
+ auto mixer = std::make_shared<ShortConvMixer>();
+ mixer->hidden_size = cfg.hidden_size;
+ mixer->precision = cfg.precision;
+ mixer->weight_fn = cfg.weight;
+ mixer->conv_dim = cfg.hidden_size;
+ cfg.linear_mixer = mixer;
+ ModelBuilder mb;
+ return mb.build_llm(cfg);
+}
+
inline std::shared_ptr<ov::Model> build_whisper_decoder_test_model() {
ModelBuilder mb;
return mb.build_whisper_decoder(make_test_model_config<WhisperConfig>());