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]Patch SWA mask for Gemma4. (#35253)
intelgaoxiongcad3ebca9f08
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 4aaf0067ef1..77d9d3e8cf1 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@@ -15,7 +15,7 @@#include "npuw_transformations/decompose_gqa.hpp"#include "npuw_transformations/lora_stateful_to_stateless.hpp"#include "npuw_transformations/optimize_value_tensors.hpp"-#include "npuw_transformations/patch_phi3_sliding_mask.hpp"+#include "npuw_transformations/patch_sliding_window_mask.hpp"#include "npuw_transformations/reshape_sliced_head_to_static.hpp"#include "npuw_transformations/reshape_to_static.hpp"#include "npuw_transformations/slice_out_embeds.hpp"@@ -786,8 +786,8 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mauto lm_head_model = check_and_cut_lm_head(kvcache_model, m_cfg);if (!m_is_whisper) {- LOG_DEBUG("Try patch Phi-3 sliding window mask, if it exists.");- ov::npuw::PatchPhi3SlidingMask().run_on_model(kvcache_model);+ LOG_DEBUG("Try patch sliding window attention mask (Phi-3, Gemma-2, Gemma-3, Gemma-4), if it exists.");+ ov::npuw::PatchSlidingWindowMask().run_on_model(kvcache_model);}LOG_DEBUG("Creating prefill model as clone of transformed kvcache one.");diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_phi3_sliding_mask.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_phi3_sliding_mask.cppdeleted file mode 100644index 01d5d78e8e1..00000000000--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_phi3_sliding_mask.cpp+++ /dev/null@@ -1,26 +0,0 @@-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#include "patch_phi3_sliding_mask.hpp"--#include "openvino/pass/manager.hpp"-#include "phi3_sliding_mask.hpp"--namespace {--bool patch_phi3_sliding_mask(const std::shared_ptr<ov::Model>& model) {- ov::pass::Manager manager;- manager.register_pass<ov::npuw::Phi3SlidingMask>();- return manager.run_passes(model);-}--} // namespace--namespace ov::npuw {--bool PatchPhi3SlidingMask::run_on_model(const std::shared_ptr<ov::Model>& model) {- return patch_phi3_sliding_mask(model);-}--} // namespace ov::npuwdiff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_phi3_sliding_mask.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_phi3_sliding_mask.hppdeleted file mode 100644index ba884e334a2..00000000000--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_phi3_sliding_mask.hpp+++ /dev/null@@ -1,18 +0,0 @@-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#pragma once--#include "openvino/pass/pass.hpp"--namespace ov::npuw {--class PatchPhi3SlidingMask : public ov::pass::ModelPass {-public:- OPENVINO_MODEL_PASS_RTTI("ov::npuw::PatchPhi3SlidingMask");- explicit PatchPhi3SlidingMask() = default;- bool run_on_model(const std::shared_ptr<ov::Model>& model) override;-};--} // namespace ov::npuwdiff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_sliding_window_mask.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_sliding_window_mask.cppnew file mode 100644index 00000000000..7ef02f665c5--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_sliding_window_mask.cpp@@ -0,0 +1,26 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "patch_sliding_window_mask.hpp"++#include "openvino/pass/manager.hpp"+#include "sliding_window_mask.hpp"++namespace {++bool patch_sliding_window_mask(const std::shared_ptr<ov::Model>& model) {+ ov::pass::Manager manager;+ manager.register_pass<ov::npuw::SlidingWindowMask>();+ return manager.run_passes(model);+}++} // namespace++namespace ov::npuw {++bool PatchSlidingWindowMask::run_on_model(const std::shared_ptr<ov::Model>& model) {+ return patch_sliding_window_mask(model);+}++} // namespace ov::npuwdiff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_sliding_window_mask.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_sliding_window_mask.hppnew file mode 100644index 00000000000..a18d0fdef12--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_sliding_window_mask.hpp@@ -0,0 +1,20 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/pass.hpp"++namespace ov::npuw {++// Public API for patching sliding window attention masks.+// Applies fixes for Phi-3, Gemma4, and other models with sliding window attention.+class PatchSlidingWindowMask : public ov::pass::ModelPass {+public:+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::PatchSlidingWindowMask");+ explicit PatchSlidingWindowMask() = default;+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;+};++} // namespace ov::npuwdiff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/phi3_sliding_mask.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/phi3_sliding_mask.hppdeleted file mode 100644index 56fca1b8bd1..00000000000--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/phi3_sliding_mask.hpp+++ /dev/null@@ -1,18 +0,0 @@-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#pragma once--#include "openvino/pass/pass.hpp"--namespace ov::npuw {--class Phi3SlidingMask : public ov::pass::ModelPass {-public:- OPENVINO_MODEL_PASS_RTTI("ov::npuw::Phi3SlidingMask");- Phi3SlidingMask() = default;- bool run_on_model(const std::shared_ptr<ov::Model>& model) override;-};--} // namespace ov::npuw\ No newline at end of filediff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/phi3_sliding_mask.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/sliding_window_mask.cppsimilarity index 57%rename from src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/phi3_sliding_mask.cpprename to src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/sliding_window_mask.cppindex 85d3d661c5b..745c902123f 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/phi3_sliding_mask.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/sliding_window_mask.cpp@@ -2,7 +2,7 @@// SPDX-License-Identifier: Apache-2.0//-#include "phi3_sliding_mask.hpp"+#include "sliding_window_mask.hpp"#include "../logging.hpp"#include "openvino/op/ops.hpp"@@ -22,6 +22,119 @@ namespace {# pragma GCC diagnostic ignored "-Wattributes"#endif+// ============================================================================+// Shared helper: Rebuild sliding window attention mask for static KV buffers+// with different paddings.+// ============================================================================+// This function implements the common 4-step transformation used by+// Phi3, Gemma2, Gemma3 or Gemma4 sliding window attention patterns:+//+// 1. (K > pos_ids - window) & (K <= Q_range)+// -- Use temporal position_ids for the left window bound to handle right-padded+// past tokens, while preserving the causal mask for present tokens.+// 2. (K > Q_range - window) | (K < past_kv_len)+// -- Bound present tokens by window size while always allowing past tokens.+// 3. Result = 1 & 2+// -- Together they form the correct sliding window mask for past and present+// tokens and the causal mask for present tokens.+// 4. Clean = 3 & attention_mask[past_kv_len:].T+// -- Remove padding artifacts.+void rebuild_sliding_window_mask(const std::shared_ptr<ov::Node>& attention_mask_node_ptr,+ const std::shared_ptr<ov::Node>& position_ids_node_ptr,+ const std::shared_ptr<ov::Node>& matched_past_kv_len,+ const std::shared_ptr<ov::Node>& matched_full_ctx_len,+ const std::shared_ptr<ov::Node>& matched_key_range_row,+ const std::shared_ptr<ov::Node>& matched_neg_window_size,+ const std::shared_ptr<ov::Node>& matched_sliding_mask,+ const std::shared_ptr<ov::Node>& matched_sliding_and_causal_mask,+ const char* log_prefix) {+ auto neg_window_size_const = std::static_pointer_cast<ov::op::v0::Constant>(matched_neg_window_size);+ OPENVINO_ASSERT(neg_window_size_const->get_output_size() == 1,+ "Sliding window size constant must be of size 1, but got " ++ std::to_string(neg_window_size_const->get_output_size()));++ OPENVINO_ASSERT(attention_mask_node_ptr, "Passed attention_mask node is nullptr!");+ OPENVINO_ASSERT(position_ids_node_ptr, "Passed position_ids node is nullptr!");++ // Create constants+ auto const_zero = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{}, 0);++ // =======================================================================+ // STEP 1: (K > pos_ids - window) & (K <= Q_range)+ // Use temporal position_ids for the left window bound to correctly handle+ // right-padded past tokens, while preserving the causal mask for present tokens.+ // =======================================================================+ std::shared_ptr<ov::Node> query_range_as_pos_ids = position_ids_node_ptr;+ if (neg_window_size_const->output(0).get_element_type() == ov::element::f32) {+ query_range_as_pos_ids = std::make_shared<ov::op::v0::Convert>(position_ids_node_ptr, ov::element::f32);+ }+ auto query_range_as_pos_ids_unsqueezed =+ std::make_shared<ov::op::v0::Unsqueeze>(query_range_as_pos_ids, const_zero);+ auto const_three = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{}, 3);+ auto query_range_as_pos_ids_col =+ std::make_shared<ov::op::v0::Unsqueeze>(query_range_as_pos_ids_unsqueezed, const_three);+ auto query_range_as_pos_left_bound =+ std::make_shared<ov::op::v1::Add>(query_range_as_pos_ids_col, matched_neg_window_size);+ auto sliding_mask_for_right_padding =+ std::make_shared<ov::op::v1::Greater>(matched_key_range_row, query_range_as_pos_left_bound);+ matched_sliding_and_causal_mask->input(0).replace_source_output(sliding_mask_for_right_padding);++ // =======================================================================+ // STEP 2: (K > Q_range - window) | (K < past_kv_len)+ // Bound present tokens by window size while always allowing+ // past prefill tokens.+ // =======================================================================+ std::shared_ptr<ov::Node> past_kv_len_argument = matched_past_kv_len;+ if (neg_window_size_const->output(0).get_element_type() == ov::element::f32) {+ past_kv_len_argument = std::make_shared<ov::op::v0::Convert>(matched_past_kv_len, ov::element::f32);+ }+ auto only_past_tokens_mask = std::make_shared<ov::op::v1::Less>(matched_key_range_row, past_kv_len_argument);+ auto sliding_mask_for_left_padding_or_only_past =+ std::make_shared<ov::op::v13::BitwiseOr>(matched_sliding_mask, only_past_tokens_mask);++ // =======================================================================+ // STEP 3: Result = 1 & 2+ // =======================================================================+ // NB: target_inputs must be captured BEFORE new_sliding_and_causal_mask is+ // created, because creating it registers it as a consumer of+ // matched_sliding_and_causal_mask. Capturing after would include the new+ // node in target_inputs and cause a graph cycle when replacing outputs.+ auto target_inputs = matched_sliding_and_causal_mask->output(0).get_target_inputs();+ auto new_sliding_and_causal_mask =+ std::make_shared<ov::op::v13::BitwiseAnd>(matched_sliding_and_causal_mask,+ sliding_mask_for_left_padding_or_only_past);++ // =======================================================================+ // STEP 4: Clean = 3 & attention_mask[past_kv_len:].T+ // Remove padding artifacts.+ // =======================================================================+ std::vector<int64_t> shape_rank_one{1};+ auto shape_rank_one_const = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, shape_rank_one);+ auto past_len_reshaped = std::make_shared<ov::op::v1::Reshape>(matched_past_kv_len, shape_rank_one_const, false);+ auto full_ctx_len_reshaped =+ std::make_shared<ov::op::v1::Reshape>(matched_full_ctx_len, shape_rank_one_const, false);+ auto const_one_rank_one = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, 1);+ auto attention_mask_bool = std::make_shared<ov::op::v0::Convert>(attention_mask_node_ptr, ov::element::boolean);+ auto present_atten_mask_bool = std::make_shared<ov::op::v8::Slice>(attention_mask_bool,+ past_len_reshaped,+ full_ctx_len_reshaped,+ const_one_rank_one,+ const_one_rank_one);+ std::vector<int64_t> vector_shape{-1, 1};+ auto vector_shape_const = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{2}, vector_shape);+ auto present_atten_mask_bool_col =+ std::make_shared<ov::op::v1::Reshape>(present_atten_mask_bool, vector_shape_const, false);+ auto clean_sliding_and_causal_mask =+ std::make_shared<ov::op::v13::BitwiseAnd>(new_sliding_and_causal_mask, present_atten_mask_bool_col);++ // Replace all target inputs+ for (auto&& input : target_inputs) {+ input.replace_source_output(clean_sliding_and_causal_mask);+ }++ LOG_INFO(std::string(log_prefix) + " sliding window attention mask pattern found and patched.");+}+class OldPhi3SlidingMaskMatcher : public ov::pass::MatcherPass {public:OPENVINO_MATCHER_PASS_RTTI("ov::npuw::patterns::OldPhi3SlidingMaskMatcher");@@ -226,7 +339,6 @@ public:// past tokens and left-padded present tokens. Logic to replace pattern is the same// as in Phi3SlidingMask rewriter, but adjusted to another set of operations for// creation of mask, obtained from transformers 4.53.- // Pattern is the same as in GemmaSlidingMask.//// Fix is a replace of following pattern:// 1. (K range > (Q range - sliding window).T) & (K range <= Q range.T)@@ -272,98 +384,130 @@ public:auto sliding_and_causal_mask = opp::wrap_type<ov::op::v13::BitwiseAnd>({sliding_and_true, causal_mask});auto callback = [=](opp::Matcher& m) {- LOG_INFO("Found (4.53) pattern for Phi-3 Sliding Window Attention, will be replaced with custom for static "- "shapes.");auto& node_to_output = m.get_pattern_value_map();++ // Extract matched nodes from patternauto optional_squeeze = node_to_output.find(past_kv_len_squeeze);auto matched_past_kv_len = optional_squeeze != node_to_output.end()? optional_squeeze->second.get_node_shared_ptr(): node_to_output.at(past_kv_len).get_node_shared_ptr();auto matched_full_ctx_len = node_to_output.at(full_ctx_len).get_node_shared_ptr();- auto node_neg_window_size = node_to_output.at(neg_window_size).get_node_shared_ptr();+ auto matched_neg_window_size = node_to_output.at(neg_window_size).get_node_shared_ptr();auto matched_sliding_mask = node_to_output.at(sliding_mask).get_node_shared_ptr();auto matched_sliding_and_causal_mask = node_to_output.at(sliding_and_causal_mask).get_node_shared_ptr();auto optional_convert = node_to_output.find(opt_key_range_row_f32);- std::shared_ptr<ov::Node> matched_key_range_row =- optional_convert != node_to_output.end() ? optional_convert->second.get_node_shared_ptr()- : node_to_output.at(key_range_row).get_node_shared_ptr();- auto matched_neg_window_size = std::static_pointer_cast<ov::op::v0::Constant>(node_neg_window_size);- OPENVINO_ASSERT(matched_neg_window_size->get_output_size() == 1,- "Sliding window size constant must be of size 1, but got " +- std::to_string(matched_neg_window_size->get_output_size()));+ auto matched_key_range_row = optional_convert != node_to_output.end()+ ? optional_convert->second.get_node_shared_ptr()+ : node_to_output.at(key_range_row).get_node_shared_ptr();++ // Call shared transformation helper+ rebuild_sliding_window_mask(attention_mask_node_ptr,+ position_ids_node_ptr,+ matched_past_kv_len,+ matched_full_ctx_len,+ matched_key_range_row,+ matched_neg_window_size,+ matched_sliding_mask,+ matched_sliding_and_causal_mask,+ "Phi-3, Gemma-2, Gemma-3");+ return true;+ };+ register_matcher(std::make_shared<opp::Matcher>(sliding_and_causal_mask, "Phi3SlidingMaskMatcher"),+ std::move(callback));+ }+};- std::shared_ptr<ov::Node> passed_attention_mask = attention_mask_node_ptr;- std::shared_ptr<ov::Node> passed_position_ids = position_ids_node_ptr;- OPENVINO_ASSERT(passed_attention_mask, "Passed attention_mask node is nullptr!");- OPENVINO_ASSERT(passed_position_ids, "Passed position_ids node is nullptr!");+class Gemma4SlidingMaskMatcher : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("ov::npuw::patterns::Gemma4SlidingMaskMatcher");- auto const_zero = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{}, 0);- auto const_one = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{}, 1);- auto const_three = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{}, 3);+ Gemma4SlidingMaskMatcher(const std::shared_ptr<ov::Node>& attention_mask_node_ptr,+ const std::shared_ptr<ov::Node>& position_ids_node_ptr) {+ // Fix Gemma-4 sliding window attention mask for static KV+ // buffers with different paddings for past and present tokens.+ //+ // Gemma-4's generate model computes the Q range (cache_position) as:+ // q_range = Range(0, seq_len, 1) -- seq_len is the statically-compiled Q+ // -- sequence length (1 for standard generate)+ // cache_pos = Add(q_range, past_kv_len) -- Q position in the full KV buffer+ // q_idx = Unsqueeze x3(cache_pos) -- shape [1,1,seq_len,1]+ //+ // Unlike Phi-3's Range(past_kv_len, past_kv_len + seq_len), Gemma-4 uses an+ // explicit Add, causing the pattern in Phi3SlidingMaskMatcher to miss it.+ //+ // With static KV buffers, the Q position >> actual temporal position_id, so+ // SWA layers incorrectly exclude past prefill tokens (distance > sliding_window).+ //+ // Fix is identical to Phi3SlidingMaskMatcher:+ // 1. (K > pos_ids - window) & (K <= Q_range)+ // -- temporal position_ids for the left window bound; causal mask for present tokens+ // 2. (K > Q_range - window) | (K < past_kv_len)+ // -- bound present tokens by window size; always allow past tokens+ // 3. Result = 1 & 2+ // -- correct sliding window + causal mask for past and present tokens+ // 4. Clean = 3 & attention_mask[past_kv_len:].T+ // -- remove padding artifacts+ auto unsqueeze_sequence = [&](std::shared_ptr<ov::Node> node) {+ auto u1 = opp::wrap_type<ov::op::v0::Unsqueeze>({node, opp::any_input()});+ auto u2 = opp::wrap_type<ov::op::v0::Unsqueeze>({u1, opp::any_input()});+ auto u3 = opp::wrap_type<ov::op::v0::Unsqueeze>({u2, opp::any_input()});+ return u3;+ };- // 1.(K range > (Q_pos range - sliding window).T) & (K range <= Q range.T)- std::shared_ptr<ov::Node> query_range_as_pos_ids = passed_position_ids;- if (matched_neg_window_size->output(0).get_element_type() == ov::element::f32) {- query_range_as_pos_ids = std::make_shared<ov::op::v0::Convert>(passed_position_ids, ov::element::f32);- }- auto query_range_as_pos_ids_unsqueezed =- std::make_shared<ov::op::v0::Unsqueeze>(query_range_as_pos_ids, const_zero);- auto query_range_as_pos_ids_col =- std::make_shared<ov::op::v0::Unsqueeze>(query_range_as_pos_ids_unsqueezed, const_three);- auto query_range_as_pos_left_bound =- std::make_shared<ov::op::v1::Add>(query_range_as_pos_ids_col, matched_neg_window_size);- auto sliding_mask_for_right_padding =- std::make_shared<ov::op::v1::Greater>(matched_key_range_row, query_range_as_pos_left_bound);- matched_sliding_and_causal_mask->input(0).replace_source_output(sliding_mask_for_right_padding);-- // 2. (K range > (Q range - sliding window).T) | (K range < shape(past_key_values, 2))- std::shared_ptr<ov::Node> past_kv_len_argument = matched_past_kv_len;- if (matched_neg_window_size->output(0).get_element_type() == ov::element::f32) {- past_kv_len_argument = std::make_shared<ov::op::v0::Convert>(matched_past_kv_len, ov::element::f32);- }- auto only_past_tokens_mask =- std::make_shared<ov::op::v1::Less>(matched_key_range_row, past_kv_len_argument);- auto sliding_mask_for_left_padding_or_only_past =- std::make_shared<ov::op::v13::BitwiseOr>(matched_sliding_mask, only_past_tokens_mask);+ // K (key) side: Range(0, past_kv_len + seq_len, 1)+ auto past_kv_len = opp::wrap_type<ov::op::v8::Gather>({opp::any_input(), opp::any_input(), opp::any_input()});+ auto past_kv_len_squeeze = opp::optional<ov::op::v0::Squeeze>({past_kv_len});+ auto zero_const = opp::wrap_type<ov::op::v0::Constant>();+ auto full_ctx_len = opp::wrap_type<ov::op::v1::Add>({opp::any_input(), past_kv_len_squeeze});+ auto key_range = opp::wrap_type<ov::op::v4::Range>({zero_const, full_ctx_len, opp::any_input()});+ auto key_range_row = unsqueeze_sequence(key_range);+ auto opt_key_range_f32 = opp::optional<ov::op::v0::Convert>({key_range_row->output(0)});- // 3. Result = 1 & 2- // Save target inputs first:- auto target_inputs = matched_sliding_and_causal_mask->output(0).get_target_inputs();- auto new_sliding_and_causal_mask =- std::make_shared<ov::op::v13::BitwiseAnd>(matched_sliding_and_causal_mask,- sliding_mask_for_left_padding_or_only_past);+ // Q (query) side: Gemma4-specific -- cache_pos = Range(0, seq_len) + past_kv_len+ auto q_range = opp::wrap_type<ov::op::v4::Range>({opp::any_input(), opp::any_input(), opp::any_input()});+ auto cache_position = opp::wrap_type<ov::op::v1::Add>({q_range, past_kv_len_squeeze});+ auto query_range_column = unsqueeze_sequence(cache_position);- // 4. Removing extra padding via : 3 & attention_mask_input[past_kv_len:].T- std::vector<int64_t> shape_rank_one{1};- auto shape_rank_one_const =- std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, shape_rank_one);- auto past_len_reshaped =- std::make_shared<ov::op::v1::Reshape>(matched_past_kv_len, shape_rank_one_const, false);- auto full_ctx_len_reshaped =- std::make_shared<ov::op::v1::Reshape>(matched_full_ctx_len, shape_rank_one_const, false);- auto const_one_rank_one = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, 1);- auto attention_mask_bool =- std::make_shared<ov::op::v0::Convert>(passed_attention_mask, ov::element::boolean);- auto present_atten_mask_bool = std::make_shared<ov::op::v8::Slice>(attention_mask_bool,- past_len_reshaped,- full_ctx_len_reshaped,- const_one_rank_one,- const_one_rank_one);- std::vector<int64_t> vector_shape{-1, 1};- auto vector_shape_const =- std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{2}, vector_shape);- auto present_atten_mask_bool_col =- std::make_shared<ov::op::v1::Reshape>(present_atten_mask_bool, vector_shape_const, false);- auto clean_sliding_and_causal_mask =- std::make_shared<ov::op::v13::BitwiseAnd>(new_sliding_and_causal_mask, present_atten_mask_bool_col);- for (auto&& input : target_inputs) {- input.replace_source_output(clean_sliding_and_causal_mask);- }+ // Sliding window & causal masks (positive form: 1 = attend)+ auto neg_window_size = opp::wrap_type<ov::op::v0::Constant>();+ auto query_left_bound = opp::wrap_type<ov::op::v1::Add>({query_range_column, neg_window_size});+ auto sliding_mask = opp::wrap_type<ov::op::v1::Greater>({opt_key_range_f32, query_left_bound});+ auto sliding_and_true = opp::wrap_type<ov::op::v13::BitwiseAnd>({opp::any_input(), sliding_mask});+ auto causal_mask = opp::wrap_type<ov::op::v1::LessEqual>({opt_key_range_f32, query_range_column});+ auto sliding_and_causal_mask = opp::wrap_type<ov::op::v13::BitwiseAnd>({sliding_and_true, causal_mask});++ auto callback = [=](opp::Matcher& m) {+ auto& node_to_output = m.get_pattern_value_map();+ // Extract matched nodes from pattern+ auto optional_squeeze = node_to_output.find(past_kv_len_squeeze);+ auto matched_past_kv_len = optional_squeeze != node_to_output.end()+ ? optional_squeeze->second.get_node_shared_ptr()+ : node_to_output.at(past_kv_len).get_node_shared_ptr();+ auto matched_full_ctx_len = node_to_output.at(full_ctx_len).get_node_shared_ptr();+ auto matched_neg_window_size = node_to_output.at(neg_window_size).get_node_shared_ptr();+ auto matched_sliding_mask = node_to_output.at(sliding_mask).get_node_shared_ptr();+ auto matched_sliding_and_causal_mask = node_to_output.at(sliding_and_causal_mask).get_node_shared_ptr();++ auto optional_convert = node_to_output.find(opt_key_range_f32);+ auto matched_key_range_row = optional_convert != node_to_output.end()+ ? optional_convert->second.get_node_shared_ptr()+ : node_to_output.at(key_range_row).get_node_shared_ptr();++ // Call shared transformation helper+ rebuild_sliding_window_mask(attention_mask_node_ptr,+ position_ids_node_ptr,+ matched_past_kv_len,+ matched_full_ctx_len,+ matched_key_range_row,+ matched_neg_window_size,+ matched_sliding_mask,+ matched_sliding_and_causal_mask,+ "Gemma4");return true;};- register_matcher(std::make_shared<opp::Matcher>(sliding_and_causal_mask, "Phi3SlidingMaskMatcher"),+ register_matcher(std::make_shared<opp::Matcher>(sliding_and_causal_mask, "Gemma4SlidingMaskMatcher"),std::move(callback));}};@@ -376,7 +520,7 @@ public:namespace ov::npuw {-bool Phi3SlidingMask::run_on_model(const std::shared_ptr<ov::Model>& model) {+bool SlidingWindowMask::run_on_model(const std::shared_ptr<ov::Model>& model) {std::shared_ptr<ov::Node> attention_mask_node_ptr = nullptr;std::shared_ptr<ov::Node> position_ids_node_ptr = nullptr;for (const auto& i : model->inputs()) {@@ -401,6 +545,7 @@ bool Phi3SlidingMask::run_on_model(const std::shared_ptr<ov::Model>& model) {ov::pass::Manager manager;manager.set_per_pass_validation(true);const auto rewriter = manager.register_pass<ov::pass::GraphRewrite>();+ rewriter->add_matcher<Gemma4SlidingMaskMatcher>(attention_mask_node_ptr, position_ids_node_ptr);rewriter->add_matcher<Phi3SlidingMaskMatcher>(attention_mask_node_ptr, position_ids_node_ptr);rewriter->add_matcher<OldPhi3SlidingMaskMatcher>();return manager.run_passes(model);diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/sliding_window_mask.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/sliding_window_mask.hppnew file mode 100644index 00000000000..e6660df3ffc--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/sliding_window_mask.hpp@@ -0,0 +1,20 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/pass.hpp"++namespace ov::npuw {++// Fixes sliding window attention mask for static KV buffers with different paddings+// in LLM models. Supports Phi-3 (transformers 4.51 & 4.53), Gemma2, Gemma3, Gemma4 patterns.+class SlidingWindowMask : public ov::pass::ModelPass {+public:+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::SlidingWindowMask");+ SlidingWindowMask() = default;+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;+};++} // namespace ov::npuwdiff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex 0efbac1b97d..122f3013ce0 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -88,8 +88,8 @@ ov_add_test_target(${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/decompose_gqa.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/lora_stateful_to_stateless.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_value_tensors.cpp- ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_phi3_sliding_mask.cpp- ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/phi3_sliding_mask.cpp+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_sliding_window_mask.cpp+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/sliding_window_mask.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_sliced_head_to_static.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/slice_out_embeds.cpp