Skip to content

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

[NPUW] Add sliding window attention mask to model builder (#35123)

Dylan Neve396f87e16568
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp
index eaead45711e..0db83393bd7 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp
@@ -720,7 +720,36 @@ std::shared_ptr<ov::Model> ModelBuilder::build_llm(const LLMConfig& config_in) {
beam_idx_output = beam_idx->output(0);
}
- auto sdpa_mask = make_causal_mask(seq_source, attention_mask->output(0), prec);
+ ov::Output<ov::Node> token_type_ids_output;
+ if (config.use_token_type_ids) {
+ auto tti = parameter(ov::element::i64, ov::PartialShape{-1, -1}, "token_type_ids");
+ token_type_ids_output = tti->output(0);
+ }
+
+ const bool has_sliding = config.sliding_window_size > 0;
+ const bool has_full_layers = !has_sliding || config.sliding_to_full_ratio > 0;
+
+ ov::Output<ov::Node> full_mask;
+ ov::Output<ov::Node> sliding_mask;
+
+ if (has_full_layers) {
+ full_mask = config.boolean_causal_mask ? make_causal_mask_boolean(seq_source, attention_mask->output(0), prec)
+ : make_causal_mask(seq_source, attention_mask->output(0), prec);
+ }
+ if (has_sliding) {
+ const auto& mask_fn = config.sliding_mask_fn ? config.sliding_mask_fn : SlidingMaskFn(make_sliding_window_mask);
+ sliding_mask = mask_fn(seq_source, attention_mask->output(0), prec, config.sliding_window_size);
+ }
+
+ // Apply VLM bidirectional modifier for image tokens
+ if (token_type_ids_output.get_node()) {
+ if (full_mask.get_node())
+ full_mask = make_vlm_bidirectional_modifier(full_mask, token_type_ids_output, seq_source, prec);
+ if (sliding_mask.get_node())
+ sliding_mask = make_vlm_bidirectional_modifier(sliding_mask, token_type_ids_output, seq_source, prec);
+ }
+
+ auto default_mask = full_mask.get_node() ? full_mask : sliding_mask;
// Shared GQA broadcast shape (embedding models only)
ov::Output<ov::Node> shared_broadcast;
@@ -744,7 +773,7 @@ std::shared_ptr<ov::Model> ModelBuilder::build_llm(const LLMConfig& config_in) {
attn.bias_fn = config.attn_bias;
attn.qk_norm = config.qk_norm;
attn.rope_fn = config.rope;
- attn.sdpa_mask = sdpa_mask;
+ attn.sdpa_mask = default_mask;
attn.shared_broadcast_shape = shared_broadcast;
if (config.use_kv_cache) {
@@ -777,6 +806,11 @@ std::shared_ptr<ov::Model> ModelBuilder::build_llm(const LLMConfig& config_in) {
config.num_layers,
"model.layers.",
[&](const ov::Output<ov::Node>& input, const std::string& prefix, size_t layer) {
+ // Per-layer mask: N sliding layers then 1 full, repeating.
+ if (has_sliding && config.sliding_to_full_ratio > 0) {
+ const size_t cycle = config.sliding_to_full_ratio + 1;
+ attn.sdpa_mask = (layer % cycle == cycle - 1) ? full_mask : sliding_mask;
+ }
if (config.pre_norm) {
return make_pre_norm_layer(
input,
@@ -936,7 +970,7 @@ std::shared_ptr<ov::Model> ModelBuilder::build_whisper_decoder(const WhisperConf
d,
prec,
"model.decoder.");
- auto shared_mask = make_whisper_causal_mask(cache_pos, "model.decoder.");
+ auto shared_mask = make_whisper_causal_mask(cache_pos, "model.decoder.", config.boolean_causal_mask);
// Self-attention (layer-0 reuses pre-built key Variable)
Attention self_attn{};
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hpp
index c0b314ca09e..cffe3323691 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hpp
@@ -144,6 +144,10 @@ struct BaseModelConfig {
RoPEFn rope; ///< Empty = auto HalfRotationRoPE. Set identity lambda to disable.
ov::Output<ov::Node> position_ids; ///< Empty = auto-creates 2D Parameter + HalfRotationRoPE
NormFn qk_norm;
+ /// Build the causal mask as boolean (true = attend) instead of float.
+ /// Exercises NPUW's boolean-mask handlers (SDPA decomposition for LLMs,
+ /// Whisper decoder model preparation).
+ bool boolean_causal_mask = false;
BaseModelConfig() : lm_head_weight(weight) {}
@@ -154,6 +158,16 @@ struct BaseModelConfig {
}
};
+/// Sliding-window mask construction. Inputs: seq_source (input_ids/inputs_embeds),
+/// attention_mask, output element type, window size. Returns a 4D mask suitable
+/// for SDPA. Empty = default Gemma-4-style float construction; set to a builder
+/// like make_sliding_window_mask_phi3 to test the older boolean Phi3 pattern.
+/// Builder declarations live in model_builder_masks.hpp.
+using SlidingMaskFn = std::function<ov::Output<ov::Node>(const ov::Output<ov::Node>&,
+ const ov::Output<ov::Node>&,
+ ov::element::Type,
+ size_t)>;
+
struct LLMConfig : public BaseModelConfig {
bool use_kv_cache = true;
bool use_inputs_embeds = false;
@@ -165,6 +179,13 @@ struct LLMConfig : public BaseModelConfig {
size_t num_experts = 0; ///< Total experts. 0 = dense model.
size_t num_experts_per_tok = 0; ///< Top-K. 0 = default to 2.
size_t moe_intermediate_size = 0; ///< Expert FFN intermediate size. 0 = use intermediate_size.
+
+ size_t sliding_window_size = 0; ///< 0 = no sliding window. >0 = window size (Phi-3, Gemma 2/3)
+ /// 0 = uniform: every layer gets the same mask (all sliding if sliding_window_size > 0,
+ /// else all full causal). N > 0 = N sliding layers per 1 full, alternating (Gemma 2: 1, Gemma 3: 5).
+ size_t sliding_to_full_ratio = 0;
+ bool use_token_type_ids = false; ///< Gemma 3 VLM: token_type_ids param (0=text/causal, 1=image/bidir)
+ SlidingMaskFn sliding_mask_fn; ///< Empty = default float SWA (matches no NPUW pass; set make_sliding_window_mask_phi3 for Phi-3/Gemma-2/Gemma-3).
};
struct WhisperConfig : public BaseModelConfig {
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_masks.cpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_masks.cpp
index 6c3ecf38b53..adaf61ea509 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_masks.cpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_masks.cpp
@@ -32,57 +32,64 @@ ov::Output<ov::Node> make_padding_mask(const ov::Output<ov::Node>& attention_mas
return padding_4d->output(0);
}
-ov::Output<ov::Node> make_causal_mask(const ov::Output<ov::Node>& input_ids_output,
- const ov::Output<ov::Node>& attention_mask_output,
- ov::element::Type prec) {
- auto padding_4d = make_padding_mask(attention_mask_output, prec);
-
- auto ids_shape = std::make_shared<ov::opset11::ShapeOf>(input_ids_output, ov::element::i64);
- ids_shape->set_friendly_name("model.ids_shape");
+CausalBool make_causal_bool(const ov::Output<ov::Node>& seq_source,
+ const ov::Output<ov::Node>& attention_mask,
+ const std::string& prefix) {
+ auto ids_shape = std::make_shared<ov::opset11::ShapeOf>(seq_source, ov::element::i64);
+ ids_shape->set_friendly_name(prefix + "ids_shape");
- auto mask_shape_node = std::make_shared<ov::opset11::ShapeOf>(attention_mask_output, ov::element::i64);
- mask_shape_node->set_friendly_name("model.mask_shape");
+ auto mask_shape = std::make_shared<ov::opset11::ShapeOf>(attention_mask, ov::element::i64);
+ mask_shape->set_friendly_name(prefix + "mask_shape");
auto idx1 = ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {1});
- auto gather_axis = ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {0});
+ auto axis0 = ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {0});
- auto seq_len_s = std::make_shared<ov::opset11::Gather>(ids_shape, idx1, gather_axis);
- seq_len_s->set_friendly_name("model.seq_len");
+ auto seq_len = std::make_shared<ov::opset11::Gather>(ids_shape, idx1, axis0);
+ seq_len->set_friendly_name(prefix + "seq_len");
- auto total_seq_s = std::make_shared<ov::opset11::Gather>(mask_shape_node, idx1, gather_axis);
- total_seq_s->set_friendly_name("model.total_seq");
+ auto total_seq = std::make_shared<ov::opset11::Gather>(mask_shape, idx1, axis0);
+ total_seq->set_friendly_name(prefix + "total_seq");
- auto offset = std::make_shared<ov::opset11::Subtract>(total_seq_s, seq_len_s);
- offset->set_friendly_name("model.causal_offset");
+ auto offset = std::make_shared<ov::opset11::Subtract>(total_seq, seq_len);
+ offset->set_friendly_name(prefix + "offset");
auto range_start = ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {0});
auto range_step = ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {1});
- auto kv_range = std::make_shared<ov::op::v4::Range>(range_start, total_seq_s, range_step, ov::element::i64);
- kv_range->set_friendly_name("model.kv_range");
+ auto kv_range = std::make_shared<ov::op::v4::Range>(range_start, total_seq, range_step, ov::element::i64);
+ kv_range->set_friendly_name(prefix + "kv_range");
- auto q_range = std::make_shared<ov::op::v4::Range>(range_start, seq_len_s, range_step, ov::element::i64);
- q_range->set_friendly_name("model.q_range");
+ auto q_range = std::make_shared<ov::op::v4::Range>(range_start, seq_len, range_step, ov::element::i64);
+ q_range->set_friendly_name(prefix + "q_range");
auto q_abs = std::make_shared<ov::opset11::Add>(q_range, offset);
- q_abs->set_friendly_name("model.q_abs_positions");
+ q_abs->set_friendly_name(prefix + "q_abs_positions");
auto axis_last = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {1});
auto axis_first = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {0});
auto q_col = std::make_shared<ov::opset11::Unsqueeze>(q_abs, axis_last);
- q_col->set_friendly_name("model.q_col");
+ q_col->set_friendly_name(prefix + "q_col");
auto kv_row = std::make_shared<ov::opset11::Unsqueeze>(kv_range, axis_first);
- kv_row->set_friendly_name("model.kv_row");
+ kv_row->set_friendly_name(prefix + "kv_row");
auto causal_bool = std::make_shared<ov::op::v1::LessEqual>(kv_row, q_col);
- causal_bool->set_friendly_name("model.causal_bool");
+ causal_bool->set_friendly_name(prefix + "causal_bool");
+
+ return {causal_bool->output(0), q_col->output(0), kv_row->output(0)};
+}
+
+ov::Output<ov::Node> make_causal_mask(const ov::Output<ov::Node>& input_ids_output,
+ const ov::Output<ov::Node>& attention_mask_output,
+ ov::element::Type prec) {
+ auto padding_4d = make_padding_mask(attention_mask_output, prec);
+ auto cb = make_causal_bool(input_ids_output, attention_mask_output, "model.");
auto select_true = ov::opset11::Constant::create(prec, ov::Shape{}, {0.0f});
auto select_false = ov::opset11::Constant::create(prec, ov::Shape{}, {kAttentionMaskPadding});
- auto causal_float = std::make_shared<ov::op::v1::Select>(causal_bool, select_true, select_false);
+ auto causal_float = std::make_shared<ov::op::v1::Select>(cb.mask, select_true, select_false);
causal_float->set_friendly_name("model.causal_mask");
auto unsqueeze_axes = ov::opset11::Constant::create(ov::element::i64, ov::Shape{2}, {0, 1});
@@ -154,7 +161,9 @@ CachePositionResult make_cache_position_ids(const ov::Output<ov::Node>& input_id
ids_shape->output(0)};
}
-ov::Output<ov::Node> make_whisper_causal_mask(const CachePositionResult& cache_pos, const std::string& prefix) {
+ov::Output<ov::Node> make_whisper_causal_mask(const CachePositionResult& cache_pos,
+ const std::string& prefix,
+ bool boolean_output) {
// kv_idx: Range -> 3x Unsqueeze -> [1, 1, 1, total_seq]
auto mask_range = std::make_shared<ov::op::v4::Range>(
ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {0})->output(0),
@@ -210,11 +219,20 @@ ov::Output<ov::Node> make_whisper_causal_mask(const CachePositionResult& cache_p
std::make_shared<ov::op::v3::Broadcast>(causal_bool, broadcast_shape, ov::op::BroadcastType::BIDIRECTIONAL);
causal_broadcast->set_friendly_name(prefix + "causal_mask_broadcast");
- // Always f32 — NPUW's AttentionMask matchers inject f32 nodes
- auto select_true = ov::opset11::Constant::create(ov::element::f32, ov::Shape{}, {0.0f});
- auto select_false = ov::opset11::Constant::create(ov::element::f32, ov::Shape{}, {kAttentionMaskPaddingFP16Min});
- auto causal_float = std::make_shared<ov::op::v1::Select>(causal_broadcast, select_true, select_false);
- causal_float->set_friendly_name(prefix + "causal_mask");
+ // Float path: Select to f32. Boolean path: skip the Select and feed the bool
+ // tensor to the Slice, exercising NPUW's boolean mask handling for Whisper.
+ ov::Output<ov::Node> mask_for_slice;
+ if (boolean_output) {
+ mask_for_slice = causal_broadcast->output(0);
+ } else {
+ // Always f32 — NPUW's AttentionMask matchers inject f32 nodes
+ auto select_true = ov::opset11::Constant::create(ov::element::f32, ov::Shape{}, {0.0f});
+ auto select_false =
+ ov::opset11::Constant::create(ov::element::f32, ov::Shape{}, {kAttentionMaskPaddingFP16Min});
+ auto causal_float = std::make_shared<ov::op::v1::Select>(causal_broadcast, select_true, select_false);
+ causal_float->set_friendly_name(prefix + "causal_mask");
+ mask_for_slice = causal_float->output(0);
+ }
// Structural no-op Slice — AttentionMaskInput (prefill) needs Slice -> SDPA input[3]
auto slice_start = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {0});
@@ -225,12 +243,361 @@ ov::Output<ov::Node> make_whisper_causal_mask(const CachePositionResult& cache_p
auto slice_step = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {1});
auto slice_axes = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {3});
auto causal_sliced =
- std::make_shared<ov::opset11::Slice>(causal_float, slice_start, slice_stop, slice_step, slice_axes);
+ std::make_shared<ov::opset11::Slice>(mask_for_slice, slice_start, slice_stop, slice_step, slice_axes);
causal_sliced->set_friendly_name(prefix + "causal_mask_sliced");
return causal_sliced->output(0);
}
+ov::Output<ov::Node> make_causal_mask_boolean(const ov::Output<ov::Node>& input_ids_output,
+ const ov::Output<ov::Node>& attention_mask_output,
+ ov::element::Type /*unused*/) {
+ auto cb = make_causal_bool(input_ids_output, attention_mask_output, "model.cmb.");
+
+ auto unsq_2d = ov::opset11::Constant::create(ov::element::i64, ov::Shape{2}, {0, 1});
+ auto causal_4d = std::make_shared<ov::opset11::Unsqueeze>(cb.mask, unsq_2d);
+ causal_4d->set_friendly_name("model.cmb.causal_4d");
+
+ // Boolean padding mask: attention_mask -> bool [batch, 1, 1, total_seq].
+ auto attn_bool = std::make_shared<ov::opset11::Convert>(attention_mask_output, ov::element::boolean);
+ attn_bool->set_friendly_name("model.cmb.attn_bool");
+ auto pad_axes = ov::opset11::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{1, 2});
+ auto attn_bool_4d = std::make_shared<ov::opset11::Unsqueeze>(attn_bool, pad_axes);
+ attn_bool_4d->set_friendly_name("model.cmb.attn_bool_4d");
+
+ auto combined = std::make_shared<ov::op::v13::BitwiseAnd>(causal_4d, attn_bool_4d);
+ combined->set_friendly_name("model.cmb.combined");
+
+ return combined->output(0);
+}
+
+ov::Output<ov::Node> make_sliding_window_mask(const ov::Output<ov::Node>& input_ids_output,
+ const ov::Output<ov::Node>& attention_mask_output,
+ ov::element::Type prec,
+ size_t window_size) {
+ auto padding_4d = make_padding_mask(attention_mask_output, prec);
+ auto cb = make_causal_bool(input_ids_output, attention_mask_output, "model.sw.");
+
+ // Sliding: kv > q - window_size (within window)
+ auto window_const =
+ ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {static_cast<int64_t>(window_size)});
+ auto lower_bound = std::make_shared<ov::opset11::Subtract>(cb.q_col, window_const);
+ lower_bound->set_friendly_name("model.sw.lower_bound");
+
+ auto sliding_bool = std::make_shared<ov::op::v1::Greater>(cb.kv_row, lower_bound);
+ sliding_bool->set_friendly_name("model.sw.sliding_bool");
+
+ // Combined: attend iff causal AND sliding
+ auto combined_bool = std::make_shared<ov::op::v1::LogicalAnd>(cb.mask, sliding_bool);
+ combined_bool->set_friendly_name("model.sw.combined_bool");
+
+ auto select_true = ov::opset11::Constant::create(prec, ov::Shape{}, {0.0f});
+ auto select_false = ov::opset11::Constant::create(prec, ov::Shape{}, {kAttentionMaskPadding});
+
+ auto mask_float = std::make_shared<ov::op::v1::Select>(combined_bool, select_true, select_false);
+ mask_float->set_friendly_name("model.sw.mask");
+
+ auto unsqueeze_axes = ov::opset11::Constant::create(ov::element::i64, ov::Shape{2}, {0, 1});
+ auto mask_4d = std::make_shared<ov::opset11::Unsqueeze>(mask_float, unsqueeze_axes);
+ mask_4d->set_friendly_name("model.sw.mask_4d");
+
+ auto combined = std::make_shared<ov::opset11::Add>(padding_4d, mask_4d);
+ combined->set_friendly_name("model.sw.combined_mask_4d");
+
+ return combined->output(0);
+}
+
+namespace {
+
+std::shared_ptr<ov::Node> unsq1(const ov::Output<ov::Node>& in, int64_t axis) {
+ auto ax = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{axis});
+ return std::make_shared<ov::opset11::Unsqueeze>(in, ax);
+}
+
+/// Shared scaffolding for the boolean SWA builders (Phi-3 and Gemma-4 shapes):
+/// scalar seq_len, scalar past_kv_len routed through Gather + Squeeze (the
+/// matcher anchor), the K-side row [1, 1, 1, total_seq] (Range -> 3x Unsqueeze)
+/// and the boolean user-attention padding [batch, 1, 1, total_seq]. The two
+/// matchers differ only in the Q-side construction.
+struct SwaParts {
+ std::shared_ptr<ov::Node> seq_len; ///< i64 scalar
+ std::shared_ptr<ov::Node> past_kv_len; ///< i64 scalar, Squeeze(Gather(...))
+ std::shared_ptr<ov::Node> step; ///< i64 scalar = 1
+ std::shared_ptr<ov::Node> zero; ///< i64 scalar = 0
+ std::shared_ptr<ov::Node> k_row; ///< i64 [1, 1, 1, total_seq]
+ std::shared_ptr<ov::Node> attn_bool_4d; ///< bool [batch, 1, 1, total_seq]
+};
+
+SwaParts make_swa_parts(const ov::Output<ov::Node>& seq_source,
+ const ov::Output<ov::Node>& attention_mask,
+ const std::string& p) {
+ SwaParts r;
+
+ auto ids_shape = std::make_shared<ov::opset11::ShapeOf>(seq_source, ov::element::i64);
+ ids_shape->set_friendly_name(p + "ids_shape");
+ auto mask_shape = std::make_shared<ov::opset11::ShapeOf>(attention_mask, ov::element::i64);
+ mask_shape->set_friendly_name(p + "mask_shape");
+
+ auto idx1 = ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {1});
+ auto axis0 = ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {0});
+ auto seq_len = std::make_shared<ov::opset11::Gather>(ids_shape, idx1, axis0);
+ seq_len->set_friendly_name(p + "seq_len");
+ auto total_seq = std::make_shared<ov::opset11::Gather>(mask_shape, idx1, axis0);
+ total_seq->set_friendly_name(p + "total_seq");
+
+ // past_kv_len = total_seq - seq_len, then routed through a Gather so the
+ // matcher anchor (Gather → optional Squeeze) is satisfied.
+ auto past_kv_diff = std::make_shared<ov::opset11::Subtract>(total_seq, seq_len);
+ past_kv_diff->set_friendly_name(p + "past_kv_diff");
+ auto rank1_shape = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{1});
+ auto past_kv_1d = std::make_shared<ov::opset11::Reshape>(past_kv_diff, rank1_shape, false);
+ past_kv_1d->set_friendly_name(p + "past_kv_1d");
+ auto past_kv_len_gather = std::make_shared<ov::opset11::Gather>(past_kv_1d, axis0, axis0);
+ past_kv_len_gather->set_friendly_name(p + "past_kv_len");
+ // Optional Squeeze in matcher — present here (no axes form).
+ auto past_kv_len = std::make_shared<ov::opset11::Squeeze>(past_kv_len_gather);
+ past_kv_len->set_friendly_name(p + "past_kv_len_sq");
+
+ r.step = ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {1});
+ r.zero = ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {0});
+
+ // K-side full context length, a separate Add node from the Q-side one,
+ // with past_kv_len as the first operand. Both details match the real
+ // exports and both matter: the matcher pairs its past_kv_len anchor with
+ // operand 0 first when permuting the commutative Add, and seq_len is also
+ // a bare Gather, so putting it first mis-binds the anchor.
+ auto full_ctx_k = std::make_shared<ov::opset11::Add>(past_kv_len, seq_len);
+ full_ctx_k->set_friendly_name(p + "full_ctx_k");
+ auto k_range = std::make_shared<ov::op::v4::Range>(r.zero, full_ctx_k, r.step, ov::element::i64);
+ k_range->set_friendly_name(p + "k_range");
+
+ // 3x Unsqueeze chain — the matchers' unsqueeze_sequence(). K goes to row
+ // [1, 1, 1, total_seq]. No Convert (matches the optional<Convert> absent).
+ auto k_row = unsq1(unsq1(unsq1(k_range, 0), 0), 0);
+ k_row->set_friendly_name(p + "k_row");
+
+ // Boolean padding (any-bool input to first BitwiseAnd) — keep things in bool domain.
+ auto attn_bool = std::make_shared<ov::opset11::Convert>(attention_mask, ov::element::boolean);
+ attn_bool->set_friendly_name(p + "attn_bool");
+ auto pad_axes = ov::opset11::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{1, 2});
+ auto attn_bool_4d = std::make_shared<ov::opset11::Unsqueeze>(attn_bool, pad_axes);
+ attn_bool_4d->set_friendly_name(p + "attn_bool_4d");
+
+ r.seq_len = seq_len;
+ r.past_kv_len = past_kv_len;
+ r.k_row = k_row;
+ r.attn_bool_4d = attn_bool_4d;
+ return r;
+}
+
+/// Shared SWA epilogue: lower bound = Add(q_col, negative window constant),
+/// then BitwiseAnd(user_attention, sliding) → BitwiseAnd(_, causal). Both
+/// matchers anchor on this exact op sequence (incl. operand order).
+ov::Output<ov::Node> combine_sliding_and_causal(const SwaParts& parts,
+ const std::shared_ptr<ov::Node>& q_col,
+ const std::shared_ptr<ov::Node>& neg_window,
+ const std::string& p) {
+ auto query_left_bound = std::make_shared<ov::opset11::Add>(q_col, neg_window);
+ query_left_bound->set_friendly_name(p + "query_left_bound");
+
+ auto sliding_bool = std::make_shared<ov::op::v1::Greater>(parts.k_row, query_left_bound);
+ sliding_bool->set_friendly_name(p + "sliding_bool");
+
+ // Multiple BitwiseAnd: BitwiseAnd(user_attention, sliding) → BitwiseAnd(_, causal).
+ // First operand is the user/padding attention mask (matcher's any_input slot).
+ auto sliding_and_user_attention = std::make_shared<ov::op::v13::BitwiseAnd>(parts.attn_bool_4d, sliding_bool);
+ sliding_and_user_attention->set_friendly_name(p + "sliding_and_user_attention");
+
+ auto causal_bool = std::make_shared<ov::op::v1::LessEqual>(parts.k_row, q_col);
+ causal_bool->set_friendly_name(p + "causal_bool");
+
+ auto sliding_and_causal = std::make_shared<ov::op::v13::BitwiseAnd>(sliding_and_user_attention, causal_bool);
+ sliding_and_causal->set_friendly_name(p + "sliding_and_causal");
+
+ return sliding_and_causal->output(0);
+}
+
+} // namespace
+
+ov::Output<ov::Node> make_sliding_window_mask_phi3(const ov::Output<ov::Node>& input_ids_output,
+ const ov::Output<ov::Node>& attention_mask_output,
+ ov::element::Type /*unused*/,
+ size_t window_size) {
+ const std::string p = "model.swp.";
+ auto parts = make_swa_parts(input_ids_output, attention_mask_output, p);
+
+ // Phi-3 / Gemma-2 / Gemma-3 Q side: Range(past_kv_len, past_kv_len + seq_len)
+ // — absolute positions, Range STARTS at past_kv_len.
+ auto full_ctx_q = std::make_shared<ov::opset11::Add>(parts.past_kv_len, parts.seq_len);
+ full_ctx_q->set_friendly_name(p + "full_ctx_q");
+ auto q_range = std::make_shared<ov::op::v4::Range>(parts.past_kv_len, full_ctx_q, parts.step, ov::element::i64);
+ q_range->set_friendly_name(p + "q_range");
+ // Q column [1, 1, seq, 1] via the 3x Unsqueeze the matcher expects.
+ auto q_col = unsq1(unsq1(unsq1(q_range, 1), 0), 0);
+ q_col->set_friendly_name(p + "q_col");
+
+ // Lower bound = Add(q_col, neg_window) with NEGATIVE constant (not Subtract).
+ auto neg_window =
+ ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {-static_cast<int64_t>(window_size)});
+ neg_window->set_friendly_name(p + "neg_window");
+
+ return combine_sliding_and_causal(parts, q_col, neg_window, p);
+}
+
+ov::Output<ov::Node> make_sliding_window_mask_gemma4(const ov::Output<ov::Node>& seq_source,
+ const ov::Output<ov::Node>& attention_mask_output,
+ ov::element::Type /*unused*/,
+ size_t window_size) {
+ const std::string p = "model.swg.";
+ auto parts = make_swa_parts(seq_source, attention_mask_output, p);
+
+ // Gemma-4 Q side: cache_position = Range(0, seq_len) + past_kv_len —
+ // the explicit Add AFTER the Range is what distinguishes this pattern
+ // from Phi-3's Range(past_kv_len, ...) and what Gemma4SlidingMaskMatcher
+ // anchors on (operand order: range first, past_kv_len second).
+ auto q_range = std::make_shared<ov::op::v4::Range>(parts.zero, parts.seq_len, parts.step, ov::element::i64);
+ q_range->set_friendly_name(p + "q_range");
+ auto cache_position = std::make_shared<ov::opset11::Add>(q_range, parts.past_kv_len);
+ cache_position->set_friendly_name(p + "cache_position");
+ auto q_col = unsq1(unsq1(unsq1(cache_position, 1), 0), 0);
+ q_col->set_friendly_name(p + "q_col");
+
+ // Real Gemma-4 exports the window as a [1,1,1,1] negative constant.
+ auto neg_window = ov::opset11::Constant::create(ov::element::i64,
+ ov::Shape{1, 1, 1, 1},
+ {-static_cast<int64_t>(window_size)});
+ neg_window->set_friendly_name(p + "neg_window");
+
+ return combine_sliding_and_causal(parts, q_col, neg_window, p);
+}
+
+ov::Output<ov::Node> make_sliding_window_mask_phi3_legacy(const ov::Output<ov::Node>& seq_source,
+ const ov::Output<ov::Node>& attention_mask_output,
+ ov::element::Type prec,
+ size_t window_size) {
+ const std::string p = "model.swl.";
+
+ // K side: Range(0, Gather(ShapeOf(attention_mask), 1)) → Convert → Convert.
+ // OldPhi3SlidingMaskMatcher requires the ShapeOf fed DIRECTLY by the
+ // attention_mask Parameter and the double Convert on the key range.
+ auto mask_shape = std::make_shared<ov::opset11::ShapeOf>(attention_mask_output, ov::element::i64);
+ mask_shape->set_friendly_name(p + "mask_shape");
+ auto idx1 = ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {1});
+ auto axis0 = ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {0});
+ auto atten_len = std::make_shared<ov::opset11::Gather>(mask_shape, idx1, axis0);
+ atten_len->set_friendly_name(p + "atten_len");
+
+ auto zero = ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {0});
+ auto step = ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {1});
+ auto k_range = std::make_shared<ov::op::v4::Range>(zero, atten_len, step, ov::element::i32);
+ k_range->set_friendly_name(p + "k_range");
+ auto k_range_i64 = std::make_shared<ov::opset11::Convert>(k_range, ov::element::i64);
+ k_range_i64->set_friendly_name(p + "k_range_i64");
+ auto k_range_f32 = std::make_shared<ov::opset11::Convert>(k_range_i64, ov::element::f32);
+ k_range_f32->set_friendly_name(p + "k_range_f32");
+
+ // Q side: the matcher anchors seq length on ShapeOf(Parameter) → Gather
+ // (it binds "position_ids" to ANY Parameter — seq_source qualifies) and
+ // past_kv_len on a bare Gather (no Squeeze in this pattern).
+ auto ids_shape = std::make_shared<ov::opset11::ShapeOf>(seq_source, ov::element::i64);
+ ids_shape->set_friendly_name(p + "ids_shape");
+ auto pos_len = std::make_shared<ov::opset11::Gather>(ids_shape, idx1, axis0);
+ pos_len->set_friendly_name(p + "pos_len");
+
+ auto past_kv_diff = std::make_shared<ov::opset11::Subtract>(atten_len, pos_len);
+ past_kv_diff->set_friendly_name(p + "past_kv_diff");
+ auto rank1_shape = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{1});
+ auto past_kv_1d = std::make_shared<ov::opset11::Reshape>(past_kv_diff, rank1_shape, false);
+ past_kv_1d->set_friendly_name(p + "past_kv_1d");
+ auto past_kv_len = std::make_shared<ov::opset11::Gather>(past_kv_1d, axis0, axis0);
+ past_kv_len->set_friendly_name(p + "past_kv_len");
+
+ auto full_ctx = std::make_shared<ov::opset11::Add>(past_kv_len, pos_len);
+ full_ctx->set_friendly_name(p + "full_ctx");
+ // f32 Q range (4.51 export computed the bounds in float domain).
+ auto q_range = std::make_shared<ov::op::v4::Range>(past_kv_len, full_ctx, step, ov::element::f32);
+ q_range->set_friendly_name(p + "q_range");
+ // Column via Reshape[-1, 1] — NOT Unsqueeze — in this pattern.
+ auto col_shape = ov::opset11::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{-1, 1});
+ auto q_col = std::make_shared<ov::opset11::Reshape>(q_range, col_shape, false);
+ q_col->set_friendly_name(p + "q_col");
+
+ auto neg_window =
+ ov::opset11::Constant::create(ov::element::f32, ov::Shape{}, {-static_cast<float>(window_size)});
+ neg_window->set_friendly_name(p + "neg_window");
+ auto query_left_bound = std::make_shared<ov::opset11::Add>(q_col, neg_window);
+ query_left_bound->set_friendly_name(p + "query_left_bound");
+
+ // INVERTED domain: true = token must NOT be attended.
+ auto forget_left = std::make_shared<ov::op::v1::LessEqual>(k_range_f32, query_left_bound);
+ forget_left->set_friendly_name(p + "forget_left");
+ auto look_future = std::make_shared<ov::op::v1::Greater>(k_range_f32, q_col);
+ look_future->set_friendly_name(p + "look_future");
+ auto inv_sliding = std::make_shared<ov::op::v13::BitwiseOr>(look_future, forget_left);
+ inv_sliding->set_friendly_name(p + "inv_sliding");
+
+ // 4.51 consumers select the padding value where the inverted mask is true.
+ auto masked = ov::opset11::Constant::create(prec, ov::Shape{}, {kAttentionMaskPadding});
+ auto attend = ov::opset11::Constant::create(prec, ov::Shape{}, {0.0f});
+ auto mask_float = std::make_shared<ov::op::v1::Select>(inv_sliding, masked, attend);
+ mask_float->set_friendly_name(p + "mask");
+
+ return mask_float->output(0);
+}
+
+ov::Output<ov::Node> make_vlm_bidirectional_modifier(const ov::Output<ov::Node>& base_mask,
+ const ov::Output<ov::Node>& token_type_ids_output,
+ const ov::Output<ov::Node>& seq_source,
+ ov::element::Type prec) {
+ auto image_const = ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {1});
+
+ // K axis: full token_type_ids [batch, total_seq] → is_image → [batch, 1, 1, total_seq]
+ auto k_is_image = std::make_shared<ov::op::v1::Equal>(token_type_ids_output, image_const);
+ k_is_image->set_friendly_name("model.tti.k_is_image");
+ auto k_axes = ov::opset11::Constant::create(ov::element::i64, ov::Shape{2}, {1, 2});
+ auto k_is_image_4d = std::make_shared<ov::opset11::Unsqueeze>(k_is_image, k_axes);
+ k_is_image_4d->set_friendly_name("model.tti.k_is_image_4d");
+
+ // Q axis: slice last seq_len entries from token_type_ids using offset = total_seq - seq_len.
+ auto tti_shape = std::make_shared<ov::opset11::ShapeOf>(token_type_ids_output, ov::element::i64);
+ auto ids_shape = std::make_shared<ov::opset11::ShapeOf>(seq_source, ov::element::i64);
+ auto idx1 = ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {1});
+ auto axis0 = ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {0});
+ auto total_seq = std::make_shared<ov::opset11::Gather>(tti_shape, idx1, axis0);
+ auto seq_len = std::make_shared<ov::opset11::Gather>(ids_shape, idx1, axis0);
+ auto offset = std::make_shared<ov::opset11::Subtract>(total_seq, seq_len);
+ offset->set_friendly_name("model.tti.offset");
+
+ auto step = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {1});
+ auto seq_axis = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {1});
+ auto offset_1d = std::make_shared<ov::opset11::Unsqueeze>(offset, axis0);
+ auto total_seq_1d = std::make_shared<ov::opset11::Unsqueeze>(total_seq, axis0);
+
+ auto q_tti_slice =
+ std::make_shared<ov::op::v8::Slice>(token_type_ids_output, offset_1d, total_seq_1d, step, seq_axis);
+ q_tti_slice->set_friendly_name("model.tti.q_slice");
+
+ auto q_is_image = std::make_shared<ov::op::v1::Equal>(q_tti_slice, image_const);
+ q_is_image->set_friendly_name("model.tti.q_is_image");
+ auto q_axes = ov::opset11::Constant::create(ov::element::i64, ov::Shape{2}, {1, 3});
+ auto q_is_image_4d = std::make_shared<ov::opset11::Unsqueeze>(q_is_image, q_axes);
+ q_is_image_4d->set_friendly_name("model.tti.q_is_image_4d");
+
+ // Both Q and K are image tokens -> bidirectional attention
+ auto both_image = std::make_shared<ov::op::v1::LogicalAnd>(q_is_image_4d, k_is_image_4d);
+ both_image->set_friendly_name("model.tti.both_image");
+
+ // Select needs matching then/else types: boolean base masks (e.g. the Phi-3
+ // style SWA pattern) stay in the bool domain with attend = true.
+ const bool bool_base = base_mask.get_element_type() == ov::element::boolean;
+ auto attend = bool_base ? ov::opset11::Constant::create(ov::element::boolean, ov::Shape{}, {true})
+ : ov::opset11::Constant::create(prec, ov::Shape{}, {0.0f});
+ auto result = std::make_shared<ov::op::v1::Select>(both_image, attend, base_mask);
+ result->set_friendly_name("model.tti.modified_mask");
+
+ return result->output(0);
+}
+
} // namespace npuw
} // namespace test
} // namespace ov
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_masks.hpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_masks.hpp
index 1c315e38175..42572dac8d6 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_masks.hpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_masks.hpp
@@ -4,6 +4,7 @@
#pragma once
+#include <cstddef>
#include <string>
#include "openvino/core/node.hpp"
@@ -20,6 +21,19 @@ constexpr float kAttentionMaskPadding = -10000.0f;
ov::Output<ov::Node> make_padding_mask(const ov::Output<ov::Node>& attention_mask,
ov::element::Type prec);
+/// Boolean causal core shared by make_causal_mask / make_causal_mask_boolean /
+/// make_sliding_window_mask. Builds absolute query positions (q_range + offset)
+/// and key positions, returns the 2D boolean relation (kv <= q, true = attend)
+/// plus the two operands the sliding-window variant reuses for its window bound.
+struct CausalBool {
+ ov::Output<ov::Node> mask; ///< LessEqual(kv_row, q_col), bool [seq, total_seq]
+ ov::Output<ov::Node> q_col; ///< absolute query positions, [seq, 1]
+ ov::Output<ov::Node> kv_row; ///< key positions, [1, total_seq]
+};
+CausalBool make_causal_bool(const ov::Output<ov::Node>& seq_source,
+ const ov::Output<ov::Node>& attention_mask,
+ const std::string& prefix);
+
/// Standard causal mask combined with padding. Returns 4D float mask
/// [batch, 1, seq, total_seq] with 0.0=attend, kAttentionMaskPadding=masked.
ov::Output<ov::Node> make_causal_mask(const ov::Output<ov::Node>& seq_source,
@@ -44,7 +58,85 @@ CachePositionResult make_cache_position_ids(const ov::Output<ov::Node>& input_id
/// Whisper-style decoder self-attn causal mask. Uses cache_pos based ranges
/// (different shape from make_causal_mask). Includes the structural Slice that
/// AttentionMaskInput (prefill) requires on SDPA input[3].
-ov::Output<ov::Node> make_whisper_causal_mask(const CachePositionResult& cache_pos, const std::string& prefix);
+/// boolean_output = true skips the Select-to-float so a bool mask reaches SDPA,
+/// exercising NPUW's boolean-mask handling in the Whisper decoder preparation.
+ov::Output<ov::Node> make_whisper_causal_mask(const CachePositionResult& cache_pos,
+ const std::string& prefix,
+ bool boolean_output = false);
+
+/// Boolean variant of the causal mask: 4D bool (true = attend), no Select-to-float.
+/// Element type argument is ignored. Exists to test the NPUW handlers that lift
+/// bool SDPA masks to float via Select(mask, 0, -inf). Shape: causal LessEqual +
+/// bool padding combined via BitwiseAnd.
+ov::Output<ov::Node> make_causal_mask_boolean(const ov::Output<ov::Node>& seq_source,
+ const ov::Output<ov::Node>& attention_mask,
+ ov::element::Type /*unused*/);
+
+/// Sliding window + causal mask (transformers >= 5 / Gemma-4 style):
+/// Range(0, seq_len)+Add(offset), single Unsqueeze, Subtract for lower bound,
+/// LogicalAnd combine, Select to float. Returns 4D float mask.
+ov::Output<ov::Node> make_sliding_window_mask(const ov::Output<ov::Node>& seq_source,
+ const ov::Output<ov::Node>& attention_mask,
+ ov::element::Type prec,
+ size_t window_size);
+
+/// Sliding window + causal mask, Phi-3 / older transformers (~4.53) shape.
+/// Mirrors Phi3SlidingMaskMatcher pattern — produces a 4D boolean mask
+/// (true = attend) that Phi3SlidingMaskMatcher can match-and-rewrite.
+///
+/// Pattern features (all matter for the matcher):
+/// - past_kv_len obtained via Gather (anchored on a Gather node + optional Squeeze).
+/// - Two SEPARATE Add nodes computing full_ctx_len: one for the Q range,
+/// one for the K range — both past_kv_len + seq_len, past FIRST (operand
+/// order matters: the matcher's commutative permutation binds its
+/// past_kv_len Gather anchor against operand 0 first, and seq_len is
+/// also a bare Gather, so past second mis-binds the anchor).
+/// - Q range = Range(past_kv_len, full_ctx_len_q) — absolute positions.
+/// - K range = Range(0, full_ctx_len_k).
+/// - 3x Unsqueeze chain on each range (axes are "any" in matcher).
+/// - Lower bound = Add(q_col, neg_window_size_const) — NOT Subtract; constant is negative.
+/// - Combine: BitwiseAnd(any_bool, sliding_bool) -> BitwiseAnd(_, causal_bool).
+/// - Output is boolean. SDPA accepts boolean masks (true = attend).
+///
+/// Element type argument is ignored (output is always boolean) — the signature
+/// matches SlidingMaskFn so it can be plugged into LLMConfig::sliding_mask_fn.
+ov::Output<ov::Node> make_sliding_window_mask_phi3(const ov::Output<ov::Node>& seq_source,
+ const ov::Output<ov::Node>& attention_mask,
+ ov::element::Type /*unused*/,
+ size_t window_size);
+
+/// Sliding window + causal mask, Gemma-4 shape (matches NPUW's
+/// Gemma4SlidingMaskMatcher). Same boolean skeleton as the Phi-3 variant —
+/// the difference is the Q side: cache_position = Add(Range(0, seq_len),
+/// past_kv_len), i.e. the past offset is added AFTER the Range instead of
+/// being its start. Window constant is a [1,1,1,1] negative i64 like the
+/// real Gemma-4 export. Output is boolean (true = attend).
+ov::Output<ov::Node> make_sliding_window_mask_gemma4(const ov::Output<ov::Node>& seq_source,
+ const ov::Output<ov::Node>& attention_mask,
+ ov::element::Type /*unused*/,
+ size_t window_size);
+
+/// Sliding window mask, legacy Phi-3 / transformers 4.51 shape (matches NPUW's
+/// OldPhi3SlidingMaskMatcher). INVERTED boolean domain combined via BitwiseOr
+/// (true = masked out): Greater(K, Q.T) | LessEqual(K, Q.T - window), with the
+/// Q column built via Reshape[-1,1] (not Unsqueeze), the K range double-
+/// Converted (i32 → i64 → f32), and a float Q Range. The inverted mask feeds
+/// Select(inv, padding, 0) so the SDPA input is a float mask of type `prec`.
+ov::Output<ov::Node> make_sliding_window_mask_phi3_legacy(const ov::Output<ov::Node>& seq_source,
+ const ov::Output<ov::Node>& attention_mask,
+ ov::element::Type prec,
+ size_t window_size);
+
+/// Modify a base mask so image tokens (token_type_ids==1) get bidirectional
+/// attention among themselves. Used for Gemma 3 VLM. base_mask shape is
+/// [batch, 1, seq, total_seq], float (attend = Select to 0.0/prec) or boolean
+/// (attend = Select to true, e.g. on top of make_sliding_window_mask_phi3).
+/// token_type_ids is [batch, total_seq] i64. With KV cache, seq < total_seq —
+/// Q-side token types are the LAST seq_len entries.
+ov::Output<ov::Node> make_vlm_bidirectional_modifier(const ov::Output<ov::Node>& base_mask,
+ const ov::Output<ov::Node>& token_type_ids,
+ const ov::Output<ov::Node>& seq_source,
+ ov::element::Type prec);
} // namespace npuw
} // namespace test
diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
index f0c1d728de1..8b1d3c64702 100644
--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
@@ -149,6 +149,7 @@ target_sources(${TARGET_NAME} PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/npuw/subgraph_behavior_infer_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/preserve_const_matmul_pattern_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/add_position_ids_param_test.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/patch_sliding_mask_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/remove_empty_kv_inputs_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/stateful_to_stateless_test.cpp
)
diff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp b/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp
index ae476dc98a7..418802f2fda 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp
@@ -155,6 +155,31 @@ inline std::shared_ptr<ov::Model> build_moe_llm_test_model() {
return mb.build_llm(cfg);
}
+inline std::shared_ptr<ov::Model> build_sliding_window_test_model(size_t window_size = 512,
+ size_t sliding_to_full_ratio = 0,
+ const SlidingMaskFn& sliding_mask_fn = {},
+ size_t num_layers = 2) {
+ auto cfg = make_test_model_config();
+ cfg.num_layers = num_layers;
+ cfg.sliding_window_size = window_size;
+ cfg.sliding_to_full_ratio = sliding_to_full_ratio;
+ cfg.sliding_mask_fn = sliding_mask_fn;
+ ModelBuilder mb;
+ return mb.build_llm(cfg);
+}
+
+inline std::shared_ptr<ov::Model> build_token_type_ids_test_model(size_t window_size = 512,
+ size_t sliding_to_full_ratio = 1,
+ const SlidingMaskFn& sliding_mask_fn = {}) {
+ auto cfg = make_test_model_config();
+ cfg.sliding_window_size = window_size;
+ cfg.sliding_to_full_ratio = sliding_to_full_ratio;
+ cfg.sliding_mask_fn = sliding_mask_fn;
+ cfg.use_inputs_embeds = true;
+ cfg.use_token_type_ids = true;
+ ModelBuilder mb;
+ return mb.build_llm(cfg);
+}
class NullPlugin : public ov::IPlugin {
public:
diff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/patch_sliding_mask_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/patch_sliding_mask_test.cpp
new file mode 100644
index 00000000000..66cae382c88
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/patch_sliding_mask_test.cpp
@@ -0,0 +1,206 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <gtest/gtest.h>
+
+#include "llm_test_helpers.hpp"
+#include "model_builder.hpp"
+#include "npuw_transformations/patch_sliding_window_mask.hpp"
+#include "openvino/op/scaled_dot_product_attention.hpp"
+#include "openvino/openvino.hpp"
+#include "openvino/pass/stateful_to_stateless.hpp"
+
+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;
+using ov::test::npuw::ModelBuilder;
+
+namespace {
+
+bool has_param_named(const std::shared_ptr<ov::Model>& model, const std::string& name) {
+ for (const auto& param : model->get_parameters()) {
+ if (param->get_friendly_name() == name) {
+ return true;
+ }
+ }
+ return false;
+}
+
+bool has_sdpa_mask_of_type(const std::shared_ptr<ov::Model>& model, ov::element::Type type) {
+ for (const auto& op : model->get_ordered_ops()) {
+ auto sdpa = ov::as_type_ptr<ov::op::v13::ScaledDotProductAttention>(op);
+ if (sdpa && sdpa->input_value(3).get_element_type() == type) {
+ return true;
+ }
+ }
+ return false;
+}
+
+} // namespace
+
+TEST(LLMMaskTest, SlidingWindow_AllLayers_Builds) {
+ auto model = ov::test::npuw::build_sliding_window_test_model();
+ ASSERT_NE(model, nullptr);
+ EXPECT_TRUE(has_param_named(model, "attention_mask"));
+}
+
+// Boolean causal mask. NPUW lifts bool SDPA masks to float when decomposing
+// SDPA (OptimizeValueTensors) and when preparing the Whisper decoder.
+TEST(LLMMaskTest, CausalMask_Boolean_Builds) {
+ auto cfg = ov::test::npuw::make_test_model_config();
+ cfg.boolean_causal_mask = true;
+
+ ModelBuilder mb;
+ auto model = mb.build_llm(cfg);
+ ASSERT_NE(model, nullptr);
+ EXPECT_TRUE(has_sdpa_mask_of_type(model, ov::element::boolean));
+}
+
+// Same boolean causal mask in the Whisper decoder, via the shared toggle on
+// BaseModelConfig.
+TEST(LLMMaskTest, WhisperDecoder_CausalMask_Boolean_Builds) {
+ auto cfg = ov::test::npuw::make_test_model_config<ov::test::npuw::WhisperConfig>();
+ cfg.boolean_causal_mask = true;
+
+ ModelBuilder mb;
+ auto model = mb.build_whisper_decoder(cfg);
+ ASSERT_NE(model, nullptr);
+ EXPECT_TRUE(has_sdpa_mask_of_type(model, ov::element::boolean));
+}
+
+// Gemma-2 layout: sliding and full attention on alternating layers. Gemma-2/3
+// exports use the Phi-3 mask shape (Phi3SlidingMaskMatcher covers all three),
+// not the Gemma-4 one.
+TEST(LLMMaskTest, SlidingWindow_Gemma2_Builds) {
+ auto model = ov::test::npuw::build_sliding_window_test_model(512, 1, make_sliding_window_mask_phi3, 4);
+ ASSERT_NE(model, nullptr);
+}
+
+// Gemma-3 layout: five sliding layers per full one, same Phi-3 mask shape.
+// Needs at least 6 layers to hit both branches of the cycle.
+TEST(LLMMaskTest, SlidingWindow_Gemma3_Builds) {
+ auto model = ov::test::npuw::build_sliding_window_test_model(1024, 5, make_sliding_window_mask_phi3, 12);
+ ASSERT_NE(model, nullptr);
+}
+
+// The Phi-3 style mask is boolean and feeds SDPA directly, without a
+// Select-to-float on the way.
+TEST(LLMMaskTest, SlidingWindow_Phi3Boolean_Builds) {
+ auto model = ov::test::npuw::build_sliding_window_test_model(512, 0, make_sliding_window_mask_phi3);
+ ASSERT_NE(model, nullptr);
+ EXPECT_TRUE(has_sdpa_mask_of_type(model, ov::element::boolean));
+}
+
+TEST(LLMMaskTest, TokenTypeIds_HasCorrectInputs) {
+ auto model = ov::test::npuw::build_token_type_ids_test_model();
+ ASSERT_NE(model, nullptr);
+ EXPECT_TRUE(has_param_named(model, "token_type_ids"));
+ EXPECT_TRUE(has_param_named(model, "inputs_embeds"));
+}
+
+// Reshape to static shapes where seq_len != total_seq, as during generation
+// with KV cache. Catches broadcast bugs in the token_type_ids mask modifier,
+// which has to slice the query part out of the full-length token_type_ids.
+TEST(LLMMaskTest, TokenTypeIds_StaticReshape_SeqNeTotalSeq) {
+ auto model = ov::test::npuw::build_token_type_ids_test_model();
+ ASSERT_NE(model, nullptr);
+
+ ov::pass::StatefulToStateless().run_on_model(model);
+ model = model->clone();
+
+ const int64_t seq_len = 1;
+ const int64_t past_kv_len = 16;
+ const int64_t total_seq = seq_len + past_kv_len;
+ std::map<std::string, ov::PartialShape> new_shapes;
+ for (const auto& input : model->inputs()) {
+ const auto& name = input.get_any_name();
+ const auto& pshape = input.get_partial_shape();
+ ov::PartialShape new_shape;
+ if (name.find("inputs_embeds") != std::string::npos) {
+ new_shape = {1, seq_len, pshape[2]};
+ } else if (name.find("attention_mask") != std::string::npos ||
+ name.find("token_type_ids") != std::string::npos) {
+ new_shape = {1, total_seq};
+ } else if (name.find("position_ids") != std::string::npos) {
+ new_shape = {1, seq_len};
+ } else if (name.find("beam_idx") != std::string::npos) {
+ new_shape = {1};
+ } else {
+ new_shape = pshape;
+ new_shape[0] = 1;
+ new_shape[2] = past_kv_len;
+ }
+ new_shapes[name] = new_shape;
+ }
+
+ EXPECT_NO_THROW(model->reshape(new_shapes));
+}
+
+// Boolean sliding mask combined with the token_type_ids modifier, like a
+// Gemma-3 VLM. The modifier has to stay in the bool domain for bool base
+// masks, while the full-attention layers keep the float causal mask.
+TEST(LLMMaskTest, TokenTypeIds_Phi3BooleanSlidingMask_Builds) {
+ auto model = ov::test::npuw::build_token_type_ids_test_model(512, 1, make_sliding_window_mask_phi3);
+ ASSERT_NE(model, nullptr);
+ EXPECT_TRUE(has_sdpa_mask_of_type(model, ov::element::boolean));
+ EXPECT_TRUE(has_sdpa_mask_of_type(model, ov::element::f32));
+}
+
+// NPUW's PatchSlidingWindowMask (sliding_window_mask.cpp) registers three
+// matchers: Gemma4SlidingMaskMatcher, Phi3SlidingMaskMatcher (Phi-3, Gemma-2,
+// Gemma-3) and OldPhi3SlidingMaskMatcher (transformers 4.51). Run the real
+// pass over the builder models and check each mask variant gets picked up.
+
+TEST(LLMMaskTest, NpuwSlidingPatch_FiresOn_Phi3Pattern) {
+ auto model = ov::test::npuw::build_sliding_window_test_model(512, 0, make_sliding_window_mask_phi3);
+ EXPECT_TRUE(ov::npuw::PatchSlidingWindowMask().run_on_model(model));
+ EXPECT_NO_THROW(model->validate_nodes_and_infer_types());
+}
+
+TEST(LLMMaskTest, NpuwSlidingPatch_FiresOn_Gemma4Pattern) {
+ auto model = ov::test::npuw::build_sliding_window_test_model(512, 0, make_sliding_window_mask_gemma4);
+ EXPECT_TRUE(ov::npuw::PatchSlidingWindowMask().run_on_model(model));
+ EXPECT_NO_THROW(model->validate_nodes_and_infer_types());
+}
+
+TEST(LLMMaskTest, NpuwSlidingPatch_FiresOn_LegacyPhi3Pattern) {
+ auto model = ov::test::npuw::build_sliding_window_test_model(512, 0, make_sliding_window_mask_phi3_legacy);
+ EXPECT_TRUE(ov::npuw::PatchSlidingWindowMask().run_on_model(model));
+ EXPECT_NO_THROW(model->validate_nodes_and_infer_types());
+}
+
+// The default float SWA mask intentionally matches none of the NPUW patterns.
+TEST(LLMMaskTest, NpuwSlidingPatch_IgnoresDefaultFloatMask) {
+ auto model = ov::test::npuw::build_sliding_window_test_model(512, 0);
+ EXPECT_FALSE(ov::npuw::PatchSlidingWindowMask().run_on_model(model));
+}
+
+// Real Gemma exports build two mask subgraphs and share them across all
+// layers: one sliding, one full, with the sliding mask on layer 0. Check
+// the builder produces the same layout.
+TEST(LLMMaskTest, SlidingFullAlternation_MatchesRealGemmaLayout) {
+ auto model = ov::test::npuw::build_sliding_window_test_model(512, 1, {}, 4);
+ ASSERT_NE(model, nullptr);
+
+ std::map<size_t, const ov::Node*> layer_mask;
+ for (const auto& op : model->get_ordered_ops()) {
+ auto sdpa = ov::as_type_ptr<ov::op::v13::ScaledDotProductAttention>(op);
+ if (!sdpa) {
+ continue;
+ }
+ const auto& name = sdpa->get_friendly_name();
+ const std::string marker = "model.layers.";
+ auto pos = name.find(marker);
+ ASSERT_NE(pos, std::string::npos) << name;
+ layer_mask[std::stoul(name.substr(pos + marker.size()))] = sdpa->input_value(3).get_node();
+ }
+ ASSERT_EQ(layer_mask.size(), 4u);
+
+ // Sliding on even layers, full on odd, one shared mask node per kind.
+ EXPECT_EQ(layer_mask[0], layer_mask[2]);
+ EXPECT_EQ(layer_mask[1], layer_mask[3]);
+ EXPECT_NE(layer_mask[0], layer_mask[1]);
+ EXPECT_NE(layer_mask[0]->get_friendly_name().find("model.sw."), std::string::npos);
+ EXPECT_EQ(layer_mask[1]->get_friendly_name().find("model.sw."), std::string::npos);
+}