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 for qwen3-vl models (#35349)
guweixin04395695da73
diff --git a/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.cppindex 7f3e374a439..5bacf2144bf 100644--- a/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.cpp@@ -94,8 +94,12 @@ ov::SoPtr<ov::ITensor> ov::npuw::IBaseInferRequest::get_tensor(const ov::Output<}}- NPUW_ASSERT(false);- return {};+ std::string requested_port_name{"<unnamed>"};+ const auto& port_names = port.get_names();+ if (!port_names.empty()) {+ requested_port_name = *port_names.begin();+ }+ OPENVINO_THROW("NPUW get_tensor(): requested port is not a top-level input/output: ", requested_port_name);}void ov::npuw::IBaseInferRequest::set_tensor(const ov::Output<const ov::Node>& port,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 31fa12c095e..0cdb064e9f4 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@@ -17,6 +17,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/replace_deepstack_scatter_with_add.hpp"#include "npuw_transformations/reshape_sliced_head_to_static.hpp"#include "npuw_transformations/reshape_to_static.hpp"#include "npuw_transformations/slice_out_embeds.hpp"@@ -836,6 +837,8 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mm_bf16_consts = ov::npuw::s11n::get_bf16_consts(model);ov::pass::ConvertPrecision(ov::element::bf16, ov::element::f16).run_on_model(kvcache_model);+ ov::npuw::ReplaceDeepstackScatterWithAdd().run_on_model(kvcache_model);+auto lm_head_model = check_and_cut_lm_head(kvcache_model, m_cfg);if (!m_is_whisper) {@@ -1028,14 +1031,12 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mmerge_config_with(generate_config, other_props);merge_config_with(prefill_config, prefill_config_addition_value);merge_config_with(generate_config, generate_config_addition_value);-if (user_compilation_mode_params.has_value() && default_compilation_mode_params.has_value() &&user_compilation_mode_params.value() != default_compilation_mode_params.value()) {LOG_WARN("User-provided NPU_COMPILATION_MODE_PARAMS overrides arch-aware setting \""<< default_compilation_mode_params.value() << "\". User value: \""<< user_compilation_mode_params.value() << "\".");}-// Generate a random weights bank name unique to this LLMCompiledModel objectauto weights_bank_name = ov::npuw::util::generate_random_string();LOG_VERB("Generated a unique weights bank name: " << weights_bank_name);@@ -1137,7 +1138,6 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m}}}-// Regularize models for the better partitioning assuming it is a transformer// Apply these transformations to all variant models{diff --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 e973f585c18..13e97fbf64e 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@@ -23,6 +23,9 @@ public:}};+constexpr const char* kVisualPosMasksParamName = "visual_pos_masks";+constexpr const char* kDeepstackVisualEmbedsParamName = "deepstack_visual_embeds";+bool has_input(const std::shared_ptr<ov::Model>& model, const std::string& name);// clang-format offdiff --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 7537cffb65a..dbe1252935b 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@@ -5,6 +5,7 @@#pragma once#include "llm_compiled_model.hpp"+#include "llm_compiled_model_utils.hpp"#include "openvino/core/descriptor/output.hpp"#include "openvino/runtime/isync_infer_request.hpp"@@ -24,6 +25,8 @@ public:static constexpr const char* token_type_ids = "token_type_ids";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;+ static constexpr const char* deepstack_visual_embeds = ov::npuw::util::kDeepstackVisualEmbedsParamName;};struct layer_ids {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 cb43940802a..fd2b197849b 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@@ -4,6 +4,8 @@#include "llm_infer_request.hpp"+#include <algorithm>+#include <cmath>#include <regex>#include "infer_request_utils.hpp"@@ -91,6 +93,122 @@ 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);}+bool is_nonzero_value(const ov::SoPtr<ov::ITensor>& tensor, size_t idx) {+ switch (tensor->get_element_type()) {+ case ov::element::i64:+ return tensor->data<int64_t>()[idx] != 0;+ case ov::element::i32:+ return tensor->data<int32_t>()[idx] != 0;+ case ov::element::u8:+ return tensor->data<uint8_t>()[idx] != 0;+ case ov::element::boolean:+ return tensor->data<bool>()[idx];+ case ov::element::f32:+ return std::fabs(tensor->data<float>()[idx]) > 0.f;+ case ov::element::f16:+ return tensor->data<ov::float16>()[idx] != ov::float16(0.f);+ default:+ OPENVINO_THROW("Unsupported visual_pos_masks source type: ", tensor->get_element_type());+ }+}++// Counts visual tokens (non-zero mask entries) located strictly before sequence position+// `seq_limit`. Used by chunked prefill to compute the deepstack row offset of a chunk: the+// deepstack rows of a chunk follow those of all earlier chunks (visual-token order).+size_t count_visual_tokens_before(const ov::SoPtr<ov::ITensor>& mask, size_t seq_limit) {+ if (!mask || seq_limit == 0) {+ return 0;+ }+ const size_t seq_len = mask->get_shape().back();+ size_t count = 0;+ for (size_t i = 0; i < mask->get_size(); ++i) {+ if ((i % seq_len) < seq_limit && is_nonzero_value(mask, i)) {+ ++count;+ }+ }+ return count;+}++// Scatters the compact deepstack_visual_embeds tensor (one row per visual token, in+// visual-token order) into the right-aligned static destination at the actual+// visual-token sequence positions described by visual_pos_masks.+//+// After the DeepStack gather/scatter cluster is replaced in the graph by a plain+// dense residual add (see ov::npuw::ReplaceDeepstackScatterWithAdd in+// npuw_transformations/replace_deepstack_scatter_with_add.cpp), the destination tensor+// must hold deepstack values at the visual positions and zeros+// everywhere else, so that "hidden + deepstack" reproduces the original per-position+// injection.+//+// src : [num_layers, N, emb] (N visual tokens, k-th row = k-th visual token)+// mask : [batch, real_len] (non-zero at visual-token positions, ascending)+// dst : [num_layers, seq, emb] (right-aligned static window)+//+// `src_row_offset` skips the first deepstack rows (visual tokens already handled by earlier+// chunks in chunked prefill); it is 0 for whole prefill. Returns the number of visual tokens+// (deepstack rows) actually scattered, so the caller can advance `src_row_offset` for the next+// chunk.+//+// Real tokens are right-aligned, so a visual token at real-sequence coordinate `c`+// lands at static position `c + (seq - real_len)`.+size_t scatter_deepstack_visual_embeds(const ov::SoPtr<ov::ITensor>& src,+ const ov::SoPtr<ov::ITensor>& mask,+ const ov::SoPtr<ov::ITensor>& dst,+ size_t src_row_offset = 0) {+ OPENVINO_ASSERT(dst);+ std::fill_n(reinterpret_cast<uint8_t*>(dst->data()), dst->get_byte_size(), 0);++ if (!src || !mask) {+ return 0;+ }+ if (src->get_element_type() != dst->get_element_type()) {+ return 0;+ }++ const auto& src_shape = src->get_shape();+ const auto& dst_shape = dst->get_shape();+ if (src_shape.size() != 3u || dst_shape.size() != 3u) {+ return 0;+ }++ const size_t num_layers = src_shape[0];+ const size_t src_seq = src_shape[1];+ const size_t emb = src_shape[2];+ const size_t dst_seq = dst_shape[1];+ if (dst_shape[0] != num_layers || dst_shape[2] != emb) {+ return 0;+ }++ const size_t mask_total = mask->get_size();+ OPENVINO_ASSERT(mask_total <= dst_seq);+ // Real tokens are right-aligned in the static window, i.e. left-padded, so this is the+ // amount of left padding (offset of the first real/masked position in dst).+ const size_t seq_left_pad = dst_seq - mask_total;++ const size_t elem_size = src->get_element_type().size();+ const size_t row_bytes = emb * elem_size;+ const auto* src_ptr = static_cast<const uint8_t*>(src->data());+ auto* dst_ptr = static_cast<uint8_t*>(dst->data());++ // Iterate visual-token positions in ascending order; the k-th non-zero mask entry+ // corresponds to deepstack row (src_row_offset + k).+ size_t k = 0;+ for (size_t linear_idx = 0; linear_idx < mask_total; ++linear_idx) {+ if (!is_nonzero_value(mask, linear_idx)) {+ continue;+ }+ OPENVINO_ASSERT(src_row_offset + k < src_seq, "More visual tokens in mask than rows in deepstack source");+ const size_t dst_pos = linear_idx + seq_left_pad;+ for (size_t l = 0; l < num_layers; ++l) {+ const auto* src_row = src_ptr + (l * src_seq + src_row_offset + k) * row_bytes;+ auto* dst_row = dst_ptr + (l * dst_seq + dst_pos) * row_bytes;+ std::copy_n(src_row, row_bytes, dst_row);+ }+ ++k;+ }+ return k;+}+void process_longrope(const std::shared_ptr<ov::IAsyncInferRequest>& infer_req,const LLMInferRequest::PortsMap& ports,const ov::SoPtr<ov::ITensor>& position_ids) {@@ -658,7 +776,9 @@ void ov::npuw::LLMInferRequest::clear_chunk_prefill_kv_cache() {void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> input_ids,ov::SoPtr<ov::ITensor> attention_mask,ov::SoPtr<ov::ITensor> position_ids,- ov::SoPtr<ov::ITensor> per_layer_inputs) {+ ov::SoPtr<ov::ITensor> per_layer_inputs,+ ov::SoPtr<ov::ITensor> visual_pos_masks,+ ov::SoPtr<ov::ITensor> deepstack_visual_embeds) {LOG_DEBUG("Calling chunked inference for prefill model.");LOG_BLOCK();@@ -672,6 +792,15 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inpauto input_ids_in_tensor = m_prefill_request->get_tensor(m_prefill_in_ports.at(m_input_ids_name));const uint64_t chunk_prompt_len = m_npuw_llm_compiled_model->m_prefill_chunk_size;+ // DeepStack (Qwen3-VL): the deepstack injection is scattered per chunk inside the loop+ // below, the same way attention_mask / input_ids are sliced for the current chunk.+ const auto deepstack_it = m_prefill_in_ports.find(layer_names::deepstack_visual_embeds);+ const bool has_deepstack = deepstack_it != m_prefill_in_ports.end();+ if (has_deepstack) {+ OPENVINO_ASSERT(deepstack_visual_embeds && visual_pos_masks,+ "deepstack_visual_embeds and visual_pos_masks must be provided for DeepStack VLM prefill.");+ }+auto attn_mask_in_tensor = m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::attention_mask));auto pos_ids_in_tensor = m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::position_ids));@@ -691,6 +820,11 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inpm_eagle3_ext.reset_chunked_prefill_state();}+ // DeepStack rows are consumed in visual-token order across chunks; track how many have+ // already been scattered so each chunk continues where the previous one left off.+ size_t visual_tokens_scattered =+ has_deepstack ? count_visual_tokens_before(visual_pos_masks, kvcache_desc.num_stored_tokens) : 0u;+while (remaining_prompts > 0) {// NB: input_ids can be either fp32(VLM) or i64(LLM)// The last chunk may not be completely filled if the actual length of the prompts is not evenly divisible by@@ -752,6 +886,23 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inp// Copy with proper stride handlingactual_position_ids_slice->copy_to(pos_ids_slice._ptr);+ // DeepStack (Qwen3-VL): scatter only the visual tokens that fall into the current+ // chunk. The chunk's visual_pos_masks slice gives their chunk-local positions, and+ // the deepstack rows for those tokens follow the visual tokens of earlier chunks.+ if (has_deepstack) {+ auto deepstack_local = m_prefill_request->get_tensor(deepstack_it->second);+ const uint32_t seq_dim = static_cast<uint32_t>(visual_pos_masks->get_shape().size() - 1);+ auto chunk_mask = ov::npuw::util::make_tensor_slice(+ visual_pos_masks,+ seq_dim,+ static_cast<uint32_t>(kvcache_desc.num_stored_tokens),+ static_cast<uint32_t>(kvcache_desc.num_stored_tokens + current_prompts_len));+ visual_tokens_scattered += scatter_deepstack_visual_embeds(deepstack_visual_embeds,+ chunk_mask._ptr,+ deepstack_local,+ visual_tokens_scattered);+ }+if (m_eagle3_ext.is_eagle3_model()) {m_eagle3_ext.prepare_inputs_for_chunk(m_prefill_request,m_prefill_in_ports,@@ -835,7 +986,9 @@ void ov::npuw::LLMInferRequest::infer_whole_prefill(ov::SoPtr<ov::ITensor> inputov::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) {+ ov::SoPtr<ov::ITensor> per_layer_inputs,+ ov::SoPtr<ov::ITensor> visual_pos_masks,+ ov::SoPtr<ov::ITensor> deepstack_visual_embeds) {LOG_DEBUG("Calling inference for prefill model in a single launch.");LOG_BLOCK();@@ -864,6 +1017,14 @@ void ov::npuw::LLMInferRequest::infer_whole_prefill(ov::SoPtr<ov::ITensor> inputauto padded_position_ids = m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::position_ids));ov::npuw::util::pad_position_ids(padded_position_ids, position_ids);+ if (const auto deepstack_it = m_prefill_in_ports.find(layer_names::deepstack_visual_embeds);+ deepstack_it != m_prefill_in_ports.end()) {+ OPENVINO_ASSERT(deepstack_visual_embeds && visual_pos_masks,+ "deepstack_visual_embeds and visual_pos_masks must be provided for DeepStack VLM prefill.");+ auto deepstack_local = m_prefill_request->get_tensor(deepstack_it->second);+ scatter_deepstack_visual_embeds(deepstack_visual_embeds, visual_pos_masks, deepstack_local);+ }+if (m_eagle3_ext.is_eagle3_model()) {m_eagle3_ext.prepare_inputs(m_prefill_request, m_prefill_in_ports);}@@ -890,7 +1051,9 @@ void ov::npuw::LLMInferRequest::infer_prefill(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) {+ ov::SoPtr<ov::ITensor> per_layer_inputs,+ ov::SoPtr<ov::ITensor> visual_pos_masks,+ ov::SoPtr<ov::ITensor> deepstack_visual_embeds) {LOG_DEBUG("Calling inference for prefill model...");LOG_BLOCK();@@ -919,9 +1082,20 @@ void ov::npuw::LLMInferRequest::infer_prefill(ov::SoPtr<ov::ITensor> input_ids,OPENVINO_ASSERT(!token_type_ids,"Chunking is not implemented for Gemma model family yet. ""Please set NPUW_LLM_PREFILL_HINT to 'STATIC'");- infer_chunked_prefill(input_ids, attention_mask, position_ids, per_layer_inputs);+ infer_chunked_prefill(input_ids,+ attention_mask,+ position_ids,+ per_layer_inputs,+ visual_pos_masks,+ deepstack_visual_embeds);} else {- infer_whole_prefill(input_ids, attention_mask, position_ids, token_type_ids, per_layer_inputs);+ infer_whole_prefill(input_ids,+ attention_mask,+ position_ids,+ token_type_ids,+ per_layer_inputs,+ visual_pos_masks,+ deepstack_visual_embeds);}});@@ -1002,6 +1176,13 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,OPENVINO_THROW("KV-Cache is full.");}+ if (const auto deepstack_it = m_kvcache_in_ports.find(layer_names::deepstack_visual_embeds);+ deepstack_it != m_kvcache_in_ports.end()) {+ auto deepstack_local = m_kvcache_request->get_tensor(deepstack_it->second);+ // No visual tokens are generated during the generate stage+ std::fill_n(reinterpret_cast<uint8_t*>(deepstack_local->data()), deepstack_local->get_byte_size(), 0);+ }+process_longrope(m_kvcache_request, m_kvcache_in_ports, position_ids);// FIXME: these tensors should be shared between the parent & child models// NB: input_ids can be either fp32(VLM) or i64(LLM)@@ -1128,12 +1309,21 @@ void ov::npuw::LLMInferRequest::infer() {}auto token_type_ids = ov::npuw::util::TensorPtr();-if (auto type_ids_port = ov::npuw::util::find_port_by_name(inputs, layer_names::token_type_ids);type_ids_port.has_value()) {token_type_ids = get_tensor(type_ids_port.value());}+ auto visual_pos_masks = ov::npuw::util::TensorPtr();+ if (auto port = ov::npuw::util::find_port_by_name(inputs, layer_names::visual_pos_masks); port.has_value()) {+ visual_pos_masks = get_tensor(port.value());+ }++ auto deepstack_visual_embeds = ov::npuw::util::TensorPtr();+ if (auto port = ov::npuw::util::find_port_by_name(inputs, layer_names::deepstack_visual_embeds); port.has_value()) {+ deepstack_visual_embeds = get_tensor(port.value());+ }+// Gemma4: Extract per_layer_inputs if presentauto per_layer_inputs = ov::npuw::util::TensorPtr();if (auto per_layer_port = ov::npuw::util::find_port_by_name(inputs, layer_names::per_layer_inputs);@@ -1186,7 +1376,13 @@ void ov::npuw::LLMInferRequest::infer() {// both main and draft models for most of LLMs.if (input_ids->get_shape()[layer_ids::INPUT_IDS_SEQ_LEN_DIM] > 1 &&position_ids->data<int64_t>()[0] == m_first_position_id) {- infer_prefill(input_ids, attention_mask, position_ids, token_type_ids, per_layer_inputs);+ infer_prefill(input_ids,+ attention_mask,+ position_ids,+ token_type_ids,+ per_layer_inputs,+ visual_pos_masks,+ deepstack_visual_embeds);} else {// FIXME: Need to make the solution smarter.// Qwen2.5VL uses 3D position_ids but current `trim_kvcache_for_speculative_decoding`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 e5c008b048c..d219f049ca0 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@@ -54,19 +54,25 @@ protected:void infer_chunked_prefill(ov::SoPtr<ov::ITensor> input_ids,ov::SoPtr<ov::ITensor> attention_mask,ov::SoPtr<ov::ITensor> position_ids,- ov::SoPtr<ov::ITensor> per_layer_inputs);+ ov::SoPtr<ov::ITensor> per_layer_inputs,+ ov::SoPtr<ov::ITensor> visual_pos_masks,+ ov::SoPtr<ov::ITensor> deepstack_visual_embeds);void infer_whole_prefill(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);+ ov::SoPtr<ov::ITensor> per_layer_inputs,+ ov::SoPtr<ov::ITensor> visual_pos_masks,+ ov::SoPtr<ov::ITensor> deepstack_visual_embeds);void infer_prefill(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);+ ov::SoPtr<ov::ITensor> per_layer_inputs,+ ov::SoPtr<ov::ITensor> visual_pos_masks,+ ov::SoPtr<ov::ITensor> deepstack_visual_embeds);void infer_generate(ov::SoPtr<ov::ITensor> input_ids,ov::SoPtr<ov::ITensor> attention_mask,diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/replace_deepstack_scatter_with_add.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/replace_deepstack_scatter_with_add.cppnew file mode 100644index 00000000000..e962e54bb58--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/replace_deepstack_scatter_with_add.cpp@@ -0,0 +1,182 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "replace_deepstack_scatter_with_add.hpp"++#include <string>+#include <unordered_set>+#include <vector>++#include "../llm_compiled_model_utils.hpp"+#include "openvino/core/rt_info.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/gather_nd.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/scatter_nd_update.hpp"+#include "openvino/pass/graph_rewrite.hpp"+#include "openvino/pass/pattern/matcher.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "openvino/pass/validate.hpp"++namespace opp = ov::pass::pattern;++namespace {++bool is_named(const std::shared_ptr<ov::Node>& node, const std::string& needle) {+ if (!node) {+ return false;+ }+ if (node->get_friendly_name().find(needle) != std::string::npos) {+ return true;+ }+ for (const auto& name : node->output(0).get_names()) {+ if (name.find(needle) != std::string::npos) {+ return true;+ }+ }+ return false;+}++// Returns the unique consumer of `node` whose op type name matches `type_name`,+// or nullptr if there is none or more than one.+std::shared_ptr<ov::Node> single_consumer_of_type(const std::shared_ptr<ov::Node>& node, const std::string& type_name) {+ std::shared_ptr<ov::Node> found;+ for (const auto& target : node->output(0).get_target_inputs()) {+ auto* consumer = target.get_node();+ if (std::string(consumer->get_type_name()) == type_name) {+ if (found) {+ return nullptr; // ambiguous - bail out+ }+ found = consumer->shared_from_this();+ }+ }+ return found;+}++// True if `target` is backward-reachable from any Result/Sink of the model (i.e. still alive).+bool is_reachable_from_outputs(const std::shared_ptr<ov::Model>& model, const ov::Node* target) {+ std::unordered_set<const ov::Node*> visited;+ std::vector<ov::Node*> stack;+ for (const auto& result : model->get_results()) {+ stack.push_back(result.get());+ }+ for (const auto& sink : model->get_sinks()) {+ stack.push_back(sink.get());+ }+ while (!stack.empty()) {+ auto* node = stack.back();+ stack.pop_back();+ if (node == target) {+ return true;+ }+ if (!visited.insert(node).second) {+ continue;+ }+ for (const auto& input : node->inputs()) {+ stack.push_back(input.get_source_output().get_node());+ }+ }+ return false;+}++// diagnostics warnings on OPENVINO_MATCHER_PASS_RTTI() definition: visibility hidden+#ifdef __GNUC__+# pragma GCC diagnostic push+# pragma GCC diagnostic ignored "-Wattributes"+#endif++// Matches a single Qwen3-VL DeepStack injection+// ScatterNDUpdate(hidden, pos, Add(GatherND(hidden, pos), Gather(deepstack, L)))+// and replaces it (plus the optional SliceAssign identity wrapper that follows) with a+// plain residual add: hidden + Gather(deepstack, L).+class DeepstackScatterToAdd : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("ov::npuw::DeepstackScatterToAdd");+ explicit DeepstackScatterToAdd(bool& matched) {+ auto deepstack = opp::wrap_type<ov::op::v0::Parameter>();+ auto select = opp::wrap_type<ov::op::v8::Gather, ov::op::v7::Gather, ov::op::v1::Gather>(+ {deepstack, opp::any_input(), opp::any_input()});+ auto gathered =+ opp::wrap_type<ov::op::v8::GatherND, ov::op::v5::GatherND>({opp::any_input(), opp::any_input()});+ auto add = opp::wrap_type<ov::op::v1::Add>({gathered, select});+ auto scatter = opp::wrap_type<ov::op::v3::ScatterNDUpdate, ov::op::v15::ScatterNDUpdate>(+ {opp::any_input(), opp::any_input(), add});++ auto callback = [=, &matched](opp::Matcher& m) {+ const auto& pattern_map = m.get_pattern_value_map();++ // The Add/GatherND/ScatterNDUpdate shape is generic; only accept it when the gathered+ // parameter is really deepstack_visual_embeds.+ if (!is_named(pattern_map.at(deepstack).get_node_shared_ptr(),+ ov::npuw::util::kDeepstackVisualEmbedsParamName)) {+ return false;+ }++ auto select_node = pattern_map.at(select).get_node_shared_ptr();+ auto scatter_node = pattern_map.at(scatter).get_node_shared_ptr();+ auto base = scatter_node->input_value(0);++ // The scatter result is wrapped by a SliceAssign (Reshape -> ScatterNDUpdate -> Reshape)+ // identity that writes the whole tensor back. Bypass it as well when present.+ ov::Output<ov::Node> cluster_out = scatter_node->output(0);+ if (auto reshape_in = single_consumer_of_type(scatter_node, "Reshape")) {+ if (auto slice_scatter = single_consumer_of_type(reshape_in, "ScatterNDUpdate")) {+ if (auto reshape_out = single_consumer_of_type(slice_scatter, "Reshape")) {+ cluster_out = reshape_out->output(0);+ }+ }+ }++ // hidden + Gather(deepstack, L). The host pre-scatters the deepstack values into their+ // visual-token positions (zeros elsewhere), so a plain broadcasted add reproduces the+ // original per-position injection.+ auto residual = std::make_shared<ov::op::v1::Add>(base, select_node->output(0));+ residual->set_friendly_name(select_node->get_friendly_name() + "/npuw_deepstack_residual_add");+ ov::copy_runtime_info(cluster_out.get_node_shared_ptr(), residual);++ for (auto& target : cluster_out.get_target_inputs()) {+ target.replace_source_output(residual->output(0));+ }+ register_new_node(residual);+ matched = true;+ return true;+ };+ register_matcher(std::make_shared<opp::Matcher>(scatter, "ov::npuw::DeepstackScatterToAdd"),+ std::move(callback));+ }+};++#ifdef __GNUC__+# pragma GCC diagnostic pop+#endif++} // namespace++namespace ov::npuw {++bool ReplaceDeepstackScatterWithAdd::run_on_model(const std::shared_ptr<ov::Model>& model) {+ bool matched = false;+ ov::pass::GraphRewrite rewr;+ rewr.add_matcher<DeepstackScatterToAdd>(matched);+ rewr.run_on_model(model);++ if (!matched) {+ return false;+ }++ // The visual_pos_masks input now only feeds the dead gather/scatter cluster; drop it.+ for (const auto& param : model->get_parameters()) {+ if (is_named(param, ov::npuw::util::kVisualPosMasksParamName) &&+ !is_reachable_from_outputs(model, param.get())) {+ model->remove_parameter(param);+ break;+ }+ }++ ov::pass::Validate().run_on_model(model);+ return true;+}++} // namespace ov::npuwdiff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/replace_deepstack_scatter_with_add.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/replace_deepstack_scatter_with_add.hppnew file mode 100644index 00000000000..e9b879553b6--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/replace_deepstack_scatter_with_add.hpp@@ -0,0 +1,34 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <memory>++#include "openvino/pass/pass.hpp"++namespace ov::npuw {++// Replaces the Qwen3-VL "DeepStack" per-position scatter injection with a plain+// residual add and drops the now-unused visual_pos_masks model input.+//+// In the source model each deepstack level L is injected into the hidden states only+// at the visual-token positions via+// ScatterNDUpdate(hidden, pos, GatherND(hidden, pos) + Gather(deepstack, L)).+// NPUW runs a static pipeline where the host can instead pre-scatter the deepstack+// values into their sequence positions, so the graph only needs+// hidden + Gather(deepstack, L)+// (zeros at non-visual positions make the add a no-op there). This removes the+// data-dependent NonZero/GatherND/ScatterNDUpdate ops and the visual_pos_masks input,+// while keeping deepstack_visual_embeds as a single [num_layers, seq, emb] input.+//+// This is a ModelPass (not a MatcherPass) because it removes a model parameter; the+// node-level rewrite is done by an inner MatcherPass.+class ReplaceDeepstackScatterWithAdd : public ov::pass::ModelPass {+public:+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::ReplaceDeepstackScatterWithAdd");+ 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/reshape_to_static.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.cppindex 17c55cdb469..49d285f7f63 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.cpp@@ -32,11 +32,36 @@ void reshape_to_static(std::shared_ptr<ov::Model> model,NPUW_ASSERT(input.get_partial_shape().size() == 3u);NPUW_ASSERT(input.get_partial_shape()[2].is_static());new_shape = ov::PartialShape({1, input_size, input.get_partial_shape()[2]});+ } else if (input_name.find(ov::npuw::util::kDeepstackVisualEmbedsParamName) != std::string::npos) {+ // NB: VLMs case (Qwen3-VL "DeepStack"). The parameter has shape+ // [num_deepstack_layers, num_visual_tokens, EMB_SIZE]: dim 0 selects one of+ // several intermediate ViT feature levels (consumed by Gather/select ops),+ // it is NOT a batch dimension. Both num_deepstack_layers and num_visual_tokens+ // are dynamic in the source model. The visual-token dim is made static to+ // input_size, while the layer dim must be resolved to its real (static) value -+ // collapsing it to 1 silently drops every deepstack level but the first.+ const auto& partial_shape = input.get_partial_shape();+ NPUW_ASSERT(partial_shape.size() == 3u);+ NPUW_ASSERT(partial_shape[2].is_static());+ ov::Dimension num_layers = partial_shape[0];+ if (!num_layers.is_static()) {+ // Resolve the number of deepstack layers from the parameter's consumers:+ // each deepstack level is read by exactly one consumer (a Gather/select+ // along dim 0), so the number of readers equals the number of levels.+ const size_t num_readers = input.get_target_inputs().size();+ if (num_readers > 0) {+ num_layers = ov::Dimension(static_cast<int64_t>(num_readers));+ }+ }+ NPUW_ASSERT(num_layers.is_static()); // num_deepstack_layers must be resolved+ new_shape = ov::PartialShape({num_layers, input_size, partial_shape[2]});} else if (input_name.find("attention_mask") != std::string::npos) {new_shape = ov::PartialShape({1, kvcache_size});if (lhs_seq_size && !is_prefill)// NB: for whisper kvcache model attn mask should be size + 1new_shape = ov::PartialShape({1, kvcache_size + 1});+ } else if (input_name.find(ov::npuw::util::kVisualPosMasksParamName) != std::string::npos) {+ new_shape = ov::PartialShape({1, input_size});} else if (input_name.find("position_ids") != std::string::npos) {const auto partial_shape_size = input.get_partial_shape().size();// NB: Regular LLM uses 2D shapes, Qwen2.5 VL/Omni, Qwen3.5 VL use 3D shapesdiff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex fc970f3d4c5..6851452b87a 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -108,6 +108,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/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/replace_deepstack_scatter_with_add.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/slice_out_embeds.cpp# kokoro pipeline${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/pipelines/kokoro/kokoro_compiled_model.cppdiff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/replace_deepstack_scatter_with_add_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/replace_deepstack_scatter_with_add_test.cppnew file mode 100644index 00000000000..e4555f5f780--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/replace_deepstack_scatter_with_add_test.cpp@@ -0,0 +1,191 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <gtest/gtest.h>++#include <memory>+#include <vector>++#include "npuw_transformations/replace_deepstack_scatter_with_add.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/gather_nd.hpp"+#include "openvino/op/non_zero.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/result.hpp"+#include "openvino/op/scatter_nd_update.hpp"+#include "openvino/op/transpose.hpp"++namespace {++constexpr int64_t kNumLayers = 3;+constexpr int64_t kSeq = 8;+constexpr int64_t kEmb = 4;++template <class Op>+std::size_t count_ops(const std::shared_ptr<ov::Model>& model) {+ std::size_t n = 0;+ for (const auto& op : model->get_ops()) {+ if (ov::is_type<Op>(op)) {+ ++n;+ }+ }+ return n;+}++std::shared_ptr<ov::op::v0::Parameter> find_param(const std::shared_ptr<ov::Model>& model, const std::string& needle) {+ for (const auto& param : model->get_parameters()) {+ if (param->get_friendly_name().find(needle) != std::string::npos) {+ return param;+ }+ for (const auto& name : param->output(0).get_names()) {+ if (name.find(needle) != std::string::npos) {+ return param;+ }+ }+ }+ return nullptr;+}++// Builds a minimal model reproducing the Qwen3-VL DeepStack injection: for each of+// kNumLayers levels, the hidden states are updated at visual-token positions via+// ScatterNDUpdate(hidden, pos, GatherND(hidden, pos) + Gather(deepstack, L))+// where pos = Transpose(NonZero(visual_pos_masks)). Levels are chained.+//+// If `with_slice_assign` is true, each index_put ScatterNDUpdate is wrapped by a+// Reshape -> ScatterNDUpdate -> Reshape "SliceAssign" identity, matching how the+// PyTorch-traced model writes the whole tensor back.+std::shared_ptr<ov::Model> build_deepstack_model(bool with_slice_assign) {+ using ov::op::v0::Constant;+ using ov::op::v0::Parameter;+ using ov::op::v0::Result;++ auto hidden = std::make_shared<Parameter>(ov::element::f32, ov::PartialShape{1, kSeq, kEmb});+ hidden->set_friendly_name("inputs_embeds");+ hidden->output(0).set_names({"inputs_embeds"});++ auto deepstack = std::make_shared<Parameter>(ov::element::f32, ov::PartialShape{kNumLayers, -1, kEmb});+ deepstack->set_friendly_name("deepstack_visual_embeds");+ deepstack->output(0).set_names({"deepstack_visual_embeds"});++ auto vpm = std::make_shared<Parameter>(ov::element::boolean, ov::PartialShape{1, kSeq});+ vpm->set_friendly_name("visual_pos_masks");+ vpm->output(0).set_names({"visual_pos_masks"});++ auto nonzero = std::make_shared<ov::op::v3::NonZero>(vpm, ov::element::i64);+ auto perm = Constant::create(ov::element::i32, ov::Shape{2}, {1, 0});+ auto pos = std::make_shared<ov::op::v1::Transpose>(nonzero, perm);++ auto axis0 = Constant::create(ov::element::i64, ov::Shape{}, {0});++ ov::Output<ov::Node> cur = hidden;+ for (int64_t l = 0; l < kNumLayers; ++l) {+ auto gathered = std::make_shared<ov::op::v8::GatherND>(cur, pos);+ auto layer_idx = Constant::create(ov::element::i64, ov::Shape{}, {l});+ auto select = std::make_shared<ov::op::v8::Gather>(deepstack, layer_idx, axis0);+ auto add = std::make_shared<ov::op::v1::Add>(gathered, select);+ auto scatter = std::make_shared<ov::op::v3::ScatterNDUpdate>(cur, pos, add);++ if (with_slice_assign) {+ // Flatten -> ScatterNDUpdate over the whole tensor -> reshape back (identity).+ auto flat_shape = Constant::create(ov::element::i64, ov::Shape{1}, {kSeq * kEmb});+ auto reshape_in = std::make_shared<ov::op::v1::Reshape>(scatter, flat_shape, false);+ std::vector<int64_t> all_idx(kSeq * kEmb);+ for (int64_t i = 0; i < kSeq * kEmb; ++i) {+ all_idx[i] = i;+ }+ auto idx_const =+ Constant::create(ov::element::i64, ov::Shape{static_cast<size_t>(kSeq * kEmb), 1}, all_idx);+ auto base_flat = std::make_shared<ov::op::v1::Reshape>(cur, flat_shape, false);+ auto updates_flat = std::make_shared<ov::op::v1::Reshape>(scatter, flat_shape, false);+ auto slice_scatter = std::make_shared<ov::op::v3::ScatterNDUpdate>(base_flat, idx_const, updates_flat);+ auto out_shape = Constant::create(ov::element::i64, ov::Shape{3}, std::vector<int64_t>{1, kSeq, kEmb});+ auto reshape_out = std::make_shared<ov::op::v1::Reshape>(slice_scatter, out_shape, false);+ cur = reshape_out;+ } else {+ cur = scatter;+ }+ }++ auto result = std::make_shared<Result>(cur);+ return std::make_shared<ov::Model>(ov::ResultVector{result},+ ov::ParameterVector{hidden, deepstack, vpm},+ "deepstack_test_model");+}++// --- Test 1 -------------------------------------------------------------------+// Core transformation: gather/scatter cluster replaced by residual adds, visual_pos_masks+// dropped, deepstack kept as a single [num_layers, ...] input.+TEST(ReplaceDeepstackScatterWithAddTest, ReplacesClusterAndDropsVisualPosMasks) {+ auto model = build_deepstack_model(/*with_slice_assign=*/false);++ ASSERT_EQ(count_ops<ov::op::v8::GatherND>(model), static_cast<std::size_t>(kNumLayers));+ ASSERT_EQ(count_ops<ov::op::v3::ScatterNDUpdate>(model), static_cast<std::size_t>(kNumLayers));+ ASSERT_EQ(count_ops<ov::op::v3::NonZero>(model), 1u);+ ASSERT_NE(find_param(model, "visual_pos_masks"), nullptr);+ ASSERT_EQ(model->get_parameters().size(), 3u);++ const bool changed = ov::npuw::ReplaceDeepstackScatterWithAdd().run_on_model(model);+ EXPECT_TRUE(changed);++ // The data-dependent ops are gone.+ EXPECT_EQ(count_ops<ov::op::v8::GatherND>(model), 0u);+ EXPECT_EQ(count_ops<ov::op::v3::ScatterNDUpdate>(model), 0u);+ EXPECT_EQ(count_ops<ov::op::v3::NonZero>(model), 0u);++ // visual_pos_masks input is dropped; deepstack is kept as a single [3, ...] input.+ EXPECT_EQ(find_param(model, "visual_pos_masks"), nullptr);+ EXPECT_EQ(model->get_parameters().size(), 2u);+ auto ds = find_param(model, "deepstack_visual_embeds");+ ASSERT_NE(ds, nullptr);+ ASSERT_EQ(ds->get_partial_shape().rank().get_length(), 3);+ EXPECT_EQ(ds->get_partial_shape()[0].get_length(), kNumLayers);++ // One residual Add per deepstack level remains, each fed by a select-Gather.+ EXPECT_EQ(count_ops<ov::op::v8::Gather>(model), static_cast<std::size_t>(kNumLayers));+ EXPECT_EQ(count_ops<ov::op::v1::Add>(model), static_cast<std::size_t>(kNumLayers));+}++// --- Test 2 -------------------------------------------------------------------+// Same, but with the SliceAssign identity wrapper present around each scatter.+TEST(ReplaceDeepstackScatterWithAddTest, BypassesSliceAssignWrapper) {+ auto model = build_deepstack_model(/*with_slice_assign=*/true);++ // 2 scatters per level: index_put + SliceAssign.+ ASSERT_EQ(count_ops<ov::op::v3::ScatterNDUpdate>(model), static_cast<std::size_t>(2 * kNumLayers));++ const bool changed = ov::npuw::ReplaceDeepstackScatterWithAdd().run_on_model(model);+ EXPECT_TRUE(changed);++ EXPECT_EQ(count_ops<ov::op::v8::GatherND>(model), 0u);+ EXPECT_EQ(count_ops<ov::op::v3::ScatterNDUpdate>(model), 0u);+ EXPECT_EQ(count_ops<ov::op::v3::NonZero>(model), 0u);+ EXPECT_EQ(find_param(model, "visual_pos_masks"), nullptr);+ EXPECT_EQ(model->get_parameters().size(), 2u);+ EXPECT_EQ(count_ops<ov::op::v1::Add>(model), static_cast<std::size_t>(kNumLayers));+}++// --- Test 3 -------------------------------------------------------------------+// A model without deepstack must be left untouched (pass returns false).+TEST(ReplaceDeepstackScatterWithAddTest, NoDeepstackIsUntouched) {+ using ov::op::v0::Parameter;+ using ov::op::v0::Result;++ auto hidden = std::make_shared<Parameter>(ov::element::f32, ov::PartialShape{1, kSeq, kEmb});+ hidden->set_friendly_name("inputs_embeds");+ auto bias = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 1, kEmb}, std::vector<float>(kEmb, 1.0f));+ auto add = std::make_shared<ov::op::v1::Add>(hidden, bias);+ auto result = std::make_shared<Result>(add);+ auto model = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{hidden}, "plain_model");++ const bool changed = ov::npuw::ReplaceDeepstackScatterWithAdd().run_on_model(model);++ EXPECT_FALSE(changed);+ EXPECT_EQ(model->get_parameters().size(), 1u);+ EXPECT_EQ(count_ops<ov::op::v1::Add>(model), 1u);+}++} // namespacediff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/reshape_to_static_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/reshape_to_static_test.cppindex 9c96b5bc9b8..529a5c6e263 100644--- a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/reshape_to_static_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/reshape_to_static_test.cpp@@ -172,6 +172,23 @@ TEST_F(ReshapeToStaticPassTest, MaxGenerationTokenLenDrivesGenerateInputShape) {EXPECT_EQ((*kv_shape)[3], 16u); // head_dim}+} // namespace+++// ---------------------------------------------------------------------------+// Direct ReshapeToStatic unit tests for Qwen3-VL inputs+// ---------------------------------------------------------------------------+// These tests build a minimal model graph with only the VLM-specific inputs+// and apply ReshapeToStatic directly, without going through LLMCompiledModel.+// This keeps the tests fast and free of plugin/mock overhead.+// ---------------------------------------------------------------------------++namespace {++using ov::npuw::KVAxesPosition;+using ov::npuw::ReshapeToStatic;++// --- Test 5 -------------------------------------------------------------------------// per_layer_inputs is consumed by Add with a static sibling tensor. The pass should// resolve dynamic {num_layers, projection_dim} from that sibling and set seq_len=input_size.@@ -269,4 +286,101 @@ TEST_F(ReshapeToStaticPassTest, LinCacheInputsOnlyBatchIsReshaped) {ASSERT_TRUE(kv_value_shape.has_value()) << "past_key_values.0.value not found";EXPECT_EQ(*kv_value_shape, (ov::Shape{1, 4, 191, 64}));}++} // namespace+++// ---------------------------------------------------------------------------+// Direct ReshapeToStatic unit tests for Qwen3-VL inputs+// ---------------------------------------------------------------------------+// These tests build a minimal model graph with only the VLM-specific inputs+// and apply ReshapeToStatic directly, without going through LLMCompiledModel.+// This keeps the tests fast and free of plugin/mock overhead.+// ---------------------------------------------------------------------------++namespace {++using ov::npuw::KVAxesPosition;+using ov::npuw::ReshapeToStatic;++// Build a minimal model that contains visual_pos_masks and attention_mask.+// Both are dynamic so ReshapeToStatic must assign static shapes to them.+static std::shared_ptr<ov::Model> build_vlm_inputs_model() {+ auto visual_pos_masks =+ std::make_shared<ov::op::v0::Parameter>(ov::element::boolean, ov::PartialShape{-1, -1});+ visual_pos_masks->set_friendly_name("visual_pos_masks");+ visual_pos_masks->output(0).set_names({"visual_pos_masks"});++ auto attention_mask =+ std::make_shared<ov::op::v0::Parameter>(ov::element::boolean, ov::PartialShape{-1, -1});+ attention_mask->set_friendly_name("attention_mask");+ attention_mask->output(0).set_names({"attention_mask"});++ auto r1 = std::make_shared<ov::op::v0::Result>(visual_pos_masks);+ auto r2 = std::make_shared<ov::op::v0::Result>(attention_mask);++ return std::make_shared<ov::Model>(+ ov::ResultVector{r1, r2},+ ov::ParameterVector{visual_pos_masks, attention_mask},+ "vlm_inputs_model");+}++// --- Test 6 -------------------------------------------------------------------+// visual_pos_masks must be reshaped to {1, input_size}.+// The Whisper kvcache override (lhs_seq_size && kvcache_size > 4) must NOT+// affect visual_pos_masks — even when lhs_seq_size is non-zero.+TEST(ReshapeToStaticVLMTest, VisualPosMasksShapeIsRowsByInputSize) {+ auto model = build_vlm_inputs_model();++ constexpr uint32_t input_size = 128;+ constexpr uint32_t kvcache_size = 192;+ KVAxesPosition kv_axes{0, 1};++ // lhs_seq_size=8 would trigger the Whisper branch for attention_mask;+ // visual_pos_masks must NOT be overwritten by it.+ ReshapeToStatic pass(input_size, kvcache_size, kv_axes, /*lora_rank=*/0, /*lhs_seq_size=*/8);+ ASSERT_TRUE(pass.run_on_model(model));++ bool found = false;+ for (const auto& input : model->inputs()) {+ const auto& names = input.get_names();+ if (names.count("visual_pos_masks")) {+ found = true;+ const auto& shape = input.get_partial_shape();+ ASSERT_TRUE(shape.is_static()) << "visual_pos_masks must be static after ReshapeToStatic";+ EXPECT_EQ(shape.to_shape(), (ov::Shape{1, input_size}))+ << "visual_pos_masks must have shape {1, input_size}";+ }+ }+ EXPECT_TRUE(found) << "visual_pos_masks input not found in model";+}++// --- Test 7 -------------------------------------------------------------------+// Sanity check: attention_mask IS affected by lhs_seq_size (Whisper path).+// This test documents the intentional difference between visual_pos_masks+// and attention_mask under the same Whisper-mode conditions.+TEST(ReshapeToStaticVLMTest, AttentionMaskIsAffectedByWhisperPath) {+ auto model = build_vlm_inputs_model();++ constexpr uint32_t input_size = 128;+ constexpr uint32_t kvcache_size = 192;+ KVAxesPosition kv_axes{0, 1};++ ReshapeToStatic pass(input_size, kvcache_size, kv_axes, /*lora_rank=*/0, /*lhs_seq_size=*/8);+ ASSERT_TRUE(pass.run_on_model(model));++ bool found = false;+ for (const auto& input : model->inputs()) {+ const auto& names = input.get_names();+ if (names.count("attention_mask")) {+ found = true;+ const auto& shape = input.get_partial_shape();+ ASSERT_TRUE(shape.is_static());+ // Whisper path: kvcache_size + 1+ EXPECT_EQ(shape.to_shape(), (ov::Shape{1, kvcache_size + 1}));+ }+ }+ EXPECT_TRUE(found) << "attention_mask input not found in model";+}+} // namespace