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] Remove token_type_ids for generate variant of Gemma3 model (#36769)
Anastasiya(Asya) Proninabead2b2b2e41
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 1d3537a8854..47efb2987c7 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@@ -21,6 +21,7 @@#include "npuw_transformations/lora_stateful_to_stateless.hpp"#include "npuw_transformations/optimize_value_tensors.hpp"#include "npuw_transformations/patch_sliding_window_mask.hpp"+#include "npuw_transformations/remove_token_type_ids.hpp"#include "npuw_transformations/replace_deepstack_scatter_with_add.hpp"#include "npuw_transformations/reshape_sliced_head_to_static.hpp"#include "npuw_transformations/reshape_to_static.hpp"@@ -969,6 +970,11 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m}LOG_DEBUG("Make kvcache model with static shapes");+ // In case of Gemma3, we should remove `token_type_ids` from generate version of the model,+ // as it leads to inaccurate output otherwise.+ // NOTE: It is important to preserve `token_type_ids` in prefill model, however, as `token_type_ids`+ // controls creation of correct blockwise attention mask for image tokens.+ ov::npuw::RemoveTokenTypeIds().run_on_model(kvcache_model);// Create generate model variants with different sizes.// A bidirectional encoder embedding model has no autoregressive generate step (no KV cache,// no single-token decode), so the seq_len=1 generate graph is invalid for it and must not bediff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.hppindex 199fc320522..d1e51b17bec 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.hpp@@ -26,6 +26,7 @@ public:constexpr const char* kVisualPosMasksParamName = "visual_pos_masks";constexpr const char* kDeepstackVisualEmbedsParamName = "deepstack_visual_embeds";+constexpr const char* kTokenTypeIdsParamName = "token_type_ids";bool has_input(const std::shared_ptr<ov::Model>& model, const std::string& name);diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_base_request.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_base_request.hppindex dbe1252935b..7f6b382fc2d 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_base_request.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_base_request.hpp@@ -22,7 +22,7 @@ public:static constexpr const char* past_key_values = "past_key_values";static constexpr const char* output_embeds = "npuw_output_embed";static constexpr const char* logits = "logits";- static constexpr const char* token_type_ids = "token_type_ids";+ static constexpr const char* token_type_ids = ov::npuw::util::kTokenTypeIdsParamName;static constexpr const char* longrope_input = "npuw_longrope_input";static constexpr const char* per_layer_inputs = "per_layer_inputs";static constexpr const char* visual_pos_masks = ov::npuw::util::kVisualPosMasksParamName;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 958f2e57238..ddc0520ad6e 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@@ -1275,7 +1275,6 @@ void ov::npuw::LLMInferRequest::infer_prefill(ov::SoPtr<ov::ITensor> input_ids,void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,ov::SoPtr<ov::ITensor> attention_mask,ov::SoPtr<ov::ITensor> position_ids,- ov::SoPtr<ov::ITensor> token_type_ids,ov::SoPtr<ov::ITensor> per_layer_inputs) {LOG_DEBUG("Calling inference for generate model...");LOG_BLOCK();@@ -1324,11 +1323,6 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,0);uu::fill_tensor<int64_t>(m_kvcache_request->get_tensor(m_kvcache_in_ports.at(layer_names::position_ids)),0);- if (token_type_ids) {- uu::fill_tensor<int64_t>(- m_kvcache_request->get_tensor(m_kvcache_in_ports.at(layer_names::token_type_ids)),- 0);- }m_generate_initialized = true;}@@ -1357,11 +1351,6 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,reinterpret_cast<uint8_t*>(kv_input_ids->data()) + kv_input_ids->get_byte_size() -input_ids->get_byte_size());- if (token_type_ids) {- auto kv_token_type_ids = m_kvcache_request->get_tensor(m_kvcache_in_ports.at(layer_names::token_type_ids));- util::copy_to_right(token_type_ids, kv_token_type_ids);- }-// NOTE: Attention mask pattern for generate model requires the set of "1"// units of length of the current prompt on the right (for present// kv layers) and the set of "1" units of number of previously calculated@@ -1552,7 +1541,7 @@ void ov::npuw::LLMInferRequest::infer() {if (position_ids->get_shape().size() < 3) {trim_kvcache_for_speculative_decoding(position_ids);}- infer_generate(input_ids, attention_mask, position_ids, token_type_ids, per_layer_inputs);+ infer_generate(input_ids, attention_mask, position_ids, per_layer_inputs);}if (!position_ids_opt.has_value()) {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 b1c49a3a6cf..a9b3512ee2d 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@@ -100,7 +100,6 @@ protected:void infer_generate(ov::SoPtr<ov::ITensor> input_ids,ov::SoPtr<ov::ITensor> attention_mask,ov::SoPtr<ov::ITensor> position_ids,- ov::SoPtr<ov::ITensor> token_type_ids,ov::SoPtr<ov::ITensor> per_layer_inputs);// Multiple generate inference request variants, each with a different KV cache sizediff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/remove_token_type_ids.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/remove_token_type_ids.cppnew file mode 100644index 00000000000..7bc0c2a57f6--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/remove_token_type_ids.cpp@@ -0,0 +1,237 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "remove_token_type_ids.hpp"++#include "../llm_compiled_model_utils.hpp"+#include "../logging.hpp"+#include "openvino/op/ops.hpp"+#include "openvino/openvino.hpp"+#include "openvino/pass/manager.hpp"+#include "openvino/pass/matcher_pass.hpp"+#include "openvino/pass/pattern/op/optional.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "openvino/pass/validate.hpp"++namespace opp = ov::pass::pattern;++namespace {++constexpr const char* kTokenTypeIds = ov::npuw::util::kTokenTypeIdsParamName;++// diagnostics warnings on OPENVINO_MATCHER_PASS_RTTI() definition: visibility hidden+#ifdef __GNUC__+# pragma GCC diagnostic push+# pragma GCC diagnostic ignored "-Wattributes"+#endif++class RemoveTTIVisionSubgraph : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("ov::npuw::patterns::RemoveTTIVisionSubgraph");++ RemoveTTIVisionSubgraph() {+ auto token_type_ids = opp::wrap_type<ov::op::v0::Parameter>();+ // `token_type_ids` vision subgraph actually can be split to two subgraphs:+ // - The first part of vision subgraph from `token_type_ids` parameter is used to create a mask for+ // blockwise attention to image tokens the same as in transformers library:+ // `get_block_sequence_ids_for_mask()` from+ // https://github.com/huggingface/transformers/blob/main/src/transformers/models/gemma3/modeling_gemma3.py.+ // - The second part of vision subgraph from `token_type_ids` parameter also handles image tokens in+ // a way to find them inside given parameter and select according result of `Less` operation.+ // Result of second subgraph is used to make BitwiseAND with the created above blockwise mask.+ auto subg1_equal = opp::wrap_type<ov::op::v1::Equal>({token_type_ids, opp::any_input()});+ auto subg1_pad = opp::wrap_type<ov::op::v1::Pad, ov::op::v12::Pad>(+ {subg1_equal, opp::any_input(), opp::any_input(), opp::any_input()});+ auto subg1_slice = opp::wrap_type<ov::op::v8::Slice>(+ {subg1_pad, opp::any_input(), opp::any_input(), opp::any_input(), opp::any_input()});+ auto subg1_bw_not = opp::wrap_type<ov::op::v13::BitwiseNot>({subg1_slice});+ auto subg1_bw_and = opp::wrap_type<ov::op::v13::BitwiseAnd>({subg1_equal, subg1_bw_not});+ auto subg1_convert = opp::wrap_type<ov::op::v0::Convert>({subg1_bw_and});+ auto subg1_cum_sum = opp::wrap_type<ov::op::v0::CumSum>({subg1_convert, opp::any_input()});+ auto subg1_add = opp::wrap_type<ov::op::v1::Add>({subg1_cum_sum, opp::any_input()});+ auto subg1_convert_add = opp::wrap_type<ov::op::v0::Convert>({subg1_add});+ auto subg1_select = opp::wrap_type<ov::op::v1::Select>({subg1_equal, subg1_convert_add, opp::any_input()});++ // We are taking only `ShapeOf` path from the first subgraph, as it is enough for us to find the+ // correct merging point with the second subgraph and the Sliding Causal/Causal mask from it.+ auto subg1_shape_of = opp::wrap_type<ov::op::v0::ShapeOf, ov::op::v3::ShapeOf>({subg1_select});+ auto subg1_gather = opp::wrap_type<ov::op::v8::Gather>({subg1_shape_of, opp::any_input(), opp::any_input()});+ auto subg1_less = opp::wrap_type<ov::op::v1::Less>({opp::any_input(), subg1_gather});++ // In dynamic version of the model, there is branching to two paths after `Less` op:+ // one path is for local attention and another one is for global attention.+ // Both path utilize the same `Select`->`Equal`subgraph below, so pattern should match twice.+ auto subg1_branch_select = opp::wrap_type<ov::op::v1::Select>({subg1_less, opp::any_input(), opp::any_input()});+ auto subg1_branch_equal = opp::wrap_type<ov::op::v1::Equal>({opp::any_input(), subg1_branch_select});++ auto subg2_reshape = opp::wrap_type<ov::op::v1::Reshape>({token_type_ids, opp::any_input()});++ // There is branching point for local and global attention after `Reshape` in the second subgraph.+ // Both local and global attentions path utilize the same subgraph with two `Gather`-s below.+ auto subg2_branch_gather1 =+ opp::wrap_type<ov::op::v8::Gather>({subg2_reshape, opp::any_input(), opp::any_input()});+ auto subg2_branch_gthr1_reshape = opp::wrap_type<ov::op::v1::Reshape>({subg2_branch_gather1, opp::any_input()});+ auto subg2_branch_gthr1_reshape_reshape =+ opp::wrap_type<ov::op::v1::Reshape>({subg2_branch_gthr1_reshape, opp::any_input()});+ auto subg2_branch_gthr1_equal =+ opp::wrap_type<ov::op::v1::Equal>({subg2_branch_gthr1_reshape_reshape, opp::any_input()});+ auto subg2_branch_gather2 =+ opp::wrap_type<ov::op::v8::Gather>({subg2_reshape, opp::any_input(), opp::any_input()});+ auto subg2_branch_gthr2_reshape = opp::wrap_type<ov::op::v1::Reshape>({subg2_branch_gather2, opp::any_input()});+ auto subg2_branch_gthr2_reshape_reshape =+ opp::wrap_type<ov::op::v1::Reshape>({subg2_branch_gthr2_reshape, opp::any_input()});+ auto subg2_branch_gthr2_select = opp::wrap_type<ov::op::v1::Select>(+ {opp::any_input(), subg2_branch_gthr2_reshape_reshape, opp::any_input()});+ auto subg2_branch_gthr2_equal =+ opp::wrap_type<ov::op::v1::Equal>({subg2_branch_gthr2_select, opp::any_input()});+ auto subg2_branch_bw_and =+ opp::wrap_type<ov::op::v13::BitwiseAnd>({subg2_branch_gthr1_equal, subg2_branch_gthr2_equal});++ // Vision block is the subgraph that will be passed to BitwiseOR with Causal mask or Causal Sliding mask futher.+ auto branch_vision_block = opp::wrap_type<ov::op::v13::BitwiseAnd>({subg2_branch_bw_and, subg1_branch_equal});+ auto branch_causal_or_vision = opp::wrap_type<ov::op::v13::BitwiseOr>({opp::any_input(), branch_vision_block});++ auto callback = [=](opp::Matcher& m) {+ auto& node_to_output = m.get_pattern_value_map();+ auto matched_token_type_ids = node_to_output.at(token_type_ids).get_node_shared_ptr();+ if (matched_token_type_ids->output(0).get_names().count(std::string(kTokenTypeIds)) == 0) {+ return false;+ }+ auto matched_causal_or_vision = node_to_output.at(branch_causal_or_vision).get_node_shared_ptr();+ // NB: `BitwiseOr` is not listed in `ov::op::util::is_commutative()`, so the matcher never+ // permutes its arguments. input(1) is therefore guaranteed to be the matched vision+ // block and input(0) the Causal/Sliding Causal mask.+ auto zero = std::make_shared<ov::op::v0::Constant>(ov::element::boolean, ov::Shape{}, false);+ matched_causal_or_vision->input(1).replace_source_output(zero);+ return true;+ };+ register_matcher(std::make_shared<opp::Matcher>(branch_causal_or_vision, "RemoveTTIVisionSubgraph"),+ std::move(callback));+ }+};++class RemoveTTIShapeOfSubgraph : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("ov::npuw::patterns::RemoveTTIShapeOfSubgraph");++ RemoveTTIShapeOfSubgraph() {+ auto token_type_ids = opp::wrap_type<ov::op::v0::Parameter>();+ // There is a subgraph from `token_type_ids` parameter which ends at ShapeOf operation, that in its turn,+ // is passed to Reshape of `attention_mask` operations chain.+ // Later on, result of that reshaped `attention_mask` will go to BitwiseAND with mask from BitwiseOR(Causal+ // mask, Vision mask). Such subgraph from `token_type_ids` should be carefully disconnected from+ // `attention_mask` components and removed to clean all dependencies.+ auto tti_shape_of = opp::wrap_type<ov::op::v0::ShapeOf, ov::op::v3::ShapeOf>({token_type_ids});+ auto tti_gather = opp::wrap_type<ov::op::v8::Gather>({tti_shape_of, opp::any_input(), opp::any_input()});+ auto tti_less = opp::wrap_type<ov::op::v1::Less>({opp::any_input(), tti_gather});+ auto tti_select = opp::wrap_type<ov::op::v1::Select>({tti_less, opp::any_input(), opp::any_input()});+ auto tti_convert = opp::wrap_type<ov::op::v0::Convert>({tti_select});+ auto tti_add = opp::wrap_type<ov::op::v1::Add>({tti_convert, opp::any_input()});+ auto tti_shape_of_2 = opp::wrap_type<ov::op::v0::ShapeOf, ov::op::v3::ShapeOf>({tti_add});++ auto attention_mask = opp::wrap_type<ov::op::v0::Parameter>();+ auto attn_convert = opp::wrap_type<ov::op::v0::Convert>({attention_mask});+ auto attn_reshape = opp::wrap_type<ov::op::v1::Reshape>({attn_convert, opp::any_input()});++ // Here we face a branching point for local and global attention+ auto branch_attn_gather =+ opp::wrap_type<ov::op::v8::Gather>({attn_reshape, opp::any_input(), opp::any_input()});+ auto branch_attn_reshape_2 = opp::wrap_type<ov::op::v1::Reshape>({branch_attn_gather, opp::any_input()});+ auto branch_attn_tti_reshape = opp::wrap_type<ov::op::v1::Reshape>({branch_attn_reshape_2, tti_shape_of_2});+ auto branch_causal_or_vis_and_reshape =+ opp::wrap_type<ov::op::v13::BitwiseAnd>({opp::any_input(), branch_attn_tti_reshape});++ auto callback = [=](opp::Matcher& m) {+ auto& node_to_output = m.get_pattern_value_map();+ auto matched_token_type_ids = node_to_output.at(token_type_ids).get_node_shared_ptr();+ if (matched_token_type_ids->output(0).get_names().count(std::string(kTokenTypeIds)) == 0) {+ return false;+ }++ // In models without `token_type_ids` the shape (for `attention_mask`) is taken+ // from the same `Add` operation which feeds the preceding `Gather->Reshape` subgraph.+ // This `Add` operation is passed as the second (indices) argument to `Gather`.+ auto matched_tti_shape_of_2 = node_to_output.at(tti_shape_of_2).get_node_shared_ptr();+ auto matched_branch_attn_gather = node_to_output.at(branch_attn_gather).get_node_shared_ptr();+ matched_tti_shape_of_2->input(0).replace_source_output(+ matched_branch_attn_gather->input(1).get_source_output());+ return true;+ };+ register_matcher(std::make_shared<opp::Matcher>(branch_causal_or_vis_and_reshape, "RemoveTTIShapeOfSubgraph"),+ std::move(callback));+ }+};++#ifdef __GNUC__+# pragma GCC diagnostic pop+#endif+} // anonymous namespace++bool ov::npuw::RemoveTokenTypeIds::run_on_model(const std::shared_ptr<ov::Model>& model) {+ if (ov::npuw::util::has_input(model, kTokenTypeIds) == false) {+ return false;+ }+ // For Gemma3 generate model, we need to remove blockwise mask created from `token_type_ids` parameter+ // as well as `shape_of` subgraph from `token_type_ids` parameter, that is used to create a reshape for the+ // `attention_mask`. These transformations are needed to avoid accuracy issues due to incorrect interaction+ // of created vision mask with static shapes and different paddings and to allow full removal of+ // `token_type_ids` parameter from the model to skip unnecessary operations with it.+ // As `token_type_ids` isn't used in the generate stage, it is safe to remove the subgraphs.+ // However, components and connections in `attention_mask` subgraph should be fully preserved.+ //+ // The two patterns are independent. Note that each pattern matches once per attention branch+ // (local and global), and `Manager::run_passes()` only reports whether a pattern fired at least once.+ // So, to check that `token_type_ids` is fully disconnected, we need to check that it has no consumers left.+ ov::pass::Manager vision_manager("remove-token-type-ids-vision");+ vision_manager.set_per_pass_validation(false);+ vision_manager.register_pass<RemoveTTIVisionSubgraph>();+ const auto vision_matched = vision_manager.run_passes(model);++ ov::pass::Manager shapeof_manager("remove-token-type-ids-shapeof");+ shapeof_manager.set_per_pass_validation(false);+ shapeof_manager.register_pass<RemoveTTIShapeOfSubgraph>();+ const auto shapeof_matched = shapeof_manager.run_passes(model);++ if (!vision_matched && !shapeof_matched) {+ LOG_WARN("RemoveTokenTypeIds: `" << kTokenTypeIds+ << "` exists, but none of the known subgraphs was found in the"+ " generate model. The parameter is kept.");+ return false;+ }++ auto token_type_ids_param =+ ov::as_type_ptr<ov::op::v0::Parameter>(model->input(kTokenTypeIds).get_node_shared_ptr());+ NPUW_ASSERT(token_type_ids_param);++ // Checking that after applying both the patterns, all consumers of `token_type_ids` were dropped.+ // Otherwise, the model is left partially transformed, thus in an undefined state.+ // Hitting this means the patterns above need to be extended to cover the reported consumer(s).+ const auto remaining_consumers = token_type_ids_param->get_output_target_inputs(0);+ if (!remaining_consumers.empty()) {+ std::string consumers;+ for (const auto& consumer : remaining_consumers) {+ consumers += " " + consumer.get_node()->get_friendly_name() + " (" ++ std::string(consumer.get_node()->get_type_name()) + ")";+ }+ OPENVINO_THROW("RemoveTokenTypeIds: the known subgraphs were rewritten (vision ",+ vision_matched ? "matched" : "didn't match",+ ", shapeof ",+ shapeof_matched ? "matched" : "didn't match",+ "), but `",+ kTokenTypeIds,+ "` still has ",+ remaining_consumers.size(),+ " unexpected consumer(s):",+ consumers,+ ". The model is left partially transformed, and left in "+ " an undefined state, the pass cannot continue.");+ }++ LOG_INFO("RemoveTokenTypeIds: `" << kTokenTypeIds << "` is fully disconnected (vision "+ << (vision_matched ? "matched" : "didn't match") << ", shapeof "+ << (shapeof_matched ? "matched" : "didn't match") << "). Removing the parameter.");+ model->remove_parameter(token_type_ids_param);+ model->validate_nodes_and_infer_types();+ return true;+}diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/remove_token_type_ids.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/remove_token_type_ids.hppnew file mode 100644index 00000000000..7686f616454--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/remove_token_type_ids.hpp@@ -0,0 +1,23 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/pass.hpp"++namespace ov::npuw {++// Drops the `token_type_ids` parameter and the subgraphs it feeds from a generate model.+// The parameter is only removed once every one of its consumers has been detached, so there are+// three possible outcomes:+// * no known subgraph is found - the model is left untouched and the pass returns false;+// * every consumer is detached - the parameter is removed and the pass returns true;+// * some consumer survives the rewrites - the model is now partially transformed and cannot be+// left that way, so the pass throws.+class RemoveTokenTypeIds : public ov::pass::ModelPass {+public:+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::RemoveTokenTypeIds");+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;+};+} // namespace ov::npuwdiff --git a/src/plugins/intel_npu/src/plugin/sources.cmake b/src/plugins/intel_npu/src/plugin/sources.cmakeindex 27839d26d0d..b7a7c3e4fd6 100644--- a/src/plugins/intel_npu/src/plugin/sources.cmake+++ b/src/plugins/intel_npu/src/plugin/sources.cmake@@ -133,6 +133,8 @@ set(NPUW_SOURCES${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/optimize_value_tensors.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/patch_sliding_window_mask.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/patch_sliding_window_mask.hpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/remove_token_type_ids.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/remove_token_type_ids.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/replace_deepstack_scatter_with_add.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/replace_deepstack_scatter_with_add.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/reshape_sliced_head_to_static.cppdiff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex 9d398add394..1d3d6a8f7e3 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -114,6 +114,7 @@ ov_add_test_target(${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/detect_causal_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/remove_token_type_ids.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/replace_deepstack_scatter_with_add.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/right_align_mask_slice_for_conv.cpp@@ -178,6 +179,7 @@ target_sources(${TARGET_NAME} PRIVATE${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/patch_sliding_mask_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/detect_causal_mask_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/remove_empty_kv_inputs_test.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/remove_token_type_ids_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/stateful_to_stateless_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/pyramid_attention_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/sdpa_pattern_matcher_test.cppdiff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/remove_token_type_ids_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/remove_token_type_ids_test.cppnew file mode 100644index 00000000000..670df87f00e--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/remove_token_type_ids_test.cpp@@ -0,0 +1,459 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "npuw_transformations/remove_token_type_ids.hpp"++#include <gtest/gtest.h>++#include <memory>+#include <numeric>+#include <set>+#include <string>+#include <vector>++#include "openvino/op/ops.hpp"++// Tests for ov::npuw::RemoveTokenTypeIds.+//+// The pass detaches two independent groups of `token_type_ids` (TTI) consumers from a Gemma-3+// generate model and then drops the parameter itself:+//+// 1. RemoveTTIVisionSubgraph - the blockwise vision mask. Two chains start at TTI and meet in+// `BitwiseAnd`, which is OR-ed into the causal (or sliding causal) mask, once per attention+// branch (global and local):+//+// subg1: TTI -> Equal -> Pad -> Slice -> BitwiseNot -> BitwiseAnd -> Convert -> CumSum+// -> Add -> Convert -> Select -> ShapeOf -> Gather -> Less+// -> per branch: Select -> Equal+// subg2: TTI -> Reshape -> per branch: two Gather -> Reshape -> Reshape -> Equal chains+// (only the second one carries a Select) -> BitwiseAnd+//+// vision_block = BitwiseAnd(subg2_branch, subg1_branch)+// merge point = BitwiseOr(causal_mask, vision_block)+//+// The callback re-points each `BitwiseOr` input[1] at `Constant(false)`, which leaves the causal+// mask untouched and drops the last consumer of the whole vision subgraph.+//+// 2. RemoveTTIShapeOfSubgraph - a ShapeOf chain that supplies the target shape for a `Reshape`+// inside the `attention_mask` chain:+//+// TTI -> ShapeOf -> Gather -> Less -> Select -> Convert -> Add -> ShapeOf ---++// attention_mask -> Convert -> Reshape -> Gather -> Reshape -> Reshape <-----++//+// Here the subgraph cannot simply be cut, so the callback re-points the second ShapeOf at the+// `Gather` indices instead - which is what a model without TTI reshapes against. The+// `attention_mask` chain itself must come out untouched.+//+// Removal contract: the parameter is dropped if and only if nothing reads it anymore. Either pattern+// firing on its own is enough, as long as it accounted for every consumer. If a consumer survives the+// rewrites the pass throws, because by then the graph is half-transformed and returning it would+// silently corrupt the generated output.++namespace {++using namespace ov;+using namespace ov::op;++constexpr size_t SEQ = 8;+constexpr int64_t SEQ_I64 = static_cast<int64_t>(SEQ);++std::shared_ptr<v0::Parameter> make_token_type_ids() {+ auto tti = std::make_shared<v0::Parameter>(element::i64, Shape{1, SEQ});+ tti->set_friendly_name("token_type_ids");+ tti->output(0).set_names({"token_type_ids"});+ return tti;+}++std::shared_ptr<v0::Parameter> make_named_param(const element::Type& type,+ const Shape& shape,+ const std::string& name) {+ auto param = std::make_shared<v0::Parameter>(type, shape);+ param->set_friendly_name(name);+ param->output(0).set_names({name});+ return param;+}++// Appends the vision-mask subgraph matched by RemoveTTIVisionSubgraph: one shared blockwise-mask+// chain (subg1) and one shared Reshape chain (subg2), both branching into a global and a local+// attention path that each merge into BitwiseOr(causal_mask, vision_block).+void add_vision_chain(const std::shared_ptr<v0::Parameter>& tti, ParameterVector& params, ResultVector& results) {+ const auto zeros = v0::Constant::create(element::i64, Shape{}, {0});++ // ---- subg1: blockwise mask, shared by both branches up to `Less` ----+ auto subg1_equal = std::make_shared<v1::Equal>(tti, v0::Constant::create(element::i64, Shape{1, 1}, {1}));+ auto subg1_pad = std::make_shared<v12::Pad>(subg1_equal,+ v0::Constant::create(element::i64, Shape{2}, {0, 1}),+ v0::Constant::create(element::i64, Shape{2}, {0, 0}),+ v0::Constant::create(element::boolean, Shape{}, {false}),+ PadMode::CONSTANT);+ auto subg1_slice = std::make_shared<v8::Slice>(subg1_pad,+ v0::Constant::create(element::i64, Shape{1}, {0}),+ v0::Constant::create(element::i64, Shape{1}, {SEQ}),+ v0::Constant::create(element::i64, Shape{1}, {1}),+ v0::Constant::create(element::i64, Shape{1}, {1}));+ auto subg1_bw_not = std::make_shared<v13::BitwiseNot>(subg1_slice);+ auto subg1_bw_and = std::make_shared<v13::BitwiseAnd>(subg1_equal, subg1_bw_not);+ auto subg1_convert = std::make_shared<v0::Convert>(subg1_bw_and, element::i32);+ auto subg1_cumsum = std::make_shared<v0::CumSum>(subg1_convert, v0::Constant::create(element::i64, Shape{}, {1}));+ auto subg1_add = std::make_shared<v1::Add>(subg1_cumsum, v0::Constant::create(element::i32, Shape{1, 1}, {-1}));+ auto subg1_convert_add = std::make_shared<v0::Convert>(subg1_add, element::i64);+ auto subg1_select = std::make_shared<v1::Select>(subg1_equal, subg1_convert_add, zeros);+ auto subg1_shape_of = std::make_shared<v3::ShapeOf>(subg1_select, element::i64);+ auto subg1_gather = std::make_shared<v8::Gather>(subg1_shape_of,+ v0::Constant::create(element::i64, Shape{}, {1}),+ v0::Constant::create(element::i32, Shape{}, {0}));++ auto range_input = make_named_param(element::i64, Shape{1, 1, 1, SEQ}, "range_input");+ auto subg1_less = std::make_shared<v1::Less>(range_input, subg1_gather);+ params.push_back(range_input);++ // ---- subg2: Reshape of `token_type_ids`, shared by both branches ----+ auto subg2_reshape = std::make_shared<v1::Reshape>(tti, v0::Constant::create(element::i64, Shape{1}, {SEQ}), false);++ std::vector<int64_t> iota_values(SEQ);+ std::iota(iota_values.begin(), iota_values.end(), 0);++ const auto row_shape = v0::Constant::create(element::i64, Shape{2}, {int64_t{1}, SEQ_I64});+ const auto col_shape = v0::Constant::create(element::i64, Shape{4}, {int64_t{1}, int64_t{1}, int64_t{1}, SEQ_I64});+ const auto group_ids = v0::Constant::create(element::i64, Shape{1, 1, SEQ, 1}, iota_values);+ const auto gather_indices = v0::Constant::create(element::i64, Shape{SEQ}, iota_values);+ const auto gather_axis = v0::Constant::create(element::i32, Shape{}, {0});++ // ---- one path per attention branch ----+ for (const char* branch : {"global", "local"}) {+ const std::string suffix = std::string("_") + branch;++ auto select_input = make_named_param(element::i64, Shape{1, 1, 1, SEQ}, "select_input" + suffix);+ auto branch_select = std::make_shared<v1::Select>(subg1_less, select_input, zeros);+ auto image_group_ids = make_named_param(element::i64, Shape{1, 1, SEQ, 1}, "image_group_ids" + suffix);+ auto branch_equal = std::make_shared<v1::Equal>(image_group_ids, branch_select);++ // First subg2 chain: Gather -> Reshape -> Reshape -> Equal.+ auto gather1 = std::make_shared<v8::Gather>(subg2_reshape, gather_indices, gather_axis);+ auto gather1_reshape = std::make_shared<v1::Reshape>(gather1, row_shape, false);+ auto gather1_reshape2 = std::make_shared<v1::Reshape>(gather1_reshape, col_shape, false);+ auto gather1_equal = std::make_shared<v1::Equal>(gather1_reshape2, group_ids);++ // Second subg2 chain: same, but with a `Select` before the `Equal`.+ auto gather2 = std::make_shared<v8::Gather>(subg2_reshape, gather_indices, gather_axis);+ auto gather2_reshape = std::make_shared<v1::Reshape>(gather2, row_shape, false);+ auto gather2_reshape2 = std::make_shared<v1::Reshape>(gather2_reshape, col_shape, false);+ auto image_token_mask = make_named_param(element::boolean, Shape{1, 1, 1, SEQ}, "image_token_mask" + suffix);+ auto gather2_select = std::make_shared<v1::Select>(image_token_mask, gather2_reshape2, zeros);+ auto gather2_equal = std::make_shared<v1::Equal>(gather2_select, group_ids);++ auto subg2_bw_and = std::make_shared<v13::BitwiseAnd>(gather1_equal, gather2_equal);+ auto vision_block = std::make_shared<v13::BitwiseAnd>(subg2_bw_and, branch_equal);+ vision_block->set_friendly_name("vision_block" + suffix);++ auto causal_mask = make_named_param(element::boolean, Shape{1, 1, SEQ, SEQ}, "causal_mask" + suffix);+ auto causal_or_vision = std::make_shared<v13::BitwiseOr>(causal_mask, vision_block);+ causal_or_vision->set_friendly_name("causal_or_vision" + suffix);++ params.insert(params.end(), {select_input, image_group_ids, image_token_mask, causal_mask});+ results.push_back(std::make_shared<v0::Result>(causal_or_vision));+ }+}++// Appends the subgraph matched by RemoveTTIShapeOfSubgraph. The `Gather` indices deliberately come+// from an `Add`: that is the node a TTI-free model reshapes against, and therefore the node the pass+// is expected to re-point the ShapeOf at.+void add_shapeof_chain(const std::shared_ptr<v0::Parameter>& tti, ParameterVector& params, ResultVector& results) {+ auto tti_shape_of = std::make_shared<v3::ShapeOf>(tti, element::i64);+ auto tti_gather = std::make_shared<v8::Gather>(tti_shape_of,+ v0::Constant::create(element::i64, Shape{}, {1}),+ v0::Constant::create(element::i32, Shape{}, {0}));+ auto tti_range = make_named_param(element::i64, Shape{1, SEQ}, "tti_range");+ auto tti_less = std::make_shared<v1::Less>(tti_range, tti_gather);+ auto tti_pos_data = make_named_param(element::i64, Shape{1, SEQ}, "tti_pos_data");+ auto tti_select =+ std::make_shared<v1::Select>(tti_less, tti_pos_data, v0::Constant::create(element::i64, Shape{}, {0}));+ auto tti_convert = std::make_shared<v0::Convert>(tti_select, element::i32);+ auto tti_add = std::make_shared<v1::Add>(tti_convert, v0::Constant::create(element::i32, Shape{1, 1}, {1}));+ tti_add->set_friendly_name("tti_add");+ auto tti_shape_of_2 = std::make_shared<v3::ShapeOf>(tti_add, element::i32);+ tti_shape_of_2->set_friendly_name("tti_shape_of_2");++ const auto row_shape = v0::Constant::create(element::i64, Shape{2}, {int64_t{1}, SEQ_I64});++ auto attention_mask = make_named_param(element::i64, Shape{1, SEQ}, "attention_mask");+ auto attn_convert = std::make_shared<v0::Convert>(attention_mask, element::boolean);+ auto attn_reshape = std::make_shared<v1::Reshape>(attn_convert, row_shape, false);++ auto attn_idx_src = make_named_param(element::i32, Shape{1, SEQ}, "attn_idx_src");+ auto attn_idx_add = std::make_shared<v1::Add>(attn_idx_src, v0::Constant::create(element::i32, Shape{1, 1}, {0}));+ attn_idx_add->set_friendly_name("attn_idx_add");++ auto attn_gather =+ std::make_shared<v8::Gather>(attn_reshape, attn_idx_add, v0::Constant::create(element::i32, Shape{}, {1}));+ auto attn_reshape_2 = std::make_shared<v1::Reshape>(attn_gather, row_shape, false);+ auto attn_tti_reshape = std::make_shared<v1::Reshape>(attn_reshape_2, tti_shape_of_2, false);+ attn_tti_reshape->set_friendly_name("attn_tti_reshape");++ auto preceding_mask = make_named_param(element::boolean, Shape{1, 1, SEQ, SEQ}, "preceding_mask");+ auto final_and = std::make_shared<v13::BitwiseAnd>(preceding_mask, attn_tti_reshape);++ params.insert(params.end(), {tti_range, tti_pos_data, attention_mask, attn_idx_src, preceding_mask});+ results.push_back(std::make_shared<v0::Result>(final_and));+}++std::shared_ptr<ov::Model> make_vision_model() {+ auto tti = make_token_type_ids();+ ParameterVector params{tti};+ ResultVector results;+ add_vision_chain(tti, params, results);+ return std::make_shared<ov::Model>(results, params, "gemma3_tti_vision");+}++std::shared_ptr<ov::Model> make_shapeof_model() {+ auto tti = make_token_type_ids();+ ParameterVector params{tti};+ ResultVector results;+ add_shapeof_chain(tti, params, results);+ return std::make_shared<ov::Model>(results, params, "gemma3_tti_shapeof");+}++std::shared_ptr<ov::Model> make_combined_model() {+ auto tti = make_token_type_ids();+ ParameterVector params{tti};+ ResultVector results;+ add_vision_chain(tti, params, results);+ add_shapeof_chain(tti, params, results);+ return std::make_shared<ov::Model>(results, params, "gemma3_tti_combined");+}++// Both known patterns plus a `token_type_ids` reader neither of them covers - stands in for e.g. an+// attention branch whose vision subgraph deviates from the matched topology.+std::shared_ptr<ov::Model> make_model_with_unmatched_consumer() {+ auto tti = make_token_type_ids();+ ParameterVector params{tti};+ ResultVector results;+ add_vision_chain(tti, params, results);+ add_shapeof_chain(tti, params, results);++ auto unmatched = std::make_shared<v1::Add>(tti, v0::Constant::create(element::i64, Shape{1, 1}, {1}));+ unmatched->set_friendly_name("unmatched_tti_consumer");+ results.push_back(std::make_shared<v0::Result>(unmatched));+ return std::make_shared<ov::Model>(results, params, "gemma3_tti_unmatched_consumer");+}++bool has_parameter_with_name(const std::shared_ptr<ov::Model>& model, const std::string& name) {+ const auto& params = model->get_parameters();+ return std::any_of(params.begin(), params.end(), [&name](const auto& param) {+ return param->get_friendly_name() == name;+ });+}++std::shared_ptr<ov::Node> find_node(const std::shared_ptr<ov::Model>& model, const std::string& name) {+ for (const auto& op : model->get_ordered_ops()) {+ if (op->get_friendly_name() == name) {+ return op;+ }+ }+ return nullptr;+}++template <typename T>+size_t count_ops_of_type(const std::shared_ptr<ov::Model>& model) {+ const auto ops = model->get_ordered_ops();+ return static_cast<size_t>(std::count_if(ops.begin(), ops.end(), [](const auto& op) {+ return ov::is_type<T>(op);+ }));+}++// ---------------------------------------------------------------------------+// Preconditions on the test models themselves+// ---------------------------------------------------------------------------++TEST(RemoveTokenTypeIdsTest, TestModelsAreValid) {+ for (const auto& model : {make_vision_model(), make_shapeof_model(), make_combined_model()}) {+ EXPECT_NO_THROW(model->validate_nodes_and_infer_types()) << "model " << model->get_friendly_name();+ EXPECT_TRUE(has_parameter_with_name(model, "token_type_ids")) << "model " << model->get_friendly_name();+ }+}++// ---------------------------------------------------------------------------+// Negative case: nothing to do+// ---------------------------------------------------------------------------++TEST(RemoveTokenTypeIdsTest, NoOpWhenTokenTypeIdsAbsent) {+ auto input = make_named_param(element::f32, Shape{1, SEQ}, "input_ids");+ auto model = std::make_shared<ov::Model>(ResultVector{std::make_shared<v0::Result>(input)},+ ParameterVector{input},+ "no_tti_model");++ ov::npuw::RemoveTokenTypeIds pass;+ EXPECT_FALSE(pass.run_on_model(model));+ EXPECT_TRUE(has_parameter_with_name(model, "input_ids"));+}++// ---------------------------------------------------------------------------+// RemoveTTIVisionSubgraph+// ---------------------------------------------------------------------------++TEST(RemoveTokenTypeIdsTest, VisionPattern_VisionBlockReplacedWithFalseConstant) {+ auto model = make_vision_model();++ ov::npuw::RemoveTokenTypeIds pass;+ EXPECT_TRUE(pass.run_on_model(model));++ size_t bw_or_count = 0;+ for (const auto& op : model->get_ordered_ops()) {+ if (!ov::is_type<v13::BitwiseOr>(op)) {+ continue;+ }+ ++bw_or_count;+ auto vision_input = ov::as_type_ptr<v0::Constant>(op->input_value(1).get_node_shared_ptr());+ ASSERT_NE(vision_input, nullptr) << "BitwiseOr input[1] must be replaced with a Constant";+ EXPECT_EQ(vision_input->get_element_type(), element::boolean);+ const auto values = vision_input->cast_vector<bool>();+ ASSERT_EQ(values.size(), 1u);+ EXPECT_FALSE(values[0]) << "the vision block must be neutralized with `false`";+ }+ EXPECT_EQ(bw_or_count, 2u) << "both the global and the local attention branch must be patched";+ EXPECT_NO_THROW(model->validate_nodes_and_infer_types());+}++TEST(RemoveTokenTypeIdsTest, VisionPattern_CausalMaskInputPreserved) {+ auto model = make_vision_model();++ ov::npuw::RemoveTokenTypeIds pass;+ ASSERT_TRUE(pass.run_on_model(model));++ std::set<std::string> causal_inputs;+ for (const auto& op : model->get_ordered_ops()) {+ if (ov::is_type<v13::BitwiseOr>(op)) {+ causal_inputs.insert(op->input_value(0).get_node()->get_friendly_name());+ }+ }+ const std::set<std::string> expected{"causal_mask_global", "causal_mask_local"};+ EXPECT_EQ(causal_inputs, expected) << "input[0] of each BitwiseOr must still be the causal mask";+}++TEST(RemoveTokenTypeIdsTest, VisionPattern_UnusedSubgraphIsRemoved) {+ auto model = make_vision_model();+ ASSERT_GT(count_ops_of_type<v0::CumSum>(model), 0u);+ ASSERT_GT(count_ops_of_type<v12::Pad>(model), 0u);++ ov::npuw::RemoveTokenTypeIds pass;+ ASSERT_TRUE(pass.run_on_model(model));++ // Neutralizing the merge points drops the last consumer of the whole vision subgraph.+ EXPECT_EQ(count_ops_of_type<v0::CumSum>(model), 0u);+ EXPECT_EQ(count_ops_of_type<v12::Pad>(model), 0u);+ EXPECT_EQ(count_ops_of_type<v13::BitwiseNot>(model), 0u);+ EXPECT_FALSE(has_parameter_with_name(model, "token_type_ids"));+}++// ---------------------------------------------------------------------------+// RemoveTTIShapeOfSubgraph+// ---------------------------------------------------------------------------++TEST(RemoveTokenTypeIdsTest, ShapeOfPattern_ShapeOfRedirectedToGatherIndices) {+ auto model = make_shapeof_model();++ auto shape_of_2 = find_node(model, "tti_shape_of_2");+ ASSERT_NE(shape_of_2, nullptr);+ ASSERT_EQ(shape_of_2->input_value(0).get_node()->get_friendly_name(), "tti_add")+ << "before the pass the Reshape target shape is derived from `token_type_ids`";++ ov::npuw::RemoveTokenTypeIds pass;+ EXPECT_TRUE(pass.run_on_model(model));++ shape_of_2 = find_node(model, "tti_shape_of_2");+ ASSERT_NE(shape_of_2, nullptr) << "the ShapeOf itself must survive - only its input is re-pointed";+ EXPECT_EQ(shape_of_2->input_value(0).get_node()->get_friendly_name(), "attn_idx_add")+ << "after the pass it must be derived from the attention_mask Gather indices";++ EXPECT_FALSE(has_parameter_with_name(model, "token_type_ids"));+ EXPECT_NO_THROW(model->validate_nodes_and_infer_types());+}++TEST(RemoveTokenTypeIdsTest, ShapeOfPattern_AttentionMaskChainPreserved) {+ auto model = make_shapeof_model();+ const auto reshapes_before = count_ops_of_type<v1::Reshape>(model);+ const auto gathers_before = count_ops_of_type<v8::Gather>(model);++ ov::npuw::RemoveTokenTypeIds pass;+ ASSERT_TRUE(pass.run_on_model(model));++ // Only the TTI-side Gather goes away; every Reshape of the attention_mask chain stays.+ EXPECT_EQ(count_ops_of_type<v1::Reshape>(model), reshapes_before);+ EXPECT_EQ(count_ops_of_type<v8::Gather>(model), gathers_before - 1);+ EXPECT_NE(find_node(model, "attn_tti_reshape"), nullptr);+ EXPECT_NE(find_node(model, "attn_idx_add"), nullptr);+ EXPECT_TRUE(has_parameter_with_name(model, "attention_mask"));+ EXPECT_TRUE(has_parameter_with_name(model, "attn_idx_src"));+ EXPECT_TRUE(has_parameter_with_name(model, "preceding_mask"));+}++// ---------------------------------------------------------------------------+// Both patterns together+// ---------------------------------------------------------------------------++TEST(RemoveTokenTypeIdsTest, CombinedPatterns_TokenTypeIdsRemoved) {+ auto model = make_combined_model();+ const auto params_before = model->get_parameters().size();++ ov::npuw::RemoveTokenTypeIds pass;+ EXPECT_TRUE(pass.run_on_model(model));++ EXPECT_FALSE(has_parameter_with_name(model, "token_type_ids"));+ EXPECT_EQ(model->get_parameters().size(), params_before - 1)+ << "`token_type_ids` must be the only parameter removed";+ for (const char* name : {"range_input",+ "select_input_global",+ "image_group_ids_global",+ "image_token_mask_global",+ "causal_mask_global",+ "select_input_local",+ "image_group_ids_local",+ "image_token_mask_local",+ "causal_mask_local",+ "tti_range",+ "tti_pos_data",+ "attention_mask",+ "attn_idx_src",+ "preceding_mask"}) {+ EXPECT_TRUE(has_parameter_with_name(model, name)) << "parameter `" << name << "` must be preserved";+ }+ EXPECT_NO_THROW(model->validate_nodes_and_infer_types());+}++// ---------------------------------------------------------------------------+// Removal contract: a consumer surviving the rewrites is a hard error+// ---------------------------------------------------------------------------++TEST(RemoveTokenTypeIdsTest, ThrowsWhenUnmatchedConsumerRemains) {+ auto model = make_model_with_unmatched_consumer();++ // Both known patterns fire and rewrite the graph, but an unmatched reader still holds+ // `token_type_ids`. The model is partially transformed by now - one attention branch would keep+ // its vision mask while another lost it - so the pass must fail loudly rather than hand back a+ // model that infers and silently produces wrong results.+ ov::npuw::RemoveTokenTypeIds pass;+ try {+ pass.run_on_model(model);+ FAIL() << "expected a throw on a `token_type_ids` consumer that neither pattern covers";+ } catch (const ov::Exception& e) {+ // The diagnostic has to name the offender - that is the only lead for extending the pattern.+ const std::string message = e.what();+ EXPECT_NE(message.find("token_type_ids"), std::string::npos) << message;+ EXPECT_NE(message.find("unmatched_tti_consumer"), std::string::npos) << message;+ }+}++TEST(RemoveTokenTypeIdsTest, SecondRunIsNoOp) {+ auto model = make_combined_model();++ ov::npuw::RemoveTokenTypeIds first;+ ASSERT_TRUE(first.run_on_model(model));+ ASSERT_FALSE(has_parameter_with_name(model, "token_type_ids"));++ ov::npuw::RemoveTokenTypeIds second;+ EXPECT_FALSE(second.run_on_model(model));+ EXPECT_NO_THROW(model->validate_nodes_and_infer_types());+}++} // namespace