Skip to content

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

[NPUW][Gemm4-E2B]Optimize shared KV arch. (#37300)

intelgaoxiong01c0ed33536d
diff --git a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
index 66c603c5105..2717860a2b4 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
@@ -576,9 +576,29 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,
compiledFunctions.insert({subgraph._funcall, id});
// For HFA, use the final tile model instead of the original SDPA model
- // because the original SDPA model won't be compiled
+ // because the original SDPA model won't be compiled.
+ // Invariant: the prototype model must expose exactly the same number of
+ // results as the HFA tile model. A mismatch means the prototype carries
+ // extra pass-through outputs (e.g. shared-KV block tensors routed to
+ // downstream subgraphs) that the tile model does not produce. Allowing
+ // this silently would leave those output slots unregistered in
+ // m_funcall_result and cause an invalid-key crash at inference time.
if (fcn_template._host_flash_attention) {
- m_compiled_submodels[id].model = fcn_template._host_flash_attention.value()._final_tile_model;
+ const auto& hfa = fcn_template._host_flash_attention.value();
+ const size_t proto_outs = fcn_template._model->get_results().size();
+ const size_t tile_outs = hfa._final_tile_model->outputs().size();
+ if (proto_outs != tile_outs) {
+ OPENVINO_THROW("NPUW HFA: subgraph[",
+ id,
+ "] prototype model has ",
+ proto_outs,
+ " result(s) but the HFA tile model has ",
+ tile_outs,
+ ". The prototype carries extra outputs that would be silently"
+ " dropped, causing inference failures. Ensure all shared-KV"
+ " fan-outs are resolved before HFA is applied.");
+ }
+ m_compiled_submodels[id].model = hfa._final_tile_model;
} else {
m_compiled_submodels[id].model = fcn_template._model;
}
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp
index 9d885babfd4..93125976c06 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp
@@ -15,6 +15,7 @@
#include "npuw_transformations/add_position_ids_param.hpp"
#include "npuw_transformations/convert_kvcache_to_precision.hpp"
#include "npuw_transformations/decompose_gqa.hpp"
+#include "npuw_transformations/duplicate_shared_kv_concat.hpp"
#include "npuw_transformations/lora_stateful_to_stateless.hpp"
#include "npuw_transformations/optimize_value_tensors.hpp"
#include "npuw_transformations/patch_sliding_window_mask.hpp"
@@ -1250,6 +1251,18 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
}
}
+ // Duplicate shared K/V broadcast chains in the prefill model so that each downstream
+ // SDPA gets its own independent Concat chain. This enables TagSDPA/SDPADecomposed to
+ // isolate and convert each SDPA to HFA independently (e.g. Gemma-4 L15–L34 reuse
+ // L13/L14 KV).
+ if ((prefill_attn_hfa || prefill_attn_pyramid) && !m_is_embedding) {
+ ov::pass::GraphRewrite rewr;
+ rewr.add_matcher<ov::npuw::pass::DuplicateSharedKVConcat>();
+ if (rewr.run_on_model(prefill_model)) {
+ LOG_INFO("DuplicateSharedKVConcat applied to prefill model");
+ }
+ }
+
// Compile multiple generate model variants with different sizes
compile_generate_model_variants(generate_model_variants, plugin, generate_config);
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/duplicate_shared_kv_concat.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/duplicate_shared_kv_concat.cpp
new file mode 100644
index 00000000000..389e9eef309
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/duplicate_shared_kv_concat.cpp
@@ -0,0 +1,197 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "duplicate_shared_kv_concat.hpp"
+
+#include <algorithm>
+#include <vector>
+
+#include "../logging.hpp"
+#include "../util.hpp"
+#include "openvino/core/rt_info.hpp"
+#include "openvino/op/broadcast.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/scaled_dot_product_attention.hpp"
+#include "openvino/op/unsqueeze.hpp"
+#include "openvino/pass/pattern/op/label.hpp"
+#include "openvino/pass/pattern/op/optional.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+
+namespace ov {
+namespace npuw {
+namespace pass {
+
+namespace {
+
+// Returns true when the parameter name is a past-KV param (contiguous or
+// block-split), using the canonical NPUW naming utilities.
+bool is_past_kv_param(const std::shared_ptr<ov::op::v0::Parameter>& param) {
+ const auto& name = param->get_friendly_name();
+ return ov::npuw::util::isPastKeyParam(name) || ov::npuw::util::isPastValueParam(name);
+}
+
+// Returns true when all inputs of `concat` except the last are past-KV
+// Parameters (or Convert wrapping one). The final input is the current-chunk
+// KV projection and is intentionally left unchecked.
+bool has_param_past_inputs(const std::shared_ptr<ov::op::v0::Concat>& concat) {
+ const size_t n = concat->get_input_size();
+ if (n < 2)
+ return false;
+
+ std::vector<std::shared_ptr<ov::op::v0::Parameter>> params;
+ params.reserve(n - 1);
+ for (size_t i = 0; i + 1 < n; ++i) {
+ auto inp = concat->get_input_node_shared_ptr(i);
+ if (auto param = ov::as_type_ptr<ov::op::v0::Parameter>(inp)) {
+ params.push_back(param);
+ continue;
+ }
+ if (auto cvt = ov::as_type_ptr<ov::op::v0::Convert>(inp)) {
+ if (auto param = ov::as_type_ptr<ov::op::v0::Parameter>(cvt->get_input_node_shared_ptr(0))) {
+ params.push_back(param);
+ continue;
+ }
+ }
+ return false;
+ }
+
+ return std::all_of(params.begin(), params.end(), is_past_kv_param);
+}
+
+struct KVBroadcastChain {
+ std::vector<std::shared_ptr<ov::op::v0::Convert>> converts;
+ std::shared_ptr<ov::op::v0::Concat> concat;
+ std::shared_ptr<ov::op::v0::Unsqueeze> unsqueeze; // may be nullptr
+ std::shared_ptr<ov::Node> broadcast; // v1 or v3 Broadcast; may be nullptr
+ std::shared_ptr<ov::op::v1::Reshape> reshape; // fan-out root
+};
+
+// Clone the Concat→[Unsqueeze]→[Broadcast]→Reshape chain for every consumer
+// beyond the first. The first consumer keeps the original chain.
+void duplicate_for_extra_consumers(const KVBroadcastChain& chain) {
+ std::vector<ov::Input<ov::Node>> consumers;
+ for (auto& ti : chain.reshape->output(0).get_target_inputs())
+ consumers.push_back(ti);
+
+ for (size_t idx = 1; idx < consumers.size(); ++idx) {
+ ov::OutputVector new_concat_inputs;
+ new_concat_inputs.reserve(chain.concat->get_input_size());
+ for (size_t ci = 0; ci < chain.concat->get_input_size(); ++ci) {
+ if (chain.converts[ci]) {
+ auto new_cvt = chain.converts[ci]->clone_with_new_inputs(chain.converts[ci]->input_values());
+ copy_runtime_info(chain.converts[ci], new_cvt);
+ new_concat_inputs.push_back(new_cvt->output(0));
+ } else {
+ new_concat_inputs.push_back(chain.concat->input_value(ci));
+ }
+ }
+ auto new_concat = chain.concat->clone_with_new_inputs(new_concat_inputs);
+ copy_runtime_info(chain.concat, new_concat);
+ ov::Output<ov::Node> data = new_concat->output(0);
+
+ if (chain.unsqueeze) {
+ ov::OutputVector inputs{data};
+ for (size_t i = 1; i < chain.unsqueeze->get_input_size(); ++i)
+ inputs.push_back(chain.unsqueeze->input_value(i));
+ auto new_unsqueeze = chain.unsqueeze->clone_with_new_inputs(inputs);
+ copy_runtime_info(chain.unsqueeze, new_unsqueeze);
+ data = new_unsqueeze->output(0);
+ }
+
+ if (chain.broadcast) {
+ ov::OutputVector inputs{data};
+ for (size_t i = 1; i < chain.broadcast->get_input_size(); ++i)
+ inputs.push_back(chain.broadcast->input_value(i));
+ auto new_broadcast = chain.broadcast->clone_with_new_inputs(inputs);
+ copy_runtime_info(chain.broadcast, new_broadcast);
+ data = new_broadcast->output(0);
+ }
+
+ {
+ ov::OutputVector inputs{data};
+ for (size_t i = 1; i < chain.reshape->get_input_size(); ++i)
+ inputs.push_back(chain.reshape->input_value(i));
+ auto new_reshape = chain.reshape->clone_with_new_inputs(inputs);
+ copy_runtime_info(chain.reshape, new_reshape);
+ data = new_reshape->output(0);
+ }
+
+ consumers[idx].replace_source_output(data);
+ }
+}
+
+} // namespace
+
+DuplicateSharedKVConcat::DuplicateSharedKVConcat() {
+ namespace opp = ov::pass::pattern;
+
+ // Pattern: Concat(past-KV params…, current_KV)
+ // → [optional Unsqueeze]
+ // → [optional Broadcast (v1 or v3)]
+ // → Reshape ← anchored here; predicate checks fan-out and consumer types
+ auto p_concat = opp::wrap_type<ov::op::v0::Concat>();
+ auto p_unsqueeze = opp::optional<ov::op::v0::Unsqueeze>({p_concat, opp::any_input()});
+ auto p_broadcast = opp::optional<ov::op::v1::Broadcast, ov::op::v3::Broadcast>({p_unsqueeze, opp::any_input()});
+ auto p_reshape =
+ opp::wrap_type<ov::op::v1::Reshape>({p_broadcast, opp::any_input()}, [](const ov::Output<ov::Node>& output) {
+ const auto& targets = output.get_target_inputs();
+ if (targets.size() <= 1)
+ return false;
+ for (const auto& ti : targets) {
+ auto* n = ti.get_node();
+ if (!ov::is_type<ov::op::v0::MatMul>(n) && !ov::is_type<ov::op::v13::ScaledDotProductAttention>(n))
+ return false;
+ }
+ return true;
+ });
+
+ // Note: Use [=] to keep pattern nodes alive in the callback.
+ auto callback = [=](ov::pass::pattern::Matcher& m) {
+ auto& vm = m.get_pattern_value_map();
+
+ auto matched_concat = ov::as_type_ptr<ov::op::v0::Concat>(vm.at(p_concat).get_node_shared_ptr());
+ if (!matched_concat || !has_param_past_inputs(matched_concat))
+ return false;
+
+ KVBroadcastChain chain;
+ chain.reshape = ov::as_type_ptr<ov::op::v1::Reshape>(vm.at(p_reshape).get_node_shared_ptr());
+ chain.concat = matched_concat;
+
+ // opp::optional nodes are absent from vm when not matched (pass-through case).
+ // Walk backward from Reshape to detect them instead of using vm.at().
+ {
+ std::shared_ptr<ov::Node> cur = chain.reshape->get_input_node_shared_ptr(0);
+ if (ov::is_type<ov::op::v1::Broadcast>(cur) || ov::is_type<ov::op::v3::Broadcast>(cur)) {
+ chain.broadcast = cur;
+ cur = cur->get_input_node_shared_ptr(0);
+ }
+ chain.unsqueeze = ov::as_type_ptr<ov::op::v0::Unsqueeze>(cur);
+ }
+
+ chain.converts.resize(matched_concat->get_input_size());
+ // Only past-KV inputs (all but the last) may have a Convert wrapper that needs
+ // to be cloned per consumer. The final input is the current-KV projection and
+ // is always shared — leave converts[n-1] as nullptr.
+ for (size_t i = 0; i + 1 < matched_concat->get_input_size(); ++i)
+ chain.converts[i] = ov::as_type_ptr<ov::op::v0::Convert>(matched_concat->get_input_node_shared_ptr(i));
+
+ const size_t fan_out = chain.reshape->output(0).get_target_inputs().size();
+ LOG_DEBUG("DuplicateSharedKVConcat: Reshape \""
+ << chain.reshape->get_friendly_name() << "\" fan-out=" << fan_out
+ << " — duplicating KV broadcast chain for " << (fan_out - 1) << " extra consumer(s)");
+
+ duplicate_for_extra_consumers(chain);
+ return true;
+ };
+
+ register_matcher(std::make_shared<opp::Matcher>(p_reshape, "DuplicateSharedKVConcat"), std::move(callback));
+}
+
+} // namespace pass
+} // namespace npuw
+} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/duplicate_shared_kv_concat.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/duplicate_shared_kv_concat.hpp
new file mode 100644
index 00000000000..83e31eb4fb5
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/duplicate_shared_kv_concat.hpp
@@ -0,0 +1,54 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/pass/matcher_pass.hpp"
+
+namespace ov {
+namespace npuw {
+namespace pass {
+
+/**
+ * @brief Duplicate shared KV broadcast chains to enable per-SDPA ATTN isolation.
+ *
+ * Some models (e.g. Gemma-4) share a single accumulated KV tensor across multiple
+ * SDPA nodes by fanning out through a Reshape node:
+ *
+ * Concat(past_K_blocks…, current_K)
+ * → [Unsqueeze] → [Broadcast] → Reshape ─┬─→ SDPA_L13
+ * ├─→ SDPA_L15
+ * ├─→ SDPA_L16
+ * └─→ …
+ *
+ * The high fan-out prevents NPUW's ATTN isolation patterns (TagSDPA /
+ * SDPADecomposed) from tagging each SDPA independently, because every tagging
+ * attempt would claim the shared Reshape (and its ancestors) as part of its
+ * own partition, creating conflicting assignments.
+ *
+ * This pass duplicates the [Convert →] Concat → [Unsqueeze] → [Broadcast] → Reshape
+ * chain for every extra consumer beyond the first, giving each SDPA its own
+ * local chain:
+ *
+ * same past_K_blocks… → [new_Convert] → new_Concat_L15 → … → new_Reshape_L15 → SDPA_L15
+ * same past_K_blocks… → [new_Convert] → new_Concat_L16 → … → new_Reshape_L16 → SDPA_L16
+ * …
+ *
+ * All duplicate chains share the same bare Parameter (block) nodes and the same
+ * current_K subgraph. However, any Convert nodes that directly wrap past-KV
+ * Parameters are cloned independently for each new chain. Without this,
+ * subgraph-isolation passes (e.g. SDPADecomposed) would pull the shared
+ * Convert nodes into the first SDPA's subgraph group, creating spurious
+ * cross-subgraph pass-through outputs on the producer subgraph and mismatching
+ * the output count expected by HFA tile compilation.
+ */
+class DuplicateSharedKVConcat : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::pass::DuplicateSharedKVConcat");
+ DuplicateSharedKVConcat();
+};
+
+} // namespace pass
+} // namespace npuw
+} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/sources.cmake b/src/plugins/intel_npu/src/plugin/sources.cmake
index 999b64b593c..ba4fee8a8d5 100644
--- a/src/plugins/intel_npu/src/plugin/sources.cmake
+++ b/src/plugins/intel_npu/src/plugin/sources.cmake
@@ -138,6 +138,8 @@ set(NPUW_SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/slice_out_embeds.hpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/sliding_window_mask.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/sliding_window_mask.hpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/duplicate_shared_kv_concat.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/duplicate_shared_kv_concat.hpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/split_kvcache_into_blocks.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/split_kvcache_into_blocks.hpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/untangle_dq_scale.cpp
diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
index a910468ec5a..86b51928679 100644
--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
@@ -76,6 +76,7 @@ ov_add_test_target(
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/v1/elements/failsafe.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/split_kvcache_into_blocks.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/duplicate_shared_kv_concat.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/kv_cache_block_manager.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/attention.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp
diff --git a/src/plugins/intel_npu/tests/unit/npuw/duplicate_shared_kv_concat_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/duplicate_shared_kv_concat_test.cpp
new file mode 100644
index 00000000000..8b3b76f71e2
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/npuw/duplicate_shared_kv_concat_test.cpp
@@ -0,0 +1,303 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "npuw_transformations/duplicate_shared_kv_concat.hpp"
+
+#include <gtest/gtest.h>
+
+#include <set>
+#include <string>
+#include <vector>
+
+#include "npuw_transformations/split_kvcache_into_blocks.hpp"
+#include "openvino/op/broadcast.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/unsqueeze.hpp"
+#include "openvino/pass/graph_rewrite.hpp"
+#include "openvino/pass/manager.hpp"
+
+namespace {
+
+std::shared_ptr<ov::op::v0::Constant> shape_const(const ov::Shape& s) {
+ return ov::op::v0::Constant::create(ov::element::i64, {s.size()}, std::vector<int64_t>(s.begin(), s.end()));
+}
+
+template <typename T>
+size_t count_ops(const std::shared_ptr<ov::Model>& model) {
+ size_t n = 0;
+ for (const auto& op : model->get_ops())
+ if (ov::is_type<T>(op))
+ ++n;
+ return n;
+}
+
+// Shared-KV fan-out pattern:
+// [Convert →] Concat(kv_param, current_k) → [Unsqueeze → Broadcast] → Reshape
+// └─ fan_out Results
+// with_gqa=true inserts the Unsqueeze + Broadcast (GQA head-expansion) chain.
+std::shared_ptr<ov::Model> build_fanout_model(const std::string& kv_param_name,
+ const ov::Shape& kv_shape,
+ int64_t concat_axis,
+ size_t fan_out,
+ bool with_gqa = false) {
+ auto kv = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, kv_shape);
+ kv->set_friendly_name(kv_param_name);
+
+ ov::Shape cur_shape = kv_shape;
+ cur_shape[concat_axis] = 1; // single current-chunk token
+ auto current = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, cur_shape);
+ current->set_friendly_name("current_k");
+
+ auto concat = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{kv, current}, concat_axis);
+ ov::Output<ov::Node> data = concat->output(0);
+
+ if (with_gqa) {
+ auto axis_c = ov::op::v0::Constant::create(ov::element::i64, {1}, {2LL});
+ data = std::make_shared<ov::op::v0::Unsqueeze>(data, axis_c)->output(0);
+
+ // Broadcast: expand the new dim from 1 → 4 (4 Q-heads per KV-head).
+ const auto& ps = data.get_partial_shape();
+ ov::Shape bcast_target(ps.rank().get_length());
+ for (int i = 0; i < (int)ps.rank().get_length(); ++i)
+ bcast_target[i] = (i == 2) ? 4u : (size_t)ps[i].get_length();
+ data = std::make_shared<ov::op::v3::Broadcast>(data, shape_const(bcast_target))->output(0);
+ }
+
+ const auto& ps = data.get_partial_shape(); // collapse batch×heads
+ ov::Shape reshape_target;
+ reshape_target.push_back((size_t)ps[0].get_length() * (size_t)ps[1].get_length());
+ for (int i = 2; i < (int)ps.rank().get_length(); ++i)
+ reshape_target.push_back((size_t)ps[i].get_length());
+ auto reshape = std::make_shared<ov::op::v1::Reshape>(data, shape_const(reshape_target), false);
+
+ // Use MatMul as consumers so the consumer-type guard in try_match() is satisfied.
+ const size_t head_dim = reshape_target.back();
+ auto matmul_weight = ov::op::v0::Constant::create(ov::element::f16,
+ ov::Shape{head_dim, head_dim},
+ std::vector<float>(head_dim * head_dim, 1.0f));
+ ov::ResultVector results;
+ for (size_t i = 0; i < fan_out; ++i) {
+ auto mm = std::make_shared<ov::op::v0::MatMul>(reshape, matmul_weight);
+ results.push_back(std::make_shared<ov::op::v0::Result>(mm));
+ }
+
+ return std::make_shared<ov::Model>(results, ov::ParameterVector{kv, current});
+}
+
+} // namespace
+
+// Convenience wrapper: MatcherPass must run inside GraphRewrite.
+static bool run_pass(const std::shared_ptr<ov::Model>& model) {
+ ov::pass::GraphRewrite rewr;
+ rewr.add_matcher<ov::npuw::pass::DuplicateSharedKVConcat>();
+ return rewr.run_on_model(model);
+}
+
+class DuplicateSharedKVConcatTest : public ::testing::Test {};
+
+// ─── No-op: Reshape has only one consumer ────────────────────────────────────
+
+TEST_F(DuplicateSharedKVConcatTest, NoOp_SingleConsumer) {
+ auto model = build_fanout_model("past_key_values.0.key", {1, 2, 4, 8}, 2, /*fan_out=*/1);
+ EXPECT_FALSE(run_pass(model));
+ EXPECT_EQ(count_ops<ov::op::v0::Concat>(model), 1u);
+}
+
+// ─── No-op: non-past-KV parameter feeding the Concat ─────────────────────────
+
+TEST_F(DuplicateSharedKVConcatTest, NoOp_NonPastKVParam) {
+ // Replace the past-KV param with an unrecognised name.
+ // MatMul consumers satisfy the type guard so the no-op is due to the name check.
+ auto model = build_fanout_model("hidden_state", {1, 2, 4, 8}, 2, /*fan_out=*/2);
+ EXPECT_FALSE(run_pass(model));
+ EXPECT_EQ(count_ops<ov::op::v0::Concat>(model), 1u);
+}
+
+// ─── No-op: consumers of the shared Reshape are not SDPA/MatMul ──────────────
+
+TEST_F(DuplicateSharedKVConcatTest, NoOp_NonSDPAConsumer) {
+ // Valid past-KV chain, fan-out > 1, but consumers are Results (not SDPA/MatMul).
+ // The consumer-type guard must reject this.
+ auto kv = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 2, 4, 8});
+ kv->set_friendly_name("past_key_values.0.key");
+ auto current = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 2, 1, 8});
+ current->set_friendly_name("current_k");
+ auto concat = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{kv, current}, 2);
+ auto reshape = std::make_shared<ov::op::v1::Reshape>(concat->output(0), shape_const(ov::Shape{2, 5, 8}), false);
+ auto model = std::make_shared<ov::Model>(
+ ov::ResultVector{std::make_shared<ov::op::v0::Result>(reshape), std::make_shared<ov::op::v0::Result>(reshape)},
+ ov::ParameterVector{kv, current});
+ EXPECT_FALSE(run_pass(model));
+ EXPECT_EQ(count_ops<ov::op::v0::Concat>(model), 1u);
+}
+
+// ─── MHA fan-out (no GQA chain) ──────────────────────────────────────────────
+
+TEST_F(DuplicateSharedKVConcatTest, MHA_FanOut3) {
+ // kv_shape [1,2,4,8]: batch=1, heads=2, seq=4, dim=8
+ auto model = build_fanout_model("past_key_values.0.key", {1, 2, 4, 8}, 2, /*fan_out=*/3);
+ const auto kv_param = model->get_parameters()[0];
+
+ EXPECT_TRUE(run_pass(model));
+
+ EXPECT_EQ(count_ops<ov::op::v0::Concat>(model), 3u);
+
+ size_t concats_with_kv = 0;
+ for (const auto& op : model->get_ops()) {
+ if (auto c = ov::as_type_ptr<ov::op::v0::Concat>(op)) {
+ for (size_t i = 0; i + 1 < c->get_input_size(); ++i)
+ if (c->get_input_node_shared_ptr(i) == kv_param)
+ ++concats_with_kv;
+ }
+ }
+ EXPECT_EQ(concats_with_kv, 3u); // all Concats share the same past-KV param
+
+ std::set<ov::Node*> reshapes;
+ for (const auto& r : model->get_results())
+ reshapes.insert(r->get_input_node_ptr(0)->get_input_node_ptr(0)); // skip MatMul
+ EXPECT_EQ(reshapes.size(), 3u);
+}
+
+// ─── GQA fan-out: Concat → Unsqueeze → Broadcast → Reshape ──────────────────
+
+TEST_F(DuplicateSharedKVConcatTest, GQA_FanOut3) {
+ auto model = build_fanout_model("past_key_values.0.key", {1, 2, 4, 8}, 2, /*fan_out=*/3, /*with_gqa=*/true);
+ const auto kv_param = model->get_parameters()[0];
+
+ EXPECT_TRUE(run_pass(model));
+
+ EXPECT_EQ(count_ops<ov::op::v0::Concat>(model), 3u);
+ EXPECT_EQ(count_ops<ov::op::v0::Unsqueeze>(model), 3u);
+ EXPECT_EQ(count_ops<ov::op::v3::Broadcast>(model), 3u);
+
+ size_t concats_with_kv = 0;
+ for (const auto& op : model->get_ops()) {
+ if (auto c = ov::as_type_ptr<ov::op::v0::Concat>(op)) {
+ for (size_t i = 0; i + 1 < c->get_input_size(); ++i)
+ if (c->get_input_node_shared_ptr(i) == kv_param)
+ ++concats_with_kv;
+ }
+ }
+ EXPECT_EQ(concats_with_kv, 3u); // all Concats share the same past-KV param
+
+ std::set<ov::Node*> reshapes;
+ for (const auto& r : model->get_results())
+ reshapes.insert(r->get_input_node_ptr(0)->get_input_node_ptr(0)); // skip MatMul
+ EXPECT_EQ(reshapes.size(), 3u);
+}
+
+// ─── Integration: SplitKVCacheIntoBlocks → DuplicateSharedKVConcat ───────────
+// Block param names (_block_0, _block_1, …) must still be recognised.
+
+TEST_F(DuplicateSharedKVConcatTest, Integration_SplitThenDuplicate) {
+ // kv [1,1,32,8] seq=32, block_size=16 → 2 blocks
+ auto model = build_fanout_model("past_key_values.0.key", {1, 1, 32, 8}, 2, /*fan_out=*/2);
+
+ // Step 1: seq=32 → block_0 + block_1 + current_k (3 params, 1 Concat, fan-out unchanged).
+ ov::pass::Manager mgr;
+ mgr.register_pass<ov::npuw::pass::SplitKVCacheIntoBlocks>(/*block_size=*/16u, /*v_transposed=*/false);
+ EXPECT_TRUE(mgr.run_passes(model));
+ EXPECT_EQ(model->get_parameters().size(), 3u);
+ EXPECT_EQ(count_ops<ov::op::v0::Concat>(model), 1u);
+
+ // Step 2: duplicate.
+ EXPECT_TRUE(run_pass(model));
+ EXPECT_EQ(count_ops<ov::op::v0::Concat>(model), 2u);
+
+ std::vector<std::shared_ptr<ov::op::v0::Concat>> concats;
+ for (const auto& op : model->get_ops())
+ if (auto c = ov::as_type_ptr<ov::op::v0::Concat>(op))
+ concats.push_back(c);
+ ASSERT_EQ(concats.size(), 2u);
+ ASSERT_EQ(concats[0]->get_input_size(), concats[1]->get_input_size());
+ // Bare Parameters (no Convert) — block params are shared across clones.
+ for (size_t i = 0; i + 1 < concats[0]->get_input_size(); ++i)
+ EXPECT_EQ(concats[0]->get_input_node_shared_ptr(i), concats[1]->get_input_node_shared_ptr(i))
+ << "Block param at position " << i << " differs";
+
+ std::set<ov::Node*> reshapes;
+ for (const auto& r : model->get_results())
+ reshapes.insert(r->get_input_node_ptr(0)->get_input_node_ptr(0)); // skip MatMul
+ EXPECT_EQ(reshapes.size(), 2u);
+}
+
+// ─── Convert-wrapped inputs: each clone must own its own Convert nodes ────────
+// Gemma-4 pattern: f16 KV block → Convert(f32) → Concat.
+// Shared Converts would be pulled into the first SDPA's subgraph by
+// SDPADecomposed, creating spurious pass-through Results.
+
+namespace {
+std::shared_ptr<ov::Model> build_fanout_model_with_convert(const std::string& kv_param_name,
+ const ov::Shape& kv_shape,
+ int64_t concat_axis,
+ size_t fan_out) {
+ auto kv = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, kv_shape); // f16 → Convert → f32 Concat
+ kv->set_friendly_name(kv_param_name);
+ auto kv_cvt = std::make_shared<ov::op::v0::Convert>(kv, ov::element::f32);
+
+ ov::Shape cur_shape = kv_shape;
+ cur_shape[concat_axis] = 1;
+ auto current = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, cur_shape);
+ current->set_friendly_name("current_k");
+
+ auto concat = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{kv_cvt, current}, concat_axis);
+
+ const auto& ps = concat->get_output_partial_shape(0);
+ ov::Shape reshape_target;
+ reshape_target.push_back((size_t)ps[0].get_length() * (size_t)ps[1].get_length());
+ for (int i = 2; i < (int)ps.rank().get_length(); ++i)
+ reshape_target.push_back((size_t)ps[i].get_length());
+ auto reshape = std::make_shared<ov::op::v1::Reshape>(concat->output(0), shape_const(reshape_target), false);
+
+ // Use MatMul as consumers so the consumer-type guard in try_match() is satisfied.
+ const size_t head_dim = reshape_target.back();
+ auto matmul_weight = ov::op::v0::Constant::create(ov::element::f32,
+ ov::Shape{head_dim, head_dim},
+ std::vector<float>(head_dim * head_dim, 1.0f));
+ ov::ResultVector results;
+ for (size_t i = 0; i < fan_out; ++i) {
+ auto mm = std::make_shared<ov::op::v0::MatMul>(reshape, matmul_weight);
+ results.push_back(std::make_shared<ov::op::v0::Result>(mm));
+ }
+
+ return std::make_shared<ov::Model>(results, ov::ParameterVector{kv, current});
+}
+} // namespace
+
+TEST_F(DuplicateSharedKVConcatTest, WithConvertInputs_ClonesHaveIndependentConverts) {
+ auto model = build_fanout_model_with_convert("past_key_values.0.key", {1, 2, 4, 8}, 2, /*fan_out=*/3);
+ const auto kv_param = model->get_parameters()[0];
+
+ EXPECT_TRUE(run_pass(model));
+
+ EXPECT_EQ(count_ops<ov::op::v0::Concat>(model), 3u);
+ EXPECT_EQ(count_ops<ov::op::v0::Convert>(model), 3u); // cloned, not shared
+
+ // Each Concat's past-KV input must be a fresh Convert wrapping the same Parameter.
+ std::vector<ov::op::v0::Convert*> converts;
+ for (const auto& op : model->get_ops()) {
+ if (auto c = ov::as_type_ptr<ov::op::v0::Concat>(op)) {
+ auto cvt = ov::as_type_ptr<ov::op::v0::Convert>(c->get_input_node_shared_ptr(0));
+ ASSERT_NE(cvt, nullptr) << "Expected Convert as first Concat input";
+ EXPECT_EQ(cvt->get_input_node_shared_ptr(0), kv_param);
+ converts.push_back(cvt.get());
+ }
+ }
+ ASSERT_EQ(converts.size(), 3u);
+ EXPECT_NE(converts[0], converts[1]);
+ EXPECT_NE(converts[0], converts[2]);
+ EXPECT_NE(converts[1], converts[2]);
+
+ // Each Result must come from a distinct Reshape.
+ std::set<ov::Node*> reshapes;
+ for (const auto& r : model->get_results())
+ reshapes.insert(r->get_input_node_ptr(0)->get_input_node_ptr(0)); // skip MatMul
+ EXPECT_EQ(reshapes.size(), 3u);
+}