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
[NPUW]Fixed V tensor transpose for shared KV-cache in Gemma4. (#35269)
intelgaoxionged497fa337ad
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_value_tensors.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_value_tensors.cppindex 5bf43afe500..324ef6e836e 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_value_tensors.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_value_tensors.cpp@@ -40,18 +40,23 @@ protected:const std::shared_ptr<ov::op::v0::Concat>& matched_concat,const std::shared_ptr<ov::op::v1::Transpose>& matched_transpose,const std::shared_ptr<ov::op::v0::MatMul>& matched_matmul) {- auto param_shape = matched_param->get_partial_shape();- NPUW_ASSERT(param_shape.size() == 4u);- // NB: Transpose Parameter that correspond to V-tensor it will- // speed-up its multiplication with attention scores- std::swap(param_shape[2], param_shape[3]);-- matched_param->set_partial_shape(param_shape);-- auto order_cst = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{4}, {0, 2, 3, 1});-- matched_transpose->set_argument(1, order_cst);- matched_concat->set_axis(3u);+ // NB: The same param->concat pair may be matched multiple times when the+ // V-concat output feeds more than one downstream branch (e.g. shared KV-cache+ // across attention layers in Gemma4). Guard the shared-state mutations so they+ // are applied exactly once; per-branch matmul transpose_b is always set.+ if (matched_concat->get_axis() != 3u) {+ auto param_shape = matched_param->get_partial_shape();+ NPUW_ASSERT(param_shape.size() == 4u);+ // NB: Transpose Parameter that correspond to V-tensor it will+ // speed-up its multiplication with attention scores+ std::swap(param_shape[2], param_shape[3]);++ matched_param->set_partial_shape(param_shape);++ auto order_cst = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{4}, {0, 2, 3, 1});+ matched_transpose->set_argument(1, order_cst);+ matched_concat->set_axis(3u);+ }matched_matmul->set_transpose_b(true);ctx.get().bTransposed = true;}@@ -330,6 +335,7 @@ bool ov::npuw::util::OptimizeValueTensors::run_on_model(const std::shared_ptr<ovTransposeValueTensors::Context ctx;rewr.add_matcher<TransposeValueTensors_MHA>(std::ref(ctx));rewr.add_matcher<TransposeValueTensors_GQA>(std::ref(ctx));+rewr.run_on_model(model);ov::pass::Validate().run_on_model(model);diff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/remove_empty_kv_inputs_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/remove_empty_kv_inputs_test.cppindex bfb2e132675..b86b1795640 100644--- a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/remove_empty_kv_inputs_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/remove_empty_kv_inputs_test.cpp@@ -57,4 +57,118 @@ TEST_F(RemoveEmptyKVInputsPassTest, HandlesDownUpProjSubgraph) {EXPECT_EQ(outputs[0].get_partial_shape(), ov::PartialShape({1, 4, 1, 16}));}+// Test for shared-KV: same empty past_k parameter is consumed by two independent Concat nodes+// (Gemma4-style shared KV-cache across attention layers). RemoveEmptyKVInputs must:+// - eliminate both Concat nodes+// - remove the shared parameter exactly once (no double-remove crash or assertion)+// - leave both current-KV parameters in the model+//+// Model topology:+// past_k[1,4,0,16] ──┬── concat1(axis=2) ── result1+// current_k1[1,4,1,16]─┘+// └── concat2(axis=2) ── result2+// current_k2[1,4,1,16]──┘+TEST_F(RemoveEmptyKVInputsPassTest, SharedParam_TwoConcats_BothEliminated) {+ using namespace ov::opset13;++ auto past_k = std::make_shared<Parameter>(ov::element::f32, ov::Shape{1, 4, 0, 16});+ past_k->set_friendly_name("past_key_values.0.key");+ past_k->output(0).set_names({"past_key_values.0.key"});++ auto current_k1 = std::make_shared<Parameter>(ov::element::f32, ov::Shape{1, 4, 1, 16});+ current_k1->set_friendly_name("current_key_values.0.key");+ current_k1->output(0).set_names({"current_key_values.0.key"});++ auto current_k2 = std::make_shared<Parameter>(ov::element::f32, ov::Shape{1, 4, 1, 16});+ current_k2->set_friendly_name("current_key_values.1.key");+ current_k2->output(0).set_names({"current_key_values.1.key"});++ // Both concat nodes share the same empty past_k (Gemma4 shared KV-cache pattern).+ auto concat1 = std::make_shared<Concat>(ov::OutputVector{past_k, current_k1}, 2);+ concat1->set_friendly_name("past_key_values.0.key_concat1");++ auto concat2 = std::make_shared<Concat>(ov::OutputVector{past_k, current_k2}, 2);+ concat2->set_friendly_name("past_key_values.0.key_concat2");++ auto result1 = std::make_shared<Result>(concat1);+ result1->output(0).set_names({"present.0.key"});+ auto result2 = std::make_shared<Result>(concat2);+ result2->output(0).set_names({"present.1.key"});++ auto model = std::make_shared<ov::Model>(ov::ResultVector{result1, result2},+ ov::ParameterVector{past_k, current_k1, current_k2},+ "shared_param_two_concats_test");++ ov::npuw::RemoveEmptyKVInputs pass;+ // Must not crash even though the same parameter is matched via two separate concat nodes.+ ASSERT_NO_THROW(pass.run_on_model(model));++ // past_k must have been removed; only the two current-KV params remain.+ EXPECT_EQ(model->get_parameters().size(), 2u);+ // Both Concat nodes must be dead (unreachable from model outputs).+ EXPECT_EQ(count_ops<ov::op::v0::Concat>(model), 0u);+ // Each output now carries only the new single-token KV slice.+ const auto outputs = model->outputs();+ ASSERT_EQ(outputs.size(), 2u);+ EXPECT_EQ(outputs[0].get_partial_shape(), ov::PartialShape({1, 4, 1, 16}));+ EXPECT_EQ(outputs[1].get_partial_shape(), ov::PartialShape({1, 4, 1, 16}));+}++// Same as SharedParam_TwoConcats_BothEliminated but with f8e4m3 past_k routed through+// two independent LPT down/up-convert subgraphs before each Concat (the realistic+// quantised-KV path that triggers the LPT branch of the matcher).+TEST_F(RemoveEmptyKVInputsPassTest, SharedParam_TwoConcats_LptSubgraph_BothEliminated) {+ using namespace ov::opset13;++ auto past_k = std::make_shared<Parameter>(ov::element::f8e4m3, ov::Shape{1, 4, 0, 16});+ past_k->set_friendly_name("past_key_values.0.key");+ past_k->output(0).set_names({"past_key_values.0.key"});++ auto current_k1 = std::make_shared<Parameter>(ov::element::f8e4m3, ov::Shape{1, 4, 1, 16});+ current_k1->set_friendly_name("current_key_values.0.key");+ current_k1->output(0).set_names({"current_key_values.0.key"});++ auto current_k2 = std::make_shared<Parameter>(ov::element::f8e4m3, ov::Shape{1, 4, 1, 16});+ current_k2->set_friendly_name("current_key_values.1.key");+ current_k2->output(0).set_names({"current_key_values.1.key"});++ // Build a minimal LPT down/up-convert subgraph rooted at `src`.+ auto make_lpt = [](const std::shared_ptr<ov::Node>& src) -> std::shared_ptr<ov::Node> {+ using namespace ov::opset13;+ auto upconv = std::make_shared<Convert>(src, ov::element::f32);+ auto upscale = Constant::create(ov::element::f32, ov::Shape{}, {1.0f});+ auto upmul = std::make_shared<Multiply>(upconv, upscale);+ auto downscale = Constant::create(ov::element::f32, ov::Shape{}, {1.0f});+ auto downmul = std::make_shared<Multiply>(upmul, downscale);+ return std::make_shared<Convert>(downmul, ov::element::f8e4m3);+ };++ // Two independent LPT chains both starting from the same past_k.+ auto lpt1 = make_lpt(past_k);+ auto lpt2 = make_lpt(past_k);+ auto concat1 = std::make_shared<Concat>(ov::OutputVector{lpt1, current_k1}, 2);+ concat1->set_friendly_name("past_key_values.0.key_concat1");+ auto concat2 = std::make_shared<Concat>(ov::OutputVector{lpt2, current_k2}, 2);+ concat2->set_friendly_name("past_key_values.0.key_concat2");++ auto result1 = std::make_shared<Result>(concat1);+ result1->output(0).set_names({"present.0.key"});+ auto result2 = std::make_shared<Result>(concat2);+ result2->output(0).set_names({"present.1.key"});++ auto model = std::make_shared<ov::Model>(ov::ResultVector{result1, result2},+ ov::ParameterVector{past_k, current_k1, current_k2},+ "shared_param_two_concats_lpt_test");++ ov::npuw::RemoveEmptyKVInputs pass;+ ASSERT_NO_THROW(pass.run_on_model(model));++ EXPECT_EQ(model->get_parameters().size(), 2u);+ EXPECT_EQ(count_ops<ov::op::v0::Concat>(model), 0u);+ const auto outputs = model->outputs();+ ASSERT_EQ(outputs.size(), 2u);+ EXPECT_EQ(outputs[0].get_partial_shape(), ov::PartialShape({1, 4, 1, 16}));+ EXPECT_EQ(outputs[1].get_partial_shape(), ov::PartialShape({1, 4, 1, 16}));+}+} // namespacediff --git a/src/plugins/intel_npu/tests/unit/npuw/transpose_vt.cpp b/src/plugins/intel_npu/tests/unit/npuw/transpose_vt.cppindex 87ecb1153fd..c521755cc3e 100644--- a/src/plugins/intel_npu/tests/unit/npuw/transpose_vt.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/transpose_vt.cpp@@ -2,22 +2,24 @@// SPDX-License-Identifier: Apache-2.0//#include <gtest/gtest.h>+#include <common_test_utils/test_common.hpp>-#include "openvino/op/ops.hpp"++#include "intel_npu/config/config.hpp"#include "intel_npu/config/npuw.hpp"#include "llm_compiled_model_utils.hpp"-#include "partitioning/partitioning.hpp"-#include "intel_npu/config/config.hpp"#include "npuw_transformations/optimize_value_tensors.hpp"+#include "openvino/op/ops.hpp"+#include "partitioning/partitioning.hpp"/*-* conditional compilation that can be used during test regression debug-* #define ANALYZE_TEST-* which in turn will dump subgraphs after partitioning-*/+ * conditional compilation that can be used during test regression debug+ * #define ANALYZE_TEST+ * which in turn will dump subgraphs after partitioning+ */-namespace npuw_utest{- using NodePtr = std::shared_ptr<ov::Node>;+namespace npuw_utest {+using NodePtr = std::shared_ptr<ov::Node>;}enum class NetworkKind {@@ -25,58 +27,54 @@ enum class NetworkKind {GQA // Grouped Query Attention (e.g., llama3, phi3, mistral, GPT-OSS) - with broadcast};-typedef std::tuple <- ov::Shape,- bool, // withConvert- bool, // withTranspose - without transpose node - matcher shouldnt detect subgraph, easy way to negative case- bool, // withSDPA - should SDPA layer present or be already unrolled or simplified- bool, // use high precision on attention_mask input- bool, // withSink - SDPA with 6th input (sink) for GPT-OSS pattern- NetworkKind-> OptimizeVTTestParamsTuple;+typedef std::tuple<ov::Shape,+ bool, // withConvert+ bool, // withTranspose - without transpose node - matcher shouldnt detect subgraph, easy way to+ // negative case+ bool, // withSDPA - should SDPA layer present or be already unrolled or simplified+ bool, // use high precision on attention_mask input+ bool, // withSink - SDPA with 6th input (sink) for GPT-OSS pattern+ NetworkKind>+ OptimizeVTTestParamsTuple;struct OptimizeVTTestParams {- #define _AT(idx) std::tuple_element<idx, OptimizeVTTestParamsTuple>::type+#define _AT(idx) std::tuple_element<idx, OptimizeVTTestParamsTuple>::type- _AT(0) inputShape;- _AT(1) withConvert;- _AT(2) withTranspose;- _AT(3) withSDPA;- _AT(4) withHpAttenMask;- _AT(5) withSink;- _AT(6) kind;- #undef _AT+ _AT(0) inputShape;+ _AT(1) withConvert;+ _AT(2) withTranspose;+ _AT(3) withSDPA;+ _AT(4) withHpAttenMask;+ _AT(5) withSink;+ _AT(6) kind;+#undef _ATOptimizeVTTestParams(const OptimizeVTTestParamsTuple& tup) {std::tie(inputShape, withConvert, withTranspose, withSDPA, withHpAttenMask, withSink, kind) = tup;}};-// based on ConcatWithDifferentChildrenTransformation-class TransposeVTTest : public testing::WithParamInterface<OptimizeVTTestParamsTuple>,- public ov::test::TestsCommon {+class TransposeVTTest : public testing::WithParamInterface<OptimizeVTTestParamsTuple>, public ov::test::TestsCommon {public:void Validate() const {auto test = OptimizeVTTestParams{GetParam()};- auto isValidSubgraph = test.withTranspose;+ auto isValidSubgraph = test.withTranspose;ASSERT_EQ(isValidSubgraph, ov::npuw::util::OptimizeValueTensors(test.withHpAttenMask).run_on_model(model));- //std::shared_ptr<ov::Model> model = ...; // your model+ // std::shared_ptr<ov::Model> model = ...; // your modelauto test_case_name = getTestCaseName(testing::TestParamInfo<OptimizeVTTestParamsTuple>{GetParam(), 0});std::string xml_path = test_case_name + ".xml";std::string bin_path = test_case_name + ".bin";-#ifdef ANALYZE_TEST// Save the modelov::pass::Serialize serialize_pass(xml_path, bin_path);serialize_pass.run_on_model(model);#endif-// validation of High Precision attention mask - implies enabling SDPA layer to be unrolled,// and also specific FP16 activation transformation in partitioning// Note: When withSink=true, standard OpenVINO SDPA decomposition is used which doesn't support HP@@ -86,7 +84,8 @@ public:auto opt_desc = std::make_shared<::intel_npu::OptionsDesc>();auto cfg = ::intel_npu::Config(opt_desc);::intel_npu::registerNPUWOptions(*opt_desc);- std::map<std::string, std::string> cfg_map = {{"NPUW_F16IC", "YES"}};//, {"NPUW_ONLINE_PIPELINE", "NONE"}};+ std::map<std::string, std::string> cfg_map = {+ {"NPUW_F16IC", "YES"}}; //, {"NPUW_ONLINE_PIPELINE", "NONE"}};cfg.update(cfg_map);ov::npuw::Partitioning partitioning;@@ -97,18 +96,18 @@ public:bool bAttentionMaskResultVerified = false;auto get_rank = [](const ov::Shape& sh) {- return std::count_if(sh.begin(), sh.end(), [](size_t dim) {return dim != 1;});+ return std::count_if(sh.begin(), sh.end(), [](size_t dim) {+ return dim != 1;+ });};- for (auto & subgraph : partitioning.subgraphs) {- auto partitioned_model = std::make_shared<ov::Model>(subgraph._results,- subgraph._sinks,- subgraph._parameters,- "m1");+ for (auto& subgraph : partitioning.subgraphs) {+ auto partitioned_model =+ std::make_shared<ov::Model>(subgraph._results, subgraph._sinks, subgraph._parameters, "m1");#ifdef ANALYZE_TESTauto test_case_name = getTestCaseName(testing::TestParamInfo<OptimizeVTTestParamsTuple>{GetParam(), 0});- std::string xml_path = test_case_name + "_"+ std::to_string(idx) +"_partitioned.xml";- std::string bin_path = test_case_name + "_"+ std::to_string(idx) +"_partitioned.bin";+ std::string xml_path = test_case_name + "_" + std::to_string(idx) + "_partitioned.xml";+ std::string bin_path = test_case_name + "_" + std::to_string(idx) + "_partitioned.bin";// Save the modelov::pass::Serialize serialize_pass(xml_path, bin_path);@@ -128,8 +127,10 @@ public:ASSERT_EQ(lhs->get_output_size(), 1);ASSERT_EQ(rhs->get_output_size(), 1);- ASSERT_NE(lhs, nullptr) << "Add layer " << op->get_friendly_name() << " need to have two inputs";- ASSERT_NE(rhs, nullptr) << "Add layer " << op->get_friendly_name() << " need to have two inputs";+ ASSERT_NE(lhs, nullptr)+ << "Add layer " << op->get_friendly_name() << " need to have two inputs";+ ASSERT_NE(rhs, nullptr)+ << "Add layer " << op->get_friendly_name() << " need to have two inputs";if (get_rank(lhs->get_output_shape(0)) != 2) {ASSERT_EQ(get_rank(rhs->get_output_shape(0)), 2)@@ -139,15 +140,24 @@ public:}if (test.withHpAttenMask) {- static constexpr char err[] = "in case of high precision, attention_mask has to accept input in fp32 without convert layer";- ASSERT_TRUE(ov::is_type<ov::op::v0::Parameter>(lhs)) << err << ", actual type: " << lhs->get_type_name();- ASSERT_EQ(ov::as_type<ov::op::v0::Parameter>(lhs)->get_element_type(), ov::element::f32) << err;+ static constexpr char err[] = "in case of high precision, attention_mask has to accept "+ "input in fp32 without convert layer";+ ASSERT_TRUE(ov::is_type<ov::op::v0::Parameter>(lhs))+ << err << ", actual type: " << lhs->get_type_name();+ ASSERT_EQ(ov::as_type<ov::op::v0::Parameter>(lhs)->get_element_type(), ov::element::f32)+ << err;} else {- static constexpr char err[] = "in case of fp16 precision, attention_mask should have preceding convert layer from fp16 to fp32";+ static constexpr char err[] = "in case of fp16 precision, attention_mask should have "+ "preceding convert layer from fp16 to fp32";// input has convert from fp16 to fp32- ASSERT_TRUE(ov::is_type<ov::op::v0::Convert>(lhs)) << err << ", actual type: " << lhs->get_type_name();;- ASSERT_EQ(ov::as_type<ov::op::v0::Convert>(lhs)->get_destination_type(), ov::element::f32) << err;- ASSERT_EQ(ov::as_type<ov::op::v0::Convert>(lhs)->get_input_element_type(0), ov::element::f16) << err;+ ASSERT_TRUE(ov::is_type<ov::op::v0::Convert>(lhs))+ << err << ", actual type: " << lhs->get_type_name();+ ;+ ASSERT_EQ(ov::as_type<ov::op::v0::Convert>(lhs)->get_destination_type(), ov::element::f32)+ << err;+ ASSERT_EQ(ov::as_type<ov::op::v0::Convert>(lhs)->get_input_element_type(0),+ ov::element::f16)+ << err;}// should be only one add as atention_mask@@ -165,14 +175,24 @@ public:auto result = result_s.begin()->get_node();if (test.withHpAttenMask) {- static constexpr char err[] = "in case of high precision, attention_mask producer need to be in fp32";- ASSERT_TRUE(ov::is_type<ov::op::v0::Result>(result)) << err << ", expected type Result, actual type: " << result->get_type_name();- ASSERT_EQ(ov::as_type<ov::op::v0::Result>(result)->get_element_type(), ov::element::f32) << err;+ static constexpr char err[] =+ "in case of high precision, attention_mask producer need to be in fp32";+ ASSERT_TRUE(ov::is_type<ov::op::v0::Result>(result))+ << err << ", expected type Result, actual type: " << result->get_type_name();+ ASSERT_EQ(ov::as_type<ov::op::v0::Result>(result)->get_element_type(), ov::element::f32)+ << err;} else {- static constexpr char err[] = "in case of fp16 precision, attention_mask producer should have convert layer from fp32 to fp16";- ASSERT_TRUE(ov::is_type<ov::op::v0::Convert>(result)) << err << ", actual type: " << result->get_type_name();;- ASSERT_EQ(ov::as_type<ov::op::v0::Convert>(result)->get_destination_type(), ov::element::f16) << err;- ASSERT_EQ(ov::as_type<ov::op::v0::Convert>(result)->get_input_element_type(0), ov::element::f32) << err;+ static constexpr char err[] = "in case of fp16 precision, attention_mask producer should "+ "have convert layer from fp32 to fp16";+ ASSERT_TRUE(ov::is_type<ov::op::v0::Convert>(result))+ << err << ", actual type: " << result->get_type_name();+ ;+ ASSERT_EQ(ov::as_type<ov::op::v0::Convert>(result)->get_destination_type(),+ ov::element::f16)+ << err;+ ASSERT_EQ(ov::as_type<ov::op::v0::Convert>(result)->get_input_element_type(0),+ ov::element::f32)+ << err;}// should be only one add as atention_mask@@ -181,8 +201,10 @@ public:}}- ASSERT_TRUE(bAttentionMaskVerified) << "no attention mask node not detected after applying optimize_value_tensors + run getPartitioning";- ASSERT_TRUE(bAttentionMaskResultVerified) << "no attention mask producer node detected after applying optimize_value_tensors + run getPartitioning";+ ASSERT_TRUE(bAttentionMaskVerified)+ << "no attention mask node not detected after applying optimize_value_tensors + run getPartitioning";+ ASSERT_TRUE(bAttentionMaskResultVerified) << "no attention mask producer node detected after applying "+ "optimize_value_tensors + run getPartitioning";}}@@ -190,28 +212,24 @@ public:auto test = OptimizeVTTestParams{obj.param};std::ostringstream result;- result << "npuw_llm_pipeline_" << test.inputShape << "_"- << (test.kind == NetworkKind::MHA ? "MHA" : "GQA")- << (test.withConvert ? "_with_convert" : "")- << (test.withSDPA ? "_SDPA" : "")- << (test.withSink ? "_Sink" : "")- << (test.withHpAttenMask ? "_HP" : "")+ result << "npuw_llm_pipeline_" << test.inputShape << "_" << (test.kind == NetworkKind::MHA ? "MHA" : "GQA")+ << (test.withConvert ? "_with_convert" : "") << (test.withSDPA ? "_SDPA" : "")+ << (test.withSink ? "_Sink" : "") << (test.withHpAttenMask ? "_HP" : "")<< (!test.withTranspose ? "_NEGATIVE" : "");return result.str();}protected:-void SetUp() override {model = CreateModel();}std::shared_ptr<ov::Model> CreateModel() {-const auto test = OptimizeVTTestParams{GetParam()};- auto create_shape_constant = [](const std::vector<int64_t> & const_data, const std::string& name) {- auto pattern = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{const_data.size()}, const_data);+ auto create_shape_constant = [](const std::vector<int64_t>& const_data, const std::string& name) {+ auto pattern =+ std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{const_data.size()}, const_data);pattern->set_friendly_name("unsqueese_pattern");return pattern;};@@ -225,24 +243,29 @@ protected:input_shape.at(1) = numChannels;// ov::Model with only a transpose node- auto param = std::make_shared<ov::op::v0::Parameter>(test.withConvert ? ov::element::f16 : ov::element::f32, input_shape);+ auto param = std::make_shared<ov::op::v0::Parameter>(test.withConvert ? ov::element::f16 : ov::element::f32,+ input_shape);param->set_friendly_name("past_key_value");- std::shared_ptr<ov::Node> convert = test.withConvert ?- std::static_pointer_cast<ov::Node>(std::make_shared<ov::op::v0::Convert>(param, ov::element::f32)) :- std::static_pointer_cast<ov::Node>(param);+ std::shared_ptr<ov::Node> convert =+ test.withConvert+ ? std::static_pointer_cast<ov::Node>(std::make_shared<ov::op::v0::Convert>(param, ov::element::f32))+ : std::static_pointer_cast<ov::Node>(param);if (test.withConvert) {convert->set_friendly_name("convert");}// todo parametrise optional reshape- auto param2 = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 1, input_shape[3] * numChannels});+ auto param2 =+ std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 1, input_shape[3] * numChannels});param2->set_friendly_name("new_token");auto reshape_pattern = create_shape_constant({0, 0, numChannels, input_3}, "reshape_pattern");auto transpose_pattern = create_shape_constant({1, numChannels, 1, input_3}, "transposed_pattern");- auto reshape = std::make_shared<ov::op::v1::Reshape>(param2, test.withTranspose ? reshape_pattern : transpose_pattern, true);+ auto reshape = std::make_shared<ov::op::v1::Reshape>(param2,+ test.withTranspose ? reshape_pattern : transpose_pattern,+ true);reshape->set_friendly_name("reshape");std::shared_ptr<ov::Node> transpose_or_reshape;@@ -262,14 +285,15 @@ protected:std::shared_ptr<ov::Node> concat_or_reshape = concat;if (test.kind == NetworkKind::GQA) {- auto unsqueeze_pattern = create_shape_constant({2}, "unsqueese_pattern");+ auto unsqueeze_pattern = create_shape_constant({2}, "unsqueese_pattern");auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(concat, unsqueeze_pattern);unsqueeze->set_friendly_name("unsqueeze");-- auto broadcast_pattern = create_shape_constant({1, 8, 4, input_2 + 1, input_3}, "broadcast_pattern");- //TODO: v1::Broadcast not working- auto broadcast = std::make_shared<ov::op::v3::Broadcast>(unsqueeze, broadcast_pattern, ov::op::BroadcastType::BIDIRECTIONAL);+ auto broadcast_pattern = create_shape_constant({1, 8, 4, input_2 + 1, input_3}, "broadcast_pattern");+ // TODO: v1::Broadcast not working+ auto broadcast = std::make_shared<ov::op::v3::Broadcast>(unsqueeze,+ broadcast_pattern,+ ov::op::BroadcastType::BIDIRECTIONAL);broadcast->set_friendly_name("broadcast");auto reshape_pattern2 = create_shape_constant({0, 32, -1, input_3}, "reshape_pattern2");@@ -279,18 +303,23 @@ protected:concat_or_reshape = reshape2;}-if (test.withSDPA) {- auto mask_input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 1, input_shape[2] + 1, input_shape[2] + 1});+ auto mask_input =+ std::make_shared<ov::op::v0::Parameter>(ov::element::f32,+ ov::Shape{1, 1, input_shape[2] + 1, input_shape[2] + 1});mask_input->set_friendly_name("mask_input");auto mask_input_1 = std::make_shared<ov::op::v0::Negative>(mask_input);mask_input_1->set_friendly_name("mask_input_1");- auto k_input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 32, input_shape[2] + 1, input_shape[3]});+ auto k_input =+ std::make_shared<ov::op::v0::Parameter>(ov::element::f32,+ ov::Shape{1, 32, input_shape[2] + 1, input_shape[3]});k_input->set_friendly_name("k_input");- auto q_input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 32, input_shape[2] + 1, input_shape[3]});+ auto q_input =+ std::make_shared<ov::op::v0::Parameter>(ov::element::f32,+ ov::Shape{1, 32, input_shape[2] + 1, input_shape[3]});q_input->set_friendly_name("q_input");auto scale_node = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1}, {1});@@ -304,11 +333,20 @@ protected:sink->set_friendly_name("sink");params.push_back(sink);- sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(- q_input, k_input, concat_or_reshape, mask_input_1, scale_node, sink, false);+ sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(q_input,+ k_input,+ concat_or_reshape,+ mask_input_1,+ scale_node,+ sink,+ false);} else {- sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(- q_input, k_input, concat_or_reshape, mask_input_1, scale_node, false);+ sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(q_input,+ k_input,+ concat_or_reshape,+ mask_input_1,+ scale_node,+ false);}sdpa->set_friendly_name("sdpa");@@ -318,7 +356,8 @@ protected:return std::make_shared<ov::Model>(ov::ResultVector{result}, params);} else {- auto param3 = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 32, 1, input_shape[2] + 1});+ auto param3 =+ std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 32, 1, input_shape[2] + 1});param3->set_friendly_name("param3");// TODO: what if v1 softmax???@@ -332,14 +371,12 @@ protected:auto result = std::make_shared<ov::op::v0::Result>(matmul);result->set_friendly_name("res");return std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{param, param2, param3});-}}std::shared_ptr<ov::Model> model;};-TEST_P(TransposeVTTest, smoke_Run_MatchAndTransposeVT) {Validate();}@@ -363,16 +400,81 @@ const std::vector<NetworkKind> networkKind = {NetworkKind::GQA // Grouped Query Attention};- INSTANTIATE_TEST_SUITE_P(smoke_Run_MatchAndTransposeVT,- TransposeVTTest,- ::testing::Combine(- ::testing::ValuesIn(input_shapes),- ::testing::ValuesIn(withTranspose),- ::testing::ValuesIn(withBroadCast),- ::testing::ValuesIn(withSDPA),- ::testing::ValuesIn(withHpAttenMask),- ::testing::ValuesIn(withSink),- ::testing::ValuesIn(networkKind)),- TransposeVTTest::getTestCaseName);+INSTANTIATE_TEST_SUITE_P(smoke_Run_MatchAndTransposeVT,+ TransposeVTTest,+ ::testing::Combine(::testing::ValuesIn(input_shapes),+ ::testing::ValuesIn(withTranspose),+ ::testing::ValuesIn(withBroadCast),+ ::testing::ValuesIn(withSDPA),+ ::testing::ValuesIn(withHpAttenMask),+ ::testing::ValuesIn(withSink),+ ::testing::ValuesIn(networkKind)),+ TransposeVTTest::getTestCaseName);} // namespace++// Regression test for shared V-concat (e.g. Gemma4 local+global attention).+// When the same past_value->concat is consumed by two matmul branches, GraphRewrite+// fires the MHA matcher once per matmul. The shared mutations (param shape swap,+// transpose order, concat axis) must be applied exactly once; transpose_b is+// per-branch and must be set on both.+//+// Model topology:+//+// param[1,4,8,64] param2[1,1,256]+// | |+// | reshape[1,1,4,64]+// | |+// | transpose{0,2,1,3}[1,4,1,64]+// +-------concat(axis=2)[1,4,9,64]--------++// | |+// softmax1->matmul1 softmax2->matmul2+//+TEST(TransposeVTSharedConcatTest, smoke_SharedConcat_MHA_MultipleUsers) {+ const size_t B = 1, H = 4, S = 8, D = 64;++ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{B, H, S, D});+ param->set_friendly_name("past_value");++ auto param2 = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{B, 1, H * D});+ param2->set_friendly_name("new_token");++ auto reshape_cst = ov::op::v0::Constant::create(ov::element::i64,+ ov::Shape{4},+ std::vector<int64_t>{0, 0, (int64_t)H, (int64_t)D});+ auto reshape = std::make_shared<ov::op::v1::Reshape>(param2, reshape_cst, true);++ auto tr_order = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{4}, std::vector<int32_t>{0, 2, 1, 3});+ auto transpose = std::make_shared<ov::op::v1::Transpose>(reshape, tr_order);+ transpose->set_friendly_name("v_transpose");++ auto concat = std::make_shared<ov::op::v0::Concat>(ov::NodeVector{param, transpose}, 2);+ concat->set_friendly_name("v_concat");++ auto attn1 = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{B, H, 1, S + 1});+ attn1->set_friendly_name("attn_scores_1");+ auto matmul1 = std::make_shared<ov::op::v0::MatMul>(std::make_shared<ov::op::v8::Softmax>(attn1, -1), concat);+ matmul1->set_friendly_name("matmul1");++ auto attn2 = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{B, H, 1, S + 1});+ attn2->set_friendly_name("attn_scores_2");+ auto matmul2 = std::make_shared<ov::op::v0::MatMul>(std::make_shared<ov::op::v8::Softmax>(attn2, -1), concat);+ matmul2->set_friendly_name("matmul2");++ auto model = std::make_shared<ov::Model>(+ ov::ResultVector{std::make_shared<ov::op::v0::Result>(matmul1), std::make_shared<ov::op::v0::Result>(matmul2)},+ ov::ParameterVector{param, param2, attn1, attn2});++ bool transposed = false;+ ASSERT_NO_THROW(transposed = ov::npuw::util::OptimizeValueTensors(false).run_on_model(model));+ ASSERT_TRUE(transposed);++ // param swapped exactly once: [B,H,S,D] -> [B,H,D,S]+ const auto& ps = param->get_partial_shape();+ ASSERT_EQ(ps[2].get_length(), (int64_t)D);+ ASSERT_EQ(ps[3].get_length(), (int64_t)S);++ ASSERT_EQ(concat->get_axis(), 3);+ ASSERT_TRUE(ov::as_type_ptr<ov::op::v0::MatMul>(matmul1)->get_transpose_b());+ ASSERT_TRUE(ov::as_type_ptr<ov::op::v0::MatMul>(matmul2)->get_transpose_b());+}