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: Dynamically switch context on generation with generation pyramid (#36701)
intelgaoxiongb92ff3c434dd
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.cppindex 25ffbb0fae2..c09b045b0b4 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.cpp@@ -268,6 +268,7 @@ void LLMBlockKVCacheStrategy::on_initialize() {}}LOG_INFO("Snapshotted " << m_prefill_original_output_tensors.size() << " original prefill output tensors");+LOG_INFO("=== Block-based KV Cache Initialization Complete ===");}@@ -460,6 +461,16 @@ void LLMBlockKVCacheStrategy::on_generate_kv_init() {LOG_DEBUG("Initial binding complete.");}+// Rebind existing block tensors to the new (larger) variant's ports (zero-copy).+// Lincache is shared across all variants by on_initialize(), so no migration is needed.+void LLMBlockKVCacheStrategy::on_generate_variant_switch(const std::shared_ptr<ov::IAsyncInferRequest>& /*old_req*/,+ const PortsMap& /*old_in_ports*/,+ const std::shared_ptr<ov::IAsyncInferRequest>& /*new_req*/,+ const PortsMap& /*new_in_ports*/) {+ LOG_DEBUG("Rebinding KV blocks to new generate variant.");+ on_generate_kv_init();+}+void LLMBlockKVCacheStrategy::on_generate_step_done(uint32_t input_tokens_len) {const auto& kvcache_desc = m_req.m_npuw_llm_compiled_model->m_kvcache_desc;const uint32_t tokens_after = kvcache_desc.num_stored_tokens;diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.hppindex 002628489eb..62b771f90d2 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.hpp@@ -114,6 +114,10 @@ public:void on_prefill_chunk_begin(uint32_t current_prompts_len) override;void on_prefill_chunk_done(uint32_t current_prompts_len, bool is_last) override;void on_generate_kv_init() override;+ void on_generate_variant_switch(const std::shared_ptr<ov::IAsyncInferRequest>& old_req,+ const PortsMap& old_in_ports,+ const std::shared_ptr<ov::IAsyncInferRequest>& new_req,+ const PortsMap& new_in_ports) override;void on_generate_step_done(uint32_t input_tokens_len) override;private: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 809935aa4f7..53b9059d03f 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@@ -567,6 +567,12 @@ std::vector<std::shared_ptr<ov::Model>> ov::npuw::LLMCompiledModel::create_generconst KVAxesPosition& axes,const uint32_t whisper_lhs_seq_size) {const uint32_t total_kv_size = m_kvcache_desc.total_size;+ OPENVINO_ASSERT(total_kv_size >= m_kvcache_desc.max_prompt_size,+ "KV cache total size ",+ total_kv_size,+ " is smaller than max_prompt_size ",+ m_kvcache_desc.max_prompt_size,+ ".");const uint32_t min_response_len = total_kv_size - m_kvcache_desc.max_prompt_size;const uint32_t max_generation_token_len = m_kvcache_desc.max_generation_token_len;const bool enable_generate_pyramid = m_cfg.get<::intel_npu::NPUW_LLM_GENERATE_PYRAMID>();diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hppindex 5fda107ecb2..d9796d2d444 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp@@ -9,6 +9,14 @@#include "compiled_model.hpp"#include "npuw_transformations/kv_axes_position.hpp"+namespace ov {+namespace test {+namespace npuw {+struct LLMVariantSwitchTestAccess;+} // namespace npuw+} // namespace test+} // namespace ov+namespace ov {namespace npuw {@@ -79,6 +87,7 @@ private:friend class EmbeddingInferRequest;friend class LLMBlockKVCacheStrategy;friend class LLMContinuousKVCacheStrategy;+ friend struct ov::test::npuw::LLMVariantSwitchTestAccess;std::shared_ptr<ov::ISyncInferRequest> create_llm_infer_request();std::shared_ptr<ov::ISyncInferRequest> create_whisper_infer_request();diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.cppindex 6df8aee021a..4b54a4694dd 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.cpp@@ -4,6 +4,7 @@#include "llm_continuous_kvcache_strategy.hpp"+#include "infer_request_utils.hpp"#include "llm_infer_request.hpp"#include "util.hpp"@@ -11,29 +12,26 @@ namespace ov {namespace npuw {// on_initialize:-// 1. Share past KV and lincache buffers from the largest generate variant into all smaller-// variants so they use the same backing allocation (saves memory).+// 1. Share past KV buffers from the largest generate variant into all smaller variants+// so they use the same backing allocation (saves memory).// 2. Bind prefill past KV to the generate model's buffer so they share memory (chunk prefill).// 3. Zero-fill the shared KV buffer so the first chunk sees clean state.// Steps 2–3 are only applicable when chunk prefill is enabled.void LLMContinuousKVCacheStrategy::on_initialize() {- // Step 1: share KV buffers across generate variants.- // Collect the largest variant's KV and lincache tensors into lookup maps (one pass).+ // Step 1: share past KV buffers across generate variants.+ // Collect the largest variant's KV tensors into a lookup map (one pass).auto& generate_requests = m_req.m_generate_requests;if (generate_requests.size() > 1) {const auto& largest_request = generate_requests.back();std::unordered_map<std::string, ov::SoPtr<ov::ITensor>> largest_past_kv_tensors;- std::unordered_map<std::string, ov::SoPtr<ov::ITensor>> past_lin_tensors;for (const auto& input_port : largest_request->get_compiled_model()->inputs()) {const auto& input_name = input_port.get_any_name();if (ov::npuw::util::starts_with(input_name, LLMInferRequest::layer_names::past_key_values)) {largest_past_kv_tensors[input_name] = largest_request->get_tensor(input_port);- } else if (ov::npuw::util::starts_with_past_lincache(input_name)) {- past_lin_tensors[input_name] = largest_request->get_tensor(input_port);}}- // For every smaller variant, share past KV and lincache tensors from the largest variant.+ // For every smaller variant, share past KV tensors from the largest variant.for (size_t i = 0; i < generate_requests.size() - 1; ++i) {auto& variant = generate_requests[i];for (const auto& input_port : variant->get_compiled_model()->inputs()) {@@ -48,11 +46,6 @@ void LLMContinuousKVCacheStrategy::on_initialize() {largest_past_kv_tensors.at(input_name)->data()),nullptr);variant->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);- variant->set_tensor(input_port, past_lin_tensors.at(input_name));}}}@@ -103,6 +96,47 @@ void LLMContinuousKVCacheStrategy::on_generate_kv_init() {m_req.copy_kvcache();}+// Migrate live KV tokens from the old variant's BNSD layout to the new variant's layout.+// All variants share the same backing buffer but have different per-head strides (S differs),+// so data must be re-packed via a temporary CPU buffer to avoid aliasing corruption.+// Lincache tensors are shared by reference and need no migration.+void LLMContinuousKVCacheStrategy::on_generate_variant_switch(const std::shared_ptr<ov::IAsyncInferRequest>& old_req,+ const PortsMap& old_in_ports,+ const std::shared_ptr<ov::IAsyncInferRequest>& new_req,+ const PortsMap& new_in_ports) {+ namespace uu = ov::npuw::util;+ const auto& kvcache_desc = m_req.m_npuw_llm_compiled_model->m_kvcache_desc;+ const uint32_t num_stored = kvcache_desc.num_stored_tokens;+ if (num_stored == 0) {+ return;+ }++ LOG_DEBUG("Migrating " << num_stored << " KV tokens to new generate variant.");++ for (const auto& name : m_req.m_kvcache_past_names) {+ auto src = old_req->get_tensor(old_in_ports.at(name));+ auto dst = new_req->get_tensor(new_in_ports.at(name));++ // Use the "present" name to distinguish key vs value — same pattern as+ // update_kvcache_for. Direct find("value") on the input name is unreliable+ // because "past_key_values.N.key" contains "value" via "key_values".+ const auto present_name =+ std::regex_replace(name, std::regex(ov::npuw::LLMInferRequest::layer_names::past_key_values), "present");+ const uint32_t kv_dim =+ (present_name.find("value") != std::string::npos && kvcache_desc.v_tensors_transposed_gen)+ ? 3u+ : kvcache_desc.dim;++ auto src_slice = uu::make_tensor_slice(src, kv_dim, 0u, num_stored);+ auto dst_slice = uu::make_tensor_slice(dst, kv_dim, 0u, num_stored);++ // Copy via a temporary CPU buffer to avoid aliasing (src and dst share backing memory).+ auto tmp = uu::allocMem(src->get_element_type(), src_slice->get_shape(), "CPU", nullptr);+ src_slice->copy_to(tmp._ptr);+ uu::copy_tensor_by_dim(tmp, dst_slice, kv_dim, kv_dim);+ }+}+// on_generate_step_done: persist the new token's KV output into the past KV input buffer// so the next generate step sees the updated context.void LLMContinuousKVCacheStrategy::on_generate_step_done(uint32_t input_tokens_len) {diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.hppindex dbb949ea55e..e0a351a8f66 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.hpp@@ -30,6 +30,10 @@ public:void on_prefill_chunk_begin(uint32_t current_prompts_len) override;void on_prefill_chunk_done(uint32_t current_prompts_len, bool is_last) override;void on_generate_kv_init() override;+ void on_generate_variant_switch(const std::shared_ptr<ov::IAsyncInferRequest>& old_req,+ const PortsMap& old_in_ports,+ const std::shared_ptr<ov::IAsyncInferRequest>& new_req,+ const PortsMap& new_in_ports) override;void on_generate_step_done(uint32_t input_tokens_len) override;};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 2e0ca64bc32..41e6ef36090 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@@ -318,6 +318,9 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCom_kvcache_strategy = std::make_unique<LLMContinuousKVCacheStrategy>(*this);}m_kvcache_strategy->on_initialize();+ // Lincache shape is kvcache_size-independent, so the same tensor can be shared across all+ // generate variants.+ share_lincache_across_generate_variants();if (m_npuw_llm_compiled_model->m_enable_prefix_caching) {const size_t prefix_cache_count = m_npuw_llm_compiled_model->m_longrope_context_limit > 0u ? 2u : 1u;@@ -601,6 +604,10 @@ void ov::npuw::LLMInferRequest::prepare_for_new_conversation(int64_t prompt_lengm_kvcache_request = select_generate_request(prompt_length);m_kvcache_in_ports = m_generate_variant_in_ports.at(m_kvcache_request);m_kvcache_out_ports = m_generate_variant_out_ports.at(m_kvcache_request);+ // Record the selected variant index for O(1) capacity queries and mid-decode switching.+ const auto& reqs = m_generate_requests;+ m_kvcache_variant_idx =+ static_cast<size_t>(std::distance(reqs.begin(), std::find(reqs.begin(), reqs.end(), m_kvcache_request)));}void ov::npuw::LLMInferRequest::copy_kvcache() {@@ -741,6 +748,26 @@ void ov::npuw::LLMInferRequest::update_kvcache_for(}}+void ov::npuw::LLMInferRequest::share_lincache_across_generate_variants() {+ if (m_generate_requests.size() <= 1 || m_lincache_past_names.empty()) {+ return;+ }+ const auto& largest_req = m_generate_requests.back();+ const auto& largest_ports = m_generate_variant_in_ports.at(largest_req);+ std::unordered_map<std::string, ov::SoPtr<ov::ITensor>> lincache_tensors;+ for (const auto& name : m_lincache_past_names) {+ lincache_tensors[name] = largest_req->get_tensor(largest_ports.at(name));+ }+ for (size_t i = 0; i < m_generate_requests.size() - 1; ++i) {+ const auto& variant_ports = m_generate_variant_in_ports.at(m_generate_requests[i]);+ for (const auto& name : m_lincache_past_names) {+ m_generate_requests[i]->set_tensor(variant_ports.at(name), lincache_tensors.at(name));+ }+ }+ LOG_INFO("Shared " << m_lincache_past_names.size() << " lincache tensors across " << m_generate_requests.size()+ << " generate variants");+}+void ov::npuw::LLMInferRequest::copy_lincache(std::shared_ptr<ov::IAsyncInferRequest> from_request,std::shared_ptr<ov::IAsyncInferRequest> to_request,@@ -769,6 +796,40 @@ void ov::npuw::LLMInferRequest::copy_lincache(LOG_DEBUG("Done.");}+uint32_t ov::npuw::LLMInferRequest::get_current_variant_capacity() const {+ // The generate model's past KV input tensor is shaped to (kv_size - max_generation_token_len)+ // by ReshapeToStatic. Capacity is the number of past tokens that fit, not the total KV window.+ const uint32_t kv_size = m_npuw_llm_compiled_model->m_kvcache_sizes[m_kvcache_variant_idx];+ const uint32_t max_gen_len = m_npuw_llm_compiled_model->m_kvcache_desc.max_generation_token_len;+ OPENVINO_ASSERT(kv_size >= max_gen_len,+ "KV cache size ",+ kv_size,+ " is smaller than max_generation_token_len ",+ max_gen_len,+ ".");+ return kv_size - max_gen_len;+}++bool ov::npuw::LLMInferRequest::try_switch_to_larger_variant() {+ const size_t next_idx = m_kvcache_variant_idx + 1;+ if (next_idx >= m_generate_requests.size()) {+ return false; // already at the largest variant+ }+ const auto& kvcache_sizes = m_npuw_llm_compiled_model->m_kvcache_sizes;+ LOG_INFO("KV cache capacity (" << kvcache_sizes[m_kvcache_variant_idx] << ") reached at "+ << m_npuw_llm_compiled_model->m_kvcache_desc.num_stored_tokens+ << " stored tokens; switching to variant with capacity " << kvcache_sizes[next_idx]+ << ".");+ const auto old_req = m_kvcache_request;+ const auto old_in_ports = m_kvcache_in_ports;+ m_kvcache_variant_idx = next_idx;+ m_kvcache_request = m_generate_requests[next_idx];+ m_kvcache_in_ports = m_generate_variant_in_ports.at(m_kvcache_request);+ m_kvcache_out_ports = m_generate_variant_out_ports.at(m_kvcache_request);+ m_kvcache_strategy->on_generate_variant_switch(old_req, old_in_ports, m_kvcache_request, m_kvcache_in_ports);+ return true;+}+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.@@ -1161,8 +1222,18 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,".\nPlease adjust it.");}- // Note: m_kvcache_request, m_kvcache_in_ports, and m_kvcache_out_ports are selected in- // prepare_for_new_conversation()+ // Lazy variant switch: if the previous step exhausted the active variant's capacity,+ // switch now before preparing inputs for this step. Guarded by m_generate_initialized+ // because on the first step KV data is still in the prefill model and hasn't been+ // copied to the generate model yet by on_generate_kv_init().+ if (m_generate_initialized && kvcache_desc.num_stored_tokens >= get_current_variant_capacity()) {+ if (!try_switch_to_larger_variant()) {+ OPENVINO_THROW("KV-Cache is full: num_stored_tokens=",+ kvcache_desc.num_stored_tokens,+ " capacity=",+ get_current_variant_capacity());+ }+ }// Eagle3: Check for sampling result from external pipeline via VariableStateif (m_eagle3_ext.is_eagle3_model() && m_generate_initialized) {@@ -1208,7 +1279,6 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,// No visual tokens are generated during the generate stagestd::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)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 b73a7fb66d0..c0dd38ef862 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@@ -17,6 +17,14 @@#include "openvino/core/descriptor/output.hpp"#include "perf.hpp"+namespace ov {+namespace test {+namespace npuw {+struct LLMVariantSwitchTestAccess;+} // namespace npuw+} // namespace test+} // namespace ov+namespace ov {namespace npuw {@@ -44,6 +52,10 @@ protected: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);+ // Share lincache tensors from the largest generate variant to all smaller variants so+ // that a variant switch requires no explicit lincache migration. Called once after+ // m_kvcache_strategy->on_initialize() and is strategy-independent.+ void share_lincache_across_generate_variants();// Select appropriate generate request variant based on prompt length// Internally calculates expected total tokens (prompt + min_response_len) to ensure// sufficient capacity for both input prompt and minimum response generation@@ -51,6 +63,14 @@ protected:void trim_kvcache_for_speculative_decoding(ov::SoPtr<ov::ITensor> position_ids);+ // Returns the KV cache capacity (max storable tokens) of the currently active variant.+ uint32_t get_current_variant_capacity() const;++ // Switches to the next larger generate variant mid-decode when the current variant's+ // KV cache is full. Updates m_kvcache_request, ports, m_kvcache_variant_idx, and+ // delegates KV rebinding to the strategy. Returns false if already at the largest variant.+ bool try_switch_to_larger_variant();+void infer_chunked_prefill(ov::SoPtr<ov::ITensor> input_ids,ov::SoPtr<ov::ITensor> attention_mask,ov::SoPtr<ov::ITensor> position_ids,@@ -124,6 +144,10 @@ protected:bool m_generate_initialized = false;+ // Index into m_generate_requests / m_kvcache_sizes for the currently active variant.+ // Updated in prepare_for_new_conversation() and try_switch_to_larger_variant().+ size_t m_kvcache_variant_idx = 0;+bool m_first_run = true;int64_t m_first_position_id = 0;@@ -161,6 +185,7 @@ protected:friend class LLMContinuousKVCacheStrategy;friend class LLMBlockKVCacheStrategy;friend class PrefixCachingHelper;+ friend struct ov::test::npuw::LLMVariantSwitchTestAccess;};} // namespace npuwdiff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_kvcache_strategy.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_kvcache_strategy.hppindex a70403ace78..4f1b0690c83 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_kvcache_strategy.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_kvcache_strategy.hpp@@ -7,6 +7,7 @@#include <cstdint>#include <memory>+#include "llm_infer_base_request.hpp"#include "openvino/runtime/iasync_infer_request.hpp"namespace ov {@@ -33,9 +34,12 @@ class LLMInferRequest; // forward declaration — strategy always outlived by i* is_last=false: intermediate chunk — persist KV outputs into past buffer* is_last=true: final chunk — store outputs into blocks (block mode) or no-op* 4. Per generate step:- * a. on_generate_kv_init() — first generate step: bind/copy prefill→generate KV+ * a. on_generate_kv_init() — first step only: bind/copy prefill KV into generate* b. infer() [called by LLMInferRequest]- * c. on_generate_step_done() — after infer(), update KV for next step+ * c. on_generate_step_done() — after infer(): persist new token KV, update bindings+ * c'. on_generate_variant_switch() — conditional, after c: if the current variant's KV+ * capacity is now full, promote to the next larger one+ * so the next iteration starts with it already selected.*/class LLMKVCacheStrategy {public:@@ -45,6 +49,8 @@ public:* The reference guarantees the request outlives the strategy (both live inside the* same LLMInferRequest object) and can never be null.*/+ using PortsMap = LLMInferBaseRequest::PortsMap;+explicit LLMKVCacheStrategy(LLMInferRequest& req) : m_req(req) {}virtual ~LLMKVCacheStrategy() = default;@@ -68,6 +74,16 @@ public:// bind/copy the accumulated prefill KV into the generate model's input ports.virtual void on_generate_kv_init() = 0;+ // Called after on_generate_step_done() when the active variant's KV cache is now full.+ // old_req/old_in_ports: the variant that just reached capacity (source of live KV data).+ // new_req/new_in_ports: the promoted larger variant (destination for KV migration).+ // Block-based: rebind existing block tensors to new variant ports (zero-copy).+ // Continuous: re-pack live tokens from old BNSD layout to new layout via a CPU temp buffer.+ virtual void on_generate_variant_switch(const std::shared_ptr<ov::IAsyncInferRequest>& old_req,+ const PortsMap& old_in_ports,+ const std::shared_ptr<ov::IAsyncInferRequest>& new_req,+ const PortsMap& new_in_ports) = 0;+// Called after each generate step's infer(): persist new token KV and update bindingsvirtual void on_generate_step_done(uint32_t input_tokens_len) = 0;diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex b670820567e..659cd90851d 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -148,6 +148,7 @@ target_sources(${TARGET_NAME} PRIVATE${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_compiled_model_graph_options_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/gqa_compiled_model_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/stored_tokens_state_test.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_infer_request_variant_switch_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/lincache_utils_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/partitioning_options_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_options_smoke_test.cppdiff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_infer_request_variant_switch_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/llm_infer_request_variant_switch_test.cppnew file mode 100644index 00000000000..49c1ef97480--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_infer_request_variant_switch_test.cpp@@ -0,0 +1,321 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <gtest/gtest.h>++#include <algorithm>+#include <cstdint>+#include <cstring>+#include <memory>+#include <string>+#include <unordered_map>+#include <utility>+#include <vector>++#include "executor.hpp"+#include "llm_block_kvcache_strategy.hpp"+#include "llm_infer_request.hpp"+#include "llm_compiled_model.hpp"+#include "llm_test_helpers.hpp"+#include "openvino/openvino.hpp"+#include "util.hpp"++namespace ov::test::npuw {++struct LLMVariantSwitchTestAccess {+ static std::size_t generate_variant_count(const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled) {+ return compiled->m_generate_compiled_variants.size();+ }++ static std::shared_ptr<ov::npuw::ICompiledModel_v0> generate_variant(+ const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled,+ std::size_t idx) {+ return compiled->m_generate_compiled_variants.at(idx);+ }++ static bool is_block_kv_cache(const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled) {+ return compiled->m_is_block_kv_cache;+ }++ static void set_num_stored_tokens(const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled, uint32_t num_tokens) {+ compiled->m_kvcache_desc.num_stored_tokens = num_tokens;+ }++ static uint32_t kv_dim_for_name(const ov::npuw::LLMInferRequest& req, const std::string& name) {+ const auto& desc = req.m_npuw_llm_compiled_model->m_kvcache_desc;+ return (ov::npuw::util::isPastValueParam(name) && desc.v_tensors_transposed_gen) ? 3u : desc.dim;+ }++ static void select_smallest_generate_variant(ov::npuw::LLMInferRequest& req) {+ ASSERT_GE(req.m_generate_requests.size(), 2u);+ req.m_kvcache_variant_idx = 0u;+ req.m_kvcache_request = req.m_generate_requests.front();+ req.m_kvcache_in_ports = req.m_generate_variant_in_ports.at(req.m_kvcache_request);+ req.m_kvcache_out_ports = req.m_generate_variant_out_ports.at(req.m_kvcache_request);+ }++ static uint32_t current_variant_capacity(ov::npuw::LLMInferRequest& req) {+ return req.get_current_variant_capacity();+ }++ static bool try_switch_to_larger_variant(ov::npuw::LLMInferRequest& req) {+ return req.try_switch_to_larger_variant();+ }++ static std::size_t current_variant_index(const ov::npuw::LLMInferRequest& req) {+ return req.m_kvcache_variant_idx;+ }++ static const std::vector<std::string>& kvcache_past_names(const ov::npuw::LLMInferRequest& req) {+ return req.m_kvcache_past_names;+ }++ static const auto& kvcache_in_ports(const ov::npuw::LLMInferRequest& req) {+ return req.m_kvcache_in_ports;+ }++ static const auto& kvcache_request(const ov::npuw::LLMInferRequest& req) {+ return req.m_kvcache_request;+ }+};++} // namespace ov::test::npuw++namespace {++using ov::test::npuw::build_llm_test_model;+using ov::test::npuw::LLMVariantSwitchTestAccess;+using ov::test::npuw::NullPlugin;+class FakeSubCompiledModel;++class FakeSubInferRequest final : public ov::ISyncInferRequest {+public:+ explicit FakeSubInferRequest(std::shared_ptr<const FakeSubCompiledModel> compiled_model);++ void infer() override;+ ov::SoPtr<ov::ITensor> get_tensor(const ov::Output<const ov::Node>& port) const override {+ return ov::ISyncInferRequest::get_tensor(port);+ }+ void set_tensor(const ov::Output<const ov::Node>& port, const ov::SoPtr<ov::ITensor>& tensor) override {+ ov::ISyncInferRequest::set_tensor(port, tensor);+ }+ void check_tensors() const override {}+ std::vector<ov::SoPtr<ov::IVariableState>> query_state() const override {+ return {};+ }+ std::vector<ov::ProfilingInfo> get_profiling_info() const override {+ return {};+ }+};++class FakeSubCompiledModel final : public ov::npuw::ICompiledModel_v0 {+public:+ FakeSubCompiledModel(const std::shared_ptr<ov::Model>& model,+ const std::shared_ptr<const ov::IPlugin>& plugin,+ const ov::AnyMap&)+ : ov::npuw::ICompiledModel_v0(model, plugin),+ m_model(model) {}++ void export_model(std::ostream&) const override {}+ std::shared_ptr<const ov::Model> get_runtime_model() const override {+ return m_model;+ }+ void set_property(const ov::AnyMap&) override {}+ ov::Any get_property(const std::string&) const override {+ return {};+ }+ std::shared_ptr<ov::ISyncInferRequest> create_sync_infer_request() const override {+ auto self = std::static_pointer_cast<const FakeSubCompiledModel>(shared_from_this());+ return std::make_shared<FakeSubInferRequest>(std::move(self));+ }+ std::shared_ptr<ov::npuw::IBaseInferRequest> create_base_infer_request() const override {+ return {};+ }+ std::shared_ptr<ov::IAsyncInferRequest> wrap_async_infer_request(+ std::shared_ptr<ov::npuw::IBaseInferRequest>) const override {+ return std::make_shared<ov::IAsyncInferRequest>(create_sync_infer_request(),+ intel_npu::make_executor("variant_switch_task", 1),+ intel_npu::make_executor("variant_switch_callback", 1));+ }+ std::string submodel_device(std::size_t) const override {+ return "CPU";+ }+ std::size_t num_submodels() const override {+ return 0;+ }+ std::shared_ptr<ov::npuw::weights::Bank> get_weights_bank() const override {+ return {};+ }+ void set_weights_bank(std::shared_ptr<ov::npuw::weights::Bank>) override {}+ void finalize_weights_bank() override {}+ void reconstruct_closure() override {}+ void serialize(std::ostream&, const ov::npuw::s11n::CompiledContext&) const override {}++private:+ std::shared_ptr<ov::Model> m_model;+};++FakeSubInferRequest::FakeSubInferRequest(std::shared_ptr<const FakeSubCompiledModel> compiled_model)+ : ov::ISyncInferRequest(std::move(compiled_model)) {+ for (const auto& input : get_compiled_model()->inputs()) {+ ov::ISyncInferRequest::set_tensor(input,+ ov::get_tensor_impl(ov::Tensor(input.get_element_type(), input.get_shape())));+ }+ for (const auto& output : get_compiled_model()->outputs()) {+ ov::ISyncInferRequest::set_tensor(output,+ ov::get_tensor_impl(ov::Tensor(output.get_element_type(), output.get_shape())));+ }+}++void FakeSubInferRequest::infer() {+ for (const auto& output : get_compiled_model()->outputs()) {+ auto tensor = ov::ISyncInferRequest::get_tensor(output);+ std::memset(tensor->data(), 0, tensor->get_byte_size());+ }+}++class VariantSwitchFactory {+public:+ ov::npuw::LLMCompiledModel::CompiledModelFactory make_factory() {+ return [](const std::shared_ptr<ov::Model>& model,+ const std::shared_ptr<const ov::IPlugin>& plugin,+ const ov::AnyMap& props) -> std::shared_ptr<ov::npuw::ICompiledModel_v0> {+ return std::make_shared<FakeSubCompiledModel>(model, plugin, props);+ };+ }+};++std::vector<uint8_t> materialize_bytes(const ov::SoPtr<ov::ITensor>& tensor) {+ ov::Tensor copy(tensor->get_element_type(), tensor->get_shape());+ tensor->copy_to(ov::get_tensor_impl(copy)._ptr);+ auto* data = static_cast<uint8_t*>(copy.data());+ return std::vector<uint8_t>(data, data + copy.get_byte_size());+}++void fill_tensor_pattern(const ov::SoPtr<ov::ITensor>& tensor, uint8_t seed) {+ ov::Tensor dense(tensor->get_element_type(), tensor->get_shape());+ auto* data = static_cast<uint8_t*>(dense.data());+ for (size_t i = 0; i < dense.get_byte_size(); ++i) {+ data[i] = static_cast<uint8_t>(seed + (i % 251));+ }+ ov::get_tensor_impl(dense)->copy_to(tensor._ptr);+}++class LLMInferRequestVariantSwitchTest : public ::testing::Test {+protected:+ void SetUp() override {+ m_plugin = std::make_shared<NullPlugin>();+ }++ static ov::AnyMap base_props() {+ return {{"NPUW_LLM", "YES"},+ {"NPUW_DEVICES", "CPU"},+ {"NPUW_LLM_MAX_PROMPT_LEN", "2048"},+ {"NPUW_LLM_MIN_RESPONSE_LEN", "64"},+ {"NPUW_LLM_GENERATE_PYRAMID", "YES"}};+ }++ static void merge_props(ov::AnyMap& dst, const ov::AnyMap& src) {+ for (const auto& [key, value] : src) {+ dst[key] = value;+ }+ }++ std::shared_ptr<ov::npuw::LLMCompiledModel> create_compiled_model(const ov::AnyMap& extra_props,+ VariantSwitchFactory& factory) const {+ auto props = base_props();+ merge_props(props, extra_props);+ return std::make_shared<ov::npuw::LLMCompiledModel>(build_llm_test_model(),+ m_plugin,+ props,+ factory.make_factory());+ }++ std::shared_ptr<ov::IPlugin> m_plugin;+};++TEST_F(LLMInferRequestVariantSwitchTest, ContinuousKvSwitchMigratesStoredTokensToLargerVariant) {+ VariantSwitchFactory factory;+ auto compiled = create_compiled_model({}, factory);+ ASSERT_NE(compiled, nullptr);+ ASSERT_EQ(LLMVariantSwitchTestAccess::generate_variant_count(compiled), 2u);++ ov::npuw::LLMInferRequest req(compiled);+ LLMVariantSwitchTestAccess::select_smallest_generate_variant(req);++ const uint32_t stored_tokens = LLMVariantSwitchTestAccess::current_variant_capacity(req);+ LLMVariantSwitchTestAccess::set_num_stored_tokens(compiled, stored_tokens);++ std::unordered_map<std::string, std::vector<uint8_t>> expected_kv_bytes;+ uint8_t seed = 17u;+ for (const auto& name : LLMVariantSwitchTestAccess::kvcache_past_names(req)) {+ auto src = LLMVariantSwitchTestAccess::kvcache_request(req)->get_tensor(+ LLMVariantSwitchTestAccess::kvcache_in_ports(req).at(name));+ auto src_slice = ov::npuw::util::make_tensor_slice(+ src, LLMVariantSwitchTestAccess::kv_dim_for_name(req, name), 0u, stored_tokens);+ fill_tensor_pattern(src_slice, seed);+ expected_kv_bytes.emplace(name, materialize_bytes(src_slice));+ seed = static_cast<uint8_t>(seed + 37u);+ }++ ASSERT_TRUE(LLMVariantSwitchTestAccess::try_switch_to_larger_variant(req));+ EXPECT_EQ(LLMVariantSwitchTestAccess::current_variant_index(req), 1u);++ for (const auto& name : LLMVariantSwitchTestAccess::kvcache_past_names(req)) {+ auto dst = LLMVariantSwitchTestAccess::kvcache_request(req)->get_tensor(+ LLMVariantSwitchTestAccess::kvcache_in_ports(req).at(name));+ auto dst_slice = ov::npuw::util::make_tensor_slice(+ dst, LLMVariantSwitchTestAccess::kv_dim_for_name(req, name), 0u, stored_tokens);+ EXPECT_EQ(materialize_bytes(dst_slice), expected_kv_bytes.at(name)) << name;+ }+}++TEST_F(LLMInferRequestVariantSwitchTest, BlockKvVariantsExposeCompatibleBindingsAcrossSwitchBoundary) {+ VariantSwitchFactory factory;+ auto compiled = create_compiled_model({{"NPUW_LLM_PREFILL_HINT", "DYNAMIC"},+ {"NPUW_LLM_PREFILL_CHUNK_SIZE", "512"},+ {"NPUW_LLM_PREFILL_ATTENTION_HINT", "PYRAMID"},+ {"NPUW_LLM_GENERATE_ATTENTION_HINT", "PYRAMID"},+ {"NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE", "YES"}},+ factory);+ ASSERT_NE(compiled, nullptr);+ ASSERT_EQ(LLMVariantSwitchTestAccess::generate_variant_count(compiled), 2u);+ ASSERT_TRUE(LLMVariantSwitchTestAccess::is_block_kv_cache(compiled));+ auto small_variant = std::dynamic_pointer_cast<FakeSubCompiledModel>(+ LLMVariantSwitchTestAccess::generate_variant(compiled, 0u));+ auto large_variant = std::dynamic_pointer_cast<FakeSubCompiledModel>(+ LLMVariantSwitchTestAccess::generate_variant(compiled,+ LLMVariantSwitchTestAccess::generate_variant_count(compiled) - 1u));+ ASSERT_NE(small_variant, nullptr);+ ASSERT_NE(large_variant, nullptr);++ const auto collect_block0_inputs = [](const std::shared_ptr<const ov::Model>& model, const std::string& suffix) {+ std::vector<std::string> names;+ for (const auto& input : model->inputs()) {+ const auto& name = input.get_any_name();+ if (name.find("past_key_values.") == 0 && name.find(suffix) != std::string::npos) {+ names.push_back(name);+ }+ }+ std::sort(names.begin(), names.end());+ return names;+ };++ const auto small_model = small_variant->get_runtime_model();+ const auto large_model = large_variant->get_runtime_model();+ ASSERT_NE(small_model, nullptr);+ ASSERT_NE(large_model, nullptr);++ const auto small_key_block0 = collect_block0_inputs(small_model, ".key_block_0");+ const auto small_value_block0 = collect_block0_inputs(small_model, ".value_block_0");+ const auto large_key_block0 = collect_block0_inputs(large_model, ".key_block_0");+ const auto large_value_block0 = collect_block0_inputs(large_model, ".value_block_0");++ ASSERT_FALSE(small_key_block0.empty());+ ASSERT_FALSE(small_value_block0.empty());+ EXPECT_EQ(small_key_block0, large_key_block0);+ EXPECT_EQ(small_value_block0, large_value_block0);+}++} // namespace