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]Annotate each Add in SDPA to make per-ATTN-subgraph mask-skipping decisions (#37407)
intelgaoxiong227e6c063d7d
diff --git a/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cpp b/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cppindex 87228370eaa..56480e8a5f8 100644--- a/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cpp@@ -11,6 +11,7 @@#include "intel_npu/ops/flash_attention_tile.hpp"#include "logging.hpp"+#include "npuw_transformations/detect_causal_mask.hpp"#include "openvino/core/validation_util.hpp"#include "openvino/op/ops.hpp"#include "openvino/openvino.hpp"@@ -1106,6 +1107,50 @@ std::optional<HostFlashAttention> HostFlashAttention::from(const std::shared_ptrLOG_INFO("Creating HFA tile models: tile_size=" << query_size << ", v_transposed=" << v_transposed<< ", block_kv=" << block_kv_dtype<< ", present_kv=" << present_kv_dtype << ", q=" << q_dtype);++ // Per-SDPA mask-skipping decision+ // DetectAttentionMask (run earlier on the original SDPA node) may have annotated+ // this subgraph's Add(QK, mask) node with its mask kind, carried here via+ // copy_runtime_info() during SDPA decomposition. Per NPUW_SDPA_MASK_RT_KEY's+ // encoding, the mask-skipping decision is:+ //+ // no annotation (Unknown) : DISABLED -- unknown mask shape, skipping it could+ // silently change results.+ // value < 0 (Causal) : ENABLED unconditionally for non-final tiles (a+ // causal mask never excludes anything a non-final+ // regular tile would otherwise include).+ // value >= 0 (SlidingWindow, value = window_size)+ // : ENABLED only if window_size >= context_size (then it+ // behaves exactly like Causal); otherwise the window+ // would truncate positions a regular tile must still+ // respect, so it stays DISABLED.+ //+ // This replaces the enable_mask_skipping flag passed in from the caller: that flag+ // is now just a master kill switch (NPUW_ATTN_HFA_MASK_SKIPPING=NO disables the+ // optimization outright, regardless of mask kind).+ bool local_enable_mask_skipping = false;+ if (enable_mask_skipping && pattern_nodes.add_node) {+ const auto& rt_info = pattern_nodes.add_node->get_rt_info();+ const auto it = rt_info.find(ov::npuw::NPUW_SDPA_MASK_RT_KEY);+ if (it != rt_info.end()) {+ const auto encoded = it->second.as<int64_t>();+ if (encoded < 0) {+ local_enable_mask_skipping = true;+ LOG_DEBUG("Per-SDPA mask annotation: Causal → mask skipping ENABLED for this ATTN subgraph");+ } else if (encoded >= static_cast<int64_t>(context_size)) {+ local_enable_mask_skipping = true;+ LOG_DEBUG("Per-SDPA mask annotation: SlidingWindow(window_size="+ << encoded << ") covers the full context (" << context_size+ << ") → mask skipping ENABLED for this ATTN subgraph");+ } else {+ LOG_DEBUG("Per-SDPA mask annotation: SlidingWindow(window_size="+ << encoded << ") is narrower than the context (" << context_size+ << ") → mask skipping DISABLED for this ATTN subgraph");+ }+ } else {+ LOG_DEBUG("No per-SDPA mask annotation (Unknown) → mask skipping DISABLED for this ATTN subgraph");+ }+ }auto tile_model = create_hfa_tile_model(q_shape_static,block_kv_dtype, // state_dtypeblock_kv_dtype, // kv_tile_dtype (past blocks)@@ -1115,7 +1160,7 @@ std::optional<HostFlashAttention> HostFlashAttention::from(const std::shared_ptrkv_num_heads,false,fused_flash_attention,- enable_mask_skipping,+ local_enable_mask_skipping,v_transposed);if (!tile_model) {LOG_WARN("Failed to create HFA tile model");@@ -1131,7 +1176,7 @@ std::optional<HostFlashAttention> HostFlashAttention::from(const std::shared_ptrkv_num_heads,true,fused_flash_attention,- enable_mask_skipping,+ local_enable_mask_skipping,v_transposed,output_dtype);if (!final_tile_model) {diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cppindex 952c7b0172b..29bb38dd93b 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp@@ -929,11 +929,11 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mauto lm_head_model = check_and_cut_lm_head(kvcache_model, m_cfg);- // Detect attention mask type before the SDPA subgraph is isolated by partitioning.- // Mask-skipping optimization on HFA regular tiles will be enabled depending on the mask type.- ov::npuw::DetectAttentionMask detect_mask;- detect_mask.run_on_model(kvcache_model);- const auto mask_info = detect_mask.get_mask_info();+ // Detect attention mask kind before the SDPA subgraph is isolated by partitioning,+ // annotating each SDPA node's rt_info. HostFlashAttention reads this per-node to+ // decide whether the regular-tile mask-skipping optimization is safe for that layer.+ ov::npuw::DetectAttentionMask().run_on_model(kvcache_model);+ ov::npuw::log_detected_masks(kvcache_model);if (!m_is_whisper) {LOG_DEBUG("Try patch sliding window attention mask (Phi-3, Gemma-2, Gemma-3, Gemma-4), if it exists.");@@ -1114,12 +1114,14 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mprefill_config_opt.value_or(get_default_prefill_config(prefill_model, npudesc)).as<ov::AnyMap>();if (prefill_attn_hfa) {- prefill_config[ov::intel_npu::npuw::partitioning::attn_hfa_mask_skipping.name()] =- mask_info.mask_type == ov::npuw::MaskInfo::MaskType::Causal ||- (mask_info.mask_type == ov::npuw::MaskInfo::MaskType::SlidingWindow &&- mask_info.window_size >= max_prompt_len)- ? "YES"- : "NO";+ // Enable the mask-skipping optimization by default; the actual per-layer+ // decision (safe only for Causal, or SlidingWindow whose window already+ // covers the full context) is made independently for each SDPA subgraph in+ // HostFlashAttention::from(), based on the rt_info DetectAttentionMask wrote+ // above. Setting this to "NO" here (or via user-supplied config, which+ // overrides this below) acts as a master kill switch disabling the+ // optimization outright.+ prefill_config[ov::intel_npu::npuw::partitioning::attn_hfa_mask_skipping.name()] = "YES";}// NB: GENERATE_HINT is only applicable for default generate config!diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hppindex a928d4a41b1..3b7030c50fd 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp@@ -26,7 +26,6 @@ class WhisperInferRequest;class LLMBlockKVCacheStrategy;class LLMContinuousKVCacheStrategy;struct PrefixCacheRestorationContext;-struct MaskInfo;class LLMCompiledModel : public ov::npuw::ICompiledModel {using GetPropertiesMap =std::map<std::string, std::tuple<ov::PropertyMutability, std::function<ov::Any(const ::intel_npu::Config&)>>>;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 abc15860d43..cec83c21e6d 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@@ -4,8 +4,18 @@#include "detect_causal_mask.hpp"+#include <algorithm>+#include <charconv>#include <cstdlib>+#include <functional>+#include <queue>+#include <regex>+#include <string>+#include <unordered_set>+#include <vector>+#include "../logging.hpp"+#include "../util.hpp"#include "openvino/op/ops.hpp"#include "openvino/op/scaled_dot_product_attention.hpp"#include "openvino/pass/graph_rewrite.hpp"@@ -48,6 +58,194 @@ int64_t get_window_size(const std::shared_ptr<ov::Node>& node) {return vals.empty() ? 0 : std::llabs(vals.front());}+// 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+// evidence for the same SDPA node (e.g. an is_causal=true node also fed an+// explicit sliding-window mask) -- fail loudly instead of silently picking one.+// Re-annotating with the *same* value (e.g. two causal matchers agreeing) is a+// harmless no-op.+void assign_mask_rt_info(const std::shared_ptr<ov::Node>& sdpa, int64_t encoded_value) {+ auto& rt_info = sdpa->get_rt_info();+ const auto it = rt_info.find(ov::npuw::NPUW_SDPA_MASK_RT_KEY);+ if (it != rt_info.end()) {+ const auto existing = it->second.as<int64_t>();+ NPUW_ASSERT(existing == encoded_value && "NPUW: conflicting attention mask detection for the same SDPA node");+ return;+ }+ rt_info[ov::npuw::NPUW_SDPA_MASK_RT_KEY] = encoded_value;+}++// Forward-propagates `encoded_value` onto every ScaledDotProductAttention node+// that (transitively) consumes `mask_output`, by writing rt_info directly on the+// SDPA node (see assign_mask_rt_info above). ScaledDotProductAttentionDecomposition::+// decompose() later calls copy_runtime_info(node, get_new_nodes()), which carries+// this rt_info onto the newly created Add(QK, mask) node for free -- so no+// separate post-decomposition detection pass is required.+void annotate_sdpa_consumers(const ov::Output<ov::Node>& mask_output, int64_t encoded_value) {+ std::unordered_set<ov::Node*> visited;+ std::queue<ov::Output<ov::Node>> to_visit;+ to_visit.push(mask_output);++ while (!to_visit.empty()) {+ auto output = to_visit.front();+ to_visit.pop();+ for (const auto& input : output.get_target_inputs()) {+ auto consumer = input.get_node()->shared_from_this();+ if (!visited.insert(consumer.get()).second)+ continue;+ if (auto sdpa = ov::as_type_ptr<ov::op::v13::ScaledDotProductAttention>(consumer)) {+ assign_mask_rt_info(sdpa, encoded_value);+ continue; // don't cross into the SDPA's own outputs+ }+ for (const auto& out : consumer->outputs())+ to_visit.push(out);+ }+ }+}++bool is_boolean_combine_op(const std::shared_ptr<ov::Node>& node) {+ return ov::is_type<ov::op::v13::BitwiseAnd>(node) || ov::is_type<ov::op::v13::BitwiseOr>(node) ||+ ov::is_type<ov::op::v1::LogicalAnd>(node);+}++// True when `node` is (or transitively nests, through boolean-combine ops) a+// sliding-window bound check (a Greater comparison). Used to tell apart a+// boolean-combine consumer that's a genuine SWA anchor -- owned by the SWA+// matchers below -- from one that's just ANDing/ORing the causal comparison+// with something unrelated (a `new_ones` identity constant, the padding+// attention_mask, ...), which is still a plain causal mask in disguise. Real+// exports commonly wrap even a "pure causal, no window" layer's mask in such an+// identity/padding combine (see e.g. Gemma's non-sliding layers), so this needs+// to be decided per boolean-combine node, not per matched causal comparison.+bool contains_window_check(const std::shared_ptr<ov::Node>& node) {+ if (ov::is_type<ov::op::v1::Greater>(node))+ return true;+ if (is_boolean_combine_op(node)) {+ return contains_window_check(node->get_input_node_shared_ptr(0)) ||+ contains_window_check(node->get_input_node_shared_ptr(1));+ }+ return false;+}++// True when `node` is (or, through single-input passthrough ops like Unsqueeze/+// Reshape/Convert/Broadcast, transitively wraps) a Gemma-4-12B-style decomposed+// sliding-window bound check: GreaterEqual(Subtract(...), window_const). Plays+// the same role as contains_window_check() above, but for the Select-based+// mask family matched by TriuCausalMatcher/TriuSlidingMatcher below (Gemma-4-12B's+// traced torch.triu()/masked_fill() decomposition uses GreaterEqual + Select+// instead of LessEqual/Greater + BitwiseAnd).+bool contains_triu_window_check(const std::shared_ptr<ov::Node>& node) {+ if (auto ge = ov::as_type_ptr<ov::op::v1::GreaterEqual>(node)) {+ return ov::is_type<ov::op::v1::Subtract>(ge->get_input_node_shared_ptr(0)) ||+ ov::is_type<ov::op::v1::Subtract>(ge->get_input_node_shared_ptr(1));+ }+ if (ov::is_type<ov::op::v0::Unsqueeze>(node) || ov::is_type<ov::op::v1::Reshape>(node) ||+ ov::is_type<ov::op::v0::Convert>(node) || ov::is_type<ov::op::v3::Broadcast>(node)) {+ return contains_triu_window_check(node->get_input_node_shared_ptr(0));+ }+ return false;+}++// True when `node` is (or, transitively through single-input/pass-through ops+// -- Add, Unsqueeze, Reshape, Convert, Broadcast -- within `depth` steps) derived+// from a Range op. Used by TriuCausalMatcher below as a post-match guard: unlike+// make_range_chain() (which anchors the LessEqual/Less family to an *exact*+// Range->Add->Unsqueeze->Reshape->Convert op ordering), this walks the graph+// looking for *any* Range reachable within a bounded number of hops, so it still+// rejects arbitrary/unrelated GreaterEqual(any_input, any_input) matches without+// having to match Gemma-4-12B's specific chain shape one op at a time. `depth` is+// capped to keep the walk local to the comparison's immediate operands.+bool traces_to_range(const std::shared_ptr<ov::Node>& node, int depth = 8) {+ if (!node || depth <= 0)+ return false;+ if (ov::is_type<ov::op::v4::Range>(node))+ return true;+ if (ov::is_type<ov::op::v1::Add>(node) || ov::is_type<ov::op::v0::Unsqueeze>(node) ||+ ov::is_type<ov::op::v1::Reshape>(node) || ov::is_type<ov::op::v0::Convert>(node) ||+ ov::is_type<ov::op::v3::Broadcast>(node)) {+ for (size_t i = 0; i < node->get_input_size(); ++i) {+ if (traces_to_range(node->get_input_node_shared_ptr(i), depth - 1))+ return true;+ }+ }+ return false;+}++// 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+// consumer reached during the walk, `should_skip_branch(consumer, output)` decides+// whether that consumer is a genuine SWA anchor already owned by a sliding-window+// matcher -- if so, traversal doesn't cross into it, leaving that branch alone;+// otherwise traversal continues through it (e.g. a combine with a `new_ones`+// identity constant or a padding mask is still just a plain causal mask).+void annotate_causal_mask_impl(+ const ov::Output<ov::Node>& mask_output,+ const std::function<bool(const std::shared_ptr<ov::Node>&, const ov::Output<ov::Node>&)>& should_skip_branch) {+ std::unordered_set<ov::Node*> visited;+ std::queue<ov::Output<ov::Node>> to_visit;+ to_visit.push(mask_output);++ while (!to_visit.empty()) {+ auto output = to_visit.front();+ to_visit.pop();+ for (const auto& input : output.get_target_inputs()) {+ auto consumer = input.get_node()->shared_from_this();+ if (!visited.insert(consumer.get()).second)+ continue;+ if (auto sdpa = ov::as_type_ptr<ov::op::v13::ScaledDotProductAttention>(consumer)) {+ assign_mask_rt_info(sdpa, ov::npuw::NPUW_SDPA_MASK_CAUSAL);+ continue; // don't cross into the SDPA's own outputs+ }+ if (should_skip_branch(consumer, output))+ continue; // this branch belongs to a SWA matcher, don't propagate into it+ for (const auto& out : consumer->outputs())+ to_visit.push(out);+ }+ }+}++// Forward-propagates a Causal annotation from a matched causal comparison's+// 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.+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 (!is_boolean_combine_op(consumer))+ return false;+ for (size_t i = 0; i < consumer->get_input_size(); ++i) {+ if (consumer->input_value(i) != output &&+ contains_window_check(consumer->input_value(i).get_node_shared_ptr())) {+ return true;+ }+ }+ return false;+ });+}++// Forward-propagates a Causal annotation from a matched Gemma-4-12B-style triu+// causal Select's output (see TriuCausalMatcher below). Real exports build the+// final per-layer mask by repeatedly Select()-ing the plain causal mask against+// further conditions (a sliding-window bound check, a user-supplied padding+// 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.+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) {+ auto select = ov::as_type_ptr<ov::op::v1::Select>(consumer);+ if (!select)+ return false;+ const bool feeds_data_operand = select->input_value(1) == output || select->input_value(2) == output;+ return feeds_data_operand && contains_triu_window_check(select->input_value(0).get_node_shared_ptr());+ });+}+#ifdef __GNUC__# pragma GCC diagnostic push# pragma GCC diagnostic ignored "-Wattributes"@@ -57,17 +255,22 @@ int64_t get_window_size(const std::shared_ptr<ov::Node>& node) {// Matches: ScaledDotProductAttention(is_causal=true)//// The case when causality is an SDPA attribute, not an explicit mask-// subgraph.+// subgraph. Anchored directly on the SDPA node itself (not reached via mask+// traversal), so it can genuinely conflict with a SlidingWindow annotation+// coming from an SWA matcher on the same node -- assign_mask_rt_info() will+// assert in that case, since it means the model has contradictory evidence+// (an explicit is_causal=true attribute together with an explicit+// sliding-window mask feeding the same SDPA).// ============================================================================class SDPACausalMatcher final : public ov::pass::MatcherPass {public:OPENVINO_MATCHER_PASS_RTTI("ov::npuw::SDPACausalMatcher");- explicit SDPACausalMatcher(ov::npuw::MaskInfo& mask_info) {+ SDPACausalMatcher() {auto sdpa = opp::wrap_type<ov::op::v13::ScaledDotProductAttention>();- auto callback = [&mask_info](opp::Matcher& m) {+ auto callback = [](opp::Matcher& m) {auto node = ov::as_type_ptr<ov::op::v13::ScaledDotProductAttention>(m.get_match_root());- if (node && node->get_causal() && mask_info.mask_type != ov::npuw::MaskInfo::MaskType::SlidingWindow)- mask_info = {ov::npuw::MaskInfo::MaskType::Causal, 0};+ if (node && node->get_causal())+ assign_mask_rt_info(node, ov::npuw::NPUW_SDPA_MASK_CAUSAL);return false;};register_matcher(std::make_shared<opp::Matcher>(sdpa, "DetectSDPACausal"), callback);@@ -84,15 +287,20 @@ public:// - MiniCPM : Less(Range, Reshape(Add(Range, offset)))// - Whisper : Range -> Unsqueeze x3//+// Uses annotate_causal_mask() rather than a blanket skip when the matched+// comparison feeds a boolean-combine op: only branches that are genuine SWA+// anchors (see contains_window_check above) are left for the SWA matchers to+// own; other combine consumers (e.g. ANDing with a `new_ones` identity or the+// padding attention_mask, as seen on Gemma's non-sliding layers) still get+// annotated Causal.// ============================================================================class StandardCausalMatcher final : public ov::pass::MatcherPass {public:OPENVINO_MATCHER_PASS_RTTI("ov::npuw::StandardCausalMatcher");- explicit StandardCausalMatcher(ov::npuw::MaskInfo& mask_info) {+ StandardCausalMatcher() {auto cmp = opp::wrap_type<ov::op::v1::LessEqual, ov::op::v1::Less>({make_range_chain(), make_range_chain()});- auto callback = [&mask_info](opp::Matcher& /*m*/) {- if (mask_info.mask_type != ov::npuw::MaskInfo::MaskType::SlidingWindow)- mask_info = {ov::npuw::MaskInfo::MaskType::Causal, 0};+ auto callback = [](opp::Matcher& m) {+ annotate_causal_mask(m.get_match_root()->output(0));return false;};register_matcher(std::make_shared<opp::Matcher>(cmp, "StandardCausal"), callback);@@ -104,16 +312,17 @@ public://// StandardCausalMatcher with extra Add: Add(cache_len, range_chain), with the range chain as the// Add's 2nd input.+//+// Same annotate_causal_mask() branch-level handling as StandardCausalMatcher above.// ============================================================================class Qwen3CausalMatcher final : public ov::pass::MatcherPass {public:OPENVINO_MATCHER_PASS_RTTI("ov::npuw::Qwen3CausalMatcher");- explicit Qwen3CausalMatcher(ov::npuw::MaskInfo& mask_info) {+ Qwen3CausalMatcher() {auto add = opp::wrap_type<ov::op::v1::Add>({opp::any_input(), make_range_chain()});auto cmp = opp::wrap_type<ov::op::v1::LessEqual, ov::op::v1::Less>({make_range_chain(), add});- auto callback = [&mask_info](opp::Matcher& /*m*/) {- if (mask_info.mask_type != ov::npuw::MaskInfo::MaskType::SlidingWindow)- mask_info = {ov::npuw::MaskInfo::MaskType::Causal, 0};+ auto callback = [](opp::Matcher& m) {+ annotate_causal_mask(m.get_match_root()->output(0));return false;};register_matcher(std::make_shared<opp::Matcher>(cmp, "Qwen3Causal"), callback);@@ -133,7 +342,7 @@ public:class BitwiseAndSlidingMatcher final : public ov::pass::MatcherPass {public:OPENVINO_MATCHER_PASS_RTTI("ov::npuw::BitwiseAndSlidingMatcher");- explicit BitwiseAndSlidingMatcher(ov::npuw::MaskInfo& mask_info) {+ BitwiseAndSlidingMatcher() {auto q_chain = make_range_chain();auto k_chain = make_range_chain();auto window_constant = opp::wrap_type<ov::op::v0::Constant>();@@ -142,11 +351,12 @@ public:auto and_win = opp::wrap_type<ov::op::v13::BitwiseAnd>({opp::any_input(), greater});auto causal = opp::wrap_type<ov::op::v1::LessEqual>({k_chain, q_chain});auto anchor = opp::wrap_type<ov::op::v13::BitwiseAnd>({and_win, causal});- auto callback = [&mask_info, window_constant](opp::Matcher& m) {+ auto callback = [window_constant](opp::Matcher& m) {const int64_t window_size =get_window_size(m.get_pattern_value_map().at(window_constant).get_node_shared_ptr());- if (window_size > 0)- mask_info = {ov::npuw::MaskInfo::MaskType::SlidingWindow, window_size};+ if (window_size > 0) {+ annotate_sdpa_consumers(m.get_match_root()->output(0), window_size);+ }return false;};register_matcher(std::make_shared<opp::Matcher>(anchor, "BitwiseAndSliding"), callback);@@ -167,7 +377,7 @@ public:class OldPhi3SlidingMatcher final : public ov::pass::MatcherPass {public:OPENVINO_MATCHER_PASS_RTTI("ov::npuw::OldPhi3SlidingMatcher");- explicit OldPhi3SlidingMatcher(ov::npuw::MaskInfo& mask_info) {+ OldPhi3SlidingMatcher() {auto k_constant = opp::wrap_type<ov::op::v0::Constant>();auto gather = opp::wrap_type<ov::op::v8::Gather>({opp::any_input(), opp::any_input(), opp::any_input()});auto k_range = opp::wrap_type<ov::op::v4::Range>({k_constant, gather, opp::any_input()});@@ -181,10 +391,11 @@ public:auto causal_mask = opp::wrap_type<ov::op::v1::LessEqual>({k_f32, q_add});auto anchor = opp::wrap_type<ov::op::v13::BitwiseOr>({sliding_mask, causal_mask});- auto callback = [=, &mask_info](opp::Matcher& m) {+ auto callback = [=](opp::Matcher& m) {const int64_t w = get_window_size(m.get_pattern_value_map().at(q_constant).get_node_shared_ptr());- if (w > 0)- mask_info = {ov::npuw::MaskInfo::MaskType::SlidingWindow, w};+ if (w > 0) {+ annotate_sdpa_consumers(m.get_match_root()->output(0), w);+ }return false;};@@ -203,7 +414,7 @@ public:class DefaultSWAMatcher final : public ov::pass::MatcherPass {public:OPENVINO_MATCHER_PASS_RTTI("ov::npuw::DefaultSWAMatcher");- explicit DefaultSWAMatcher(ov::npuw::MaskInfo& mask_info) {+ DefaultSWAMatcher() {auto k_chain = make_range_chain();auto q_chain = make_range_chain();auto window_const = opp::wrap_type<ov::op::v0::Constant>();@@ -211,16 +422,104 @@ public:auto subtract = opp::wrap_type<ov::op::v1::Subtract>({q_chain, window_const});auto sliding_mask = opp::wrap_type<ov::op::v1::Greater>({k_chain, subtract});auto anchor = opp::wrap_type<ov::op::v1::LogicalAnd>({causal_mask, sliding_mask});- auto callback = [=, &mask_info](opp::Matcher& m) {+ auto callback = [=](opp::Matcher& m) {const int64_t w = get_window_size(m.get_pattern_value_map().at(window_const).get_node_shared_ptr());- if (w > 0)- mask_info = {ov::npuw::MaskInfo::MaskType::SlidingWindow, w};+ if (w > 0) {+ annotate_sdpa_consumers(m.get_match_root()->output(0), w);+ }return false;};register_matcher(std::make_shared<opp::Matcher>(anchor, "DefaultSWA"), callback);}};+// ============================================================================+// Matches Gemma-4-12B's decomposed torch.triu(...)-style causal mask:+//+// Select(GreaterEqual(row, col), any_input, any_input)+//+// Unlike every other causal matcher above (LessEqual/Less feeding a boolean+// combine op), Gemma-4-12B's trace decomposes torch.triu()/masked_fill() into a+// GreaterEqual boolean feeding a Select that directly picks between the+// unmasked (0) and masked (-inf) float fill values -- there is no+// BitwiseAnd/BitwiseOr/LogicalAnd anywhere in this family. Row/col operands are+// left as any_input() rather than make_range_chain(), since this export's+// Range/Unsqueeze/Add ordering doesn't match that chain's grammar.+//+// Uses annotate_triu_causal_mask() (see its own doc comment above) rather than a+// blanket skip when the matched Select feeds another Select down the line.+//+// The GreaterEqual/Select shapes themselves are common enough (unlike e.g.+// LessEqual/Less feeding a boolean-combine op) that this anchor alone is too+// permissive -- nothing here ties `ge` to actual position indices the way+// make_range_chain() does for the other matchers. The callback additionally+// requires the Select's output to be a floating-point tensor (a real mask+// always selects between float fill values, 0 / -inf) and that at least one of+// `ge`'s operands (transitively) derives from a Range op (see traces_to_range+// above), i.e. is a genuine row/col position-index computation -- ruling out+// unrelated boolean/integer Select(GreaterEqual(...)) uses elsewhere in the+// model without requiring an exact match on this export's Range/Unsqueeze/Add+// chain ordering.+// ============================================================================+class TriuCausalMatcher final : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("ov::npuw::TriuCausalMatcher");+ TriuCausalMatcher() {+ auto ge = opp::wrap_type<ov::op::v1::GreaterEqual>({opp::any_input(), opp::any_input()});+ auto sel = opp::wrap_type<ov::op::v1::Select>({ge, opp::any_input(), opp::any_input()});+ auto callback = [ge](opp::Matcher& m) {+ auto root = m.get_match_root();+ if (!root->get_output_element_type(0).is_real())+ return false;+ auto ge_node = m.get_pattern_value_map().at(ge).get_node_shared_ptr();+ if (!traces_to_range(ge_node->get_input_node_shared_ptr(0)) &&+ !traces_to_range(ge_node->get_input_node_shared_ptr(1)))+ return false;+ annotate_triu_causal_mask(root->output(0));+ return false;+ };+ register_matcher(std::make_shared<opp::Matcher>(sel, "TriuCausal"), callback);+ }+};++// ============================================================================+// Matches Gemma-4-12B's decomposed sliding-window "beyond window" overwrite:+//+// diff = Subtract(row, col)+// beyond_window = GreaterEqual(diff, window_const)+// windowed = Select(opt Unsqueeze x2(beyond_window), any_input, any_input)+//+// `windowed`'s data operands are the plain triu-causal mask matched by+// TriuCausalMatcher above (as either its then or else operand -- Gemma-4-12B+// puts it in the "else" slot, but that's not load-bearing here) and a fill+// constant; this Select overwrites the causal mask with the fill value+// wherever the key is further back than `window_const` positions. Anchored+// (and annotated) independently of TriuCausalMatcher, same as+// BitwiseAndSlidingMatcher/DefaultSWAMatcher above vs. the LessEqual family.+// ============================================================================+class TriuSlidingMatcher final : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("ov::npuw::TriuSlidingMatcher");+ TriuSlidingMatcher() {+ auto diff = opp::wrap_type<ov::op::v1::Subtract>({opp::any_input(), opp::any_input()});+ auto window_const = opp::wrap_type<ov::op::v0::Constant>();+ auto beyond_window = opp::wrap_type<ov::op::v1::GreaterEqual>({diff, window_const});+ 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());+ if (w > 0) {+ annotate_sdpa_consumers(m.get_match_root()->output(0), w);+ }+ return false;+ };+ register_matcher(std::make_shared<opp::Matcher>(windowed, "TriuSliding"), callback);+ }+};+#ifdef __GNUC__# pragma GCC diagnostic pop#endif@@ -230,18 +529,80 @@ public:namespace ov::npuw {bool DetectAttentionMask::run_on_model(const std::shared_ptr<ov::Model>& model) {- m_mask_info = MaskInfo{};-+ // Matchers below annotate individual SDPA nodes as they recognize Causal or+ // SlidingWindow patterns feeding that node's mask input (see+ // NPUW_SDPA_MASK_RT_KEY in the header for the annotation/encoding contract); a+ // node that no matcher recognizes stays Unknown.ov::pass::GraphRewrite detector;- detector.add_matcher<BitwiseAndSlidingMatcher>(m_mask_info);- detector.add_matcher<OldPhi3SlidingMatcher>(m_mask_info);- detector.add_matcher<DefaultSWAMatcher>(m_mask_info);- detector.add_matcher<SDPACausalMatcher>(m_mask_info);- detector.add_matcher<StandardCausalMatcher>(m_mask_info);- detector.add_matcher<Qwen3CausalMatcher>(m_mask_info);+ detector.add_matcher<BitwiseAndSlidingMatcher>();+ detector.add_matcher<OldPhi3SlidingMatcher>();+ detector.add_matcher<DefaultSWAMatcher>();+ detector.add_matcher<TriuSlidingMatcher>();+ detector.add_matcher<SDPACausalMatcher>();+ detector.add_matcher<StandardCausalMatcher>();+ detector.add_matcher<Qwen3CausalMatcher>();+ detector.add_matcher<TriuCausalMatcher>();detector.run_on_model(model);return false;}+void log_detected_masks(const std::shared_ptr<ov::Model>& model) {+ if (ov::npuw::get_log_level() < ov::npuw::LogLevel::Debug) {+ return;+ }++ // Best-effort: pull a transformer layer index out of the SDPA node's friendly+ // name (HF/ONNX exports commonly retain the originating module's scope, e.g.+ // "__module.model.layers.4.self_attn/aten::scaled_dot_product_attention").+ // Falls back to topological position when no such index can be found (e.g. in+ // standalone/synthetic test graphs).+ static const std::regex layer_idx_re(R"([Ll]ayers?[._/]([0-9]+))");++ struct Entry {+ std::string name;+ std::string type;+ int64_t sort_key;+ };+ std::vector<Entry> entries;++ int64_t position = 0;+ for (const auto& node : model->get_ordered_ops()) {+ auto sdpa = ov::as_type_ptr<ov::op::v13::ScaledDotProductAttention>(node);+ if (!sdpa)+ continue;++ std::string type;+ const auto& rt_info = sdpa->get_rt_info();+ const auto it = rt_info.find(NPUW_SDPA_MASK_RT_KEY);+ if (it == rt_info.end()) {+ type = "Unknown";+ } else {+ const auto encoded = it->second.as<int64_t>();+ type = (encoded < 0) ? "Causal" : ("SlidingWindow(" + std::to_string(encoded) + ")");+ }++ const auto& name = sdpa->get_friendly_name();+ std::smatch match;+ int64_t sort_key = position;+ if (std::regex_search(name, match, layer_idx_re) && match.size() > 1) {+ const auto& digits = match[1].str();+ int64_t parsed = 0;+ const auto res = std::from_chars(digits.data(), digits.data() + digits.size(), parsed);+ if (res.ec == std::errc{}) {+ sort_key = parsed;+ }+ }+ entries.push_back({name, std::move(type), sort_key});+ ++position;+ }++ std::stable_sort(entries.begin(), entries.end(), [](const Entry& lhs, const Entry& rhs) {+ return lhs.sort_key < rhs.sort_key;+ });+ for (const auto& entry : entries) {+ LOG_DEBUG("layer " << entry.sort_key << " (" << entry.name << "): " << entry.type);+ }+}+} // namespace ov::npuwdiff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/detect_causal_mask.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/detect_causal_mask.hppindex 283de4ad216..71bf2bb96b9 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/detect_causal_mask.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/detect_causal_mask.hpp@@ -8,35 +8,42 @@namespace ov::npuw {-// Detected attention mask type and (for sliding window) its window size.-struct MaskInfo {- // No recognized mask pattern (e.g. full attention), plain causal, or- // causal + sliding-window (local attention).- enum class MaskType : int { Unknown = 0, Causal, SlidingWindow };-- // Value-initialized to MaskType::Unknown (== 0).- MaskType mask_type{};- // Valid only when mask_type == SlidingWindow.- int64_t window_size = 0;-};--// Analysis pass: detects the attention mask type of a model by inspecting the-// mask-construction subgraph (Range/LessEqual/Greater/BitwiseAnd) and the SDPA-// is_causal attribute. It never modifies the model (run_on_model returns false),-// so the result is retrieved via get_mask_info() after running.+// Analysis pass: detects the attention mask type of each SDPA node in the model by+// inspecting its mask-construction subgraph (Range/LessEqual/Greater/BitwiseAnd) or+// its is_causal attribute, and annotates the node's rt_info[NPUW_SDPA_MASK_RT_KEY]+// accordingly (see the encoding documented there). A node may only be annotated+// once -- a matcher that would overwrite an already-annotated node with a+// conflicting kind asserts instead, since that indicates genuinely contradictory+// evidence (e.g. an is_causal=true SDPA fed an explicit sliding-window mask), not+// just two matchers agreeing.+//+// Must run before SDPA decomposition (OptimizeValueTensors) so the SDPA nodes it+// annotates still exist.class DetectAttentionMask : public ov::pass::ModelPass {public:OPENVINO_MODEL_PASS_RTTI("ov::npuw::DetectAttentionMask");DetectAttentionMask() = default;bool run_on_model(const std::shared_ptr<ov::Model>& model) override;+};- const MaskInfo& get_mask_info() const {- return m_mask_info;- }+void log_detected_masks(const std::shared_ptr<ov::Model>& model);-private:- MaskInfo m_mask_info;-};+// rt_info key written by DetectAttentionMask onto each ScaledDotProductAttention+// node, propagated onto the decomposed Add(QK, mask) node by+// ScaledDotProductAttentionDecomposition::decompose() (via copy_runtime_info), and+// read directly by HostFlashAttention::from().+//+// Value type: int64_t, encoding both the mask kind and (for sliding window) its+// window size in a single slot:+// * key absent -> Unknown (no recognized mask pattern, e.g. full/bidirectional+// attention)+// * value < 0 -> Causal (equivalent to a sliding window whose size covers the+// whole context, i.e. "infinite window")+// * value >= 0 -> SlidingWindow, value is the window size+static constexpr const char* NPUW_SDPA_MASK_RT_KEY = "npuw_sdpa_mask_type";++// Sentinel value written for the Causal case -- see NPUW_SDPA_MASK_RT_KEY above.+static constexpr int64_t NPUW_SDPA_MASK_CAUSAL = -1;} // namespace ov::npuwdiff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cppindex 709cd22cbc3..85a1f7596a4 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp@@ -4,10 +4,12 @@#include "partitioning.hpp"+#include <limits>#include <memory>#include <set>#include "../logging.hpp"+#include "../npuw_transformations/detect_causal_mask.hpp"#include "../util.hpp"#include "intel_npu/config/npuw.hpp"#include "online/compiler.hpp"@@ -2097,10 +2099,52 @@ void Partitioner::attention(const std::string& func_name) {// Try HFA (Host Flash Attention)if (attn_mode == "HFA") {LOG_DEBUG("Attempting HostFlashAttention based on config");- f._host_flash_attention =- ov::npuw::function::HostFlashAttention::from(f._model,- cfg.get<::intel_npu::NPUW_ATTN_HFA_FUSED>(),- cfg.get<::intel_npu::NPUW_ATTN_HFA_MASK_SKIPPING>());++ // Consistency check: HostFlashAttention::from() inspects a single representative+ // instance (f._model) of this repeated "attn" function to decide whether the+ // compiled tile model can structurally drop the mask input. That decision is only+ // valid if all funcall instances sharing this function have the same mask kind --+ // otherwise it's a correctness bug (e.g. a Causal representative stripping a mask+ // a SlidingWindow instance still needs), not just a missed optimization. This is a+ // defensive backstop, not the primary separation mechanism: distinct mask kinds+ // normally yield structurally distinct subgraphs, so partitioning already tends to+ // keep them in separate functions. If a mix is still found here, disable+ // mask-skipping for the whole function (safe: only forgoes an optimization).+ //+ // NPUW_SDPA_MASK_RT_KEY encodes mask kind + (for sliding window) window size in+ // one int64_t, so raw-value comparison also catches differing window sizes.+ std::optional<int64_t> common_mask_value;+ bool mask_kind_consistent = true;+ for (const auto& mdl : all_functions.at(func_name).mdls) {+ const auto pattern_nodes = ov::npuw::util::find_sdpa_pattern_nodes(mdl);+ if (!pattern_nodes.add_node) {+ continue;+ }++ int64_t mask_value = std::numeric_limits<int64_t>::min();+ const auto& rt_info = pattern_nodes.add_node->get_rt_info();+ if (auto it = rt_info.find(ov::npuw::NPUW_SDPA_MASK_RT_KEY); it != rt_info.end()) {+ mask_value = it->second.as<int64_t>();+ }+ if (!common_mask_value) {+ common_mask_value = mask_value;+ } else if (*common_mask_value != mask_value) {+ LOG_WARN("NPUW: mixed mask types (e.g. sliding-window + global/causal attention, or different "+ "sliding window sizes) detected across funcall instances sharing the same repeated 'attn' "+ "function '"+ << func_name+ << "'. The mask-skipping optimization's compile-time decision is based on a single "+ "representative instance, which would be unsafe here -- disabling mask skipping for "+ "this function.");+ mask_kind_consistent = false;+ break;+ }+ }++ f._host_flash_attention = ov::npuw::function::HostFlashAttention::from(+ f._model,+ cfg.get<::intel_npu::NPUW_ATTN_HFA_FUSED>(),+ mask_kind_consistent && cfg.get<::intel_npu::NPUW_ATTN_HFA_MASK_SKIPPING>());if (f._host_flash_attention) {LOG_VERB("Done - HFA (Host Flash Attention)");return;diff --git a/src/plugins/intel_npu/tests/unit/npuw/host_flash_attention_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/host_flash_attention_test.cppindex f005b12fe7f..87883e39c51 100644--- a/src/plugins/intel_npu/tests/unit/npuw/host_flash_attention_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/host_flash_attention_test.cpp@@ -9,6 +9,7 @@#include <memory>#include <string>+#include "npuw_transformations/detect_causal_mask.hpp"#include "openvino/op/add.hpp"#include "openvino/op/concat.hpp"#include "openvino/op/convert.hpp"@@ -237,6 +238,24 @@ void check_output_shapes(const std::shared_ptr<ov::Model>& model,}}+// Test models built in this file don't run DetectAttentionMask, so their Add(QK, mask)+// node starts unannotated (Unknown). This helper emulates what DetectAttentionMask would+// have written, so tests can exercise HostFlashAttention::from()'s per-SDPA mask-skipping+// decision directly. `encoded_value` follows NPUW_SDPA_MASK_RT_KEY's encoding: negative+// (e.g. ov::npuw::NPUW_SDPA_MASK_CAUSAL) for Causal, >= 0 for SlidingWindow(window_size).+void annotate_mask_rt_info(const std::shared_ptr<ov::Model>& model,+ int64_t encoded_value,+ const std::string& add_name = "add.0") {+ for (const auto& node : model->get_ops()) {+ auto add = ov::as_type_ptr<ov::op::v1::Add>(node);+ if (add && add->get_friendly_name() == add_name) {+ add->get_rt_info()[ov::npuw::NPUW_SDPA_MASK_RT_KEY] = encoded_value;+ return;+ }+ }+ throw std::runtime_error("add node '" + add_name + "' not found");+}+} // namespaceTEST(HostFlashAttentionFromTest, ReturnsNulloptForNonSDPAModel) {@@ -293,9 +312,24 @@ TEST(HostFlashAttentionFromTest, NonFused_MaskTileAtIndexSixInBothModels) {expect_input_name(result->_final_tile_model, 6, "MASK_TILE", "non-fused final tile");}-TEST(HostFlashAttentionFromTest, Fused_MaskTileAtIndexSixInFinalTileOnly) {+TEST(HostFlashAttentionFromTest, Fused_NoRtInfoAnnotation_KeepsMaskEvenWhenGlobalYes) {+ // Without a DetectAttentionMask annotation (Unknown), mask skipping must stay+ // disabled even when the global switch is on -- the mask shape/semantics are+ // unproven, so skipping it could silently change results.auto result = ov::npuw::function::HostFlashAttention::from(build_sdpa_model(), true, true);ASSERT_TRUE(result.has_value());+ EXPECT_EQ(result->_tile_model->inputs().size(), 7u);+ EXPECT_EQ(result->_final_tile_model->inputs().size(), 7u);+ expect_input_name(result->_tile_model, 6, "MASK_TILE", "fused regular tile without rt_info annotation");+ expect_input_name(result->_final_tile_model, 6, "MASK_TILE", "fused final tile");+}++TEST(HostFlashAttentionFromTest, Fused_MaskTileAtIndexSixInFinalTileOnly) {+ auto model = build_sdpa_model();+ annotate_mask_rt_info(model, ov::npuw::NPUW_SDPA_MASK_CAUSAL);++ auto result = ov::npuw::function::HostFlashAttention::from(model, true, true);+ ASSERT_TRUE(result.has_value());EXPECT_EQ(result->_tile_model->inputs().size(), 6u);EXPECT_EQ(result->_final_tile_model->inputs().size(), 7u);expect_input_name(result->_final_tile_model, 6, "MASK_TILE", "fused final tile");@@ -310,6 +344,56 @@ TEST(HostFlashAttentionFromTest, Fused_MaskTileAtIndexSixInRegularTileWhenMaskSkexpect_input_name(result->_final_tile_model, 6, "MASK_TILE", "fused final tile");}+TEST(HostFlashAttentionFromTest, Fused_PerSDPACausalRtInfo_EnablesRegularTileMaskSkipping) {+ auto model = build_sdpa_model();+ annotate_mask_rt_info(model, ov::npuw::NPUW_SDPA_MASK_CAUSAL);++ auto result = ov::npuw::function::HostFlashAttention::from(model, true, true);+ ASSERT_TRUE(result.has_value());++ // Regular tile skips mask (6 inputs), final tile still keeps mask (7 inputs).+ EXPECT_EQ(result->_tile_model->inputs().size(), 6u);+ EXPECT_EQ(result->_final_tile_model->inputs().size(), 7u);+}++TEST(HostFlashAttentionFromTest, Fused_PerSDPACausalRtInfo_DisabledByGlobalKillSwitch) {+ auto model = build_sdpa_model();+ annotate_mask_rt_info(model, ov::npuw::NPUW_SDPA_MASK_CAUSAL);++ // NPUW_ATTN_HFA_MASK_SKIPPING=NO (global) acts as a master kill switch: even a+ // Causal per-SDPA annotation cannot re-enable mask skipping.+ auto result = ov::npuw::function::HostFlashAttention::from(model, true, false);+ ASSERT_TRUE(result.has_value());+ EXPECT_EQ(result->_tile_model->inputs().size(), 7u);+ EXPECT_EQ(result->_final_tile_model->inputs().size(), 7u);+}++TEST(HostFlashAttentionFromTest, Fused_PerSDPASlidingRtInfo_NarrowerThanContext_KeepsMask) {+ auto model = build_sdpa_model(); // context_size = QUERY_SIZE + PAST_LEN+ annotate_mask_rt_info(model, /*window_size=*/8);++ auto result = ov::npuw::function::HostFlashAttention::from(model, true, true);+ ASSERT_TRUE(result.has_value());++ // Window is narrower than the context, so a regular tile can't safely skip the+ // mask -- keeps mask (7 inputs) in both tiles.+ EXPECT_EQ(result->_tile_model->inputs().size(), 7u);+ EXPECT_EQ(result->_final_tile_model->inputs().size(), 7u);+}++TEST(HostFlashAttentionFromTest, Fused_PerSDPASlidingRtInfo_CoversWholeContext_SkipsRegularMask) {+ auto model = build_sdpa_model(); // context_size = QUERY_SIZE + PAST_LEN+ annotate_mask_rt_info(model, /*window_size=*/static_cast<int64_t>(QUERY_SIZE + PAST_LEN));++ auto result = ov::npuw::function::HostFlashAttention::from(model, true, true);+ ASSERT_TRUE(result.has_value());++ // Window covers the whole context, behaves like Causal -- skips mask (6 inputs)+ // in the regular tile, final tile still keeps mask (7 inputs).+ EXPECT_EQ(result->_tile_model->inputs().size(), 6u);+ EXPECT_EQ(result->_final_tile_model->inputs().size(), 7u);+}+// ============================================================================// Tile param index map// ============================================================================@@ -423,7 +507,9 @@ std::shared_ptr<ov::Model> build_sdpa_model_transposed_v(size_t query_size = QUE// Fused path with mask skipping enabled — regular tile (6 inputs, no mask); v_tile in normal layoutTEST(HostFlashAttentionFromTest, Fused_RegularTileInputShapes) {- auto result = ov::npuw::function::HostFlashAttention::from(build_sdpa_model(), true, true);+ auto model = build_sdpa_model();+ annotate_mask_rt_info(model, ov::npuw::NPUW_SDPA_MASK_CAUSAL);+ auto result = ov::npuw::function::HostFlashAttention::from(model, true, true);ASSERT_TRUE(result.has_value());// [past_acc, past_max, past_d, k_tile, v_tile, q]const std::vector<ov::Shape> expected_inputs = {@@ -533,7 +619,9 @@ TEST(HostFlashAttentionFromTest, VSeqDimIsTwoForNormalModel) {// Fused regular tile with mask skipping enabled: v_tile in transposed layout [B, H, head_dim, tile]TEST(HostFlashAttentionTransposedVTest, Fused_RegularTileVTileIsTransposed) {- auto result = ov::npuw::function::HostFlashAttention::from(build_sdpa_model_transposed_v(), true, true);+ auto model = build_sdpa_model_transposed_v();+ annotate_mask_rt_info(model, ov::npuw::NPUW_SDPA_MASK_CAUSAL);+ auto result = ov::npuw::function::HostFlashAttention::from(model, true, true);ASSERT_TRUE(result.has_value());const std::vector<ov::Shape> expected = {{BATCH, NUM_HEADS, QUERY_SIZE, HEAD_DIM}, // past_accdiff --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 b1008e35374..e01141d1693 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@@ -6,7 +6,9 @@#include <gtest/gtest.h>+#include <algorithm>#include <limits>+#include <vector>#include "../llm_test_helpers.hpp"#include "model_builder.hpp"@@ -15,8 +17,6 @@#include "openvino/openvino.hpp"using ov::npuw::DetectAttentionMask;-using ov::npuw::MaskInfo;-using MaskType = ov::npuw::MaskInfo::MaskType;using ov::test::npuw::make_sliding_window_mask_gemma4;using ov::test::npuw::make_sliding_window_mask_phi3;using ov::test::npuw::make_sliding_window_mask_phi3_legacy;@@ -26,10 +26,66 @@ namespace {constexpr int64_t kWindow = 512;-MaskType detect(const std::shared_ptr<ov::Model>& model) {- DetectAttentionMask pass;- pass.run_on_model(model);- return pass.get_mask_info().mask_type;+// Local, test-only mirror of NPUW_SDPA_MASK_RT_KEY's encoding (see+// detect_causal_mask.hpp) -- kept here purely for readable assertions; DetectAttentionMask+// itself only ever writes the raw encoded int64_t.+enum class DetectedMaskType { Unknown, Causal, SlidingWindow };++struct DetectedMask {+ DetectedMaskType type = DetectedMaskType::Unknown;+ int64_t window_size = 0; // meaningful only when type == SlidingWindow+};++bool operator==(const DetectedMask& lhs, DetectedMaskType rhs) {+ return lhs.type == rhs;+}++DetectedMask decode_rt_info(const ov::Node::RTMap& rt_info) {+ const auto it = rt_info.find(ov::npuw::NPUW_SDPA_MASK_RT_KEY);+ if (it == rt_info.end())+ return {DetectedMaskType::Unknown, 0};+ const auto encoded = it->second.as<int64_t>();+ if (encoded < 0)+ return {DetectedMaskType::Causal, 0};+ return {DetectedMaskType::SlidingWindow, encoded};+}++// Returns the annotation DetectAttentionMask wrote on every ScaledDotProductAttention+// node in `model`, in model order. Test models in this file always model one attention+// subgraph per SDPA node, so the returned vector's size equals the number of SDPA nodes.+std::vector<DetectedMask> detect_all(const std::shared_ptr<ov::Model>& model) {+ DetectAttentionMask().run_on_model(model);+ std::vector<DetectedMask> result;+ for (const auto& node : model->get_ordered_ops()) {+ if (ov::is_type<ov::op::v13::ScaledDotProductAttention>(node)) {+ result.push_back(decode_rt_info(node->get_rt_info()));+ }+ }+ return result;+}++// Convenience wrapper for the (common) single-SDPA-node case.+DetectedMask detect(const std::shared_ptr<ov::Model>& model) {+ const auto all = detect_all(model);+ return all.empty() ? DetectedMask{} : all.front();+}++// Builds a minimal SDPA model whose attn_mask input is `mask_output` -- the+// constructed mask expression under test. DetectAttentionMask's matchers only write+// rt_info onto an actual ScaledDotProductAttention node reached by walking forward+// from the recognized mask expression (see annotate_sdpa_consumers() in+// detect_causal_mask.cpp), so every standalone "real pattern" mask builder in this+// file needs one downstream of the mask it constructs.+std::shared_ptr<ov::Model> wrap_mask_in_sdpa_model(const ov::Output<ov::Node>& mask_output,+ ov::ParameterVector params) {+ using namespace ov::op;+ 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 sdpa = std::make_shared<v13::ScaledDotProductAttention>(q, k, v, mask_output, false);+ auto result = std::make_shared<v0::Result>(sdpa->output(0));+ params.insert(params.end(), {q, k, v});+ return std::make_shared<ov::Model>(ov::ResultVector{result}, params);}// ---------------------------------------------------------------------------@@ -87,8 +143,7 @@ std::shared_ptr<ov::Model> build_llama_causal() {auto le = std::make_shared<v1::LessEqual>(kv_idx, q_idx);auto new_ones = v0::Constant::create(ov::element::boolean, ov::Shape{}, {true});auto combined = std::make_shared<v13::BitwiseAnd>(new_ones, le);- auto result = std::make_shared<v0::Result>(combined);- return std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{seq, amask});+ return wrap_mask_in_sdpa_model(combined, {seq, amask});}// ---------------------------------------------------------------------------@@ -139,8 +194,141 @@ std::shared_ptr<ov::Model> build_phi3_sliding(int64_t window) {auto causal = std::make_shared<v1::LessEqual>(kv_row, q_col);auto mask = std::make_shared<v13::BitwiseAnd>(and_win, causal);- auto result = std::make_shared<v0::Result>(mask);- return std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{seq, amask});+ return wrap_mask_in_sdpa_model(mask, {seq, amask});+}++// ---------------------------------------------------------------------------+// Faithful reproduction of Gemma-4-E2B's layer split, where a single shared+// causal comparison feeds two structurally different SDPA branches:+//+// causal = LessEqual(kv_row, q_col)+// -- sliding-window layer --+// and_win = BitwiseAnd(attn_bool, greater) (greater = kv > q - window)+// sliding = BitwiseAnd(and_win, causal) -> SDPA #0+// -- global/full-attention layer --+// full = BitwiseAnd(new_ones, causal) -> SDPA #1+//+// Both branches reuse the exact same `causal` node. Regression test for the+// bug where StandardCausalMatcher used to bail out entirely as soon as+// `causal` fed *any* boolean-combine op, silently leaving the global-attention+// branch (SDPA #1) undetected (see annotate_causal_mask()/contains_window_check()+// in detect_causal_mask.cpp).+// ---------------------------------------------------------------------------+std::shared_ptr<ov::Model> build_gemma4_e2b_shared_causal(int64_t window) {+ 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 ids_shape = std::make_shared<v3::ShapeOf>(seq, ov::element::i64);+ auto mask_shape = std::make_shared<v3::ShapeOf>(amask, ov::element::i64);+ auto seq_len = std::make_shared<v8::Gather>(ids_shape, one, zero);+ auto total = std::make_shared<v8::Gather>(mask_shape, one, zero);+ auto past = std::make_shared<v1::Subtract>(total, seq_len);++ auto kv_range = std::make_shared<v4::Range>(zero, total, one, ov::element::i64);+ auto kv0 = std::make_shared<v0::Unsqueeze>(kv_range, one);+ auto kv1 = std::make_shared<v0::Unsqueeze>(kv0, one);+ auto kv_row = std::make_shared<v0::Unsqueeze>(kv1, one);++ auto q_range = std::make_shared<v4::Range>(past, total, one, ov::element::i64);+ auto q0 = std::make_shared<v0::Unsqueeze>(q_range, one);+ auto q1 = std::make_shared<v0::Unsqueeze>(q0, one);+ auto q_col = std::make_shared<v0::Unsqueeze>(q1, one);++ auto causal = std::make_shared<v1::LessEqual>(kv_row, q_col);++ // Sliding-window branch: same shape as build_phi3_sliding()'s mask.+ auto neg_window = v0::Constant::create(ov::element::i64, ov::Shape{}, {-window});+ auto bound = std::make_shared<v1::Add>(q_col, neg_window);+ auto greater = std::make_shared<v1::Greater>(kv_row, bound);+ auto attn_bool = std::make_shared<v0::Convert>(amask, ov::element::boolean);+ auto and_win = std::make_shared<v13::BitwiseAnd>(attn_bool, greater);+ auto sliding_mask = std::make_shared<v13::BitwiseAnd>(and_win, causal);++ // Global/full-attention branch: identity BitwiseAnd, same shape as+ // build_llama_causal()'s mask.+ auto new_ones = v0::Constant::create(ov::element::boolean, ov::Shape{}, {true});+ auto full_mask = std::make_shared<v13::BitwiseAnd>(new_ones, causal);++ 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 sliding_sdpa = std::make_shared<v13::ScaledDotProductAttention>(q, k, v, sliding_mask, false);+ auto full_sdpa = std::make_shared<v13::ScaledDotProductAttention>(q, k, v, full_mask, false);+ auto sliding_result = std::make_shared<v0::Result>(sliding_sdpa->output(0));+ auto full_result = std::make_shared<v0::Result>(full_sdpa->output(0));+ return std::make_shared<ov::Model>(ov::ResultVector{sliding_result, full_result},+ ov::ParameterVector{seq, amask, q, k, v});+}++// ---------------------------------------------------------------------------+// Faithful reproduction of Gemma-4-12B's decomposed torch.triu()/masked_fill()+// mask subgraph, as seen in a real Gemma-4-12B export (openvino_language_model.xml):+//+// row_pos, col_pos = Range(...)-derived position indices+// causal_cond = GreaterEqual(row_pos, col_pos) (aten::triu)+// causal_mask = Select(causal_cond, zero_const, fill_const)+//+// diff = Subtract(row_pos, col_pos)+// beyond_window = GreaterEqual(diff, window_const)+// sliding_mask = Select(Unsqueeze x2(beyond_window), fill_const, causal_mask)+//+// attention_mask (global) = Select(padding_bool, fill_const, causal_mask) (aten::masked_fill)+//+// causal_mask feeds *both* the sliding-window overwrite (one SDPA) and a plain+// padding combine on another, independent SDPA (a global/full-attention layer)+// -- the same "one causal expression feeds two structurally different+// branches" shape as build_gemma4_e2b_shared_causal() above, but built from+// GreaterEqual + Select instead of LessEqual + BitwiseAnd.+// ---------------------------------------------------------------------------+std::shared_ptr<ov::Model> build_gemma4_12b_triu_shared_causal(int64_t window) {+ 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 ids_shape = std::make_shared<v3::ShapeOf>(seq, ov::element::i64);+ auto mask_shape = std::make_shared<v3::ShapeOf>(amask, ov::element::i64);+ auto seq_len = std::make_shared<v8::Gather>(ids_shape, one, zero);+ auto total = std::make_shared<v8::Gather>(mask_shape, one, zero);+ auto past = std::make_shared<v1::Subtract>(total, seq_len);++ auto col_range = std::make_shared<v4::Range>(zero, total, one, ov::element::i64);+ auto col_pos = std::make_shared<v0::Unsqueeze>(col_range, zero); // [1, -1]++ auto row_range = std::make_shared<v4::Range>(past, total, one, ov::element::i64);+ auto row_pos = std::make_shared<v0::Unsqueeze>(row_range, one); // [-1, 1]++ auto zero_f = v0::Constant::create(ov::element::f32, ov::Shape{}, {0.0f});+ auto fill = v0::Constant::create(ov::element::f32, ov::Shape{}, {-1e9f});++ auto causal_cond = std::make_shared<v1::GreaterEqual>(row_pos, col_pos);+ auto causal_mask = std::make_shared<v1::Select>(causal_cond, zero_f, fill);++ auto window_const = v0::Constant::create(ov::element::i64, ov::Shape{}, {window});+ auto diff = std::make_shared<v1::Subtract>(row_pos, col_pos);+ auto beyond_window = std::make_shared<v1::GreaterEqual>(diff, window_const);+ auto bw0 = std::make_shared<v0::Unsqueeze>(beyond_window, zero);+ auto bw1 = std::make_shared<v0::Unsqueeze>(bw0, zero);+ auto sliding_mask = std::make_shared<v1::Select>(bw1, fill, causal_mask);++ auto pad_bool = std::make_shared<v0::Convert>(amask, ov::element::boolean);+ auto global_mask = std::make_shared<v1::Select>(pad_bool, fill, causal_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 sliding_sdpa = std::make_shared<v13::ScaledDotProductAttention>(q, k, v, sliding_mask, false);+ auto global_sdpa = std::make_shared<v13::ScaledDotProductAttention>(q, k, v, global_mask, false);+ auto sliding_result = std::make_shared<v0::Result>(sliding_sdpa->output(0));+ auto global_result = std::make_shared<v0::Result>(global_sdpa->output(0));+ return std::make_shared<ov::Model>(ov::ResultVector{sliding_result, global_result},+ ov::ParameterVector{seq, amask, q, k, v});}// ---------------------------------------------------------------------------@@ -173,28 +361,27 @@ std::shared_ptr<ov::Model> build_minicpm_less() {auto q_col = std::make_shared<v1::Reshape>(q_abs, col_shape, false);auto mask = std::make_shared<v1::Less>(kv, q_col);- auto result = std::make_shared<v0::Result>(mask);- return std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{seq, amask});+ return wrap_mask_in_sdpa_model(mask, {seq, amask});}} // namespace// ============================================================================-// Causal masks — must report MaskType::Causal+// Causal masks — must report DetectedMaskType::Causal// ============================================================================// NPUW model builder: LLaMA/Qwen-style LessEqual(Range, Range) causal mask.TEST(DetectAttentionMaskTest, ModelBuilder_StandardLLM_IsCausal) {auto model = ov::test::npuw::build_llm_test_model();ASSERT_NE(model, nullptr);- EXPECT_EQ(detect(model), MaskType::Causal);+ EXPECT_EQ(detect(model), DetectedMaskType::Causal);}// NPUW model builder: grouped-query attention shares the same causal structure.TEST(DetectAttentionMaskTest, ModelBuilder_GQA_IsCausal) {auto model = ov::test::npuw::build_llm_gqa_test_model();ASSERT_NE(model, nullptr);- EXPECT_EQ(detect(model), MaskType::Causal);+ EXPECT_EQ(detect(model), DetectedMaskType::Causal);}// NPUW model builder: boolean causal mask feeding SDPA directly (Phi-3 plain).@@ -204,14 +391,14 @@ TEST(DetectAttentionMaskTest, ModelBuilder_BooleanCausal_IsCausal) {ModelBuilder mb;auto model = mb.build_llm(cfg);ASSERT_NE(model, nullptr);- EXPECT_EQ(detect(model), MaskType::Causal);+ EXPECT_EQ(detect(model), DetectedMaskType::Causal);}// NPUW model builder: Whisper decoder cache-position causal mask.TEST(DetectAttentionMaskTest, ModelBuilder_WhisperDecoder_IsCausal) {auto model = ov::test::npuw::build_whisper_decoder_test_model();ASSERT_NE(model, nullptr);- EXPECT_EQ(detect(model), MaskType::Causal);+ EXPECT_EQ(detect(model), DetectedMaskType::Causal);}// NPUW model builder: Whisper decoder with a boolean mask output.@@ -221,17 +408,58 @@ TEST(DetectAttentionMaskTest, ModelBuilder_WhisperDecoderBoolean_IsCausal) {ModelBuilder mb;auto model = mb.build_whisper_decoder(cfg);ASSERT_NE(model, nullptr);- EXPECT_EQ(detect(model), MaskType::Causal);+ EXPECT_EQ(detect(model), DetectedMaskType::Causal);}// Real pattern: LLaMA / TinyLlama LessEqual + BitwiseAnd(new_ones) chain.TEST(DetectAttentionMaskTest, RealPattern_LlamaCausal_IsCausal) {- EXPECT_EQ(detect(build_llama_causal()), MaskType::Causal);+ EXPECT_EQ(detect(build_llama_causal()), DetectedMaskType::Causal);+}++// Real pattern: Gemma-4-E2B, where a single shared causal comparison feeds+// both a sliding-window layer and a global/full-attention layer (see+// build_gemma4_e2b_shared_causal()). Regression test for the bug where the+// causal matcher used to bail out entirely as soon as the causal comparison+// fed *any* boolean-combine op, silently leaving the global-attention branch+// undetected even though the sliding-window branch was correctly annotated.+TEST(DetectAttentionMaskTest, RealPattern_Gemma4E2BSharedCausal_BothBranchesDetected) {+ auto model = build_gemma4_e2b_shared_causal(kWindow);+ ASSERT_NE(model, nullptr);+ const auto all = detect_all(model);+ ASSERT_EQ(all.size(), 2u);+ // Topological order between the two independent SDPA branches isn't+ // guaranteed, so check both are present regardless of position.+ const auto sliding_count = std::count_if(all.begin(), all.end(), [](const DetectedMask& m) {+ return m.type == DetectedMaskType::SlidingWindow && m.window_size == kWindow;+ });+ const auto causal_count = std::count(all.begin(), all.end(), DetectedMaskType::Causal);+ EXPECT_EQ(sliding_count, 1);+ EXPECT_EQ(causal_count, 1);+}++// Real pattern: Gemma-4-12B's decomposed torch.triu()/masked_fill() mask family+// (GreaterEqual + Select, not LessEqual/Greater + BitwiseAnd), where a single+// shared triu-causal Select feeds both a sliding-window overwrite (one SDPA)+// and a plain padding combine on an independent global-attention SDPA (see+// build_gemma4_12b_triu_shared_causal()). Mirrors+// RealPattern_Gemma4E2BSharedCausal_BothBranchesDetected above, but for the+// Select-based mask family matched by TriuCausalMatcher/TriuSlidingMatcher.+TEST(DetectAttentionMaskTest, RealPattern_Gemma4_12B_TriuSharedCausal_BothBranchesDetected) {+ auto model = build_gemma4_12b_triu_shared_causal(kWindow);+ ASSERT_NE(model, nullptr);+ const auto all = detect_all(model);+ ASSERT_EQ(all.size(), 2u);+ const auto sliding_count = std::count_if(all.begin(), all.end(), [](const DetectedMask& m) {+ return m.type == DetectedMaskType::SlidingWindow && m.window_size == kWindow;+ });+ const auto causal_count = std::count(all.begin(), all.end(), DetectedMaskType::Causal);+ EXPECT_EQ(sliding_count, 1);+ EXPECT_EQ(causal_count, 1);}// Real pattern: MiniCPM uses Less (aten::lt) instead of LessEqual (aten::le).TEST(DetectAttentionMaskTest, RealPattern_MiniCPMLess_IsCausal) {- EXPECT_EQ(detect(build_minicpm_less()), MaskType::Causal);+ EXPECT_EQ(detect(build_minicpm_less()), DetectedMaskType::Causal);}// Real pattern: Qwen3 embedding mask — LessEqual(kv, Add(cache_len, q)).@@ -260,10 +488,9 @@ TEST(DetectAttentionMaskTest, RealPattern_Qwen3_IsCausal) {auto causal = std::make_shared<v1::LessEqual>(k_unsq, threshold);auto mask_f = std::make_shared<v1::Select>(causal, zero_f, neg_inf);- auto result = std::make_shared<v0::Result>(mask_f);- auto model = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{input_ids, attn_mask});+ auto model = wrap_mask_in_sdpa_model(mask_f, {input_ids, attn_mask});- EXPECT_EQ(detect(model), MaskType::Causal);+ EXPECT_EQ(detect(model), DetectedMaskType::Causal);}// Real pattern: torch.tril / ONNX Trilu — LessEqual(Range unsq0, Range unsq1).@@ -282,10 +509,9 @@ TEST(DetectAttentionMaskTest, RealPattern_Tril_IsCausal) {auto input = std::make_shared<v0::Parameter>(ov::element::f32, ov::Shape{8, 8});auto zero_f = v0::Constant::create(ov::element::f32, ov::Shape{}, {0.0f});auto out = std::make_shared<v1::Select>(mask, input, zero_f);- auto result = std::make_shared<v0::Result>(out);- auto model = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{input});+ auto model = wrap_mask_in_sdpa_model(out, {input});- EXPECT_EQ(detect(model), MaskType::Causal);+ EXPECT_EQ(detect(model), DetectedMaskType::Causal);}// Real pattern: torch.tril with non-zero diagonal — Range(k, N+k).@@ -306,29 +532,26 @@ TEST(DetectAttentionMaskTest, RealPattern_TrilOffDiagonal_IsCausal) {auto input = std::make_shared<v0::Parameter>(ov::element::f32, ov::Shape{8, 8});auto zero_f = v0::Constant::create(ov::element::f32, ov::Shape{}, {0.0f});auto out = std::make_shared<v1::Select>(mask, input, zero_f);- auto result = std::make_shared<v0::Result>(out);- auto model = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{input});+ auto model = wrap_mask_in_sdpa_model(out, {input});- EXPECT_EQ(detect(model), MaskType::Causal);+ EXPECT_EQ(detect(model), DetectedMaskType::Causal);}// SDPA is_causal=true — no explicit mask, causality via the op attribute.TEST(DetectAttentionMaskTest, SDPAIsCausalAttribute_IsCausal) {- EXPECT_EQ(detect(make_sdpa_model(/*is_causal=*/true)), MaskType::Causal);+ EXPECT_EQ(detect(make_sdpa_model(/*is_causal=*/true)), DetectedMaskType::Causal);}// ============================================================================-// Sliding-window masks — must report MaskType::SlidingWindow + window size+// Sliding-window masks — must report DetectedMaskType::SlidingWindow + window size// ============================================================================// NPUW model builder: Phi-3 / Gemma-2 / Gemma-3 sliding-window mask.TEST(DetectAttentionMaskTest, ModelBuilder_SlidingWindowPhi3_IsSlidingWindow) {auto model = ov::test::npuw::build_sliding_window_test_model(kWindow, 0, make_sliding_window_mask_phi3);ASSERT_NE(model, nullptr);- DetectAttentionMask pass;- pass.run_on_model(model);- const auto& info = pass.get_mask_info();- EXPECT_EQ(info.mask_type, MaskInfo::MaskType::SlidingWindow);+ const auto info = detect(model);+ EXPECT_EQ(info.type, DetectedMaskType::SlidingWindow);EXPECT_EQ(info.window_size, kWindow);}@@ -336,10 +559,8 @@ TEST(DetectAttentionMaskTest, ModelBuilder_SlidingWindowPhi3_IsSlidingWindow) {TEST(DetectAttentionMaskTest, ModelBuilder_SlidingWindowPhi3Legacy_IsSlidingWindow) {auto model = ov::test::npuw::build_sliding_window_test_model(kWindow, 0, make_sliding_window_mask_phi3_legacy);ASSERT_NE(model, nullptr);- DetectAttentionMask pass;- pass.run_on_model(model);- const auto& info = pass.get_mask_info();- EXPECT_EQ(info.mask_type, MaskInfo::MaskType::SlidingWindow);+ const auto info = detect(model);+ EXPECT_EQ(info.type, DetectedMaskType::SlidingWindow);EXPECT_EQ(info.window_size, kWindow);}@@ -347,43 +568,56 @@ TEST(DetectAttentionMaskTest, ModelBuilder_SlidingWindowPhi3Legacy_IsSlidingWindTEST(DetectAttentionMaskTest, ModelBuilder_SlidingWindowGemma4_IsSlidingWindow) {auto model = ov::test::npuw::build_sliding_window_test_model(kWindow, 0, make_sliding_window_mask_gemma4);ASSERT_NE(model, nullptr);- DetectAttentionMask pass;- pass.run_on_model(model);- const auto& info = pass.get_mask_info();- EXPECT_EQ(info.mask_type, MaskInfo::MaskType::SlidingWindow);+ const auto info = detect(model);+ EXPECT_EQ(info.type, DetectedMaskType::SlidingWindow);EXPECT_EQ(info.window_size, kWindow);}-// NPUW model builder: Gemma-2 alternating sliding + full layers.+// NPUW model builder: Gemma-2 alternating sliding + full layers. With+// sliding_to_full_ratio=1 and num_layers=4, layers alternate sliding/full 1:1 -- each+// layer gets its own SDPA node, annotated independently (there is no whole-model+// "dominant" mask type anymore).TEST(DetectAttentionMaskTest, ModelBuilder_SlidingWindowGemma2Alternating_IsSlidingWindow) {auto model = ov::test::npuw::build_sliding_window_test_model(kWindow, 1, make_sliding_window_mask_phi3, 4);ASSERT_NE(model, nullptr);- EXPECT_EQ(detect(model), MaskInfo::MaskType::SlidingWindow);++ const auto annotations = detect_all(model);+ ASSERT_EQ(annotations.size(), 4u);++ size_t sliding_count = 0;+ size_t causal_count = 0;+ for (const auto& mask : annotations) {+ if (mask.type == DetectedMaskType::SlidingWindow) {+ EXPECT_EQ(mask.window_size, kWindow);+ ++sliding_count;+ } else if (mask.type == DetectedMaskType::Causal) {+ ++causal_count;+ }+ }+ EXPECT_EQ(sliding_count, 2u);+ EXPECT_EQ(causal_count, 2u);}// NPUW model builder: default float SWA — LogicalAnd(LessEqual, Greater).TEST(DetectAttentionMaskTest, ModelBuilder_SlidingWindowDefault_IsSlidingWindow) {auto model = ov::test::npuw::build_sliding_window_test_model();ASSERT_NE(model, nullptr);- EXPECT_EQ(detect(model), MaskInfo::MaskType::SlidingWindow);+ EXPECT_EQ(detect(model), DetectedMaskType::SlidingWindow);}// Real pattern: Phi-3.5 Greater(kv, q - W) & LessEqual(kv, q) with a known window.TEST(DetectAttentionMaskTest, RealPattern_Phi3Sliding_IsSlidingWindowWithSize) {const int64_t window = 2047;- DetectAttentionMask pass;- pass.run_on_model(build_phi3_sliding(window));- const auto& info = pass.get_mask_info();- EXPECT_EQ(info.mask_type, MaskInfo::MaskType::SlidingWindow);+ const auto info = detect(build_phi3_sliding(window));+ EXPECT_EQ(info.type, DetectedMaskType::SlidingWindow);EXPECT_EQ(info.window_size, window);}// ============================================================================-// Unknown / unmasked — must report MaskType::Unknown+// Unknown / unmasked — must report DetectedMaskType::Unknown// ============================================================================// Full attention — SDPA with no mask and is_causal=false.TEST(DetectAttentionMaskTest, FullAttentionSDPA_IsUnknown) {- EXPECT_EQ(detect(make_sdpa_model(/*is_causal=*/false)),- MaskInfo::MaskType::Unknown);+ EXPECT_EQ(detect(make_sdpa_model(/*is_causal=*/false)), DetectedMaskType::Unknown);}