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] Fix conflicting attention mask detection for nested Select SWA masks (#39267)
Pengqiang Li1aef8e86bdb6
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/detect_causal_mask.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/detect_causal_mask.cppindex cec83c21e6d..0e66cbfde89 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/detect_causal_mask.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/detect_causal_mask.cpp@@ -58,6 +58,24 @@ int64_t get_window_size(const std::shared_ptr<ov::Node>& node) {return vals.empty() ? 0 : std::llabs(vals.front());}+// Keep branch filtering consistent with TriuSlidingMatcher: only skip a nested+// mask when that matcher can actually annotate its SDPA consumers.+int64_t get_triu_sliding_window(const std::shared_ptr<ov::Node>& node) {+ auto select = ov::as_type_ptr<ov::op::v1::Select>(node);+ if (!select || !select->get_output_element_type(0).is_real())+ return 0;++ auto condition = select->get_input_node_shared_ptr(0);+ for (size_t i = 0; i < 2 && ov::is_type<ov::op::v0::Unsqueeze>(condition); ++i) {+ condition = condition->get_input_node_shared_ptr(0);+ }+ auto ge = ov::as_type_ptr<ov::op::v1::GreaterEqual>(condition);+ if (!ge || !ov::is_type<ov::op::v1::Subtract>(ge->get_input_node_shared_ptr(0)))+ return 0;++ return get_window_size(ge->get_input_node_shared_ptr(1));+}+// Writes `encoded_value` (see NPUW_SDPA_MASK_RT_KEY for the encoding) onto `sdpa`'s// rt_info. A node may only be annotated once: if it is already annotated with a// *different* value, that means two matchers produced genuinely contradictory@@ -172,6 +190,25 @@ bool traces_to_range(const std::shared_ptr<ov::Node>& node, int depth = 8) {return false;}+// True when `consumer` is a Select that merges our causal mask (as its+// *condition*) with an already-built triu sliding-window mask (as one of its+// *data* operands):+//+// Select(~(causal & padding), fill, Select(GreaterEqual(Subtract(q, k), window), fill, 0))+//+// The mirror image of the triu form handled in annotate_triu_causal_mask() below+// (causal mask in a data operand, window check as the condition). The data+// operand is required to be exactly what TriuSlidingMatcher annotates (see+// get_triu_sliding_window above), so this branch is only skipped when that+// matcher really owns it.+bool merges_triu_window_mask(const std::shared_ptr<ov::Node>& consumer, const ov::Output<ov::Node>& output) {+ auto select = ov::as_type_ptr<ov::op::v1::Select>(consumer);+ if (!select || select->input_value(0) != output)+ return false;+ return get_triu_sliding_window(select->get_input_node_shared_ptr(1)) > 0 ||+ get_triu_sliding_window(select->get_input_node_shared_ptr(2)) > 0;+}+// Shared BFS skeleton behind annotate_causal_mask()/annotate_triu_causal_mask()// below: forward-propagates a Causal annotation from `mask_output` onto every// ScaledDotProductAttention node it (transitively) feeds. For every non-SDPA@@ -210,10 +247,14 @@ void annotate_causal_mask_impl(// output (LessEqual/Less family). A boolean-combine op (BitwiseAnd/BitwiseOr/// LogicalAnd) is only treated as SWA-owned when its *other* operand// (transitively) contains a sliding-window bound check (see contains_window_check-// above) -- meaning this specific combine node is a genuine SWA anchor.+// above) -- meaning this specific combine node is a genuine SWA anchor. A Select+// merging the mask with a triu sliding-window mask (see merges_triu_window_mask+// above) is SWA-owned as well.void annotate_causal_mask(const ov::Output<ov::Node>& mask_output) {annotate_causal_mask_impl(mask_output,[](const std::shared_ptr<ov::Node>& consumer, const ov::Output<ov::Node>& output) {+ if (merges_triu_window_mask(consumer, output))+ return true;if (!is_boolean_combine_op(consumer))return false;for (size_t i = 0; i < consumer->get_input_size(); ++i) {@@ -233,11 +274,15 @@ void annotate_causal_mask(const ov::Output<ov::Node>& mask_output) {// mask, ...); a Select is only treated as SWA-owned when our matched mask feeds// one of its *data* operands (then/else, not the condition) AND that Select's// condition is a genuine sliding-window bound check (see contains_triu_window_check-// above) -- meaning TriuSlidingMatcher already owns that branch.+// above) -- meaning TriuSlidingMatcher already owns that branch. The mirror form,+// where our mask is the Select's condition (see merges_triu_window_mask above),+// is SWA-owned too.void annotate_triu_causal_mask(const ov::Output<ov::Node>& mask_output) {annotate_causal_mask_impl(mask_output,[](const std::shared_ptr<ov::Node>& consumer, const ov::Output<ov::Node>& output) {+ if (merges_triu_window_mask(consumer, output))+ return true;auto select = ov::as_type_ptr<ov::op::v1::Select>(consumer);if (!select)return false;@@ -507,10 +552,8 @@ public:auto beyond_window_unsq1 = opp::optional<ov::op::v0::Unsqueeze>({beyond_window, opp::any_input()});auto beyond_window_unsq2 = opp::optional<ov::op::v0::Unsqueeze>({beyond_window_unsq1, opp::any_input()});auto windowed = opp::wrap_type<ov::op::v1::Select>({beyond_window_unsq2, opp::any_input(), opp::any_input()});- auto callback = [=](opp::Matcher& m) {- if (!m.get_match_root()->get_output_element_type(0).is_real())- return false;- const int64_t w = get_window_size(m.get_pattern_value_map().at(window_const).get_node_shared_ptr());+ auto callback = [](opp::Matcher& m) {+ const int64_t w = get_triu_sliding_window(m.get_match_root());if (w > 0) {annotate_sdpa_consumers(m.get_match_root()->output(0), w);}diff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/detect_causal_mask_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/detect_causal_mask_test.cppindex e01141d1693..09010f05ea8 100644--- a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/detect_causal_mask_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/detect_causal_mask_test.cpp@@ -331,6 +331,51 @@ std::shared_ptr<ov::Model> build_gemma4_12b_triu_shared_causal(int64_t window) {ov::ParameterVector{seq, amask, q, k, v});}+// Combines the causal/padding condition with a separately constructed+// window mask: Select(invalid, fill, Select(beyond_window, fill, zero)).+std::shared_ptr<ov::Model> build_lfm3_shared_causal(int64_t window,+ size_t window_unsqueezes = 2,+ bool invert_condition = false) {+ using namespace ov::op;+ auto seq = std::make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{1, -1});+ auto amask = std::make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{1, -1});+ auto zero = v0::Constant::create(ov::element::i64, ov::Shape{}, {0});+ auto one = v0::Constant::create(ov::element::i64, ov::Shape{}, {1});+ auto seq_len = std::make_shared<v8::Gather>(std::make_shared<v3::ShapeOf>(seq), one, zero);+ auto total = std::make_shared<v8::Gather>(std::make_shared<v3::ShapeOf>(amask), one, zero);+ auto past = std::make_shared<v1::Subtract>(total, seq_len);+ auto key = std::make_shared<v0::Unsqueeze>(std::make_shared<v4::Range>(zero, total, one, ov::element::i64), zero);+ auto query = std::make_shared<v0::Unsqueeze>(std::make_shared<v4::Range>(past, total, one, ov::element::i64), one);+ auto causal = std::make_shared<v1::LessEqual>(key, query);+ auto axes = v0::Constant::create(ov::element::i64, ov::Shape{2}, {0, 1});+ auto causal_4d = std::make_shared<v0::Unsqueeze>(causal, axes);+ auto padding_axes = v0::Constant::create(ov::element::i64, ov::Shape{2}, {1, 2});+ auto padding =+ std::make_shared<v0::Unsqueeze>(std::make_shared<v0::Convert>(amask, ov::element::boolean), padding_axes);+ auto allowed = std::make_shared<v13::BitwiseAnd>(causal_4d, padding);+ auto invalid = std::make_shared<v13::BitwiseNot>(allowed);+ auto fill = v0::Constant::create(ov::element::f32, ov::Shape{}, {-65504.0f});+ auto zero_f = v0::Constant::create(ov::element::f32, ov::Shape{}, {0.0f});+ auto full_mask = std::make_shared<v1::Select>(invalid, fill, zero_f);+ auto window_const = v0::Constant::create(ov::element::i64, ov::Shape{1, 1}, {window});+ std::shared_ptr<ov::Node> beyond_window =+ std::make_shared<v1::GreaterEqual>(std::make_shared<v1::Subtract>(query, key), window_const);+ for (size_t i = 0; i < window_unsqueezes; ++i) {+ beyond_window = std::make_shared<v0::Unsqueeze>(beyond_window, zero);+ }+ auto window_mask = std::make_shared<v1::Select>(beyond_window, fill, zero_f);+ auto sliding_mask = invert_condition ? std::make_shared<v1::Select>(allowed, window_mask, fill)+ : std::make_shared<v1::Select>(invalid, fill, window_mask);++ auto q = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{1, 1, -1, 8});+ auto k = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{1, 1, -1, 8});+ auto v = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{1, 1, -1, 8});+ auto full_sdpa = std::make_shared<v13::ScaledDotProductAttention>(q, k, v, full_mask, false);+ auto sliding_sdpa = std::make_shared<v13::ScaledDotProductAttention>(q, k, v, sliding_mask, false);+ return std::make_shared<ov::Model>(ov::OutputVector{full_sdpa, sliding_sdpa},+ ov::ParameterVector{seq, amask, q, k, v});+}+// ---------------------------------------------------------------------------// Faithful reproduction of the MiniCPM causal-mask subgraph (uses aten::lt =>// Less instead of aten::le => LessEqual), as seen in real MiniCPM exports:@@ -457,6 +502,55 @@ TEST(DetectAttentionMaskTest, RealPattern_Gemma4_12B_TriuSharedCausal_BothBranchEXPECT_EQ(causal_count, 1);}+TEST(DetectAttentionMaskTest, RealPattern_LFM3NestedSelect_BothBranchesDetected) {+ for (const int64_t window : {256, 512}) {+ for (const size_t unsqueezes : {0u, 1u, 2u}) {+ for (const bool invert_condition : {false, true}) {+ SCOPED_TRACE(testing::Message() << "window=" << window << ", unsqueezes=" << unsqueezes+ << ", invert_condition=" << invert_condition);+ auto model = build_lfm3_shared_causal(window, unsqueezes, invert_condition);+ ASSERT_NO_THROW(DetectAttentionMask().run_on_model(model));+ const auto full = decode_rt_info(model->get_results()[0]->get_input_node_shared_ptr(0)->get_rt_info());+ const auto sliding =+ decode_rt_info(model->get_results()[1]->get_input_node_shared_ptr(0)->get_rt_info());+ EXPECT_EQ(full.type, DetectedMaskType::Causal);+ EXPECT_EQ(sliding.type, DetectedMaskType::SlidingWindow);+ EXPECT_EQ(sliding.window_size, window);+ EXPECT_NO_THROW(DetectAttentionMask().run_on_model(model));+ }+ }+ }+}++TEST(DetectAttentionMaskTest, LFM3NestedSelect_ZeroWindowDoesNotSuppressCausalDetection) {+ const auto all = detect_all(build_lfm3_shared_causal(0));+ ASSERT_EQ(all.size(), 2u);+ EXPECT_EQ(std::count(all.begin(), all.end(), DetectedMaskType::Causal), 2);+}++TEST(DetectAttentionMaskTest, LFM3NestedSelect_UnrelatedComparisonDoesNotSuppressCausalDetection) {+ auto model = build_lfm3_shared_causal(256);+ for (const auto& node : model->get_ordered_ops()) {+ if (auto ge = ov::as_type_ptr<ov::op::v1::GreaterEqual>(node)) {+ const auto query = ge->get_input_node_shared_ptr(0)->input_value(0);+ ge->input(0).replace_source_output(query);+ }+ }+ model->validate_nodes_and_infer_types();+ const auto all = detect_all(model);+ ASSERT_EQ(all.size(), 2u);+ EXPECT_EQ(std::count(all.begin(), all.end(), DetectedMaskType::Causal), 2);+}++TEST(DetectAttentionMaskTest, LFM3NestedSelect_ConflictingCausalAttributeStillThrows) {+ auto model = build_lfm3_shared_causal(256);+ auto sdpa =+ ov::as_type_ptr<ov::op::v13::ScaledDotProductAttention>(model->get_results()[1]->get_input_node_shared_ptr(0));+ ASSERT_NE(sdpa, nullptr);+ sdpa->set_causal(true);+ EXPECT_THROW(DetectAttentionMask().run_on_model(model), ov::Exception);+}+// Real pattern: MiniCPM uses Less (aten::lt) instead of LessEqual (aten::le).TEST(DetectAttentionMaskTest, RealPattern_MiniCPMLess_IsCausal) {EXPECT_EQ(detect(build_minicpm_less()), DetectedMaskType::Causal);