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] Add new sdpa pattern for quantized case (#36354)
Alexander Kalistratovf82c0379dbf4
diff --git a/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.cpp b/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.cppindex 4703a0c8f52..6f32a588889 100644--- a/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.cpp@@ -645,14 +645,8 @@ ov::npuw::v1::subgraphs::RuntimeBehaviorFactory make_runtime_factory() {if (ov::shape_size(shape) == 0) {ctx.target_request->get_tensor(iport)->set_shape(shape);} else if (use_tensor_view) {- const auto model_past_len =- static_cast<int64_t>(pyramid->get_context_length(pyramid_id)) -- static_cast<int64_t>(pyramid->query_size_at(pyramid_id));- LOG_DEBUG("Use tensor view: past_len=" << past_len << " model_past_len="- << model_past_len);- ctx.target_request->set_tensor(- pyramid_iport,- ov::npuw::util::view(tensor, dim, 0, model_past_len));+ LOG_DEBUG("Use tensor view: past_len=" << past_len);+ ctx.target_request->set_tensor(pyramid_iport, view);} else {const auto& dst = ctx.target_request->get_tensor(iport);ov::npuw::util::copy_tensor_by_dim(view,@@ -845,8 +839,13 @@ ov::npuw::v1::subgraphs::RuntimeBehaviorFactory make_runtime_factory() {return;}if (this_case == pyramid_attention::Selector::Case::PREFILL) {- copy_mask_segment(past_len, full_mask_shape[ATTN_KV_DIM] - present_len, present_len);- copy_mask_segment(0, 0, past_len);+ if (pyramid->_data_left_aligned) {+ copy_mask_segment(0, 0, pyramid->get_context_length(pyramid_id));+ } else {+ const auto present_len = pyramid->get_context_length(pyramid_id) - past_len;+ copy_mask_segment(past_len, full_mask_shape[ATTN_KV_DIM] - present_len, present_len);+ copy_mask_segment(0, 0, past_len);+ }state.cached_attention_mask = dst;return;}diff --git a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cppindex 577355d9ffa..66c603c5105 100644--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp@@ -44,6 +44,7 @@#include "openvino/runtime/internal_properties.hpp"#include "openvino/runtime/properties.hpp"#include "openvino/util/file_util.hpp"+#include "partitioning/patterns/sdpa.hpp"#include "transformations/convert_precision.hpp"namespace {@@ -347,6 +348,24 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,m_bf16_consts = ov::npuw::s11n::get_bf16_consts(model);pre_load_transform(model, properties);+ auto attn_isolation = [](auto properties) {+ if (properties.count("NPUW_ATTN") > 0 && properties.at("NPUW_ATTN") != "STATIC") {+ return true;+ }++ if (properties.count("NPUW_ONLINE_ISOLATE") > 0) {+ auto val = properties.at("NPUW_ONLINE_ISOLATE").template as<std::string>();+ return val == "ATTN" || val.find("attn") != std::string::npos;+ }+ return false;+ };++ if (attn_isolation(properties)) {+ // In case we bypass LLMCompiledModel and step directly into CompiledModel we still need to regularize SDPA for+ // the attention isolation to work properly+ ov::npuw::patterns::regularize::RegularizeSDPA(true).run_on_model(model);+ }+::intel_npu::registerNPUWOptions(*m_options_desc);std::map<std::string, ov::Any> npuw_props;diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/snapshot.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/snapshot.cppindex 88774901e6b..24bba59df0a 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/snapshot.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/snapshot.cpp@@ -769,6 +769,7 @@ void Snapshot::earlyRegroup() {HNDL_FAKE(FakeQuantize);HNDL_ATTN(SDPA);HNDL_ATTN(SDPADecomposed);+ HNDL_ATTN(QuantizedSDPAWithGlobalMask);HNDL_ATTN(GQA);HNDL_ATTN(SDPACompressed);#undef HNDL_MOE@@ -1040,7 +1041,10 @@ std::shared_ptr<Repeated> Snapshot::tryMergeTriangles(const std::vector<Group::Greturn {};}for (const auto& el : cons) {- if (el->dstNodes().size() > 1 || el->srcNodes().size() > 1) {+ // Note: a consumer group with no destination (e.g. it feeds a Result directly)+ // has nothing to look up via dstNodes().front() below - reject it here rather+ // than triggering undefined behavior on an empty vector.+ if (el->dstNodes().empty() || el->dstNodes().size() > 1 || el->srcNodes().size() > 1) {return {};}}diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.hppindex a5c5e18bb9e..940f3523725 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.hpp@@ -104,7 +104,9 @@ static const std::map<std::string, std::string> ISOL_PRESETS = {"P:RMSNorm3/compute,P:RMSNorm4/compute,""P:VariadicSplit/compute"},{"FAKE", "P:FakeConvert/fake,P:FakeQuantize/fake"},- {"ATTN", "P:SDPA/attn,P:SDPADecomposed/attn,P:GQA/attn,P:SDPACompressed/attn"},+ {"ATTN",+ "P:SDPA/attn,P:SDPADecomposed/attn,"+ "P:QuantizedSDPAWithGlobalMask/attn,P:GQA/attn,P:SDPACompressed/attn"},{"MOE","P:GPTOSSExpert/expert,P:GPTOSSRouter/router,""P:Qwen3Expert/expert,P:Qwen3Router/router"}};diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.cppindex 46b46389b1d..501b5a29ce5 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.cpp@@ -4,7 +4,7 @@#include "sdpa.hpp"-#include <iostream>+#include <regex>#include "../../logging.hpp"#include "../online/group.hpp" // online::Group@@ -18,6 +18,70 @@namespace ov {namespace npuw {namespace patterns {++namespace {+namespace opp = ov::pass::pattern;++// Predicate for opp::wrap_type: returns true when the Add node's second input+// comes from a global attention mask path: Reshape(Tile(Convert(Parameter("..attention_mask_global..")))+bool consumes_global_mask(const ov::Output<ov::Node>& output) {+ auto node_ptr = output.get_node_shared_ptr();+ if (!node_ptr) {+ return false;+ }+ auto reshape = node_ptr->get_input_node_shared_ptr(1);+ if (!reshape || !ov::is_type<ov::op::v1::Reshape>(reshape)) {+ return false;+ }+ auto tile = reshape->get_input_node_shared_ptr(0);+ if (!tile || !ov::is_type<ov::op::v0::Tile>(tile)) {+ return false;+ }+ auto convert = tile->get_input_node_shared_ptr(0);+ if (!convert || !ov::is_type<ov::op::v0::Convert>(convert)) {+ return false;+ }+ auto mask_param = convert->get_input_node_shared_ptr(0);+ if (!mask_param || !ov::is_type<ov::op::v0::Parameter>(mask_param)) {+ return false;+ }+ return mask_param->get_friendly_name().find("attention_mask_global") != std::string::npos;+}++// Pattern nodes for the global-attention decomposed SDPA sub-graph shared by+// QuantizedSDPAWithGlobalMask and SeparateKVCache. The Add node carries the consumes_global_mask+// predicate, so this pattern only matches global-attention blocks -- which is exactly+// what SeparateKVCache needs, since local attention is not isolated/folded.+struct QuantizedSDPAWithGlobalMaskNodes {+ std::shared_ptr<ov::Node> past_k, concat1, convert1, multiply1, transpose1, matmul1;+ std::shared_ptr<ov::Node> add, softmax;+ std::shared_ptr<ov::Node> past_v, concat2, convert2, multiply2;+ std::shared_ptr<ov::Node> matmul2, reshape1, transpose, reshape2, fake_quantize;+};++inline QuantizedSDPAWithGlobalMaskNodes make_sdpa_decomposed1_pattern() {+ QuantizedSDPAWithGlobalMaskNodes n;+ n.past_k = opp::wrap_type<ov::op::v0::Parameter>();+ n.concat1 = opp::wrap_type<ov::op::v0::Concat>({opp::any_input(), n.past_k});+ n.convert1 = opp::wrap_type<ov::op::v0::Convert>({n.concat1});+ n.multiply1 = opp::wrap_type<ov::op::v1::Multiply>({n.convert1, opp::any_input()});+ n.transpose1 = opp::wrap_type<ov::op::v1::Transpose>({n.multiply1, opp::any_input()});+ n.matmul1 = opp::wrap_type<ov::op::v0::MatMul>({opp::any_input(), n.transpose1});+ n.add = opp::wrap_type<ov::op::v1::Add>({n.matmul1, opp::any_input()}, consumes_global_mask);+ n.softmax = opp::wrap_type<ov::op::v8::Softmax>({n.add});+ n.past_v = opp::wrap_type<ov::op::v0::Parameter>();+ n.concat2 = opp::wrap_type<ov::op::v0::Concat>({opp::any_input(), n.past_v});+ n.convert2 = opp::wrap_type<ov::op::v0::Convert>({n.concat2});+ n.multiply2 = opp::wrap_type<ov::op::v1::Multiply>({n.convert2, opp::any_input()});+ n.matmul2 = opp::wrap_type<ov::op::v0::MatMul>({n.softmax, n.multiply2});+ n.reshape1 = opp::wrap_type<ov::op::v1::Reshape>({n.matmul2, opp::any_input()});+ n.transpose = opp::wrap_type<ov::op::v1::Transpose>({n.reshape1, opp::any_input()});+ n.reshape2 = opp::wrap_type<ov::op::v1::Reshape>({n.transpose, opp::any_input()});++ return n;+}+} // namespace+namespace attn {namespace opp = ov::pass::pattern;@@ -352,6 +416,68 @@ SDPACompressed::SDPACompressed(const std::shared_ptr<ov::npuw::online::Snapshot>register_matcher(std::make_shared<opp::Matcher>(reshape3, "TagSDPADecomposedDQ"), std::move(callback));}+QuantizedSDPAWithGlobalMask::QuantizedSDPAWithGlobalMask(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot,+ const std::string& isol_tag) {+ // AttentionBroadcast4 pre-folds the shape sub-graph before this pass runs.+ auto n = make_sdpa_decomposed1_pattern();++ auto node_to_gptr = snapshot->getNodeToGroupMap();++ // Note: Use [=] to make sure the above objects stay alive in the callback+ auto callback = [=](ov::pass::pattern::Matcher& m) {+ LOG_DEBUG("Decomposed1 SDPA pattern matched!");++ auto& node_to_output = m.get_pattern_value_map();++ // Helper lambda to extract and isolate matched nodes+ auto isolate_matched = [&](const auto& pattern) {+ auto optional_node = node_to_output.find(pattern);+ if (optional_node != node_to_output.end()) {+ auto matched_node = optional_node->second.get_node_shared_ptr();+ node_to_gptr->at(matched_node)->isolate(isol_tag);+ }+ };++ auto concat_name = node_to_output.at(n.concat1).get_node()->get_friendly_name();+ int block_index = 0;+ std::regex pattern(R"(__module\.decoder\.blocks\.(\d+).*)");+ std::smatch match;+ if (std::regex_match(concat_name, match, pattern)) {+ block_index = std::stoi(match[1].str());+ } else {+ // doesn't matter+ }++ node_to_output.at(n.past_k).get_node()->set_friendly_name("past_key_values." + std::to_string(block_index) ++ ".key");+ node_to_output.at(n.past_v).get_node()->set_friendly_name("past_key_values." + std::to_string(block_index) ++ ".value");++ isolate_matched(n.concat1);+ isolate_matched(n.convert1);+ isolate_matched(n.multiply1);+ isolate_matched(n.transpose1);+ isolate_matched(n.matmul1);++ isolate_matched(n.add);++ isolate_matched(n.softmax);++ isolate_matched(n.concat2);+ isolate_matched(n.convert2);+ isolate_matched(n.multiply2);++ isolate_matched(n.matmul2);+ isolate_matched(n.reshape1);+ isolate_matched(n.transpose);+ isolate_matched(n.reshape2);++ return false; // root hasn't changed+ };++ register_matcher(std::make_shared<opp::Matcher>(n.reshape2, "TagQuantizedSDPAWithGlobalMask"), std::move(callback));+}+} // namespace attnnamespace regularize {@@ -502,6 +628,171 @@ ShapeOfParameter::ShapeOfParameter() {register_matcher(std::make_shared<opp::Matcher>(param_shp, "ShapeOfParameter"), std::move(callback));}+// AttentionBroadcast4: folds the ShapeOf->Gather->Concat->Reshape chain that+// appears on the attention mask path (originally part of QuantizedSDPAWithGlobalMask before+// it was simplified). Running this before QuantizedSDPAWithGlobalMask allows that pattern+// to use any_input() for the Add's second operand.+AttentionBroadcast4::AttentionBroadcast4() {+ // Pattern derived from the original QuantizedSDPAWithGlobalMask mask-shape sub-graph:+ // ShapeOf(kv) -> Gather+ // Concat(any, any, any, Gather) -> Reshape -> Add+ auto multiply = opp::wrap_type<ov::op::v1::Multiply>({opp::any_input(), opp::any_input()});+ auto shape_of = opp::wrap_type<ov::op::v3::ShapeOf>(multiply);+ auto gather = opp::wrap_type<ov::op::v8::Gather>({shape_of, opp::any_input(), opp::any_input()});+ auto concat_gather =+ opp::wrap_type<ov::op::v0::Concat>({opp::any_input(), opp::any_input(), opp::any_input(), gather});+ auto reshape_gather = opp::wrap_type<ov::op::v1::Reshape>({opp::any_input(), concat_gather});++ // Note: Use [=] to make sure the above objects stay alive in the callback+ auto callback = [=](ov::pass::pattern::Matcher& m) {+ auto& node_to_output = m.get_pattern_value_map();+ auto matched_gather_out = node_to_output.at(gather);+ if (matched_gather_out.get_target_inputs().size() > 1) {+ // This pattern is for the Gather that feeds a single Concat.+ return false;+ }+ auto matched_concat_out = node_to_output.at(concat_gather);+ auto& matched_concat_tensor = matched_concat_out.get_tensor();+ if (matched_concat_tensor.has_and_set_bound()) {+ // Replace the dynamic shape calculation with a static constant+ // This is bad but it in the current realm it is what it is+ auto new_const = std::make_shared<ov::op::v0::Constant>(matched_concat_tensor.get_upper_value());+ new_const->set_friendly_name("NPUW/Precalculated/" ++ matched_concat_out.get_node_shared_ptr()->get_friendly_name());+ for (auto&& input : matched_concat_out.get_target_inputs()) {+ input.replace_source_output(new_const);+ }++ return true; // root changed+ }+ return false; // root hasn't changed+ };++ register_matcher(std::make_shared<opp::Matcher>(reshape_gather, "AttentionBroadcast4"), std::move(callback));+}++// SeparateKVCache: OpenVINO's SharedOpOptimization (run by Model::reshape) merges the+// identical K- and V-cache dequantization chains across global-attention blocks that+// reuse the same KV cache, so a single K-transpose / V-multiply can feed several blocks'+// MatMuls. The NPUW repeated-block partitioner cannot represent such a shared node -- it+// leaks as an extra output of one block while being consumed by others, producing repeated+// blocks with inconsistent output counts. This pass duplicates the shared cache chain per+// consumer so each attention block owns an independent copy. The K side+// (Concat->Convert->Multiply->Transpose) and the V side (Concat->Convert->Multiply) are+// handled the same way.+//+// NB: This pass reuses the QuantizedSDPAWithGlobalMask pattern (with the consumes_global_mask+// predicate), so it only fires for global-attention blocks. Local attention is not+// isolated/folded here, so leaving its (also shared) KV chains untouched is fine.+SeparateKVCache::SeparateKVCache() {+ auto n = make_sdpa_decomposed1_pattern();++ // Note: Use [=] to make sure the above objects stay alive in the callback+ auto callback = [=](ov::pass::pattern::Matcher& m) {+ auto& node_to_output = m.get_pattern_value_map();++ // Clone a (possibly weight) constant so each duplicated chain owns its own node.+ // Sharing one constant across multiple call-site subgraph models confuses the+ // partitioner's propagateWeights bank-assignment, which expects exactly one+ // constant per call site. Non-constant sources (e.g. a Parameter) are reused.+ auto clone_source = [](const ov::Output<ov::Node>& src) -> ov::Output<ov::Node> {+ if (auto c = std::dynamic_pointer_cast<ov::op::v0::Constant>(src.get_node_shared_ptr())) {+ return std::make_shared<ov::op::v0::Constant>(*c)->output(0);+ }+ return src;+ };++ // Duplicate the cache chain feeding `shared_node` for every consumer other than the+ // one already matched in this pattern. `clone_chain` builds a fresh, independent copy+ // of the chain. Returns true if any consumer was redirected.+ auto unshare = [&](const std::shared_ptr<ov::Node>& shared_node,+ const ov::Node* pattern_consumer,+ auto&& clone_chain) -> bool {+ if (!shared_node) {+ return false;+ }+ auto targets = shared_node->output(0).get_target_inputs();+ if (targets.size() <= 1) {+ return false; // only the matched consumer -- nothing to unshare.+ }+ bool changed = false;+ for (auto& target_input : targets) {+ if (target_input.get_node() == pattern_consumer) {+ continue; // keep the matched consumer on the original chain.+ }+ if (!dynamic_cast<ov::op::v0::MatMul*>(target_input.get_node())) {+ continue;+ }+ target_input.replace_source_output(clone_chain());+ changed = true;+ }+ return changed;+ };++ auto concat1_node =+ std::dynamic_pointer_cast<ov::op::v0::Concat>(node_to_output.at(n.concat1).get_node_shared_ptr());+ auto convert1_node =+ std::dynamic_pointer_cast<ov::op::v0::Convert>(node_to_output.at(n.convert1).get_node_shared_ptr());+ auto multiply1_node =+ std::dynamic_pointer_cast<ov::op::v1::Multiply>(node_to_output.at(n.multiply1).get_node_shared_ptr());+ auto transpose1_node =+ std::dynamic_pointer_cast<ov::op::v1::Transpose>(node_to_output.at(n.transpose1).get_node_shared_ptr());+ auto matmul1_node =+ std::dynamic_pointer_cast<ov::op::v0::MatMul>(node_to_output.at(n.matmul1).get_node_shared_ptr());++ auto concat2_node =+ std::dynamic_pointer_cast<ov::op::v0::Concat>(node_to_output.at(n.concat2).get_node_shared_ptr());+ auto convert2_node =+ std::dynamic_pointer_cast<ov::op::v0::Convert>(node_to_output.at(n.convert2).get_node_shared_ptr());+ auto multiply2_node =+ std::dynamic_pointer_cast<ov::op::v1::Multiply>(node_to_output.at(n.multiply2).get_node_shared_ptr());+ auto matmul2_node =+ std::dynamic_pointer_cast<ov::op::v0::MatMul>(node_to_output.at(n.matmul2).get_node_shared_ptr());++ auto concat1_inputs = concat1_node->inputs();+ auto multiply1_inputs = multiply1_node->inputs();+ auto transpose1_inputs = transpose1_node->inputs();+ auto concat2_inputs = concat2_node->inputs();+ auto multiply2_inputs = multiply2_node->inputs();++ // K-cache chain clone: Concat -> Convert -> Multiply -> Transpose+ auto clone_k = [&]() -> ov::Output<ov::Node> {+ auto new_concat = std::make_shared<ov::op::v0::Concat>(+ ov::OutputVector{concat1_inputs[0].get_source_output(), concat1_inputs[1].get_source_output()},+ concat1_node->get_axis());+ auto new_convert =+ std::make_shared<ov::op::v0::Convert>(new_concat, convert1_node->get_convert_element_type());+ auto new_multiply =+ std::make_shared<ov::op::v1::Multiply>(new_convert,+ clone_source(multiply1_inputs[1].get_source_output()));+ auto new_transpose =+ std::make_shared<ov::op::v1::Transpose>(new_multiply,+ clone_source(transpose1_inputs[1].get_source_output()));+ return new_transpose->output(0);+ };++ // V-cache chain clone: Concat -> Convert -> Multiply+ auto clone_v = [&]() -> ov::Output<ov::Node> {+ auto new_concat = std::make_shared<ov::op::v0::Concat>(+ ov::OutputVector{concat2_inputs[0].get_source_output(), concat2_inputs[1].get_source_output()},+ concat2_node->get_axis());+ auto new_convert =+ std::make_shared<ov::op::v0::Convert>(new_concat, convert2_node->get_convert_element_type());+ auto new_multiply =+ std::make_shared<ov::op::v1::Multiply>(new_convert,+ clone_source(multiply2_inputs[1].get_source_output()));+ return new_multiply->output(0);+ };++ bool changed = false;+ changed = unshare(transpose1_node, matmul1_node.get(), clone_k) || changed;+ changed = unshare(multiply2_node, matmul2_node.get(), clone_v) || changed;+ return changed;+ };++ register_matcher(std::make_shared<opp::Matcher>(n.reshape2, "SeparateKVCache"), std::move(callback));+}+bool RegularizeSDPA::run_on_model(const std::shared_ptr<ov::Model>& model) {bool model_changed = false;if (m_run_broadcast_pattern) {@@ -509,6 +800,8 @@ bool RegularizeSDPA::run_on_model(const std::shared_ptr<ov::Model>& model) {rewr.add_matcher<ov::npuw::patterns::regularize::AttentionBroadcast>();rewr.add_matcher<ov::npuw::patterns::regularize::AttentionBroadcast2>();rewr.add_matcher<ov::npuw::patterns::regularize::AttentionBroadcast3>();+ rewr.add_matcher<ov::npuw::patterns::regularize::AttentionBroadcast4>();+ rewr.add_matcher<ov::npuw::patterns::regularize::SeparateKVCache>();model_changed |= rewr.run_on_model(model);}diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.hppindex 8f973de67e6..335fceaa9fc 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.hpp@@ -52,6 +52,22 @@ public:SDPADecomposed(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag);};+class QuantizedSDPAWithGlobalMask : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::attn::QuantizedSDPAWithGlobalMask");+ static constexpr const char* pattern_name() {+ return "QuantizedSDPAWithGlobalMask";+ }+ static constexpr const char* isolation_tag() {+ return "attn";+ }+ static constexpr const char* group_name() {+ return "attn";+ }+ QuantizedSDPAWithGlobalMask(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot,+ const std::string& isol_tag);+};+// Matches decomposed SDPA pattern where past KV cache inputs have been converted// to integer precision (i8/u8) with dynamic dequantization nodes inserted by// ConvertKVCacheToPrecision. The dequantization chain is:@@ -95,6 +111,18 @@ public:AttentionBroadcast3();};+class AttentionBroadcast4 : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::regularize::AttentionBroadcast4");+ AttentionBroadcast4();+};++class SeparateKVCache : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::regularize::SeparateKVCache");+ SeparateKVCache();+};+class ShapeOfParameter : public ov::pass::MatcherPass {public:OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::attn::ShapeOfParameter");diff --git a/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp b/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cppindex 1e7e53f74af..fbf6dfd1bdf 100644--- a/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp@@ -8,12 +8,85 @@#include <utility>#include "openvino/core/validation_util.hpp"+#include "openvino/op/broadcast.hpp"#include "openvino/op/concat.hpp"#include "openvino/op/convert.hpp"+#include "openvino/op/multiply.hpp"#include "openvino/op/parameter.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/op/unsqueeze.hpp"#include "openvino/op/util/op_types.hpp"#include "util.hpp"+namespace {++using ov::npuw::runtime::pyramid_attention::Selector;++// Returns the last positive position ID value (used to determine current sequence length),+// or nullopt when no positive position ID was found in the tensor.+std::optional<int64_t> current_length_from_position_ids(const ov::SoPtr<ov::ITensor>& tensor, const ov::Shape& shape) {+ const auto elem_type = tensor->get_element_type();++ // Read a single position ID value, handling both i32 and i64 tensors+ auto get_pos = [&](size_t i) -> int64_t {+ if (elem_type == ov::element::i64) {+ return tensor->data<int64_t>()[i];+ } else if (elem_type == ov::element::i32) {+ return static_cast<int64_t>(tensor->data<int32_t>()[i]);+ } else {+ OPENVINO_ASSERT(false, "Unsupported element type for position IDs: " + elem_type.get_type_name());+ }++ return -1; // Should never reach here+ };+ // Read the last position ID value to determine current sequence length+ // This assumes that position IDs are contiguous and start from 0+ // TODO: we are not zeroing the position IDs during chunked prefill,+ // so this logic is broken for left-aligned data case.+ // Also need additional checks for eagle case where position IDs might not be contiguous at all.+ // Return wrong value when PositionIDs are start from 1+ for (int64_t idx = static_cast<int64_t>(shape.back()) - 1; idx >= 0; idx--) {+ const auto pos = get_pos(idx);+ if (pos > 0) {+ return pos;+ }+ }++ return std::nullopt;+}++int64_t get_past_length_for_case(Selector::Case c, int64_t current_length, int64_t pyramid_step) {+ switch (c) {+ case Selector::Case::GENERATE:+ // In generate case, past length is equal to current length (since query length is 1)+ return current_length;+ case Selector::Case::PREFILL:+ // In prefill case, past length is the largest multiple of pyramid_step that is less than current_length+ // This ensures we select the correct pyramid model for the current sequence length+ // For chunked prefill we have all the chunks full except maybe last one,+ // so we can calculate past length directly from current length and pyramid step+ return (current_length / pyramid_step) * pyramid_step;+ default:+ NPUW_ASSERT(false && "Reached the unreachable code");+ return -1;+ }+}++// Picks the smallest pyramid model whose context length can accommodate current_seq_length,+// falling back to the largest model when the sequence length exceeds all models' capacity.+// Shared by all position-id-based selectors so the pattern-specific past/current length+// calculation stays the only thing that differs between them.+std::size_t select_pyramid_id(const std::vector<std::size_t>& context_lengths, int64_t current_seq_length) {+ for (std::size_t i = 0; i < context_lengths.size(); ++i) {+ if (current_seq_length <= static_cast<int64_t>(context_lengths[i])) {+ return i;+ }+ }+ return context_lengths.size() - 1;+}+} // namespace+namespace ov {namespace npuw {namespace function {@@ -93,6 +166,59 @@ static void collect_concat_block_indices(const std::shared_ptr<ov::Model>& model}}+// Determine, for `concat_node`, the input index carrying the past KV cache.+//+// The past input traces back (through the usual dequant / layout ops) to a+// past_key_values Parameter; the present input is computed from the current tokens and+// never reaches such a Parameter. Returns nullopt when no past input is found.+static std::optional<size_t> find_past_concat_input_index(const std::shared_ptr<ov::Node>& concat_node, bool is_key) {+ auto concat_op = std::dynamic_pointer_cast<ov::op::v0::Concat>(concat_node);+ if (!concat_op) {+ return std::nullopt;+ }++ auto reaches_past_param = [is_key](std::shared_ptr<ov::Node> node) -> bool {+ // Walk back along the data input (input 0) through dequant / layout ops until a+ // Parameter (or an unrecognized op) is reached.+ while (node) {+ if (auto param = std::dynamic_pointer_cast<ov::op::v0::Parameter>(node)) {+ const auto& name = param->get_friendly_name();+ return is_key ? ov::npuw::util::isPastKeyValuesKeyContiguous(name).has_value()+ : ov::npuw::util::isPastKeyValuesValueContiguous(name).has_value();+ }+ if (ov::is_type<ov::op::v0::Convert>(node) || ov::is_type<ov::op::v1::Multiply>(node) ||+ ov::is_type<ov::op::v1::Reshape>(node) || ov::is_type<ov::op::v1::Transpose>(node) ||+ ov::is_type<ov::op::v0::Unsqueeze>(node) || ov::is_type<ov::op::v3::Broadcast>(node)) {+ if (node->get_input_size() == 0) {+ break;+ }+ node = node->get_input_node_shared_ptr(0);+ continue;+ }+ break;+ }+ return false;+ };++ const size_t n = concat_op->get_input_size();+ for (size_t i = 0; i < n; ++i) {+ if (reaches_past_param(concat_op->get_input_node_shared_ptr(i))) {+ return i;+ }+ }+ return std::nullopt;+}++// True when, for `concat_node`, the freshly-computed present KV input precedes the past+// KV cache input (Concat order [present | past], i.e. the past cache is appended last).+// This encodes the left-aligned KV layout independently of tensor dtype or seq-dim index.+static bool concat_present_before_past(const std::shared_ptr<ov::Node>& concat_node, bool is_key) {+ const auto past_idx = find_past_concat_input_index(concat_node, is_key);+ // "present before past" means the past input is not the first input (a present input+ // precedes it). For the contiguous 2-input case this is simply past_idx == 1.+ return past_idx.has_value() && *past_idx > 0;+}+// Helper function to process a single pyramid model (clone, reshape, patch, optimize)std::optional<PyramidModelResult> process_pyramid_model(const std::shared_ptr<ov::Model>& original_model,size_t model_idx,@@ -119,7 +245,7 @@ std::optional<PyramidModelResult> process_pyramid_model(const std::shared_ptr<ov} else {// PREFILLcurrent_context_length = (model_idx + 1) * pyramid_step;- current_past_length = current_context_length - query_length;+ current_past_length = current_context_length - pyramid_step;}// FIXME: Probably the generic formula for all cases is:// current_context_length = (model_idx + 1) * pyramid_step;@@ -502,9 +628,25 @@ std::optional<PyramidValidationResult> validate_and_setup_pyramid_attention(consreturn std::nullopt;}+ // Left-aligned KV layout is defined structurally: for both K and V the freshly-computed+ // present KV is concatenated *before* the past KV cache (Concat order [present | past],+ // i.e. the past cache is appended last).+ const bool present_before_past = concat_present_before_past(pattern_nodes.past_key_concat_node, /*is_key=*/true) &&+ concat_present_before_past(pattern_nodes.past_value_concat_node, /*is_key=*/false);++ // Additional guard: the specific quantized layout this path was validated against+ // (i8 KV, key sequence dim 1, value sequence dim 3).+ const bool matches_quantized_layout = past_key_sequence_dims.begin()->second == 1 &&+ past_value_sequence_dims.begin()->second == 3 &&+ pattern_nodes.past_key_concat_node->get_element_type() == ov::element::i8 &&+ pattern_nodes.past_value_concat_node->get_element_type() == ov::element::i8;++ const bool data_left_aligned = present_before_past && matches_quantized_layout;+return PyramidValidationContiguousResult{query_length,full_context_length,past_kv_length,+ data_left_aligned,std::move(past_key_sequence_dims),std::move(past_value_sequence_dims)};}@@ -520,6 +662,7 @@ std::optional<PyramidAttention> PyramidAttention::from(const std::shared_ptr<ov:size_t query_length = 0;size_t full_past_kv_length = 0;size_t full_context_length = 0;+ bool is_left_aligned = false;std::map<std::string, size_t> past_key_sequence_dims;std::map<std::string, size_t> past_value_sequence_dims;bool is_block_split = false;@@ -535,6 +678,7 @@ std::optional<PyramidAttention> PyramidAttention::from(const std::shared_ptr<ov:full_past_kv_length = result.past_kv_length;past_key_sequence_dims = result.past_key_sequence_dims;past_value_sequence_dims = result.past_value_sequence_dims;+ is_left_aligned = result.data_left_aligned;} else {static_assert(std::is_same_v<T, PyramidValidationBlockResult>);is_block_split = true;@@ -550,7 +694,8 @@ std::optional<PyramidAttention> PyramidAttention::from(const std::shared_ptr<ov:// FIXME: Make it configurable// FIXME: Handle the speculative case here (query_length > 1; << 1024)bool is_generate = query_length == 1;- size_t pyramid_step = is_generate ? 1024u : query_length;+ size_t kv_step = full_context_length - full_past_kv_length;+ size_t pyramid_step = is_generate ? 1024u : kv_step;// FIXME: Check all the right alignmentssize_t num_models = full_context_length / pyramid_step;LOG_INFO("Creating " << num_models << " pyramid attention models");@@ -611,6 +756,7 @@ std::optional<PyramidAttention> PyramidAttention::from(const std::shared_ptr<ov:pyramid_attention._full_context_length = full_context_length;pyramid_attention._models = pyramid_models;pyramid_attention._attentions = pyramid_attentions;+ pyramid_attention._data_left_aligned = is_left_aligned;// Block indices are empty in contiguous mode; assigned unconditionally for simplicity.pyramid_attention.past_key_block_global_param_indices = std::move(block_key_global_indices);pyramid_attention.past_value_block_global_param_indices = std::move(block_val_global_indices);@@ -686,6 +832,7 @@ std::shared_ptr<PyramidAttention> PyramidAttention::make(const function::Pyramidobj->query_size = func_pyramid._query_length;obj->full_context_size = func_pyramid._full_context_length;obj->_models_to_compile = func_pyramid._models;+ obj->_data_left_aligned = func_pyramid._data_left_aligned;obj->_attention_infos.reserve(num_models);obj->_context_lengths.reserve(num_models);@@ -787,11 +934,21 @@ Selector::Ptr PositionIDs::find(const compiled::PyramidAttention& d, const ov::Iconst auto& inputs = rq.get_inputs();auto pos_ids_iter = std::find_if(inputs.begin(), inputs.end(), is_position_ids);- if (pos_ids_iter != inputs.end()) {- const auto param_idx = std::distance(inputs.begin(), pos_ids_iter);- return Selector::Ptr{new PositionIDs(param_idx, d, rq)};+ if (pos_ids_iter == inputs.end()) {+ return Selector::Ptr{};}- return Selector::Ptr{};++ const auto param_idx = std::distance(inputs.begin(), pos_ids_iter);++ // Reuse the same structural signal as the mask/left-alignment decision: a left-aligned+ // KV layout (present concatenated before past, quantized i8 KV) corresponds to the+ // QuantizedSDPAWithGlobalMask pattern, where a large query is matched against a+ // smaller-granularity KV cache update and GlobalPositionIDs is required. The regular+ // contiguous case (e.g. SDPADecomposed) is not left-aligned and uses PositionIDs.+ if (d._data_left_aligned) {+ return Selector::Ptr{new GlobalPositionIDs(param_idx, d, rq)};+ }+ return Selector::Ptr{new PositionIDs(param_idx, d, rq)};}void PositionIDs::prepare(int64_t past_len) {@@ -799,7 +956,13 @@ void PositionIDs::prepare(int64_t past_len) {const auto in_tensor = m_rq.get_tensor(iport);const auto in_dims = in_tensor->get_shape();+ NPUW_ASSERT(m_pyramid_attention && "PyramidAttention reference must not be null");+ const auto& context_lengths = m_pyramid_attention->_context_lengths;+// Same logic as regular attention PositionIDs+ // NOTE: assumes i64 position IDs, matching the original (master) implementation.+ // TODO: models with i32 position IDs would need the i32/i64-aware read used by+ // current_length_from_position_ids() (see GlobalPositionIDs::prepare()).auto* pos_data_ptr = in_tensor->data<int64_t>();for (int64_t idx = static_cast<int64_t>(in_dims.back()) - 1; idx >= 0; idx--) {if (pos_data_ptr[idx] > 0) {@@ -820,30 +983,16 @@ void PositionIDs::prepare(int64_t past_len) {}// Select the optimal pyramid model based on current sequence length- NPUW_ASSERT(m_pyramid_attention && "PyramidAttention reference must not be null");-- const auto& context_lengths = m_pyramid_attention->_context_lengths;- const int64_t current_seq_length = m_query_size + m_past_length;-- // Find the smallest pyramid model that can handle the current sequence length- for (std::size_t i = 0; i < context_lengths.size(); ++i) {- if (current_seq_length <= static_cast<int64_t>(context_lengths[i])) {- m_pyramid_id = i;- return;- }- }-- // If sequence length exceeds all models' capacity, use the largest model- m_pyramid_id = context_lengths.size() - 1;+ const int64_t current_seq_length = static_cast<int64_t>(m_query_size) + m_past_length;+ m_pyramid_id = select_pyramid_id(context_lengths, current_seq_length);return;}}LOG_WARN("Dynamic selector - no data found in the feature?");m_current_length = -1;- NPUW_ASSERT(m_pyramid_attention && "PyramidAttention reference must not be null");// Default to largest model if no data found (safest choice for unknown sequence length)- m_pyramid_id = m_pyramid_attention->_context_lengths.size() - 1;+ m_pyramid_id = context_lengths.size() - 1;}int64_t PositionIDs::length() const {@@ -854,6 +1003,55 @@ int64_t PositionIDs::past_length() const {return m_past_length;}+// Pyramid Attention GlobalPositionIDs implementation+GlobalPositionIDs::GlobalPositionIDs(std::size_t param_idx,+ const compiled::PyramidAttention& d,+ const ov::ISyncInferRequest& rq)+ : m_position_ids_idx(param_idx),+ m_query_size(d.query_size),+ m_pyramid_step(d._context_lengths.empty() ? d.query_size : d._context_lengths[0]),+ m_pyramid_attention(&d),+ m_rq(rq) {+ // FIXME: speculative decode is indistinguishable at this point!+ m_case = m_query_size == 1 ? Case::GENERATE : Case::PREFILL;+}++void GlobalPositionIDs::prepare(int64_t past_len) {+ const auto& iport = m_rq.get_compiled_model()->inputs()[m_position_ids_idx];+ const auto in_tensor = m_rq.get_tensor(iport);+ const auto in_dims = in_tensor->get_shape();++ NPUW_ASSERT(m_pyramid_attention && "PyramidAttention reference must not be null");+ const auto& context_lengths = m_pyramid_attention->_context_lengths;++ const auto found_length = current_length_from_position_ids(in_tensor, in_dims);+ if (!found_length) {+ // Same fallback as PositionIDs: no positive position id found anywhere in the+ // tensor - default to the largest model (safest choice for unknown sequence length).+ LOG_WARN("Dynamic selector - no data found in the feature?");+ m_current_length = -1;+ m_pyramid_id = context_lengths.size() - 1;+ return;+ }++ m_current_length = *found_length;+ m_past_length = get_past_length_for_case(m_case, m_current_length, m_pyramid_step);++ // Select the optimal pyramid model based on current sequence length+ const int64_t query_contrib =+ (m_case == Case::PREFILL) ? static_cast<int64_t>(m_pyramid_step) : static_cast<int64_t>(m_query_size);+ const int64_t current_seq_length = query_contrib + m_past_length;+ m_pyramid_id = select_pyramid_id(context_lengths, current_seq_length);+}++int64_t GlobalPositionIDs::length() const {+ return m_current_length;+}++int64_t GlobalPositionIDs::past_length() const {+ return m_past_length;+}+} // namespace pyramid_attention} // namespace runtime} // namespace npuwdiff --git a/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.hpp b/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.hppindex b99b11a3de8..00722502b51 100644--- a/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.hpp@@ -35,6 +35,7 @@ struct PyramidValidationContiguousResult {size_t query_length = 0;size_t full_context_length = 0;size_t past_kv_length = 0;+ bool data_left_aligned = false;std::map<std::string, size_t> past_key_sequence_dims;std::map<std::string, size_t> past_value_sequence_dims;@@ -100,6 +101,7 @@ struct PyramidAttention {std::vector<std::shared_ptr<ov::Model>> _models;size_t _query_length = 0;size_t _full_context_length = 0;+ bool _data_left_aligned = false;// Block mode only: global KV block parameter indices (block_0..block_N).// Global (full-model) KV block parameter indices (block0..blockN).@@ -183,6 +185,8 @@ struct PyramidAttention {std::size_t full_context_size = 0u;/// Whether non-last pyramid models were compiled with strided-input support.bool _can_use_tensor_view = false;++ bool _data_left_aligned = false;/// Temporary storage for models pending compilation; cleared by set_compiled_models().std::vector<std::shared_ptr<ov::Model>> _models_to_compile;@@ -354,7 +358,9 @@ public:}};-// Define pyramid model selection based on position ids+// Define pyramid model selection based on position ids.+// Handles the regular (contiguous) case where the KV update step matches the query+// length, e.g. the SDPADecomposed pattern.class PositionIDs final : public Selector {std::size_t m_position_ids_idx = 0u;int64_t m_current_length = 0;@@ -375,6 +381,31 @@ public:static Selector::Ptr find(const compiled::PyramidAttention& d, const ov::ISyncInferRequest& rq);};+// Define pyramid model selection based on position ids for attention patterns where the+// KV update step (pyramid_step) differs from the query length - e.g. QuantizedSDPAWithGlobalMask,+// where a large query is matched against a smaller-granularity KV cache update.+// Equivalent to PositionIDs, except past/current sequence length are derived from+// pyramid_step instead of query_size. Constructed only via PositionIDs::find().+class GlobalPositionIDs final : public Selector {+ std::size_t m_position_ids_idx = 0u;+ int64_t m_current_length = 0;+ int64_t m_past_length = 0;+ std::size_t m_query_size = 0u;+ std::size_t m_pyramid_step = 0u;++ // Store pyramid attention reference for pyramid model selection+ const compiled::PyramidAttention* m_pyramid_attention = nullptr;++ const ov::ISyncInferRequest& m_rq;++ GlobalPositionIDs(std::size_t param_idx, const compiled::PyramidAttention& d, const ov::ISyncInferRequest& rq);+ void prepare(int64_t past_len) override;+ int64_t length() const override;+ int64_t past_length() const override;++ friend class PositionIDs; // constructed only via PositionIDs::find()+};+} // namespace pyramid_attention} // namespace runtimediff --git a/src/plugins/intel_npu/src/plugin/npuw/util.cpp b/src/plugins/intel_npu/src/plugin/npuw/util.cppindex e96e03fa24a..07fd8249de0 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util.cpp@@ -19,10 +19,13 @@#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/multiply.hpp"#include "openvino/op/parameter.hpp"#include "openvino/op/reshape.hpp"#include "openvino/op/softmax.hpp"+#include "openvino/op/transpose.hpp"#include "openvino/op/unsqueeze.hpp"#include "openvino/op/util/op_types.hpp"#include "openvino/runtime/make_tensor.hpp" // get_tensor_impl@@ -1068,7 +1071,8 @@ std::vector<ov::npuw::util::SDPAPatternNodes> find_sdpa_pattern_nodes_internal(c// Allow traversing through Reshape and Transposeif (ov::is_type<ov::op::v1::Reshape>(current_node) || ov::is_type<ov::op::v3::Broadcast>(current_node) ||- ov::is_type<ov::op::v0::Unsqueeze>(current_node)) {+ ov::is_type<ov::op::v0::Unsqueeze>(current_node) || ov::is_type<ov::op::v1::Transpose>(current_node) ||+ ov::is_type<ov::op::v1::Multiply>(current_node) || ov::is_type<ov::op::v0::Convert>(current_node)) {if (current_node->get_input_size() > 0) {current_node = current_node->input(0).get_source_output().get_node_shared_ptr();} else {diff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/regularize_sdpa_passes_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/regularize_sdpa_passes_test.cppnew file mode 100644index 00000000000..5f591147f47--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/regularize_sdpa_passes_test.cpp@@ -0,0 +1,699 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Unit tests for the three passes introduced alongside the QuantizedSDPAWithGlobalMask+// online-partitioner pattern:+//+// 1. AttentionBroadcast4 (regularize namespace)+// Folds a ShapeOf → Gather → [any, Constant, any, Gather] Concat → Reshape+// chain into a static Constant when the ShapeOf input has a known static+// shape. This pre-processing step is required before QuantizedSDPAWithGlobalMask can+// match the simplified attention-mask sub-graph.+//+// 2. SeparateVCache (regularize namespace)+// When the V-cache chain (Concat→Convert→Multiply) is consumed by more than+// one MatMul (i.e. shared across attention heads), duplicates the chain for+// every extra consumer so that each MatMul owns an independent copy. This+// is required for correct partition-weight bank assignment.+//+// 3. QuantizedSDPAWithGlobalMask (attn namespace, online-partitioner MatcherPass)+// Tags all nodes of a KV-cache-augmented decomposed SDPA sub-graph with the+// given isolation tag so that the online partitioner can isolate them into+// a single attention partition.+//+// Model building is local to each test suite; no external model builder is used.++#include <gtest/gtest.h>++#include <algorithm>+#include <memory>++#include "openvino/op/add.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/result.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/softmax.hpp"+#include "openvino/op/tile.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/core/bound_evaluation_util.hpp"+#include "openvino/pass/graph_rewrite.hpp"+#include "partitioning/online/group.hpp"+#include "partitioning/online/snapshot.hpp"+#include "partitioning/patterns/sdpa.hpp"++namespace {++using namespace ov;+namespace op = ov::op;++// ---------------------------------------------------------------------------+// Shared helpers+// ---------------------------------------------------------------------------++template <class Op>+static std::size_t count_ops(const std::shared_ptr<Model>& model) {+ const auto ops = model->get_ops();+ return std::count_if(ops.begin(), ops.end(), [](const auto& n) {+ return ov::is_type<Op>(n);+ });+}++// ---------------------------------------------------------------------------+// AttentionBroadcast4 tests+// ---------------------------------------------------------------------------++// Builds: kv_param → Multiply → ShapeOf → Gather → Concat([a, b, c, Gather]) → Reshape+// with a static-shape kv_param so the pass can fold the shape chain away.+static std::shared_ptr<Model> build_attention_broadcast4_static_model() {+ // kv has static shape – bounds can be evaluated so the pass can fold.+ auto kv_param = std::make_shared<op::v0::Parameter>(element::f32, Shape{1, 2, 4, 8});+ kv_param->set_friendly_name("kv_param");++ // Multiply is required by the updated pattern: ShapeOf(Multiply(...))+ auto scale = op::v0::Constant::create(element::f32, Shape{}, {0.5f});+ auto multiply = std::make_shared<op::v1::Multiply>(kv_param, scale);+ multiply->set_friendly_name("kv_multiply");++ // ShapeOf(multiply) → i64 [4], value = {1, 2, 4, 8}+ auto shape_of = std::make_shared<op::v3::ShapeOf>(multiply, element::i64);++ // Gather position 2 (the sequence dimension = 4) as a 1-element tensor.+ auto gather_indices = op::v0::Constant::create(element::i64, Shape{1}, {2});+ auto gather_axis = op::v0::Constant::create(element::i64, Shape{}, {0});+ auto gather = std::make_shared<op::v8::Gather>(shape_of, gather_indices, gather_axis);++ // Build shape tensor [{1}, {2}, {1}, {seq_len}] via Concat.+ // Pattern: Concat({any_input, Constant, any_input, gather})+ auto dim_a = op::v0::Constant::create(element::i64, Shape{1}, {1}); // any_input (0)+ auto dim_c = op::v0::Constant::create(element::i64, Shape{1}, {2}); // the Constant node+ auto dim_b = op::v0::Constant::create(element::i64, Shape{1}, {1}); // any_input (2)+ // gather is input 3+ auto concat_gather = std::make_shared<op::v0::Concat>(+ OutputVector{dim_a, dim_c, dim_b, gather}, /*axis=*/0);++ // Reshape data (8 elements, matching the concat_gather-derived shape [1,2,1,4]) using+ // concat_gather as the shape-pattern input - this is the order the AttentionBroadcast4+ // pattern actually matches: Reshape({any_input (data), concat_gather (shape)}).+ auto reshape_data = op::v0::Constant::create(element::f32, Shape{8}, std::vector<float>(8, 1.0f));+ auto reshape_gather = std::make_shared<op::v1::Reshape>(reshape_data, concat_gather, false);+ reshape_gather->set_friendly_name("reshape_gather");++ auto result = std::make_shared<op::v0::Result>(reshape_gather);+ auto model = std::make_shared<Model>(ResultVector{result}, ParameterVector{kv_param});+ model->validate_nodes_and_infer_types();+ return model;+}++// Same as above but with a dynamic sequence dimension so the pass cannot fold.+static std::shared_ptr<Model> build_attention_broadcast4_dynamic_model() {+ // Sequence dimension is dynamic → bounds cannot be fully evaluated, pass must not fire.+ auto kv_param = std::make_shared<op::v0::Parameter>(+ element::f32, PartialShape{1, 2, Dimension::dynamic(), 8});+ kv_param->set_friendly_name("kv_param");++ // Same Multiply→ShapeOf pattern as the static model.+ auto scale = op::v0::Constant::create(element::f32, Shape{}, {0.5f});+ auto multiply = std::make_shared<op::v1::Multiply>(kv_param, scale);++ auto shape_of = std::make_shared<op::v3::ShapeOf>(multiply, element::i64);+ auto gather_indices = op::v0::Constant::create(element::i64, Shape{1}, {2});+ auto gather_axis = op::v0::Constant::create(element::i64, Shape{}, {0});+ auto gather = std::make_shared<op::v8::Gather>(shape_of, gather_indices, gather_axis);++ auto dim_a = op::v0::Constant::create(element::i64, Shape{1}, {1});+ auto dim_c = op::v0::Constant::create(element::i64, Shape{1}, {2});+ auto dim_b = op::v0::Constant::create(element::i64, Shape{1}, {1});+ auto concat_gather = std::make_shared<op::v0::Concat>(+ OutputVector{dim_a, dim_c, dim_b, gather}, /*axis=*/0);++ // Reshape order matches the production pattern: data first, concat_gather (shape-pattern) second.+ auto reshape_gather = std::make_shared<op::v1::Reshape>(kv_param, concat_gather, true);++ auto result = std::make_shared<op::v0::Result>(reshape_gather);+ auto model = std::make_shared<Model>(ResultVector{result}, ParameterVector{kv_param});+ model->validate_nodes_and_infer_types();+ return model;+}++TEST(AttentionBroadcast4Test, FoldsShapeOfChainIntoConstant) {+ auto model = build_attention_broadcast4_static_model();++ ASSERT_EQ(count_ops<op::v3::ShapeOf>(model), 1u) << "expect one ShapeOf before the pass";++ // The new AttentionBroadcast4 callback checks has_and_set_bound() on the Concat+ // output rather than is_static() on the ShapeOf input. Propagate bounds+ // through the shape sub-graph without folding any nodes so the pattern can+ // still match.+ auto ops = model->get_ops();+ for (const auto& op : ops) {+ if (ov::is_type<op::v0::Concat>(op)) {+ ov::util::evaluate_both_bounds(op->output(0));+ break;+ }+ }++ ov::pass::GraphRewrite rewr;+ rewr.add_matcher<ov::npuw::patterns::regularize::AttentionBroadcast4>();+ rewr.run_on_model(model);++ // After folding, the ShapeOf node has no consumers and is no longer reachable+ // from the graph outputs.+ EXPECT_EQ(count_ops<op::v3::ShapeOf>(model), 0u)+ << "ShapeOf must be eliminated when its input has a static shape";+}++TEST(AttentionBroadcast4Test, DoesNotFoldWhenShapeIsDynamic) {+ auto model = build_attention_broadcast4_dynamic_model();++ ASSERT_EQ(count_ops<op::v3::ShapeOf>(model), 1u);++ ov::pass::GraphRewrite rewr;+ rewr.add_matcher<ov::npuw::patterns::regularize::AttentionBroadcast4>();+ rewr.run_on_model(model);++ // The pass must not fire: the ShapeOf input has a dynamic dimension.+ EXPECT_EQ(count_ops<op::v3::ShapeOf>(model), 1u)+ << "ShapeOf must be preserved when the input shape is dynamic";+}++// ---------------------------------------------------------------------------+// SeparateVCache tests+// ---------------------------------------------------------------------------++// Builds the full decomposed SDPA pattern where the V-cache chain+// (concat2 → convert2 → multiply2) is consumed by TWO MatMul nodes:+// - matmul2 : the "pattern" consumer (part of the full QuantizedSDPAWithGlobalMask sub-graph)+// - extra_matmul : an extra head consuming the same V-cache+// This simulates shared V-cache across attention heads.+//+// Graph (all tensors f16 except Parameters which are f32):+//+// past_k, new_k → Concat1 → Convert1 → Multiply1 → Transpose1+// ↓+// query_k ─────────────────────────────────────── MatMul1(q, K^T)+// ↓+// mask ──────────────────────────────────── Add → Softmax → MatMul2 → Reshape1 → Transpose → Reshape2+// ↑+// past_v, new_v → Concat2 → Convert2 → Multiply2 ───────────────┤+// └─── extra_matmul(extra_q, V)+struct SharedVCacheModel {+ std::shared_ptr<Model> model;+ // Node pointers kept for post-pass inspection+ std::shared_ptr<op::v0::Concat> concat2;+ std::shared_ptr<op::v1::Multiply> multiply2;+};++static SharedVCacheModel build_shared_vcache_model() {+ // Shapes: batch=1, heads=2, past_seq=4, head_dim=8; new_seq=1 → total_seq=5+ const Shape kv_past = {1, 2, 4, 8};+ const Shape kv_new = {1, 2, 1, 8};+ const Shape query_sh = {1, 2, 1, 8};+ const Shape mask_sh = {1, 1, 1, 5};+ const Shape attn_sh = {1, 2, 1, 5}; // query x K^T output++ ParameterVector params;+ ResultVector results;++ auto make_param = [&](const std::string& name, const Shape& shape, element::Type et = element::f16) {+ auto p = std::make_shared<op::v0::Parameter>(et, shape);+ p->set_friendly_name(name);+ params.push_back(p);+ return p;+ };+ auto make_result = [&](Output<Node> out, const std::string& name) {+ auto r = std::make_shared<op::v0::Result>(out);+ r->set_friendly_name(name);+ results.push_back(r);+ };++ // --- K-path ---+ auto past_k = make_param("past_k", kv_past);+ auto new_k = make_param("new_k", kv_new);+ auto concat1 = std::make_shared<op::v0::Concat>(OutputVector{past_k, new_k}, /*axis=*/2);+ concat1->set_friendly_name("concat1");++ auto convert1 = std::make_shared<op::v0::Convert>(concat1, element::f32);+ auto scale_k = op::v0::Constant::create(element::f32, Shape{1}, {0.5f});+ auto multiply1 = std::make_shared<op::v1::Multiply>(convert1, scale_k);+ multiply1->set_friendly_name("multiply1");++ auto perm_k = op::v0::Constant::create(element::i64, Shape{4}, {0, 1, 3, 2});+ auto transpose1 = std::make_shared<op::v1::Transpose>(multiply1, perm_k);++ // --- Q×K^T matmul ---+ auto query_k = make_param("query_k", query_sh, element::f32);+ auto matmul1 = std::make_shared<op::v0::MatMul>(query_k, transpose1);++ // --- Attention mask and softmax ---+ // SeparateVCache shares the same pattern as QuantizedSDPAWithGlobalMask, so the Add+ // must consume the global attention mask chain (consumes_global_mask predicate).+ auto mask_global = make_param("attention_mask_global", mask_sh, element::f32);+ auto mask_convert = std::make_shared<op::v0::Convert>(mask_global, element::f32);+ auto tile_repeats = op::v0::Constant::create(element::i64, Shape{4}, {1, 1, 1, 1});+ auto mask_tile = std::make_shared<op::v0::Tile>(mask_convert, tile_repeats);+ auto reshape_sh = op::v0::Constant::create(element::i64, Shape{4}, {1, 1, 1, 5});+ auto mask_reshape = std::make_shared<op::v1::Reshape>(mask_tile, reshape_sh, false);+ auto add = std::make_shared<op::v1::Add>(matmul1, mask_reshape);+ auto softmax = std::make_shared<op::v8::Softmax>(add, /*axis=*/3);++ // --- V-cache (shared between two consumers) ---+ auto past_v = make_param("past_v", kv_past);+ auto new_v = make_param("new_v", kv_new);+ auto concat2_node = std::make_shared<op::v0::Concat>(OutputVector{past_v, new_v}, /*axis=*/2);+ concat2_node->set_friendly_name("concat2");++ auto convert2 = std::make_shared<op::v0::Convert>(concat2_node, element::f32);+ auto scale_v = op::v0::Constant::create(element::f32, Shape{1}, {0.5f});+ auto multiply2_node = std::make_shared<op::v1::Multiply>(convert2, scale_v);+ multiply2_node->set_friendly_name("multiply2");++ // --- Head-0 output path (full matched sub-graph) ---+ auto matmul2 = std::make_shared<op::v0::MatMul>(softmax, multiply2_node);+ matmul2->set_friendly_name("matmul2");++ auto r1_shape = op::v0::Constant::create(element::i64, Shape{3}, {1, 1, 16});+ auto reshape1 = std::make_shared<op::v1::Reshape>(matmul2, r1_shape, false);+ auto perm_out = op::v0::Constant::create(element::i64, Shape{3}, {0, 2, 1});+ auto transpose_out = std::make_shared<op::v1::Transpose>(reshape1, perm_out);+ auto r2_shape = op::v0::Constant::create(element::i64, Shape{2}, {1, 16});+ auto reshape2 = std::make_shared<op::v1::Reshape>(transpose_out, r2_shape, false);++ // --- Extra consumer: another head reusing the same V-cache chain ---+ auto extra_q = make_param("extra_q", attn_sh, element::f32);+ auto extra_matmul = std::make_shared<op::v0::MatMul>(extra_q, multiply2_node);+ extra_matmul->set_friendly_name("extra_matmul");++ make_result(reshape2->output(0), "out_head0");+ make_result(extra_matmul->output(0), "out_extra");++ auto model = std::make_shared<Model>(results, params, "shared_vcache");+ model->validate_nodes_and_infer_types();+ return {model, concat2_node, multiply2_node};+}++// Same model but without the extra consumer – SeparateVCache should not fire.+static std::shared_ptr<Model> build_unshared_vcache_model() {+ const Shape kv_past = {1, 2, 4, 8};+ const Shape kv_new = {1, 2, 1, 8};+ const Shape query_sh = {1, 2, 1, 8};+ const Shape mask_sh = {1, 1, 1, 5};++ ParameterVector params;+ ResultVector results;++ auto make_param = [&](const std::string& name, const Shape& shape, element::Type et = element::f16) {+ auto p = std::make_shared<op::v0::Parameter>(et, shape);+ p->set_friendly_name(name);+ params.push_back(p);+ return p;+ };+ auto make_result = [&](Output<Node> out, const std::string& name) {+ auto r = std::make_shared<op::v0::Result>(out);+ r->set_friendly_name(name);+ results.push_back(r);+ };++ auto past_k = make_param("past_k", kv_past);+ auto new_k = make_param("new_k", kv_new);+ auto concat1 = std::make_shared<op::v0::Concat>(OutputVector{past_k, new_k}, 2);+ auto convert1 = std::make_shared<op::v0::Convert>(concat1, element::f32);+ auto scale_k = op::v0::Constant::create(element::f32, Shape{1}, {0.5f});+ auto multiply1 = std::make_shared<op::v1::Multiply>(convert1, scale_k);+ auto perm_k = op::v0::Constant::create(element::i64, Shape{4}, {0, 1, 3, 2});+ auto transpose1 = std::make_shared<op::v1::Transpose>(multiply1, perm_k);++ auto query_k = make_param("query_k", query_sh, element::f32);+ auto matmul1 = std::make_shared<op::v0::MatMul>(query_k, transpose1);++ auto mask_global = make_param("attention_mask_global", mask_sh, element::f32);+ auto mask_convert = std::make_shared<op::v0::Convert>(mask_global, element::f32);+ auto tile_repeats = op::v0::Constant::create(element::i64, Shape{4}, {1, 1, 1, 1});+ auto mask_tile = std::make_shared<op::v0::Tile>(mask_convert, tile_repeats);+ auto reshape_sh = op::v0::Constant::create(element::i64, Shape{4}, {1, 1, 1, 5});+ auto mask_reshape = std::make_shared<op::v1::Reshape>(mask_tile, reshape_sh, false);+ auto add = std::make_shared<op::v1::Add>(matmul1, mask_reshape);+ auto softmax = std::make_shared<op::v8::Softmax>(add, 3);++ auto past_v = make_param("past_v", kv_past);+ auto new_v = make_param("new_v", kv_new);+ auto concat2 = std::make_shared<op::v0::Concat>(OutputVector{past_v, new_v}, 2);+ auto convert2 = std::make_shared<op::v0::Convert>(concat2, element::f32);+ auto scale_v = op::v0::Constant::create(element::f32, Shape{1}, {0.5f});+ auto multiply2 = std::make_shared<op::v1::Multiply>(convert2, scale_v);++ auto matmul2 = std::make_shared<op::v0::MatMul>(softmax, multiply2);+ auto r1_shape = op::v0::Constant::create(element::i64, Shape{3}, {1, 1, 16});+ auto reshape1 = std::make_shared<op::v1::Reshape>(matmul2, r1_shape, false);+ auto perm_out = op::v0::Constant::create(element::i64, Shape{3}, {0, 2, 1});+ auto trans_out = std::make_shared<op::v1::Transpose>(reshape1, perm_out);+ auto r2_shape = op::v0::Constant::create(element::i64, Shape{2}, {1, 16});+ auto reshape2 = std::make_shared<op::v1::Reshape>(trans_out, r2_shape, false);++ make_result(reshape2->output(0), "out");++ auto model = std::make_shared<Model>(results, params, "unshared_vcache");+ model->validate_nodes_and_infer_types();+ return model;+}++TEST(SeparateKVCacheTest, DuplicatesSharedVCacheChain) {+ auto [model, concat2_node, multiply2_node] = build_shared_vcache_model();++ // Sanity-check the model before the pass.+ ASSERT_EQ(count_ops<op::v0::Concat>(model), 2u) << "expect 2 Concat before pass";+ ASSERT_EQ(count_ops<op::v1::Multiply>(model), 2u) << "expect 2 Multiply before pass";+ ASSERT_EQ(multiply2_node->output(0).get_target_inputs().size(), 2u)+ << "V-cache multiply must have 2 consumers before the pass";++ ov::pass::GraphRewrite rewr;+ rewr.add_matcher<ov::npuw::patterns::regularize::SeparateKVCache>();+ rewr.run_on_model(model);++ // The pass must add one new Concat and one new Multiply for the extra consumer.+ EXPECT_EQ(count_ops<op::v0::Concat>(model), 3u) << "expect 3 Concat after pass";+ EXPECT_EQ(count_ops<op::v1::Multiply>(model), 3u) << "expect 3 Multiply after pass";++ // The original V-cache multiply must now have exactly one consumer.+ EXPECT_EQ(multiply2_node->output(0).get_target_inputs().size(), 1u)+ << "V-cache multiply must have a single consumer after separation";+}++TEST(SeparateKVCacheTest, NoChangeWhenVCacheNotShared) {+ auto model = build_unshared_vcache_model();++ ASSERT_EQ(count_ops<op::v0::Concat>(model), 2u);+ ASSERT_EQ(count_ops<op::v1::Multiply>(model), 2u);++ ov::pass::GraphRewrite rewr;+ rewr.add_matcher<ov::npuw::patterns::regularize::SeparateKVCache>();+ rewr.run_on_model(model);++ // V-cache is not shared → nothing to separate.+ EXPECT_EQ(count_ops<op::v0::Concat>(model), 2u) << "graph must be unchanged";+ EXPECT_EQ(count_ops<op::v1::Multiply>(model), 2u) << "graph must be unchanged";+}++// Builds the full decomposed SDPA pattern where the K-cache chain+// (concat1 → convert1 → multiply1 → transpose1) is consumed by TWO MatMul nodes:+// - matmul1 : the "pattern" consumer (Q × K^T inside the matched sub-graph)+// - extra_matmul : an extra head consuming the same shared K-transpose+// This simulates the shared K-cache produced by SharedOpOptimization when+// several attention blocks reuse the same KV cache.+struct SharedKCacheModel {+ std::shared_ptr<Model> model;+ std::shared_ptr<op::v1::Transpose> transpose1;+};++static SharedKCacheModel build_shared_kcache_model() {+ const Shape kv_past = {1, 2, 4, 8};+ const Shape kv_new = {1, 2, 1, 8};+ const Shape query_sh = {1, 2, 1, 8};+ const Shape mask_sh = {1, 1, 1, 5};++ ParameterVector params;+ ResultVector results;++ auto make_param = [&](const std::string& name, const Shape& shape, element::Type et = element::f16) {+ auto p = std::make_shared<op::v0::Parameter>(et, shape);+ p->set_friendly_name(name);+ params.push_back(p);+ return p;+ };+ auto make_result = [&](Output<Node> out, const std::string& name) {+ auto r = std::make_shared<op::v0::Result>(out);+ r->set_friendly_name(name);+ results.push_back(r);+ };++ // --- K-cache chain (shared between two consumers) ---+ auto past_k = make_param("past_k", kv_past);+ auto new_k = make_param("new_k", kv_new);+ auto concat1 = std::make_shared<op::v0::Concat>(OutputVector{past_k, new_k}, /*axis=*/2);+ concat1->set_friendly_name("concat1");+ auto convert1 = std::make_shared<op::v0::Convert>(concat1, element::f32);+ auto scale_k = op::v0::Constant::create(element::f32, Shape{1}, {0.5f});+ auto multiply1 = std::make_shared<op::v1::Multiply>(convert1, scale_k);+ multiply1->set_friendly_name("multiply1");+ auto perm_k = op::v0::Constant::create(element::i64, Shape{4}, {0, 1, 3, 2});+ auto transpose1 = std::make_shared<op::v1::Transpose>(multiply1, perm_k);+ transpose1->set_friendly_name("transpose1");++ // --- Q×K^T matmul (pattern consumer) ---+ auto query_k = make_param("query_k", query_sh, element::f32);+ auto matmul1 = std::make_shared<op::v0::MatMul>(query_k, transpose1);++ // --- Attention mask and softmax (global-mask chain, required by the pattern) ---+ auto mask_global = make_param("attention_mask_global", mask_sh, element::f32);+ auto mask_convert = std::make_shared<op::v0::Convert>(mask_global, element::f32);+ auto tile_repeats = op::v0::Constant::create(element::i64, Shape{4}, {1, 1, 1, 1});+ auto mask_tile = std::make_shared<op::v0::Tile>(mask_convert, tile_repeats);+ auto reshape_sh = op::v0::Constant::create(element::i64, Shape{4}, {1, 1, 1, 5});+ auto mask_reshape = std::make_shared<op::v1::Reshape>(mask_tile, reshape_sh, false);+ auto add = std::make_shared<op::v1::Add>(matmul1, mask_reshape);+ auto softmax = std::make_shared<op::v8::Softmax>(add, /*axis=*/3);++ // --- V-cache (NOT shared) ---+ auto past_v = make_param("past_v", kv_past);+ auto new_v = make_param("new_v", kv_new);+ auto concat2 = std::make_shared<op::v0::Concat>(OutputVector{past_v, new_v}, /*axis=*/2);+ auto convert2 = std::make_shared<op::v0::Convert>(concat2, element::f32);+ auto scale_v = op::v0::Constant::create(element::f32, Shape{1}, {0.5f});+ auto multiply2 = std::make_shared<op::v1::Multiply>(convert2, scale_v);++ auto matmul2 = std::make_shared<op::v0::MatMul>(softmax, multiply2);+ auto r1_shape = op::v0::Constant::create(element::i64, Shape{3}, {1, 1, 16});+ auto reshape1 = std::make_shared<op::v1::Reshape>(matmul2, r1_shape, false);+ auto perm_out = op::v0::Constant::create(element::i64, Shape{3}, {0, 2, 1});+ auto transpose_out = std::make_shared<op::v1::Transpose>(reshape1, perm_out);+ auto r2_shape = op::v0::Constant::create(element::i64, Shape{2}, {1, 16});+ auto reshape2 = std::make_shared<op::v1::Reshape>(transpose_out, r2_shape, false);++ // --- Extra consumer: another head reusing the same K-transpose ---+ auto extra_q = make_param("extra_q", query_sh, element::f32);+ auto extra_matmul = std::make_shared<op::v0::MatMul>(extra_q, transpose1);+ extra_matmul->set_friendly_name("extra_matmul");++ make_result(reshape2->output(0), "out_head0");+ make_result(extra_matmul->output(0), "out_extra");++ auto model = std::make_shared<Model>(results, params, "shared_kcache");+ model->validate_nodes_and_infer_types();+ return {model, transpose1};+}++TEST(SeparateKVCacheTest, DuplicatesSharedKCacheChain) {+ auto [model, transpose1_node] = build_shared_kcache_model();++ // Sanity-check the model before the pass.+ ASSERT_EQ(count_ops<op::v1::Transpose>(model), 2u) << "expect 2 Transpose before pass";+ ASSERT_EQ(transpose1_node->output(0).get_target_inputs().size(), 2u)+ << "K-cache transpose must have 2 consumers before the pass";++ ov::pass::GraphRewrite rewr;+ rewr.add_matcher<ov::npuw::patterns::regularize::SeparateKVCache>();+ rewr.run_on_model(model);++ // The pass must add a full duplicate K-cache chain (Concat->Convert->Multiply->Transpose)+ // for the extra consumer.+ EXPECT_EQ(count_ops<op::v1::Transpose>(model), 3u) << "expect 3 Transpose after pass";++ // The original K-cache transpose must now have exactly one consumer.+ EXPECT_EQ(transpose1_node->output(0).get_target_inputs().size(), 1u)+ << "K-cache transpose must have a single consumer after separation";+}++// ---------------------------------------------------------------------------+// QuantizedSDPAWithGlobalMask online-partitioner pattern tests+// ---------------------------------------------------------------------------++// Builds the full decomposed SDPA sub-graph that QuantizedSDPAWithGlobalMask is designed+// to match:+//+// past_k, new_k → Concat1 → Convert1 → Multiply1 → Transpose1+// ↓+// query ─────────────────────────────────────────── MatMul1(Q, K^T)+// ↓+// mask ───────────────────────────────────── Add → Softmax → MatMul2 → Reshape1 → Transpose → Reshape2+// ↑+// past_v, new_v → Concat2 → Convert2 → Multiply2 ──────────┘+//+// The new_k and new_v parameters are expected to be renamed to+// "past_key_values.0.key" / "past_key_values.0.value" by the callback.+struct QuantizedSDPAWithGlobalMaskModel {+ std::shared_ptr<Model> model;+ std::shared_ptr<op::v0::Parameter> new_k;+ std::shared_ptr<op::v0::Parameter> new_v;+};++static QuantizedSDPAWithGlobalMaskModel build_sdpa_decomposed1_model() {+ const Shape kv_past = {1, 2, 4, 8};+ const Shape kv_new = {1, 2, 1, 8};+ const Shape query_sh = {1, 2, 1, 8};+ const Shape mask_sh = {1, 1, 1, 5};++ ParameterVector params;+ ResultVector results;++ auto make_param = [&](const std::string& name, const Shape& shape, element::Type et = element::f16) {+ auto p = std::make_shared<op::v0::Parameter>(et, shape);+ p->set_friendly_name(name);+ params.push_back(p);+ return p;+ };++ // K-path+ auto past_k = make_param("past_k", kv_past);+ auto new_k = make_param("new_k", kv_new);+ auto concat1 = std::make_shared<op::v0::Concat>(OutputVector{past_k, new_k}, 2);+ concat1->set_friendly_name("concat1");+ auto convert1 = std::make_shared<op::v0::Convert>(concat1, element::f32);+ auto scale_k = op::v0::Constant::create(element::f32, Shape{1}, {0.5f});+ auto multiply1 = std::make_shared<op::v1::Multiply>(convert1, scale_k);+ multiply1->set_friendly_name("multiply1");+ auto perm_k = op::v0::Constant::create(element::i64, Shape{4}, {0, 1, 3, 2});+ auto transpose1 = std::make_shared<op::v1::Transpose>(multiply1, perm_k);+ transpose1->set_friendly_name("transpose1");++ // Q×K^T+ auto query = make_param("query", query_sh, element::f32);+ auto matmul1 = std::make_shared<op::v0::MatMul>(query, transpose1);+ matmul1->set_friendly_name("matmul1");++ // Mask path: the updated QuantizedSDPAWithGlobalMask predicate (consumes_global_mask) requires+ // Reshape(Tile(Convert(Parameter("..attention_mask_global..")))) as Add's second input.+ auto mask_global = make_param("attention_mask_global", mask_sh, element::f32);+ auto mask_convert = std::make_shared<op::v0::Convert>(mask_global, element::f32);+ auto tile_repeats = op::v0::Constant::create(element::i64, Shape{4}, {1, 1, 1, 1});+ auto mask_tile = std::make_shared<op::v0::Tile>(mask_convert, tile_repeats);+ auto reshape_sh = op::v0::Constant::create(element::i64, Shape{4}, {1, 1, 1, 5});+ auto mask_reshape = std::make_shared<op::v1::Reshape>(mask_tile, reshape_sh, false);++ auto add = std::make_shared<op::v1::Add>(matmul1, mask_reshape);+ add->set_friendly_name("add");+ auto softmax = std::make_shared<op::v8::Softmax>(add, 3);+ softmax->set_friendly_name("softmax");++ // V-path+ auto past_v = make_param("past_v", kv_past);+ auto new_v = make_param("new_v", kv_new);+ auto concat2 = std::make_shared<op::v0::Concat>(OutputVector{past_v, new_v}, 2);+ concat2->set_friendly_name("concat2");+ auto convert2 = std::make_shared<op::v0::Convert>(concat2, element::f32);+ auto scale_v = op::v0::Constant::create(element::f32, Shape{1}, {0.5f});+ auto multiply2 = std::make_shared<op::v1::Multiply>(convert2, scale_v);+ multiply2->set_friendly_name("multiply2");++ // S×V + output reshape+ auto matmul2 = std::make_shared<op::v0::MatMul>(softmax, multiply2);+ matmul2->set_friendly_name("matmul2");+ auto r1_shape = op::v0::Constant::create(element::i64, Shape{3}, {1, 1, 16});+ auto reshape1 = std::make_shared<op::v1::Reshape>(matmul2, r1_shape, false);+ reshape1->set_friendly_name("reshape1");+ auto perm_out = op::v0::Constant::create(element::i64, Shape{3}, {0, 2, 1});+ auto trans_out = std::make_shared<op::v1::Transpose>(reshape1, perm_out);+ trans_out->set_friendly_name("transpose_out");+ auto r2_shape = op::v0::Constant::create(element::i64, Shape{2}, {1, 16});+ auto reshape2 = std::make_shared<op::v1::Reshape>(trans_out, r2_shape, false);+ reshape2->set_friendly_name("reshape2");++ auto result = std::make_shared<op::v0::Result>(reshape2);+ auto model = std::make_shared<Model>(ResultVector{result}, params, "sdpa_decomposed1");+ model->validate_nodes_and_infer_types();+ return {model, new_k, new_v};+}++TEST(QuantizedSDPAWithGlobalMaskTest, IsolatesAllPatternNodes) {+ auto [model, new_k, new_v] = build_sdpa_decomposed1_model();++ // Build the online-partitioner Snapshot and initialize per-node groups.+ auto snap = std::make_shared<ov::npuw::online::Snapshot>(model);+ snap->buildGraph();++ // No nodes should be tagged before the pass runs.+ {+ const auto& gptr_map = snap->getNodeToGroupMap();+ for (const auto& [node, gptr] : *gptr_map) {+ ASSERT_TRUE(gptr->isolatedTag().empty())+ << "No node must be tagged before the pattern pass runs";+ }+ }++ ov::pass::GraphRewrite rewr;+ rewr.add_matcher<ov::npuw::patterns::attn::QuantizedSDPAWithGlobalMask>(snap, "attn");+ rewr.run_on_model(model);++ // After matching, at least all 14 pattern nodes must carry the "attn" tag:+ // concat1, convert1, multiply1, transpose1, matmul1, add, softmax,+ // concat2, convert2, multiply2, matmul2, reshape1, transpose_out, reshape2.+ const std::size_t kPatternNodes = 14u;+ const auto& gptr_map = snap->getNodeToGroupMap();+ std::size_t tagged = 0;+ for (const auto& [node, gptr] : *gptr_map) {+ if (gptr->isolatedTag() == "attn") {+ ++tagged;+ }+ }+ EXPECT_GE(tagged, kPatternNodes)+ << "at least " << kPatternNodes << " pattern nodes must be tagged 'attn'";+}++TEST(QuantizedSDPAWithGlobalMaskTest, RenamesNewKVInputsToKVCacheNames) {+ auto [model, new_k, new_v] = build_sdpa_decomposed1_model();++ auto snap = std::make_shared<ov::npuw::online::Snapshot>(model);+ snap->buildGraph();++ ov::pass::GraphRewrite rewr;+ rewr.add_matcher<ov::npuw::patterns::attn::QuantizedSDPAWithGlobalMask>(snap, "attn");+ rewr.run_on_model(model);++ // The callback renames concat1->input(1) and concat2->input(1) to the+ // canonical KV-cache names used by downstream partitioning logic.+ EXPECT_EQ(new_k->get_friendly_name(), "past_key_values.0.key")+ << "new_k must be renamed to the KV-cache key name";+ EXPECT_EQ(new_v->get_friendly_name(), "past_key_values.0.value")+ << "new_v must be renamed to the KV-cache value name";+}++TEST(QuantizedSDPAWithGlobalMaskTest, NoTaggingOnNonMatchingModel) {+ // Build a model that does NOT match the pattern (missing the K-path).+ // A plain MatMul(q, k) → Add(mask) → Softmax → MatMul(softmax, v) → Result+ // is not matched because it lacks the Concat→Convert→Multiply→Transpose chain.+ const Shape s = {1, 2, 1, 8};+ auto q = std::make_shared<op::v0::Parameter>(element::f32, s);+ auto k = std::make_shared<op::v0::Parameter>(element::f32, Shape{1, 2, 8, 1});+ auto v = std::make_shared<op::v0::Parameter>(element::f32, Shape{1, 2, 1, 8});+ auto m = std::make_shared<op::v0::Parameter>(element::f32, Shape{1, 1, 1, 1});++ auto mm1 = std::make_shared<op::v0::MatMul>(q, k);+ auto add = std::make_shared<op::v1::Add>(mm1, m);+ auto sf = std::make_shared<op::v8::Softmax>(add, 3);+ auto mm2 = std::make_shared<op::v0::MatMul>(sf, v);+ auto res = std::make_shared<op::v0::Result>(mm2);++ auto model = std::make_shared<Model>(ResultVector{res}, ParameterVector{q, k, v, m});+ model->validate_nodes_and_infer_types();++ auto snap = std::make_shared<ov::npuw::online::Snapshot>(model);+ snap->buildGraph();++ ov::pass::GraphRewrite rewr;+ rewr.add_matcher<ov::npuw::patterns::attn::QuantizedSDPAWithGlobalMask>(snap, "attn");+ rewr.run_on_model(model);++ const auto& gptr_map = snap->getNodeToGroupMap();+ for (const auto& [node, gptr] : *gptr_map) {+ EXPECT_TRUE(gptr->isolatedTag().empty())+ << "No node should be tagged when the model does not match the pattern";+ }+}++} // namespace