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] Support sliding mask pattern transformers 4.55 (#33804)
Alexander Kalistratov60f901e176f6
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 cff7c9b68f5..1cf075f6d52 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@@ -310,95 +310,6 @@ public:}};-class GemmaSlidingMask : public ov::pass::MatcherPass {-public:- OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::GemmaSlidingMask");-- struct Result {- Result() = default;-- bool found = false;- int32_t window_size = 0;- std::shared_ptr<ov::op::v0::Parameter> mask_input;- };-- explicit GemmaSlidingMask(Result* result) {- // Searching for gemma sliding mask pattern and replace it's output- // with Paramater of the same size and type.- /* -\- range_w -> unsqueeze -> unsqueeze -> unsqueeze1 -> convert -\/ => LessEqual -\- \ /\-/ \- /-----\----/ =>BWAnd_res- / \ /- range_h -> unsqueeze -> unsqueeze -> unsqueeze2 -> add -=> Greater -> BWAnd --/- const (-window_size) ----/- */- // Basically this subgrapgh is doing the following:- // range_w is range (0, ..., width - 1) (probably + something)- // renge_h is range (0, ..., height - 1) (probably + something)- // And then doing the following check:- // y - window_size < x <= y- // Producing squared sliding mask:- // 1 0 0 0 0 0- // 1 1 0 0 0 0- // 1 1 1 0 0 0- // 0 1 1 1 0 0- // 0 0 1 1 1 0- // 0 0 0 1 1 1- //- // Please also note, that sliding windows size is stored as negative value and the- // subgraph is actually doing:- // y + (negative)window_size < x <= y-- auto range_sequence = [&]() {- auto range = opp::wrap_type<ov::op::v4::Range>({opp::any_input(), opp::any_input(), opp::any_input()});- auto unsqueeze1 = opp::wrap_type<ov::op::v0::Unsqueeze>({range, opp::any_input()});- auto unsqueeze2 = opp::wrap_type<ov::op::v0::Unsqueeze>({unsqueeze1, opp::any_input()});- auto unsqueeze3 = opp::wrap_type<ov::op::v0::Unsqueeze>({unsqueeze2, opp::any_input()});-- return unsqueeze3;- };-- auto unsqueeze1 = range_sequence();- auto convert = opp::wrap_type<ov::op::v0::Convert>({unsqueeze1});- auto unsqueeze2 = range_sequence();- auto window_size = opp::wrap_type<ov::op::v0::Constant>();- auto add = opp::wrap_type<ov::op::v1::Add>({unsqueeze2, window_size});- auto greater = opp::wrap_type<ov::op::v1::Greater>({convert, add});- auto bwand = opp::wrap_type<ov::op::v13::BitwiseAnd>({opp::any_input(), greater});- auto less_equal = opp::wrap_type<ov::op::v1::LessEqual>({convert, unsqueeze2});- auto bwand_res = opp::wrap_type<ov::op::v13::BitwiseAnd>({bwand, less_equal});-- auto callback = [=](ov::pass::pattern::Matcher& m) {- auto& node_to_output = m.get_pattern_value_map();- auto* bwand_matched_node = node_to_output.at(bwand_res).get_node();- auto* window_size_node = node_to_output.at(window_size).get_node();- auto output = bwand_matched_node->output(0);- auto target_inputs = output.get_target_inputs();-- auto* window_size_constant = static_cast<ov::op::v0::Constant*>(window_size_node);- OPENVINO_ASSERT(window_size_constant->get_output_size() == 1,- "Sliding window size constant must be of size 1, but got " +- std::to_string(window_size_constant->get_output_size()));- OPENVINO_ASSERT(!result->found, "Second gemma sliding mask pattern found, what is unexpected!");-- auto input = std::make_shared<ov::op::v0::Parameter>(output.get_element_type(), output.get_partial_shape());- input->set_friendly_name(ov::npuw::LLMInferRequest::layer_names::gemma_sliding_mask);- output.replace(input->output(0));-- auto window_size_vec = window_size_constant->cast_vector<int32_t>(1);-- result->found = true;- // since we are doing Add and need to do subtract window size is stored as negative value- result->window_size = -window_size_vec[0];- result->mask_input = input;-- return true;- };- register_matcher(std::make_shared<opp::Matcher>(bwand_res, "GemmaSlidingMask"), std::move(callback));- }-};-class OldPhi3SlidingMaskMatcher : public ov::pass::MatcherPass {public:OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::OldPhi3SlidingMaskMatcher");@@ -766,6 +677,13 @@ public:return false;}+ auto pos_id_shape = position_ids_node_ptr->get_output_tensor(0).get_partial_shape();+ if (pos_id_shape.size() != 2) {+ // FIXME: Qwen2.5 VL/Omni uses 3D position_ids, which can't be directly used+ // in creation of sliding window mask.+ return false;+ }+ov::pass::Manager manager;manager.set_per_pass_validation(true);const auto rewriter = manager.register_pass<ov::pass::GraphRewrite>();@@ -847,15 +765,9 @@ void decompose_GQA(std::shared_ptr<ov::Model> model, bool is_prefill_model) {}void patch_phi3_sliding_mask(const std::shared_ptr<ov::Model>& model) {- // FIXME: Don't do these transformations for gemma3 which has token_type_ids input.- // FIXME: Don't do these transformations for VLMs identified by inputs_embeds input.- // Qwen2.5 VL/Omni uses 3D position_ids, which can't be directly used- // in creation of sliding window mask.- if (!ov::npuw::util::has_input(model, "token_type_ids") && !ov::npuw::util::has_input(model, "inputs_embeds")) {- ov::pass::Manager manager;- manager.register_pass<Phi3SlidingMask>();- manager.run_passes(model);- }+ ov::pass::Manager manager;+ manager.register_pass<Phi3SlidingMask>();+ manager.run_passes(model);}} // namespace@@ -1340,41 +1252,6 @@ void ov::npuw::LLMCompiledModel::convert_stateful_lora_to_stateless(std::shared_model->add_parameters(new_parameters);}-void ov::npuw::LLMCompiledModel::gemma_transformations(const std::shared_ptr<ov::Model>& model) {- // For now only do transformations for gemma3 which has token_type_ids input.- bool token_type_ids_found = false;- for (const auto& input : model->inputs()) {- const auto& input_name = input.get_any_name();- if (input_name.find("token_type_ids") != std::string::npos) {- token_type_ids_found = true;- break;- }- }-- if (token_type_ids_found) {- ov::pass::GraphRewrite rewr;- auto RewrRes = std::make_unique<GemmaSlidingMask::Result>();- rewr.add_matcher<GemmaSlidingMask>(RewrRes.get());- rewr.run_on_model(model);-- if (RewrRes->found) {- OPENVINO_ASSERT(- RewrRes->window_size > 0,- "Gemma sliding window size must be strictly positive, but got " + std::to_string(RewrRes->window_size));-- m_gemma_sliding_window_size = RewrRes->window_size;- auto mask_input = RewrRes->mask_input;- model->add_parameters({mask_input});- for (auto&& input : model->inputs()) {- if (input.get_node() == mask_input.get()) {- input.set_names({mask_input->get_friendly_name()});- }- }- model->validate_nodes_and_infer_types();- }- }-}-std::vector<std::shared_ptr<ov::Model>> ov::npuw::LLMCompiledModel::create_generate_model_variants(const std::shared_ptr<ov::Model>& generate_model,const KVAxesPosition& axes,@@ -1536,6 +1413,10 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m// If chunk size covers the entire prompt, just follow the static behavior.// Otherwise, use chunking and align the prompt size to the chunk size.if (m_use_chunk_prefill) {+ OPENVINO_ASSERT(+ !ov::npuw::util::has_input(model, "token_type_ids") || !ov::npuw::util::has_input(model, "inputs_embeds"),+ "Chunking is not implemented for Gemma model family yet. "+ "Please set NPUW_LLM_PREFILL_HINT to 'STATIC'");if (m_prefill_chunk_size >= max_prompt_len) {m_use_chunk_prefill = false;} else {@@ -1656,12 +1537,6 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m// Create generate model variants with different sizesauto generate_model_variants = create_generate_model_variants(kvcache_model, axes, whisper_lhs_seq_size);- // Apply transformations to all generate variants- LOG_DEBUG("Try parametrize Gemma sliding window mask, if it exists.");- for (auto& model_variant : generate_model_variants) {- gemma_transformations(model_variant);- }-if (lm_head_model) {LOG_DEBUG("Shared LM head: slice the prefill output");// KVCache model is already reshaped to [1, max_generation_token_len, embed size],@@ -1995,7 +1870,6 @@ void ov::npuw::LLMCompiledModel::serialize(std::ostream& stream, const ov::npuw:write(model_stream, m_enable_prefix_caching);write(model_stream, m_prefix_caching_block_size);write(model_stream, m_prefix_caching_max_num_blocks);- write(model_stream, m_gemma_sliding_window_size);write(model_stream, m_is_whisper);write(model_stream, m_is_eagle);write(model_stream, m_is_embedding);@@ -2221,7 +2095,6 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::deserialread(model_stream, compiled->m_enable_prefix_caching);read(model_stream, compiled->m_prefix_caching_block_size);read(model_stream, compiled->m_prefix_caching_max_num_blocks);- read(model_stream, compiled->m_gemma_sliding_window_size);read(model_stream, compiled->m_is_whisper);read(model_stream, compiled->m_is_eagle);read(model_stream, compiled->m_is_embedding);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 f40bdacc515..9a890da6d07 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@@ -112,9 +112,6 @@ private:// Friend declarations for PrefixCachingHelper to access protected membersfriend class PrefixCachingHelper;- void gemma_transformations(const std::shared_ptr<ov::Model>& model);- int32_t m_gemma_sliding_window_size = 0;-bool m_is_whisper = false;bool m_is_embedding = false;diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cppindex 8e6feb3bbd5..a82bd878a11 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp@@ -88,20 +88,6 @@ std::pair<uint32_t, uint32_t> get_lora_dims_by_name(const std::string& state_namreturn std::make_pair(low_rank_dim, full_rank_dim);}-void fill_sliding_mask(const ov::SoPtr<ov::ITensor>& mask, int64_t curr_pos, int64_t window_size) {- auto start = curr_pos - window_size;- auto end = curr_pos;-- auto* mask_data = mask->data<bool>();- for (int64_t i = 0; i < static_cast<int64_t>(mask->get_size()); ++i) {- // Unlike original subgraph which do i <= end we are excluding end- // as it is a new token and is located in last position of mask buffer- mask_data[i] = i > start && i < end;- }-- mask_data[mask->get_size() - 1] = true;-}-} // anonymous namespacevoid ov::npuw::LLMInferRequest::init_lora_states() {@@ -218,7 +204,6 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCo}m_generate_initialized = false;- m_gemma_sliding_window_size = compiled_model->m_gemma_sliding_window_size;}std::string ov::npuw::LLMInferRequest::init_pre_alloc_device() {@@ -816,9 +801,9 @@ void ov::npuw::LLMInferRequest::infer_prefill(ov::SoPtr<ov::ITensor> input_ids,const bool use_chunk_prefill = m_npuw_llm_compiled_model->m_use_chunk_prefill;if (use_chunk_prefill) {- OPENVINO_ASSERT(m_gemma_sliding_window_size == 0,+ OPENVINO_ASSERT(!token_type_ids,"Chunking is not implemented for Gemma model family yet. "- "Please use set NPUW_LLM_PREFILL_HINT to 'STATIC'");+ "Please set NPUW_LLM_PREFILL_HINT to 'STATIC'");infer_chunked_prefill(input_ids, attention_mask, position_ids);} else {infer_whole_prefill(input_ids, attention_mask, position_ids, token_type_ids);@@ -881,14 +866,6 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,OPENVINO_THROW("KV-Cache is full.");}- if (auto sliding_mask_port = m_kvcache_in_ports.find(layer_names::gemma_sliding_mask);- sliding_mask_port != m_kvcache_in_ports.end()) {- // TODO: Fill once and update on each iteration instead- fill_sliding_mask(m_kvcache_request->get_tensor(sliding_mask_port->second),- kvcache_desc.num_stored_tokens + input_tokens_len,- m_gemma_sliding_window_size);- }-// FIXME: these tensors should be shared between the parent & child models// NB: input_ids can be either fp32(VLM) or i64(LLM)auto kv_input_ids = m_kvcache_request->get_tensor(m_kvcache_in_ports.at(m_input_ids_name));diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.hppindex 48e50e41d9e..429c0775ace 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.hpp@@ -107,7 +107,6 @@ protected:bool m_first_run = true;int64_t m_first_position_id = 0;- int32_t m_gemma_sliding_window_size = 0;uint64_t m_tokens_in_present_chunk = 0;diff --git a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp b/src/plugins/intel_npu/src/plugin/npuw/serialization.hppindex 9cc34bac0bb..28fcea5b34f 100644--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp@@ -36,7 +36,7 @@ const constexpr ov::npuw::s11n::IndicatorType NPUW_COMPILED_MODEL_INDICATOR =const constexpr ov::npuw::s11n::IndicatorType NPUW_LLM_COMPILED_MODEL_INDICATOR ={char{0x4c}, char{0x4c}, char{0x4d}, char{0x43}, char{0x4d}, char{0x4f}};-const constexpr char* NPUW_SERIALIZATION_VERSION = "0.17";+const constexpr char* NPUW_SERIALIZATION_VERSION = "0.18";// Forward declarationnamespace intel_npu {