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 models with Linear Attention (#35221)
Anastasiya(Asya) Pronina945cec49736e
diff --git a/src/core/src/pass/stateful_to_stateless.cpp b/src/core/src/pass/stateful_to_stateless.cppindex 3e7002499e3..89dc9a129c5 100644--- a/src/core/src/pass/stateful_to_stateless.cpp+++ b/src/core/src/pass/stateful_to_stateless.cpp@@ -33,6 +33,10 @@ struct Variable {// to hold compiled once regex for all Variable instancesconst std::regex naming_convention =std::regex(R"((past_key_values\.(\d+)\.(key|value))(present\.(\d+)\.(key|value)))");+ // Pattern 2: Convention for models with Linear Attention (e.g.,+ // cache_params.past.key.0cache_params.present.key.0)+ const std::regex lin_cache_naming_convention = std::regex(+ R"((cache_params)\.past\.(key|value|conv|ssm)\.(\d+)cache_params\.present\.(key|value|conv|ssm)\.(\d+))");};Variable(const Context& context, const std::string& variable_name) : variable_name(variable_name) {@@ -48,6 +52,41 @@ struct Variable {} else {index = -1;}+ } else if (std::regex_match(variable_name, match, context.lin_cache_naming_convention)) {+ // Linear Attention pattern: cache_params.past.key.0cache_params.present.key.0+ // cache_params.past.value.0cache_params.present.value.0+ // cache_params.past.ssm.0cache_params.present.ssm.0 OR/AND+ // cache_params.past.conv.0cache_params.present.conv.0+ std::string prefix = match[1].str();+ std::string past_type = match[2].str();+ std::string past_idx = match[3].str();+ std::string present_type = match[4].str();+ std::string present_idx = match[5].str();++ auto create_name = [](const std::string& type,+ const std::string& idx,+ const std::string& original_prefix,+ const std::string& past_or_present) {+ if (type == "key" || type == "value") {+ std::string prefix = past_or_present == "past" ? "past_key_values" : "present";+ return prefix + "." + idx + "." + type;+ } else if (type == "conv" || type == "ssm") {+ return original_prefix + "." + past_or_present + "." + type + "." + idx;+ }+ OPENVINO_THROW("Incorrect type of state: ", type);+ };++ input_name = create_name(past_type, past_idx, prefix, "past");+ output_name = create_name(present_type, present_idx, prefix, "present");++ if (past_idx == present_idx && past_idx.length() <= std::numeric_limits<int>::digits10 &&+ past_type == present_type && (past_type == "key" || past_type == "value")) {+ // NB: We enumerate only key and value caches to restore KVCache order.+ // Conv and SSM caches will be placed after them in their natural order in the model.+ index = std::stoi(past_idx) * 2 + int(past_type == "value"); // order key before value+ } else {+ index = -1;+ }} else {// Variable name doesn't follow the expected naming convention. It doens't prevent forming// a correct stateless model but doesn't give a way to restore all names and inputs/outputs ordering@@ -95,6 +134,7 @@ bool ov::pass::StatefulToStateless::run_on_model(const std::shared_ptr<ov::ModelVariable::Context context;std::unordered_map<std::string, std::shared_ptr<ov::Node>>future_params; // to collect nodes, each with a single output that will be replaced by new parameters+ std::unordered_set<std::string> processed_variable_ids; // Track which ReadValues we've processedif (beam_idx) {for (const ov::Input<ov::Node>& input : beam_idx->get_output_target_inputs(0)) {if (auto gather = ov::as_type_ptr<op::util::GatherBase>(input.get_node()->shared_from_this())) {@@ -105,13 +145,30 @@ bool ov::pass::StatefulToStateless::run_on_model(const std::shared_ptr<ov::Modelauto variable_name = read_value->get_variable_id();variables.push_back(Variable(context, variable_name));future_params[variable_name] = gather;+ processed_variable_ids.insert(variable_name);}}+ model->remove_parameter(beam_idx);} else {OPENVINO_THROW("Stateful models without `beam_idx` input are not supported in StatefulToStateless transformation");}- model->remove_parameter(beam_idx);++ // Process ReadValues that are NOT connected via beam_idx: Conv and SSM caches in models with Linear Attention.+ for (const auto& op : model->get_ops()) {+ if (auto read_value = ov::as_type_ptr<op::util::ReadValueBase>(op)) {+ auto variable_name = read_value->get_variable_id();+ std::smatch match;+ if ((processed_variable_ids.find(variable_name) == processed_variable_ids.end()) &&+ std::regex_match(variable_name, match, context.lin_cache_naming_convention)) {+ variables.push_back(Variable(context, variable_name));+ // For models with Linear Attention, ReadValue for Conv and SSM caches connects directly to the useful+ // Ops after.+ future_params[variable_name] = read_value;+ processed_variable_ids.insert(variable_name);+ }+ }+ }typedef std::shared_ptr<op::util::AssignBase> PAssign;std::unordered_map<std::string, PAssign> assigns_by_var_id;diff --git a/src/plugins/intel_npu/src/plugin/npuw/embedding/remove_empty_kv_inputs.cpp b/src/plugins/intel_npu/src/plugin/npuw/embedding/remove_empty_kv_inputs.cppindex 93c2c53b3dd..dc712df0fe7 100644--- a/src/plugins/intel_npu/src/plugin/npuw/embedding/remove_empty_kv_inputs.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/embedding/remove_empty_kv_inputs.cpp@@ -4,6 +4,7 @@#include "remove_empty_kv_inputs.hpp"+#include "../util.hpp"#include "openvino/core/graph_util.hpp"#include "openvino/op/ops.hpp"#include "openvino/op/util/node_util.hpp"@@ -60,6 +61,19 @@ public:auto callback = [=](opp::Matcher& m) {auto& node_to_output = m.get_pattern_value_map();auto matched_param = ov::as_type_ptr<ov::op::v0::Parameter>(node_to_output.at(param).get_node_shared_ptr());++ // Note: Additional precaution for only KVCache parameters to match.+ // As an example linear cache of GDN blocks can match pattern above too.+ // Note 2: In Whisper model KVCache state names got badly handled by StatefulToStateless pass,+ // so their created parameters names are not standard. As Whisper rename goes after this+ // transformation, we need to ensure matching of these incorrect names as well+ // to remove all empty KV inputs.+ std::string param_name = matched_param->get_friendly_name();+ if (!ov::npuw::util::isPastKeyValuesKey(param_name) && !ov::npuw::util::isPastKeyValuesValue(param_name) &&+ !ov::npuw::util::isRestoredPastKeyValueParam(param_name)) {+ return false;+ }+auto matched_node_concat = node_to_output.at(concat).get_node_shared_ptr();ctx.get().old_params.push_back(matched_param);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 7073bee0507..2166db0c621 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@@ -11,6 +11,7 @@#include "llm_infer_request.hpp"#include "logging.hpp"#include "moe_transformations/apply_moe_device_routed_transforms.hpp"+#include "npuw_transformations/add_position_ids_param.hpp"#include "npuw_transformations/convert_kvcache_to_precision.hpp"#include "npuw_transformations/decompose_gqa.hpp"#include "npuw_transformations/lora_stateful_to_stateless.hpp"@@ -771,6 +772,8 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mLOG_DEBUG("Text-embedding model rebuild");ov::npuw::util::PrepareTextEmbeddingModel(seq_len_dim).run_on_model(kvcache_model);} else {+ LOG_DEBUG("Adding position_ids input in case it doesn't exist in model: LFM-2 case.");+ ov::npuw::AddPositionIdsParam().run_on_model(kvcache_model);LOG_DEBUG("Transform kvcache model from stateful to stateless.");ov::pass::StatefulToStateless().run_on_model(kvcache_model);}diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_base_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_base_request.cppindex dc28a17e4d4..e74ceb9236d 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_base_request.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_base_request.cpp@@ -1,4 +1,4 @@-// Copyright (C) 2025 Intel Corporation+// Copyright (C) 2018-2026 Intel Corporation// SPDX-License-Identifier: Apache-2.0//@@ -8,6 +8,8 @@#include "infer_request_utils.hpp"+// NOTE: This is a basic method for updating KVCache after handling its part.+// It is not intended to work with model supporting Linear Cache.void ov::npuw::LLMInferBaseRequest::update_kvcache_for(std::shared_ptr<ov::IAsyncInferRequest> request,const std::unordered_map<std::string, ov::Output<const ov::Node>>& in_ports,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 6f0403360d3..7537cffb65a 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@@ -46,11 +46,11 @@ public:}protected:- void update_kvcache_for(std::shared_ptr<ov::IAsyncInferRequest> request,- const PortsMap& in_ports,- const PortsMap& out_ports,- uint32_t num_tokens,- bool v_transposed);+ virtual void update_kvcache_for(std::shared_ptr<ov::IAsyncInferRequest> request,+ const PortsMap& in_ports,+ const PortsMap& out_ports,+ uint32_t num_tokens,+ bool v_transposed);void init_tensor(const ov::Output<const ov::Node>& port);void init_ports();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 98b677d16d5..0e88c2d1f19 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@@ -103,7 +103,6 @@ void process_longrope(const std::shared_ptr<ov::IAsyncInferRequest>& infer_req,longrope_input->data<int64_t>()[0] = max_pos_id;}}-} // anonymous namespacevoid ov::npuw::LLMInferRequest::init_lora_states() {@@ -140,16 +139,27 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCofor (const auto& input_port : m_prefill_request->get_compiled_model()->inputs()) {m_prefill_in_ports.emplace(input_port.get_any_name(), input_port);- // Cache past_key_values ports for efficient clearing- if (input_port.get_any_name().find(layer_names::past_key_values) != std::string::npos) {- m_prefill_past_kv_ports.push_back(input_port);- }}for (const auto& output_port : m_prefill_request->get_compiled_model()->outputs()) {m_prefill_out_ports.emplace(output_port.get_any_name(), output_port);}+ for (const auto& input_port : m_kvcache_request->get_compiled_model()->inputs()) {+ const auto& all_names = input_port.get_names();+ for (const auto& name : all_names) {+ if (ov::npuw::util::starts_with(name, layer_names::past_key_values)) {+ m_kvcache_past_names.push_back(name);+ break;+ }+ if (ov::npuw::util::starts_with_past_lincache(name)) {+ m_lincache_past_names.push_back(name);+ break;+ }+ }+ }+init_pre_alloc_device();+ m_stored_tokens_state = std::make_shared<ov::npuw::StoredTokensState>();init_lora_states();m_eagle3_ext.initialize(m_npuw_llm_compiled_model->m_is_eagle, m_prefill_in_ports, m_prefill_out_ports);@@ -158,6 +168,8 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCoif (use_chunk_prefill) {// FIXME: enable w/o chunking as well. Although need to align the paddings beforehandbind_past_kv();+ // FIXME: Why do we need this if the same is done in prepare_for_new_conversation() before each prefill+ // inference? Can we do it only once?clear_chunk_prefill_kv_cache();}@@ -203,22 +215,17 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCoif (enable_cpu_wa) {// Apply CPU workaround only for the largest variant since all variants share its past KV tensorsauto& largest_kvcache_req = m_generate_requests.back();- const auto& kvcache_compiled = largest_kvcache_req->get_compiled_model();const auto& variant_in_ports = m_generate_variant_in_ports.at(largest_kvcache_req);- // FIXME: Find only matching by names outputs and copy them, having previously checked that such inputs- // exist- for (std::size_t i = layer_ids::kStartOutputKVCacheLayers; i < kvcache_compiled->outputs().size(); ++i) {- const auto& output_name = kvcache_compiled->outputs()[i].get_any_name();- const auto& input_name =- std::regex_replace(output_name, std::regex("present"), layer_names::past_key_values);- if (variant_in_ports.find(input_name) == variant_in_ports.end()) {- continue;- }- auto kvcache_in_tensor = largest_kvcache_req->get_tensor(variant_in_ports.at(input_name));+ for (const auto& kv_past_name : m_kvcache_past_names) {+ auto kvcache_in_tensor = largest_kvcache_req->get_tensor(variant_in_ports.at(kv_past_name));// NB: Use fill_tensor_bytes to zero-fill regardless of element type.// fill_tensor<ov::float16> would fail with a type mismatch error for i8 kv-cacheov::npuw::util::fill_tensor_bytes(kvcache_in_tensor, 0u);}+ for (const auto& lincache_past_name : m_lincache_past_names) {+ auto lincache_in_tensor = largest_kvcache_req->get_tensor(variant_in_ports.at(lincache_past_name));+ ov::npuw::util::fill_tensor_bytes(lincache_in_tensor, 0u);+ }}m_generate_initialized = false;@@ -286,11 +293,19 @@ void ov::npuw::LLMInferRequest::create_generate_request_variants(std::unordered_map<std::string, ov::SoPtr<ov::ITensor>> largest_past_kv_tensors;for (const auto& input_port : largest_generate_request->get_compiled_model()->inputs()) {const auto& input_name = input_port.get_any_name();- if (input_name.find(layer_names::past_key_values) != std::string::npos) {+ if (ov::npuw::util::starts_with(input_name, layer_names::past_key_values)) {largest_past_kv_tensors[input_name] = largest_generate_request->get_tensor(input_port);}}+ std::unordered_map<std::string, ov::SoPtr<ov::ITensor>> past_lin_tensors;+ for (const auto& input_port : largest_generate_request->get_compiled_model()->inputs()) {+ const auto& input_name = input_port.get_any_name();+ if (ov::npuw::util::starts_with_past_lincache(input_name)) {+ past_lin_tensors[input_name] = largest_generate_request->get_tensor(input_port);+ }+ }+// Create all variant requests and share past KV tensorsfor (size_t i = 0; i < compiled_model->m_generate_compiled_variants.size(); ++i) {std::shared_ptr<ov::IAsyncInferRequest> generate_request;@@ -305,20 +320,25 @@ void ov::npuw::LLMInferRequest::create_generate_request_variants(// Share past KV tensors from the largest variantfor (const auto& input_port : generate_request->get_compiled_model()->inputs()) {const auto& input_name = input_port.get_any_name();- if (input_name.find(layer_names::past_key_values) != std::string::npos) {- if (largest_past_kv_tensors.find(input_name) != largest_past_kv_tensors.end()) {- auto largest_tensor = largest_past_kv_tensors[input_name];- auto small_shape = input_port.get_shape();-- // Wrap the largest tensor's data pointer with smaller shape- auto shared_tensor = ov::SoPtr<ov::ITensor>(- ov::make_tensor(input_port.get_element_type(), small_shape, largest_tensor->data()),- nullptr);-- generate_request->set_tensor(input_port, shared_tensor);- } else {- OPENVINO_ASSERT(false, "Unexpected input name: ", input_name);- }+ if (ov::npuw::util::starts_with(input_name, layer_names::past_key_values)) {+ OPENVINO_ASSERT(largest_past_kv_tensors.find(input_name) != largest_past_kv_tensors.end(),+ "Unexpected input name: ",+ input_name);+ auto largest_tensor = largest_past_kv_tensors[input_name];+ auto small_shape = input_port.get_shape();++ // Wrap the largest tensor's data pointer with smaller shape+ auto shared_tensor = ov::SoPtr<ov::ITensor>(+ ov::make_tensor(input_port.get_element_type(), small_shape, largest_tensor->data()),+ nullptr);++ generate_request->set_tensor(input_port, shared_tensor);+ } else if (ov::npuw::util::starts_with_past_lincache(input_name)) {+ OPENVINO_ASSERT(past_lin_tensors.find(input_name) != past_lin_tensors.end(),+ "Unexpected input name: ",+ input_name);+ auto lin_tensor = past_lin_tensors[input_name];+ generate_request->set_tensor(input_port, lin_tensor);}}}@@ -483,9 +503,17 @@ void ov::npuw::LLMInferRequest::prepare_for_new_conversation(int64_t prompt_lenguu::fill_tensor_bytes(m_prefill_request->get_tensor(per_layer_port->second), 0u);}- // Clear all past_key_values tensors - use cached ports for efficiency- for (const auto& port : m_prefill_past_kv_ports) {- uu::fill_tensor_bytes(m_prefill_request->get_tensor(port), 0u);+ for (const auto& input_name : m_kvcache_past_names) {+ // NOTE: Non-chunked prefill model doesn't contain input KVCache.+ if (m_prefill_in_ports.find(input_name) != m_prefill_in_ports.end()) {+ uu::fill_tensor_bytes(m_prefill_request->get_tensor(m_prefill_in_ports.at(input_name)), 0u);+ }+ }++ for (const auto& input_name : m_lincache_past_names) {+ if (m_prefill_in_ports.find(input_name) != m_prefill_in_ports.end()) {+ uu::fill_tensor_bytes(m_prefill_request->get_tensor(m_prefill_in_ports.at(input_name)), 0u);+ }}m_npuw_llm_compiled_model->m_kvcache_desc.num_stored_tokens = 0u;@@ -502,19 +530,18 @@ void ov::npuw::LLMInferRequest::copy_kvcache() {LOG_DEBUG("Copying kv-cache from prefill to generate model.");LOG_BLOCK();auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;- const auto& kvcache_compiled = m_kvcache_request->get_compiled_model();// FIXME: Find only matching by names outputs and copy them, having previously checked that such inputs exist- ov::parallel_for(kvcache_compiled->outputs().size() - layer_ids::kStartOutputKVCacheLayers, [&](size_t out_idx) {- const std::size_t i = layer_ids::kStartOutputKVCacheLayers + out_idx;- const auto& output_name = kvcache_compiled->outputs()[i].get_any_name();+ ov::parallel_for(m_kvcache_past_names.size(), [&](size_t out_idx) {+ const auto& input_name = m_kvcache_past_names[out_idx];+ auto kvcache_in_tensor = m_kvcache_request->get_tensor(m_kvcache_in_ports.at(input_name));++ const auto& output_name = std::regex_replace(input_name, std::regex(layer_names::past_key_values), "present");+ OPENVINO_ASSERT(m_prefill_out_ports.find(output_name) != m_prefill_out_ports.end(),+ "Incosistent input/output naming for KV cache: ",+ output_name,+ " not found in prefill model outputs.");auto prefill_out_tensor = m_prefill_request->get_tensor(m_prefill_out_ports.at(output_name));- const auto& input_name = std::regex_replace(output_name, std::regex("present"), layer_names::past_key_values);- if (m_kvcache_in_ports.find(input_name) == m_kvcache_in_ports.end()) {- // FIXME: Totally wrong debug message. input_name is an invalid name of input layer.- LOG_DEBUG("Input name " << input_name << " doesn't contain kv cache. Skipping.");- return;- }const auto is_value_tensor = output_name.find("value") != std::string::npos;const auto kv_dim = [&](bool v_trans) -> uint32_t {return (is_value_tensor && v_trans) ? 3u : kvcache_desc.dim;@@ -522,7 +549,6 @@ void ov::npuw::LLMInferRequest::copy_kvcache() {const auto& pre_kv_dim = kv_dim(kvcache_desc.v_tensors_transposed_pre);const auto& gen_kv_dim = kv_dim(kvcache_desc.v_tensors_transposed_gen);- auto kvcache_in_tensor = m_kvcache_request->get_tensor(m_kvcache_in_ports.at(input_name));const auto prefill_chunk_size = m_npuw_llm_compiled_model->m_prefill_chunk_size;const bool use_chunk_prefill = m_npuw_llm_compiled_model->m_use_chunk_prefill;@@ -595,6 +621,76 @@ void ov::npuw::LLMInferRequest::copy_kvcache() {LOG_DEBUG("Done.");}+void ov::npuw::LLMInferRequest::update_kvcache_for(+ std::shared_ptr<ov::IAsyncInferRequest> request,+ const std::unordered_map<std::string, ov::Output<const ov::Node>>& in_ports,+ const std::unordered_map<std::string, ov::Output<const ov::Node>>& out_ports,+ uint32_t num_tokens,+ bool v_transposed) {+ namespace uu = ov::npuw::util;+ auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;++ for (std::size_t i = 0; i < m_kvcache_past_names.size(); ++i) {+ const auto& input_name = m_kvcache_past_names[i];+ OPENVINO_ASSERT(in_ports.find(input_name) != in_ports.end(),+ "There is no ",+ input_name,+ " in input ports map, while it is expected!");+ const auto& output_name = std::regex_replace(input_name, std::regex(layer_names::past_key_values), "present");+ OPENVINO_ASSERT(out_ports.find(output_name) != out_ports.end(),+ "There is no ",+ output_name,+ " in output ports map, while it is expected!");++ auto dst_tensor = request->get_tensor(in_ports.at(input_name));+ const auto& kv_dim = (output_name.find("value") != std::string::npos && v_transposed) ? 3u : kvcache_desc.dim;+ auto dst_slice = uu::make_tensor_slice(dst_tensor,+ kv_dim,+ kvcache_desc.num_stored_tokens - num_tokens,+ kvcache_desc.num_stored_tokens);+ auto src_tensor = request->get_tensor(out_ports.at(output_name));++ // NOTE: Sometimes present kv layer can contain greater seq_len+ // than was sent to be processed+ uint32_t src_seq_len = static_cast<uint32_t>(src_tensor->get_shape()[kv_dim]);+ OPENVINO_ASSERT(num_tokens <= src_seq_len);+ if (src_seq_len > num_tokens) {+ auto src_slice = uu::make_tensor_slice(src_tensor, kv_dim, src_seq_len - num_tokens, src_seq_len);+ uu::copy_tensor_by_dim(src_slice, dst_slice, kv_dim, kv_dim);+ } else {+ uu::copy_tensor_by_dim(src_tensor, dst_slice, kv_dim, kv_dim);+ }+ }+}++void ov::npuw::LLMInferRequest::copy_lincache(+ std::shared_ptr<ov::IAsyncInferRequest> from_request,+ std::shared_ptr<ov::IAsyncInferRequest> to_request,+ const std::unordered_map<std::string, ov::Output<const ov::Node>>& from_ports,+ const std::unordered_map<std::string, ov::Output<const ov::Node>>& to_ports) {+ namespace uu = ov::npuw::util;+ LOG_DEBUG("Copying linear cache.");+ LOG_BLOCK();+ ov::parallel_for(m_lincache_past_names.size(), [&](size_t out_idx) {+ const auto& input_name = m_lincache_past_names[out_idx];+ OPENVINO_ASSERT(to_ports.find(input_name) != to_ports.end(),+ "Incosistent input/output naming for linear cache: ",+ input_name,+ " not found in model inputs.");+ auto to_tensor = to_request->get_tensor(to_ports.at(input_name));++ const auto& output_name = std::regex_replace(input_name, std::regex("past"), "present");+ OPENVINO_ASSERT(from_ports.find(output_name) != from_ports.end(),+ "Incosistent input/output naming for linear cache: ",+ output_name,+ " not found in model outputs.");+ auto from_tensor = from_request->get_tensor(from_ports.at(output_name));++ from_tensor->copy_to(to_tensor._ptr);+ });+ LOG_DEBUG("Done.");+}+void ov::npuw::LLMInferRequest::trim_kvcache_for_speculative_decoding(ov::SoPtr<ov::ITensor> position_ids) {auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;// FIXME: It won't work with Qwen2.5-VL/Omni for now.@@ -609,16 +705,11 @@ void ov::npuw::LLMInferRequest::trim_kvcache_for_speculative_decoding(ov::SoPtr<}void ov::npuw::LLMInferRequest::clear_chunk_prefill_kv_cache() {- const auto& prefill_compiled = m_prefill_request->get_compiled_model();-- for (std::size_t i = layer_ids::kStartOutputKVCacheLayers; i < prefill_compiled->outputs().size(); ++i) {- const auto& output_name = prefill_compiled->outputs()[i].get_any_name();- const auto& input_name = std::regex_replace(output_name, std::regex("present"), "past_key_values");- if (m_prefill_in_ports.find(input_name) == m_prefill_in_ports.end()) {- // FIXME: Totally wrong debug message. input_name is an invalid name of input layer.- LOG_DEBUG("Input name " << input_name << " doesn't contain kv cache. Skipping.");- continue;- }+ for (const auto& input_name : m_kvcache_past_names) {+ OPENVINO_ASSERT(m_prefill_in_ports.find(input_name) != m_prefill_in_ports.end(),+ "Incosistent input/output naming for KV cache: ",+ input_name,+ " not found in prefill model inputs.");auto chunk_prefill_kvcache_in_tensor = m_prefill_request->get_tensor(m_prefill_in_ports.at(input_name));@@ -638,8 +729,8 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inpconst auto input_prompt_len = input_ids->get_shape()[layer_ids::INPUT_IDS_SEQ_LEN_DIM];- // For LLM, model accepts 2d inputs_embeds[BATCH, SEQ_LEN]- // For VLM, model accepts 3d inputs_ids[BATCH, SEQ_LEN, EMB_SIZE]+ // For LLM, model accepts 2d inputs_ids[BATCH, SEQ_LEN]+ // For VLM, model accepts 3d inputs_embeds[BATCH, SEQ_LEN, EMB_SIZE]bool is_input_embeds = input_ids->get_shape().size() == 2 ? false : true;const auto input_ids_elem_size = input_ids->get_element_type().size();@@ -707,7 +798,7 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inpreinterpret_cast<uint8_t*>(input_ids_in_tensor->data()) + input_ids_in_tensor->get_byte_size() -current_prefill_bytes);- // NB: Regular LLM uses 2D position_ids [BATCH, SEQ_LEN], Qwen2.5 VL/Omni uses 3D position_ids+ // NB: Regular LLM uses 2D position_ids [BATCH, SEQ_LEN], Qwen2.5 VL/Omni, Qwen3.5 VL use 3D position_ids// [3, BATCH, SEQ_LEN]// Copy postion ids with considering the 3D position_idsauto last_dim = position_ids->get_shape().size() - 1;@@ -787,6 +878,8 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inpstatic_cast<uint32_t>(current_prompts_len),kvcache_desc.v_tensors_transposed_pre);+ copy_lincache(m_prefill_request, m_prefill_request, m_prefill_out_ports, m_prefill_in_ports);+// Update attention mask for the next iterationstd::copy_n(attn_mask_in_tensor->data<int64_t>() + attn_mask_in_tensor->get_size() - current_prompts_len,current_prompts_len,@@ -948,6 +1041,7 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,LOG_DEBUG("Copy kv-cache from prefill to generate model.");if (kvcache_desc.num_stored_tokens > 0) {copy_kvcache();+ copy_lincache(m_prefill_request, m_kvcache_request, m_prefill_out_ports, m_kvcache_in_ports);}LOG_DEBUG("Prepare inputs.");@@ -1037,7 +1131,10 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,kvcache_desc.v_tensors_transposed_gen);}});- m_llm_profile["N/generate:4.lm_head"].record([&]() {+ m_llm_profile["N/generate:4.copy_lincache"].record([&]() {+ copy_lincache(m_kvcache_request, m_kvcache_request, m_kvcache_out_ports, m_kvcache_in_ports);+ });+ m_llm_profile["N/generate:5.lm_head"].record([&]() {m_lm_head_request->wait();LOG_DEBUG("Calling inference for LM head model -- done.");@@ -1053,6 +1150,9 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,kvcache_desc.v_tensors_transposed_gen);}});+ m_llm_profile["N/generate:4.copy_lincache"].record([&]() {+ copy_lincache(m_kvcache_request, m_kvcache_request, m_kvcache_out_ports, m_kvcache_in_ports);+ });m_logits = m_kvcache_request->get_tensor(m_kvcache_out_ports.at(layer_names::logits));}@@ -1069,8 +1169,33 @@ void ov::npuw::LLMInferRequest::infer() {auto input_ids = get_tensor(ov::npuw::util::find_port_by_name(inputs, m_input_ids_name).value());auto attention_mask = get_tensor(ov::npuw::util::find_port_by_name(inputs, layer_names::attention_mask).value());- // FIXME: position_ids might be optional for some models!- auto position_ids = get_tensor(ov::npuw::util::find_port_by_name(inputs, layer_names::position_ids).value());++ auto position_ids = ov::npuw::util::TensorPtr();+ auto position_ids_opt = ov::npuw::util::find_port_by_name(inputs, layer_names::position_ids);+ if (position_ids_opt.has_value()) {+ position_ids = get_tensor(position_ids_opt.value());+ } else {+ // Sync num_stored_tokens before infer with external updates+ auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;+ auto externally_set_num_stored_tokens = m_stored_tokens_state->get_num_stored_tokens();+ if (externally_set_num_stored_tokens > kvcache_desc.total_size) {+ OPENVINO_THROW("Number of updated stored tokens in KV-Cache is greater than total KV-Cache size.");+ }+ if (externally_set_num_stored_tokens < 0) {+ OPENVINO_THROW("Number of updated stored tokens is negative!");+ }+ if (externally_set_num_stored_tokens == 0) {+ m_first_run = true;+ }+ kvcache_desc.num_stored_tokens = static_cast<uint32_t>(externally_set_num_stored_tokens);++ // FIXME: ov::SoPtr<ov::ITensor>?+ position_ids =+ ov::make_tensor(ov::element::i64, ov::Shape{input_ids->get_shape()[0], input_ids->get_shape()[1]});+ std::iota(position_ids->data<int64_t>(),+ position_ids->data<int64_t>() + position_ids->get_size(),+ kvcache_desc.num_stored_tokens);+ }auto token_type_ids = ov::npuw::util::TensorPtr();@@ -1142,6 +1267,11 @@ void ov::npuw::LLMInferRequest::infer() {}infer_generate(input_ids, attention_mask, position_ids, token_type_ids, per_layer_inputs);}++ if (!position_ids_opt.has_value()) {+ // Sync num_stored_tokens after infer with internal updates+ m_stored_tokens_state->set_num_stored_tokens(m_npuw_llm_compiled_model->m_kvcache_desc.num_stored_tokens);+ }}ov::SoPtr<ov::ITensor> ov::npuw::LLMInferRequest::get_tensor(const ov::Output<const ov::Node>& port) const {@@ -1170,6 +1300,10 @@ ov::SoPtr<ov::ITensor> ov::npuw::LLMInferRequest::get_tensor(const ov::Output<costd::vector<ov::SoPtr<ov::IVariableState>> ov::npuw::LLMInferRequest::query_state() const {auto states = m_variableStates;+ if (m_stored_tokens_state) {+ states.push_back(m_stored_tokens_state);+ }+// Add Eagle3 sampling state if availableauto eagle3_state = m_eagle3_ext.get_sampling_state();if (eagle3_state) {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 9ccc05cbcca..8f8576396e7 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@@ -12,6 +12,7 @@#include "llm_infer_base_request.hpp"#include "llm_lora_states.hpp"#include "llm_prefix_caching.hpp"+#include "llm_stored_tokens_state.hpp"#include "openvino/core/descriptor/output.hpp"#include "perf.hpp"@@ -33,7 +34,15 @@ protected:void apply_lora();void clear_chunk_prefill_kv_cache();void copy_kvcache();-+ void update_kvcache_for(std::shared_ptr<ov::IAsyncInferRequest> request,+ const PortsMap& in_ports,+ const PortsMap& out_ports,+ uint32_t num_tokens,+ bool v_transposed) override;+ void copy_lincache(std::shared_ptr<ov::IAsyncInferRequest> from_request,+ std::shared_ptr<ov::IAsyncInferRequest> to_request,+ const std::unordered_map<std::string, ov::Output<const ov::Node>>& from_ports,+ const std::unordered_map<std::string, ov::Output<const ov::Node>>& to_ports);// Create and initialize generate variant requests with memory sharingvoid create_generate_request_variants(const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled_model);@@ -97,8 +106,8 @@ protected:ov::Output<const ov::Node> m_lm_head_logits_port;- // Cache past_key_values ports for efficient clearing in prepare_for_new_conversation- std::vector<ov::Output<const ov::Node>> m_prefill_past_kv_ports;+ std::vector<std::string> m_kvcache_past_names;+ std::vector<std::string> m_lincache_past_names;// NB: It can be either input_ids(LLM) or inputs_embeds(VLM)std::string m_input_ids_name;@@ -114,6 +123,9 @@ protected:// Support Eagle3 speculative decodingEagle3Extension m_eagle3_ext;+ // Support reset of stored tokens to 0 from external pipeline+ ov::SoPtr<ov::npuw::StoredTokensState> m_stored_tokens_state;+// Support LoRAstd::vector<ov::SoPtr<ov::IVariableState>> m_variableStates;void init_lora_states();diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_stored_tokens_state.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_stored_tokens_state.hppnew file mode 100644index 00000000000..ffa45c1f18e--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_stored_tokens_state.hpp@@ -0,0 +1,52 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/runtime/itensor.hpp"+#include "openvino/runtime/ivariable_state.hpp"+#include "openvino/runtime/make_tensor.hpp"++namespace ov {+namespace npuw {++// Special VariableState for already processed/stored tokens in LLM.+// Allows external pipelines to call reset on that state where needed.+class StoredTokensState : public ov::IVariableState {+public:+ friend class ov::npuw::LLMInferRequest;+ StoredTokensState() : ov::IVariableState("npuw_stored_tokens_state") {+ auto tensor = ov::Tensor(ov::element::i64, ov::Shape{1});+ m_state = ov::get_tensor_impl(tensor);+ reset();+ }++ void reset() override {+ m_state->data<int64_t>()[0] = 0;+ }++ void set_state(const ov::SoPtr<ov::ITensor>&) override {+ OPENVINO_THROW("StoredTokensState::set_state() should not be called!");+ }++ // Returns a copy of state to prevent external modfication.+ ov::SoPtr<ov::ITensor> get_state() const override {+ const auto* state_data = m_state->data<int64_t>();+ auto result = ov::Tensor(ov::element::i64, ov::Shape{1});+ result.data<int64_t>()[0] = state_data[0];+ return ov::get_tensor_impl(result);+ }++private:+ int64_t get_num_stored_tokens() const {+ return m_state->data<int64_t>()[0];+ }++ void set_num_stored_tokens(int64_t num_tokens) {+ m_state->data<int64_t>()[0] = num_tokens;+ }+};++} // namespace npuw+} // namespace ovdiff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/add_position_ids_param.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/add_position_ids_param.cppnew file mode 100644index 00000000000..79d06af7574--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/add_position_ids_param.cpp@@ -0,0 +1,121 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "add_position_ids_param.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/multi_matcher.hpp"+#include "openvino/pass/pattern/op/optional.hpp"+#include "openvino/pass/pattern/op/or.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "openvino/pass/validate.hpp"++namespace opp = ov::pass::pattern;++namespace {++// diagnostics warnings on OPENVINO_MATCHER_PASS_RTTI() definition: visibility hidden+#ifdef __GNUC__+# pragma GCC diagnostic push+# pragma GCC diagnostic ignored "-Wattributes"+#endif++void set_node_name(std::shared_ptr<ov::Node> node, const std::string& name) {+ node->set_friendly_name(name);+ node->get_output_tensor(0).set_names({name});+}++// TODO: Consolidate with similar pattern in prepare_embedding_model.cpp+class HardcodedPositionIdsMatcher : public ov::pass::MultiMatcher {+public:+ OPENVINO_MATCHER_PASS_RTTI("ov::npuw::HardcodedPositionIdsMatcher");+ explicit HardcodedPositionIdsMatcher(ov::ParameterVector& new_params) {+ auto range = opp::wrap_type<ov::op::v4::Range>();+ auto unsqueeze_axes = opp::wrap_type<ov::op::v0::Constant>();+ auto unsqueeze = opp::wrap_type<ov::op::v0::Unsqueeze>({range, unsqueeze_axes});++ auto unsqueeze1_axes = opp::wrap_type<ov::op::v0::Constant>();+ auto unsqueeze1 = opp::wrap_type<ov::op::v0::Unsqueeze>({unsqueeze, unsqueeze1_axes});++ // FIXME: Convert probably needs to be made optional in future as in similar transformation from+ // prepare_embedding_model.cpp+ auto convert = opp::wrap_type<ov::op::v0::Convert>({unsqueeze1});+ auto matmul = opp::wrap_type<ov::op::v0::MatMul>({opp::any_input(), convert});+ auto transpose = opp::wrap_type<ov::op::v1::Transpose>({matmul, opp::any_input()});++ auto concat = opp::wrap_type<ov::op::v0::Concat>({transpose, transpose});+ auto cos = opp::wrap_type<ov::op::v0::Cos>(concat);+ auto sin = opp::wrap_type<ov::op::v0::Sin>(concat);++ ov::pass::MultiMatcher::Callback callback = [=, &new_params](const auto& m) {+ // NOTE: Range that mimics `position_ids` is consumed by RoPE operation as well as by Causal Mask creation+ // (LessEqual operation) and Gated Short Convolution Block's ScattedNDUpdate operation.+ // For static shapes case, it is not right to use actual `position_ids` for the second argument of+ // LessEqual operation (=Q range), because causal triangular mask will only allow positions from+ // the left till the real current positions in the sequence (inclusively), while our current items+ // are lied at the right end of the static `input_ids` after a window of padding.+ // Thus, the Range is preserved for Causal Mask creation, while added `position_ids` parameter is+ // used only for RoPE and ScatterNDUpdate in Gated Short Convolution Block.+ auto& pattern_to_output = m.at(cos).front();++ auto range_node = pattern_to_output.at(range).get_node_shared_ptr();+ auto unsqueeze_node = pattern_to_output.at(unsqueeze).get_node_shared_ptr();+ // Point of branching:+ auto unsqueeze1_node = pattern_to_output.at(unsqueeze1).get_node_shared_ptr();+ auto convert_node = pattern_to_output.at(convert).get_node_shared_ptr();++ // Create `position_ids` parameter+ auto position_ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});+ set_node_name(position_ids, "position_ids");++ // Create new Unsqueeze node for point of branching+ auto unsqueeze1_node_copy =+ unsqueeze1_node->clone_with_new_inputs({position_ids, unsqueeze1_node->input_value(1)});+ convert_node->input(0).replace_source_output(unsqueeze1_node_copy->output(0));++ // FIXME: For Gated Short Convolution Block, there is ScatterNDUpdate that also consumes generated+ // positions.+ // It seems to right to use the newly created `position_ids` for it as well, however, real tests show+ // no difference against usage of hardcoded QRange: both are similarly accurate.+ auto position_ids_squeezed = std::make_shared<ov::op::v0::Squeeze>(+ position_ids,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0}));+ OPENVINO_ASSERT(range_node->get_output_size() == 1, "Range node should have exactly one output");+ auto range_consumers = range_node->get_output_target_inputs(0);+ for (auto&& consumer : range_consumers) {+ if (consumer.get_node()->get_type_name() == std::string("Unsqueeze") &&+ consumer.get_node() == unsqueeze_node.get()) {+ // Preserve original Range for Causal Mask creation+ continue;+ }+ consumer.replace_source_output(position_ids_squeezed->output(0));+ }++ new_params.push_back(position_ids);+ return true;+ };++ register_patterns({sin, cos}, std::move(callback));+ }+};++#ifdef __GNUC__+# pragma GCC diagnostic pop+#endif+} // anonymous namespace++bool ov::npuw::AddPositionIdsParam::run_on_model(const std::shared_ptr<ov::Model>& model) {+ ov::ParameterVector new_parameters;+ ov::pass::Manager manager("add-position-ids-param");+ manager.set_per_pass_validation(false);+ manager.register_pass<HardcodedPositionIdsMatcher>(new_parameters);+ manager.run_passes(model);++ model->add_parameters(new_parameters);+ model->validate_nodes_and_infer_types();+ return true;+}diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/add_position_ids_param.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/add_position_ids_param.hppnew file mode 100644index 00000000000..b34001c089d--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/add_position_ids_param.hpp@@ -0,0 +1,16 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/openvino.hpp"++namespace ov::npuw {++class AddPositionIdsParam : public ov::pass::ModelPass {+public:+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::AddPositionIdsParam");+ 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 dedbfac3db3..17c55cdb469 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@@ -39,12 +39,14 @@ void reshape_to_static(std::shared_ptr<ov::Model> model,new_shape = ov::PartialShape({1, kvcache_size + 1});} 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 uses 3D shapes+ // NB: Regular LLM uses 2D shapes, Qwen2.5 VL/Omni, Qwen3.5 VL use 3D shapes// The first dimension (3) represents the three components of position encoding: time, height, and width// enabling alignment across multimodal inputs like text, audio, and video+ // Update: Qwen3.5 has first dimension = 4.NPUW_ASSERT(partial_shape_size == 3u || partial_shape_size == 2u);- new_shape =- partial_shape_size == 3u ? ov::PartialShape({3, 1, input_size}) : ov::PartialShape({1, input_size});+ auto first_dim_value = input.get_partial_shape()[0];+ new_shape = partial_shape_size == 3u ? ov::PartialShape({first_dim_value, 1, input_size})+ : ov::PartialShape({1, input_size});} else if (input_name.find("cache_position") != std::string::npos) {// NB: Whisper casenew_shape = ov::PartialShape({1});@@ -103,6 +105,14 @@ void reshape_to_static(std::shared_ptr<ov::Model> model,NPUW_ASSERT(num_layers.is_static()); // num_layers must be resolvedNPUW_ASSERT(proj_dim.is_static()); // projection_dim must be resolvednew_shape = ov::PartialShape({1, input_size, num_layers, proj_dim});+ } else if (ov::npuw::util::matchLinCacheString(input_name)) {+ const auto& partial_shape = input.get_partial_shape();+ new_shape = partial_shape;+ // NOTE: Batch axes of KVCache and Linear Cache have same positions, however+ // need to track that this assumption holds in future versions.+ const auto& shape_batch_dim = partial_shape[kv_axes_position.batch];+ NPUW_ASSERT(shape_batch_dim.is_dynamic() || shape_batch_dim.get_length() <= 1);+ new_shape[kv_axes_position.batch] = 1; // batch_dim} else {const auto& partial_shape = input.get_partial_shape();new_shape = partial_shape;diff --git a/src/plugins/intel_npu/src/plugin/npuw/util.cpp b/src/plugins/intel_npu/src/plugin/npuw/util.cppindex ec4faddbd5d..64a2e81a4ed 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util.cpp@@ -913,6 +913,19 @@ bool ov::npuw::util::matchLoRAMatMulAlphaString(const std::string& input) {return ov::npuw::util::matchStringWithLoRAPattern(input, LoRANames::MatMul_alpha);}+bool ov::npuw::util::matchLinCacheString(const std::string& input, const std::string& past_or_present) {+ static std::regex past_regex_pattern("^cache_params\\.past\\.(conv|ssm)\\.(\\d+)$");+ static std::regex present_regex_pattern("^cache_params\\.present\\.(conv|ssm)\\.(\\d+)$");+ const std::regex& regex_pattern = (past_or_present == "past") ? past_regex_pattern : present_regex_pattern;+ return std::regex_match(input, regex_pattern);+}++bool ov::npuw::util::starts_with_past_lincache(const std::string& input_name) {+ static constexpr const char* past_lin_conv_cache = "cache_params.past.conv";+ static constexpr const char* past_lin_ssm_cache = "cache_params.past.ssm";+ return ov::npuw::util::starts_with(input_name, past_lin_conv_cache) ||+ ov::npuw::util::starts_with(input_name, past_lin_ssm_cache);+}void ov::npuw::util::fill_tensor_bytes(ov::SoPtr<ov::ITensor> tensor, uint8_t fill_val) {auto* tensor_data = reinterpret_cast<uint8_t*>(tensor->data());const size_t byte_size = tensor->get_byte_size();@@ -931,6 +944,14 @@ bool ov::npuw::util::isPastValueParam(const std::string& str) {return std::regex_match(str, pattern);}+bool ov::npuw::util::isRestoredPastKeyValueParam(const std::string& str) {+ // Match badly handled KVCache states by StatefulToStateless pass for Whisper.+ static const std::regex restored_pattern(+ R"((input_restored\.past_key_values\.(\d+)\.decoder\.(key|value))(present\.(\d+)\.decoder\.(key|value)))");+ ;+ return std::regex_match(str, restored_pattern);+}+std::optional<int> ov::npuw::util::isPastKeyValuesKeyContiguous(const std::string& str) {// Match only the single contiguous past key param (no _block_ suffix).// Allows optional intermediate parts like "encoder" or "decoder" (for Whisper).diff --git a/src/plugins/intel_npu/src/plugin/npuw/util.hpp b/src/plugins/intel_npu/src/plugin/npuw/util.hppindex fdfffd65a10..8907b1358fb 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util.hpp@@ -196,6 +196,10 @@ bool matchLoRAMatMulBString(const std::string& input);bool matchLoRAMatMulAlphaString(const std::string& input);+bool matchLinCacheString(const std::string& input, const std::string& past_or_present = "past");++bool starts_with_past_lincache(const std::string& input_name);+// Structure to hold SDPA pattern nodesstruct SDPAPatternNodes {std::shared_ptr<ov::Node> matmul1_node = nullptr;@@ -303,6 +307,10 @@ bool isPastKeyParam(const std::string& str);// Matches any past value param: contiguous or block-split.bool isPastValueParam(const std::string& str);+// To remove input KV params that got badly matched in StatefulToStateless pass+// in Whisper model.+bool isRestoredPastKeyValueParam(const std::string& str);+} // namespace util} // namespace npuw} // namespace ovdiff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex cc80704c97e..c0bd129129d 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -89,6 +89,7 @@ ov_add_test_target(# attn${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.cpp# npuw_transformations+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/add_position_ids_param.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/convert_kvcache_to_precision.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/decompose_gqa.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/lora_stateful_to_stateless.cpp