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] Block-based KV cache integration in LLM pipeline. (#35018)
intelgaoxiongcd8bdde2bfdc
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.incindex dfd6f58511f..3a74ea04010 100644--- a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc+++ b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc@@ -68,6 +68,7 @@ INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_ENABLE_PREFIX_CACHING, bool, false, ov::intelINTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_PREFIX_CACHING_BLOCK_SIZE, uint64_t, 256, ov::intel_npu::npuw::llm, prefix_caching_block_size, "NPUW_LLM_PREFIX_CACHING_BLOCK_SIZE", LLM, EXPOSED, CACHED, ALL)INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_PREFIX_CACHING_MAX_NUM_BLOCKS, uint64_t, 128, ov::intel_npu::npuw::llm, prefix_caching_max_num_blocks, "NPUW_LLM_PREFIX_CACHING_MAX_NUM_BLOCKS", LLM, EXPOSED, CACHED, ALL)INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_CACHE_ROPE, bool, true, ov::intel_npu::npuw::llm, cache_rope, "NPUW_LLM_CACHE_ROPE", LLM, EXPOSED, CACHED, ALL)+INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE, bool, false, ov::intel_npu::npuw::llm, enable_block_based_kv_cache, "NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE", LLM, EXPOSED, CACHED, ALL)INTEL_NPU_NPUW_STRING_ENUM_OPT(NPUW_LLM_PREFILL_MOE_HINT, ::intel_npu::npuw::llm::MoEHint, MoEHintOptionTraits, ov::intel_npu::npuw::llm, prefill_moe_hint, "NPUW_LLM_PREFILL_MOE_HINT", LLM, EXPOSED, CACHED, ALL)INTEL_NPU_NPUW_STRING_ENUM_OPT(NPUW_LLM_GENERATE_MOE_HINT, ::intel_npu::npuw::llm::MoEHint, MoEHintOptionTraits, ov::intel_npu::npuw::llm, generate_moe_hint, "NPUW_LLM_GENERATE_MOE_HINT", LLM, EXPOSED, CACHED, ALL)INTEL_NPU_NPUW_STRING_ENUM_OPT(NPUW_LLM_PREFILL_HINT, ::intel_npu::npuw::llm::PrefillHint, PrefillHintOptionTraits, ov::intel_npu::npuw::llm, prefill_hint, "NPUW_LLM_PREFILL_HINT", LLM, EXPOSED, CACHED, ALL)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 951ea2e5baa..7f3e374a439 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@@ -179,6 +179,14 @@ void ov::npuw::IBaseInferRequest::handle_set_remote_input(const ov::Output<const}}+void ov::npuw::IBaseInferRequest::propagate_params_to_subrequests() {+ for (std::size_t idx = 0; idx < m_subrequests.size(); ++idx) {+ if (m_subrequests[idx]) {+ bind_global_params(idx, m_subrequests[idx]);+ }+ }+}+std::vector<ov::SoPtr<ov::IVariableState>> ov::npuw::IBaseInferRequest::query_state() const {std::vector<ov::SoPtr<ov::IVariableState>> variable_states = {};for (const auto& request : m_subrequests) {diff --git a/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.hpp b/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.hppindex e116f4b5890..203d652c4f8 100644--- a/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.hpp@@ -90,6 +90,19 @@ public:protected:int64_t m_history_size = 0;+ // After set_tensor() has replaced block tensors with dummies on the outer (LLM-level)+ // request, call this to push those updated tensors into sub-requests via bind_global_params.+ // Sub-requests hold their own shared_ptr to block tensors and only pick up new tensors+ // the next time infer() runs their function_prologue. For variants that are not selected+ // in the next conversation, infer() may never run again, so this call drops all remaining+ // block tensor refs immediately on conversation reset.+ // Only LLMBlockKVCacheStrategy should call this (via friend declaration below).+ virtual void propagate_params_to_subrequests();++ // LLMBlockKVCacheStrategy calls propagate_params_to_subrequests() from on_reset() to drop+ // stale block tensor refs from sub-requests before block memory is freed.+ friend class LLMBlockKVCacheStrategy;+using RqPtr = ov::SoPtr<ov::IAsyncInferRequest>;using RqPtrs = std::vector<RqPtr>;diff --git a/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cppindex 769b4af352f..5337f8080ee 100644--- a/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cpp@@ -705,6 +705,24 @@ void ov::npuw::JustInferRequest::start_subrequest(std::size_t idx) {m_subrequests[idx]->start_async();}+void ov::npuw::JustInferRequest::propagate_params_to_subrequests() {+ // Handle m_subrequests (primary subrequests for all real subgraphs).+ IBaseInferRequest::propagate_params_to_subrequests();++ // When function pipelining is active, m_funcall_pipeline[real_idx].subrequest is a+ // "reserve" request swapped with the primary after each funcall epilogue. It may+ // hold live block tensor refs from the last executed or pre-prepared inference step+ // and must be cleared here, otherwise release() cannot free device memory.+ if (!m_use_function_pipelining) {+ return;+ }+ for (std::size_t idx = 0; idx < m_funcall_pipeline.size(); ++idx) {+ if (m_funcall_pipeline[idx].subrequest) {+ bind_global_params(idx, m_funcall_pipeline[idx].subrequest);+ }+ }+}+void ov::npuw::JustInferRequest::bind_global_parameters(std::size_t idx) {auto& comp_model_desc = m_npuw_model->m_compiled_submodels[idx];const auto real_idx = comp_model_desc.replaced_by.value_or(idx);diff --git a/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.hpp b/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.hppindex 125ed36f909..e1e380042f6 100644--- a/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.hpp@@ -152,6 +152,7 @@ protected:bool is_pipelined(std::size_t idx) const;bool m_use_function_pipelining = false;+ void propagate_params_to_subrequests() override;struct FuncallPipeline {// A "brother" subrequest for a "primary" subrequest. Initialized only// for function bodies (replaced_by == idx)diff --git a/src/plugins/intel_npu/src/plugin/npuw/kv_cache_block_manager.cpp b/src/plugins/intel_npu/src/plugin/npuw/kv_cache_block_manager.cppindex b55a3a55c81..80a3e3aef41 100644--- a/src/plugins/intel_npu/src/plugin/npuw/kv_cache_block_manager.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/kv_cache_block_manager.cpp@@ -142,12 +142,28 @@ std::vector<uint32_t> KVCacheBlockManager::get_allocated_blocks() const {return allocated;}-void KVCacheBlockManager::clear_all() {- LOG_DEBUG("KVCacheBlockManager: Clearing all blocks");+void KVCacheBlockManager::release(uint32_t keep_warm_count) {+ LOG_DEBUG("KVCacheBlockManager: Resetting blocks (keep_warm_count=" << keep_warm_count << ")");+ // Iterate allocated blocks in ascending block-ID order.+ // The first keep_warm_count retain their device tensors (warm reuse next round).+ // The remainder have tensors dropped to reduce RSS.+ uint32_t warm_seen = 0;for (auto& block : blocks_) {- block.num_tokens = 0;+ if (!block.is_allocated) {+ continue;+ }block.is_allocated = false;+ block.num_tokens = 0;+ if (warm_seen >= keep_warm_count) {+ block.tensor = {}; // Drop SoPtr — returns device memory to allocator+ }+ ++warm_seen;+ }++ if (warm_seen > keep_warm_count) {+ LOG_DEBUG("KVCacheBlockManager: Released " << (warm_seen - keep_warm_count) << " block tensor(s), kept "+ << keep_warm_count << " warm");}// Rebuild free stack (push in reverse order so block 0 is on top)@@ -158,6 +174,10 @@ void KVCacheBlockManager::clear_all() {}}+void KVCacheBlockManager::clear_all() {+ release(0);+}+void KVCacheBlockManager::validate_block_id(uint32_t block_id) const {if (block_id >= max_blocks_) {OPENVINO_THROW("KVCacheBlockManager: Invalid block ID ", block_id, " (valid range: 0-", max_blocks_ - 1, ")");diff --git a/src/plugins/intel_npu/src/plugin/npuw/kv_cache_block_manager.hpp b/src/plugins/intel_npu/src/plugin/npuw/kv_cache_block_manager.hppindex 65b82d9f820..7c831b38038 100644--- a/src/plugins/intel_npu/src/plugin/npuw/kv_cache_block_manager.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/kv_cache_block_manager.hpp@@ -104,11 +104,26 @@ public:std::vector<uint32_t> get_allocated_blocks() const;/**- * @brief Reset all blocks to FREE state and clear token counts.+ * @brief Release blocks to FREE state, selectively dropping device memory.*- * Note: tensor memory is retained in the pool for reuse; no device- * deallocation occurs. Individual block release is not supported —- * use this method to reset the entire pool between requests.+ * The first `keep_warm_count` allocated blocks (by block ID, ascending) retain+ * their device tensors so they can be reused in the next conversation without+ * re-allocating device memory. Blocks beyond that count have their tensors+ * dropped to reduce RSS.+ *+ * @param keep_warm_count Number of blocks whose device tensors should be kept.+ * Pass 0 (default) to release all device memory.+ *+ * Note: for NPU-backed tensors, re-allocation adds latency to the first prefill+ * chunk of a new conversation. Keeping `ceil(prompt_len / block_size)` blocks+ * warm avoids that latency for the common case.+ */+ void release(uint32_t keep_warm_count = 0);++ /**+ * @brief Release all blocks and drop all device tensor memory.+ *+ * Equivalent to release(0). Kept for compatibility.*/void clear_all();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.cppnew file mode 100644index 00000000000..25ffbb0fae2--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.cpp@@ -0,0 +1,936 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "llm_block_kvcache_strategy.hpp"++#include <cmath>+#include <regex>++#include "infer_request_utils.hpp"+#include "llm_compiled_model.hpp"+#include "llm_infer_base_request.hpp"+#include "llm_infer_request.hpp"+#include "logging.hpp"+#include "util.hpp"++namespace {++// Construct numbered block input name: e.g. "past_key_values.5.key_block_2"+std::string make_numbered_block_input_name(const std::string& kv_type, const std::string& layer_idx, size_t block_idx) {+ return "past_key_values." + layer_idx + "." + kv_type + "_block_" + std::to_string(block_idx);+}++// Classify a port name into its KV block role.+// Returns Key/Value for numbered blocks, Tail for block_tail ports,+// and Skip for contiguous KV params or unrelated ports.+ov::npuw::BlockParamKind classify_block_param(const std::string& name) {+ using ov::npuw::BlockParamKind;+ namespace uu = ov::npuw::util;+ const bool is_key = uu::isPastKeyParam(name);+ const bool is_value = uu::isPastValueParam(name);+ if (!is_key && !is_value) {+ return ov::npuw::BlockParamKind::Skip;+ }+ if (uu::isPastKeyValuesKeyContiguous(name).has_value() || uu::isPastKeyValuesValueContiguous(name).has_value()) {+ return ov::npuw::BlockParamKind::Skip;+ }+ if (name.find("block_tail") != std::string::npos) {+ return ov::npuw::BlockParamKind::TailBlock;+ }+ return is_key ? ov::npuw::BlockParamKind::KeyBlock : ov::npuw::BlockParamKind::ValueBlock;+}++// Build a ClassifiedPortsMap from a raw PortsMap, classifying each port once.+ov::npuw::LLMBlockKVCacheStrategy::ClassifiedPortsMap build_classified_ports_map(+ const ov::npuw::LLMBlockKVCacheStrategy::PortsMap& ports_map) {+ ov::npuw::LLMBlockKVCacheStrategy::ClassifiedPortsMap result;+ result.reserve(ports_map.size());+ for (const auto& [name, port] : ports_map) {+ result.emplace(name, ov::npuw::LLMBlockKVCacheStrategy::ClassifiedPort{port, classify_block_param(name)});+ }+ return result;+}++// Set dummy tensors on all numbered block inputs in a classified ports map.+// Returns the count of block inputs that were set.+template <typename SetTensorFn>+size_t set_dummy_block_tensors(const ov::npuw::LLMBlockKVCacheStrategy::ClassifiedPortsMap& ports_map,+ SetTensorFn&& set_tensor_fn,+ const ov::SoPtr<ov::ITensor>& dummy_key_tensor,+ const ov::SoPtr<ov::ITensor>& dummy_value_tensor) {+ using ov::npuw::BlockParamKind;+ size_t block_count = 0;+ for (const auto& [name, cp] : ports_map) {+ if (cp.kind == BlockParamKind::Skip || cp.kind == BlockParamKind::TailBlock) {+ continue; // skip non-block ports and tail ports (tail is copy-filled separately)+ }+ set_tensor_fn(cp.port, cp.kind == BlockParamKind::KeyBlock ? dummy_key_tensor : dummy_value_tensor);+ block_count++;+ }+ return block_count;+}++// Build the complete per-layer binding helpers for one generate variant by scanning+// its ClassifiedPortsMap once and parsing block indices directly from port names.+std::unordered_map<uint32_t, ov::npuw::LayerBlockBindingHelpers> build_variant_layer_helpers(+ const ov::npuw::LLMBlockKVCacheStrategy::ClassifiedPortsMap& classified,+ uint32_t block_size) {+ using ov::npuw::BlockParamKind;+ namespace uu = ov::npuw::util;++ // Accumulate ports per layer, using std::map to keep numbered slots sorted by block_idx.+ struct PerLayerKV {+ std::map<uint32_t, ov::Output<const ov::Node>> key_numbered; // block_idx → port+ std::map<uint32_t, ov::Output<const ov::Node>> value_numbered;+ std::optional<ov::Output<const ov::Node>> key_tail;+ std::optional<ov::Output<const ov::Node>> value_tail;+ };+ std::unordered_map<uint32_t, PerLayerKV> per_layer;++ // Matches tail ports: past_key_values.{layer}.* → group 1 = layer+ // Matches numbered ports: past_key_values.{layer}.[key|value]_block_{idx}+ // → group 1 = layer, group 2 = block index+ static const std::regex tail_regex(R"(past_key_values\.(\d+)\.)");+ static const std::regex numbered_regex(R"(past_key_values\.(\d+)\.[a-z]+_block_(\d+)$)");+ for (const auto& [name, cp] : classified) {+ if (cp.kind == BlockParamKind::Skip)+ continue;++ std::smatch match;+ if (cp.kind == BlockParamKind::TailBlock) {+ if (!std::regex_search(name, match, tail_regex) || match.size() <= 1)+ continue;+ const uint32_t layer_idx = static_cast<uint32_t>(std::stoi(match[1].str()));+ if (uu::isPastKeyParam(name))+ per_layer[layer_idx].key_tail = cp.port;+ else+ per_layer[layer_idx].value_tail = cp.port;+ } else {+ if (!std::regex_search(name, match, numbered_regex) || match.size() <= 2)+ continue;+ const uint32_t layer_idx = static_cast<uint32_t>(std::stoi(match[1].str()));+ const uint32_t block_idx = static_cast<uint32_t>(std::stoi(match[2].str()));+ if (cp.kind == BlockParamKind::KeyBlock)+ per_layer[layer_idx].key_numbered[block_idx] = cp.port;+ else+ per_layer[layer_idx].value_numbered[block_idx] = cp.port;+ }+ }++ // Convert accumulated per-layer data into LayerBlockBindingHelpers.+ std::unordered_map<uint32_t, ov::npuw::LayerBlockBindingHelpers> result;+ for (auto& [layer_idx, lkv] : per_layer) {+ ov::npuw::LayerBlockBindingHelpers helpers;++ std::vector<ov::Output<const ov::Node>> key_vec;+ key_vec.reserve(lkv.key_numbered.size());+ for (auto& [idx, port] : lkv.key_numbered)+ key_vec.push_back(port);+ helpers.key_helper = ov::npuw::BlockBindingHelper::from_ports(std::move(key_vec), lkv.key_tail, block_size);++ std::vector<ov::Output<const ov::Node>> val_vec;+ val_vec.reserve(lkv.value_numbered.size());+ for (auto& [idx, port] : lkv.value_numbered)+ val_vec.push_back(port);+ helpers.value_helper = ov::npuw::BlockBindingHelper::from_ports(std::move(val_vec), lkv.value_tail, block_size);++ result[layer_idx] = std::move(helpers);+ }+ return result;+}++// Copy a block tensor (or a slice of it) into the tail input port, handling padding correctly.+void copy_block_to_tail_input(const ov::SoPtr<ov::ITensor>& block_tensor,+ uint32_t start_token,+ uint32_t end_token,+ uint32_t kv_dim,+ const ov::Output<const ov::Node>& tail_input_port,+ std::shared_ptr<ov::IAsyncInferRequest> request) {+ namespace uu = ov::npuw::util;+ NPUW_ASSERT(start_token <= end_token);+ auto tail_input_tensor = request->get_tensor(tail_input_port);+ NPUW_ASSERT(end_token <= static_cast<uint32_t>(tail_input_tensor->get_shape()[kv_dim]));+ auto src_slice = uu::make_tensor_slice(block_tensor, kv_dim, start_token, end_token);+ auto dst_slice = uu::make_tensor_slice(tail_input_tensor, kv_dim, start_token, end_token);+ uu::copy_tensor_by_dim(src_slice, dst_slice, kv_dim, kv_dim);+}++// Shapes and element type of one key/value block pair — derived from the first+// numbered block port found during initialization.+struct BlockShapeInfo {+ ov::Shape key_shape;+ ov::Shape value_shape;+ ov::element::Type elem_type;+ bool found_key = false;+ bool found_value = false;+};++// Scan classified prefill input ports to discover the shape and element type of block tensors.+BlockShapeInfo find_block_shapes(const ov::npuw::LLMBlockKVCacheStrategy::ClassifiedPortsMap& classified_ports) {+ using ov::npuw::BlockParamKind;+ BlockShapeInfo shapes;+ for (const auto& [name, cp] : classified_ports) {+ if (cp.kind == BlockParamKind::Skip || cp.kind == BlockParamKind::TailBlock) {+ continue;+ }+ const bool is_key = cp.kind == BlockParamKind::KeyBlock;+ if (!shapes.found_key && is_key) {+ shapes.key_shape = cp.port.get_shape();+ shapes.elem_type = cp.port.get_element_type();+ shapes.found_key = true;+ LOG_DEBUG("Detected key block shape: " << shapes.key_shape << ", type: " << shapes.elem_type);+ }+ if (!shapes.found_value && !is_key) {+ shapes.value_shape = cp.port.get_shape();+ shapes.found_value = true;+ LOG_DEBUG("Detected value block shape: " << shapes.value_shape);+ }+ if (shapes.found_key && shapes.found_value) {+ break;+ }+ }+ return shapes;+}++// Set dummy tensors on all numbered block input ports of a single inference request.+size_t set_dummy_tensors_to_request(const std::shared_ptr<ov::IAsyncInferRequest>& request,+ const ov::npuw::LLMBlockKVCacheStrategy::ClassifiedPortsMap& classified_ports,+ const ov::npuw::LLMBlockKVCacheStrategy::DummyTensors& dummies) {+ return set_dummy_block_tensors(+ classified_ports,+ [&request](const ov::Output<const ov::Node>& port, const ov::SoPtr<ov::ITensor>& tensor) {+ request->set_tensor(port, tensor);+ },+ dummies.key_tensor,+ dummies.value_tensor);+}++} // anonymous namespace++namespace ov {+namespace npuw {++// ============================================================================+// LLMKVCacheStrategy interface+// ============================================================================++void LLMBlockKVCacheStrategy::on_initialize() {+ LOG_INFO("=== Initializing Block-based KV Cache Managers ===");++ const auto& prefill_in_ports = m_req.m_prefill_in_ports;+ const auto& prefill_out_ports = m_req.m_prefill_out_ports;++ // Pre-classify all port names once — reused by find_block_shapes,+ // set_dummy_block_tensors, and the phase-1 layer scan.+ m_prefill_classified_in_ports = build_classified_ports_map(prefill_in_ports);+ for (const auto& [request, ports] : m_req.m_generate_variant_in_ports) {+ m_gen_classified_in_ports.emplace(request, build_classified_ports_map(ports));+ }++ auto block_shapes = find_block_shapes(m_prefill_classified_in_ports);+ if (block_shapes.found_key) {+ // Dummy tensor optimization: share one dummy tensor per shape across all block inputs.+ // Store in m_dummy_tensors so on_reset() can restore ports to release block tensor refs.+ const auto& plugin = m_req.m_npuw_llm_compiled_model->get_plugin();+ m_dummy_tensors.key_tensor =+ ov::npuw::util::allocMem(block_shapes.elem_type, block_shapes.key_shape, m_req.m_pre_alloc_device, plugin);+ LOG_INFO("Allocated shared dummy key tensor: " << block_shapes.key_shape << " ("+ << m_dummy_tensors.key_tensor->get_byte_size() << " bytes)");+ if (block_shapes.found_value && block_shapes.value_shape != block_shapes.key_shape) {+ m_dummy_tensors.value_tensor = ov::npuw::util::allocMem(block_shapes.elem_type,+ block_shapes.value_shape,+ m_req.m_pre_alloc_device,+ plugin);+ LOG_INFO("Allocated shared dummy value tensor: "+ << block_shapes.value_shape << " (" << m_dummy_tensors.value_tensor->get_byte_size() << " bytes)");+ } else {+ m_dummy_tensors.value_tensor = m_dummy_tensors.key_tensor;+ }+ set_dummy_tensors_to_all_requests();+ }++ // Create block managers and pre-compute per-variant binding helpers+ create_block_managers_and_helpers();++ // Snapshot original prefill output tensors (for restore_prefill_output_buffers()) and+ // build m_output_kv_info (output_name → layer/kv) to avoid per-call regex.+ for (const auto& [layer_idx, layer_managers] : m_kv_cache_block_managers) {+ const std::string layer_str = std::to_string(layer_idx);+ for (const bool is_key : {true, false}) {+ const std::string kv_type = is_key ? "key" : "value";+ const std::string output_name = "present." + layer_str + "." + kv_type;+ m_output_kv_info[output_name] = {layer_idx, is_key};+ auto port_it = prefill_out_ports.find(output_name);+ if (port_it != prefill_out_ports.end()) {+ m_prefill_original_output_tensors[output_name] = m_req.m_prefill_request->get_tensor(port_it->second);+ }+ }+ }+ LOG_INFO("Snapshotted " << m_prefill_original_output_tensors.size() << " original prefill output tensors");+ LOG_INFO("=== Block-based KV Cache Initialization Complete ===");+}++void LLMBlockKVCacheStrategy::set_dummy_tensors_to_all_requests() {+ size_t prefill_count =+ set_dummy_tensors_to_request(m_req.m_prefill_request, m_prefill_classified_in_ports, m_dummy_tensors);+ LOG_INFO("Set " << prefill_count << " prefill numbered block inputs to shared dummy tensors");++ size_t gen_count = 0;+ for (const auto& generate_request : m_req.m_generate_requests) {+ gen_count += set_dummy_tensors_to_request(generate_request,+ m_gen_classified_in_ports.at(generate_request),+ m_dummy_tensors);+ }+ LOG_INFO("Set " << gen_count << " generate numbered block inputs to shared dummy tensors");+}++void LLMBlockKVCacheStrategy::on_reset(uint32_t next_prompt_length) {+ // When no block inputs were found during on_initialize() there are no block+ // tensors to release and no dummy tensors to propagate — nothing to do.+ if (m_kv_cache_block_managers.empty()) {+ return;+ }++ // ── Step 1: drop prefill OUTPUT port refs ────────────────────────────────────────+ // Only needed when the last prefill chunk used the zero-copy path, which redirects+ // prefill output ports directly to block tensors. The copy path leaves output ports+ // pointing to the original buffers, so no restore is needed in that case.+ {+ if (m_zero_copy_last_chunk) {+ restore_prefill_output_buffers(m_req.m_prefill_request, m_req.m_prefill_out_ports);+ m_zero_copy_last_chunk = false;+ }+ }++ // ── Step 2: drop prefill/generate INPUT port refs ────────────────────────────────+ // Only the prefill request and the currently-selected generate variant were ever+ // re-bound to live block tensors. Other variants remain on dummy tensors from+ // on_initialize() and need no action.+ {+ set_dummy_tensors_to_request(m_req.m_prefill_request, m_prefill_classified_in_ports, m_dummy_tensors);+ set_dummy_tensors_to_request(m_req.m_kvcache_request,+ m_gen_classified_in_ports.at(m_req.m_kvcache_request),+ m_dummy_tensors);+ }++ // ── Step 3: propagate dummies into sub-requests ──────────────────────────────────+ // set_tensor() on the outer (LLM-level) request updates the tensor stored at that+ // level, but NPUW sub-requests each hold an independent SoPtr to block tensors and+ // only pick up new tensors via bind_global_params() at the start of their next+ // infer() call. If this variant is not selected in the next conversation, infer()+ // may never run again, leaving sub-requests with live refs that prevent release()+ // from actually freeing device memory. Propagating the dummies now drops those+ // refs immediately. Other variants were never bound to live block tensors, so they+ // do not need propagation.+ {+ auto it =+ std::find(m_req.m_generate_requests.begin(), m_req.m_generate_requests.end(), m_req.m_kvcache_request);+ if (it != m_req.m_generate_requests.end()) {+ const size_t idx = static_cast<size_t>(std::distance(m_req.m_generate_requests.begin(), it));+ m_req.m_generate_base_requests[idx]->propagate_params_to_subrequests();+ }+ }++ // ── Step 4: release block tensors ────────────────────────────────────────────────+ // All SoPtr references to block tensors have been dropped above; calling release()+ // here will actually return device memory to the allocator.+ // Keep ceil(next_prompt_length / block_size) blocks warm to avoid re-allocating+ // them on the next prefill. Pass 0 when the next prompt length is unknown.+ {+ const uint32_t keep_warm_blocks =+ (m_block_size > 0 && next_prompt_length > 0)+ ? static_cast<uint32_t>(+ std::ceil(static_cast<double>(next_prompt_length) / static_cast<double>(m_block_size)))+ : 0u;+ for (auto& [layer_idx, layer_managers] : m_kv_cache_block_managers) {+ if (layer_managers.key_manager) {+ layer_managers.key_manager->release(keep_warm_blocks);+ }+ if (layer_managers.value_manager) {+ layer_managers.value_manager->release(keep_warm_blocks);+ }+ }+ }+}++void LLMBlockKVCacheStrategy::on_prefill_chunk_begin(uint32_t current_prompts_len) {+ OPENVINO_ASSERT(!m_kv_cache_block_managers.empty(),+ "Block-based KV cache is enabled but no block inputs were found. "+ "Ensure NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE is only set together with "+ "chunk prefill and a supported attention pattern (HFA or Pyramid).");++ load_past_kv_blocks_to_prefill(m_req.m_prefill_request, m_req.m_prefill_in_ports);++ if (current_prompts_len % m_block_size == 0) {+ m_zero_copy_last_chunk = redirect_prefill_outputs_to_new_blocks(m_req.m_prefill_request,+ m_req.m_prefill_out_ports,+ current_prompts_len);+ } else {+ m_zero_copy_last_chunk = false;+ }+ if (!m_zero_copy_last_chunk) {+ LOG_DEBUG("Chunk not block-aligned (" << current_prompts_len << " % " << m_block_size+ << " != 0), falling back to copy path");+ // Restore original output buffers so the model does not write into blocks that were+ // redirected by a previous zero-copy chunk.+ restore_prefill_output_buffers(m_req.m_prefill_request, m_req.m_prefill_out_ports);+ }+}++void LLMBlockKVCacheStrategy::on_prefill_chunk_done(uint32_t current_prompts_len, bool /*is_last*/) {+ if (m_zero_copy_last_chunk) {+ // Zero-copy: model wrote directly into blocks; redirect_prefill_outputs_to_new_blocks()+ // already updated metadata — nothing to do.+ LOG_DEBUG("Zero-copy prefill complete - no post-inference work needed");+ } else {+ // Copy path: copy from the model's output buffer into blocks.+ // write start = num_stored_tokens (already incremented) - current_prompts_len.+ const auto& kvcache_desc = m_req.m_npuw_llm_compiled_model->m_kvcache_desc;+ const uint32_t write_start = kvcache_desc.num_stored_tokens - current_prompts_len;+ LOG_DEBUG("Copying prefill outputs to blocks: num_tokens=" << current_prompts_len+ << " kv_position=" << write_start);+ const bool v_transposed = kvcache_desc.v_tensors_transposed_pre;+ copy_outputs_to_blocks(m_req.m_prefill_request,+ m_req.m_prefill_out_ports,+ current_prompts_len,+ v_transposed,+ write_start);+ }+}++void LLMBlockKVCacheStrategy::on_generate_kv_init() {+ if (m_kv_cache_block_managers.empty()) {+ return;+ }++ LOG_DEBUG("=== Initial Block Binding for Generate Model ===");+ LOG_BLOCK();++ // Initial block binding (called once per conversation on the first generate step):+ // Numbered blocks (block_0…block_N): zero-copy via set_tensor(); subsequent generate steps+ // write directly into the shared BlockManager buffer — no re-binding needed.+ // Tail block (block_tail port): copy-based; refreshed by update_generate_bindings() each step.++ auto& kvcache_desc = m_req.m_npuw_llm_compiled_model->m_kvcache_desc;+ const auto& variant_layer_helpers = m_variant_block_binding_helpers.at(m_req.m_kvcache_request);++ auto process_blocks = [&](uint32_t layer_idx,+ KVCacheBlockManager* manager,+ const BlockBindingHelper& helper,+ uint32_t kv_dim,+ const char* kv_type_name) {+ auto allocated_blocks = manager->get_allocated_blocks();+ if (allocated_blocks.empty()) {+ return;+ }+ for (size_t block_idx = 0; block_idx < allocated_blocks.size(); ++block_idx) {+ const uint32_t block_id = allocated_blocks[block_idx];+ const auto block_tensor = manager->get_block_tensor(block_id);+ if (helper.should_treat_as_tail(static_cast<uint32_t>(block_idx))) {+ copy_block_to_tail_input(block_tensor,+ 0u,+ manager->get_block_tokens(block_id),+ kv_dim,+ helper.tail_input_port.value(),+ m_req.m_kvcache_request);+ LOG_VERB("Bound tail " << kv_type_name << " layer_" << layer_idx << " block_" << block_idx);+ } else if (block_idx < helper.numbered_input_ports.size()) {+ m_req.m_kvcache_request->set_tensor(helper.numbered_input_ports[block_idx], block_tensor);+ LOG_VERB("Bound numbered " << kv_type_name << " layer_" << layer_idx << " block_" << block_idx);+ }+ }+ };++ for (const auto& [layer_idx, layer_managers] : m_kv_cache_block_managers) {+ const auto& layer_helpers = variant_layer_helpers.at(layer_idx);+ if (layer_managers.key_manager) {+ process_blocks(layer_idx,+ layer_managers.key_manager.get(),+ layer_helpers.key_helper,+ kvcache_desc.dim,+ "key");+ }+ if (layer_managers.value_manager) {+ const uint32_t kv_dim = kvcache_desc.v_tensors_transposed_gen ? 3u : kvcache_desc.dim;+ process_blocks(layer_idx, layer_managers.value_manager.get(), layer_helpers.value_helper, kv_dim, "value");+ }+ }++ LOG_DEBUG("Initial binding complete.");+}++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;+ const uint32_t tokens_before = tokens_after - input_tokens_len;+ copy_outputs_to_blocks(m_req.m_kvcache_request,+ m_req.m_kvcache_out_ports,+ input_tokens_len,+ kvcache_desc.v_tensors_transposed_gen,+ tokens_before);+ update_generate_bindings(tokens_before, tokens_after, m_req.m_kvcache_request);+}++// ============================================================================+// Private: prefill path primitives+// ============================================================================++void LLMBlockKVCacheStrategy::load_past_kv_blocks_to_prefill(+ const std::shared_ptr<ov::IAsyncInferRequest>& prefill_request,+ const PortsMap& prefill_in_ports) {+ if (m_kv_cache_block_managers.empty()) {+ return;+ }+ LOG_DEBUG("=== Binding Block Tensors to Prefill Model Inputs ===");+ for (const auto& [layer_idx, layer_managers] : m_kv_cache_block_managers) {+ const std::string layer_idx_str = std::to_string(layer_idx);+ auto bind_kv_blocks = [&](KVCacheBlockManager* manager, const char* kv_type) {+ if (!manager) {+ return;+ }+ auto allocated_blocks = manager->get_allocated_blocks();+ for (size_t block_idx = 0; block_idx < allocated_blocks.size(); ++block_idx) {+ std::string input_name = make_numbered_block_input_name(kv_type, layer_idx_str, block_idx);+ auto port_it = prefill_in_ports.find(input_name);+ if (port_it != prefill_in_ports.end()) {+ prefill_request->set_tensor(port_it->second,+ manager->get_block_tensor(allocated_blocks[block_idx]));+ LOG_VERB("Bound " << kv_type << " block layer " << layer_idx_str << " block_" << block_idx);+ }+ }+ };+ bind_kv_blocks(layer_managers.key_manager.get(), "key");+ bind_kv_blocks(layer_managers.value_manager.get(), "value");+ }+}++bool LLMBlockKVCacheStrategy::redirect_prefill_outputs_to_new_blocks(+ const std::shared_ptr<ov::IAsyncInferRequest>& prefill_request,+ const PortsMap& prefill_out_ports,+ uint32_t num_new_tokens) {+ if (m_kv_cache_block_managers.empty()) {+ return false;+ }+ auto& kvcache_desc = m_req.m_npuw_llm_compiled_model->m_kvcache_desc;+ uint32_t current_position = kvcache_desc.num_stored_tokens;+ if (current_position % m_block_size != 0) {+ return false;+ }++ // Zero-copy: bind prefill output ports directly to fresh blocks BEFORE inference so the+ // model writes KV cache straight into BlockManager memory with no post-inference copy.+ // Requires current_position to be block-aligned and num_new_tokens to fit in one block;+ // callers must call restore_prefill_output_buffers() and fall back to copy_outputs_to_blocks()+ // when this does not hold.+ LOG_DEBUG("=== Redirecting Prefill Outputs to New Blocks (Zero-Copy) ===");+ LOG_DEBUG("Pre-allocating blocks for " << num_new_tokens << " new tokens");++ size_t total_blocks_allocated = 0;+ size_t total_outputs_bound = 0;++ auto process_kv_blocks = [&](uint32_t layer_idx, KVCacheBlockManager* manager, const char* kv_type_name) -> bool {+ uint32_t start_pos = current_position;+ uint32_t end_pos = current_position + num_new_tokens;+ uint32_t start_block_idx = start_pos / m_block_size;+ uint32_t end_block_idx = (end_pos - 1) / m_block_size;++ // Alignment postconditions for zero-copy+ OPENVINO_ASSERT(start_pos % m_block_size == 0,+ "Zero-copy prefill requires block-aligned position. ",+ "current_position=",+ start_pos,+ ", block_size=",+ m_block_size);+ OPENVINO_ASSERT(start_block_idx == end_block_idx,+ "Zero-copy prefill requires writing to a single block. ",+ "start_block=",+ start_block_idx,+ ", end_block=",+ end_block_idx,+ ", num_new_tokens=",+ num_new_tokens,+ ", block_size=",+ m_block_size);++ uint32_t tokens_in_block = end_pos - (start_block_idx * m_block_size);+ OPENVINO_ASSERT(tokens_in_block == m_block_size || tokens_in_block == num_new_tokens,+ "Zero-copy prefill requires writing full blocks. ",+ "tokens_in_block=",+ tokens_in_block,+ ", block_size=",+ m_block_size,+ ", num_new_tokens=",+ num_new_tokens);++ uint32_t blocks_needed = end_block_idx + 1;+ auto allocated_blocks = manager->get_allocated_blocks();+ while (allocated_blocks.size() < blocks_needed) {+ auto new_block_id = manager->allocate_block();+ OPENVINO_ASSERT(new_block_id.has_value(),+ "Failed to allocate ",+ kv_type_name,+ " block for layer ",+ layer_idx);+ total_blocks_allocated++;+ allocated_blocks = manager->get_allocated_blocks();+ }++ std::string output_name = "present." + std::to_string(layer_idx) + "." + kv_type_name;+ auto port_it = prefill_out_ports.find(output_name);+ if (port_it != prefill_out_ports.end()) {+ uint32_t target_block_id = allocated_blocks[start_block_idx];+ auto target_block_tensor = manager->get_block_tensor(target_block_id);+ prefill_request->set_tensor(port_it->second, target_block_tensor);+ // Update metadata immediately — we know how many tokens will be written+ uint32_t block_start_pos = start_block_idx * m_block_size;+ manager->update_block_tokens(target_block_id, end_pos - block_start_pos);+ total_outputs_bound++;+ LOG_VERB("Bound " << kv_type_name << " output layer " << layer_idx << " to block_" << start_block_idx+ << " (zero-copy, " << num_new_tokens << " tokens, metadata updated)");+ }+ return true;+ };++ for (const auto& [layer_idx, layer_managers] : m_kv_cache_block_managers) {+ if (layer_managers.key_manager) {+ process_kv_blocks(layer_idx, layer_managers.key_manager.get(), "key");+ }+ if (layer_managers.value_manager) {+ process_kv_blocks(layer_idx, layer_managers.value_manager.get(), "value");+ }+ }++ LOG_DEBUG("Pre-binding complete: allocated=" << total_blocks_allocated << " blocks, bound=" << total_outputs_bound+ << " outputs");+ return true;+}++void LLMBlockKVCacheStrategy::restore_prefill_output_buffers(+ const std::shared_ptr<ov::IAsyncInferRequest>& prefill_request,+ const PortsMap& prefill_out_ports) {+ if (m_kv_cache_block_managers.empty()) {+ return;+ }+ // CRITICAL: Must be called before any non-aligned prefill chunk to prevent silent block corruption.+ //+ // Failure scenario without this restore:+ // Chunk 1: zero-copy binds "present.0.key" output → block 0 (block-aligned, works correctly).+ // Chunk 2: chunk is NOT block-aligned, so zero-copy is skipped.+ // But "present.0.key" is STILL bound to block 0 from the previous chunk.+ // infer() now overwrites block 0 with misaligned data → silent data corruption.+ //+ // Fix: restore the original model output buffers (snapshotted in on_initialize()).+ // The model then writes into its own buffers; copy_outputs_to_blocks() copies+ // the result into the correct blocks afterwards.+ OPENVINO_ASSERT(!m_prefill_original_output_tensors.empty(),+ "Original output tensors were not snapshotted during on_initialize().");+ LOG_DEBUG("=== Restoring Original Output Tensors (Non-Zero-Copy Path) ===");+ size_t total_restored = 0;+ for (const auto& [layer_idx, layer_managers] : m_kv_cache_block_managers) {+ const std::string layer_str = std::to_string(layer_idx);+ for (const char* kv_type : {"key", "value"}) {+ std::string output_name = "present." + layer_str + "." + kv_type;+ auto orig_it = m_prefill_original_output_tensors.find(output_name);+ auto port_it = prefill_out_ports.find(output_name);+ if (orig_it == m_prefill_original_output_tensors.end() || port_it == prefill_out_ports.end()) {+ continue;+ }+ auto current_tensor = prefill_request->get_tensor(port_it->second);+ if (current_tensor->data() != orig_it->second->data()) {+ prefill_request->set_tensor(port_it->second, orig_it->second);+ total_restored++;+ LOG_VERB("Restored original buffer for " << output_name);+ }+ }+ }+ LOG_DEBUG("Restore complete: restored=" << total_restored << " tensors");+}++// ============================================================================+// Private: generate path — update bindings after each step+// ============================================================================++void LLMBlockKVCacheStrategy::update_generate_bindings(uint32_t old_num_tokens,+ uint32_t new_num_tokens,+ const std::shared_ptr<ov::IAsyncInferRequest>& kvcache_request) {+ if (m_kv_cache_block_managers.empty()) {+ return;+ }+ LOG_DEBUG("=== Update Block Bindings After Generate ===");+ LOG_BLOCK();++ auto& kvcache_desc = m_req.m_npuw_llm_compiled_model->m_kvcache_desc;+ const auto& variant_layer_helpers = m_variant_block_binding_helpers.at(kvcache_request);++ auto update_blocks = [&](uint32_t layer_idx,+ KVCacheBlockManager* manager,+ const BlockBindingHelper& helper,+ uint32_t kv_dim,+ const char* kv_type_name) {+ const auto allocated_blocks = manager->get_allocated_blocks();+ if (allocated_blocks.empty()) {+ return;+ }+ NPUW_ASSERT(old_num_tokens > 0);+ // update_generate_bindings is only called after at least one prefill has run,+ // so old_num_tokens must be positive.+ const uint32_t old_block_idx = helper.get_block_index_for_position(old_num_tokens - 1);+ const uint32_t final_block_idx = helper.get_block_index_for_position(new_num_tokens - 1);++ if (final_block_idx > old_block_idx) {+ // A block boundary was crossed: bind each newly entered block.+ // In standard decoding (input_tokens_len=1) this loop runs exactly once.+ // In speculative decoding it may run more times if input_tokens_len > block_size.+ // - Numbered blocks: zero-copy via set_tensor().+ // - Tail block: full copy from token 0 of the block.+ for (uint32_t bidx = old_block_idx + 1;+ bidx <= final_block_idx && bidx < static_cast<uint32_t>(allocated_blocks.size());+ ++bidx) {+ const uint32_t block_id = allocated_blocks[bidx];+ if (helper.should_treat_as_tail(bidx)) {+ copy_block_to_tail_input(manager->get_block_tensor(block_id),+ 0u,+ manager->get_block_tokens(block_id),+ kv_dim,+ helper.tail_input_port.value(),+ kvcache_request);+ LOG_VERB("Updated tail " << kv_type_name << " layer_" << layer_idx << " block_" << bidx+ << " (crossed block boundary)");+ } else if (bidx < helper.numbered_input_ports.size()) {+ kvcache_request->set_tensor(helper.numbered_input_ports[bidx], manager->get_block_tensor(block_id));+ LOG_VERB("Bound new numbered " << kv_type_name << " layer_" << layer_idx << " block_" << bidx);+ }+ }+ } else {+ // No block boundary crossed: old and new tokens both reside in the same block.+ // Numbered blocks share memory with BlockManager — no action needed.+ // Tail block requires an incremental copy for the newly added tokens only.+ if (helper.should_treat_as_tail(final_block_idx)) {+ const uint32_t block_id = allocated_blocks[final_block_idx];+ const uint32_t block_start = final_block_idx * helper.block_size;+ const uint32_t prev_tokens = old_num_tokens - block_start;+ const uint32_t new_tokens = manager->get_block_tokens(block_id);+ copy_block_to_tail_input(manager->get_block_tensor(block_id),+ prev_tokens,+ new_tokens,+ kv_dim,+ helper.tail_input_port.value(),+ kvcache_request);+ LOG_VERB("Refreshed tail " << kv_type_name << " layer_" << layer_idx << " block_" << final_block_idx+ << " [" << prev_tokens << ".." << new_tokens << "]");+ }+ }+ };++ for (const auto& [layer_idx, layer_managers] : m_kv_cache_block_managers) {+ const auto& layer_helpers = variant_layer_helpers.at(layer_idx);+ if (layer_managers.key_manager) {+ update_blocks(layer_idx,+ layer_managers.key_manager.get(),+ layer_helpers.key_helper,+ kvcache_desc.dim,+ "key");+ }+ if (layer_managers.value_manager) {+ const uint32_t kv_dim = kvcache_desc.v_tensors_transposed_gen ? 3u : kvcache_desc.dim;+ update_blocks(layer_idx, layer_managers.value_manager.get(), layer_helpers.value_helper, kv_dim, "value");+ }+ }+}++// ============================================================================+// Private: KV copy engine+// ============================================================================++void LLMBlockKVCacheStrategy::copy_outputs_to_blocks(const std::shared_ptr<ov::IAsyncInferRequest>& request,+ const PortsMap& src_ports,+ uint32_t num_tokens,+ bool v_transposed,+ uint32_t current_kv_position) {+ namespace uu = ov::npuw::util;+ auto& kvcache_desc = m_req.m_npuw_llm_compiled_model->m_kvcache_desc;+ auto& compiled = request->get_compiled_model();++ for (std::size_t i = LLMInferBaseRequest::layer_ids::kStartOutputKVCacheLayers; i < compiled->outputs().size();+ ++i) {+ const auto& output_name = compiled->outputs()[i].get_any_name();+ // Classify output port via pre-computed map (avoids per-call regex).+ auto info_it = m_output_kv_info.find(output_name);+ if (info_it == m_output_kv_info.end()) {+ continue;+ }+ const bool is_key = info_it->second.is_key;+ const uint32_t layer_idx = info_it->second.layer_idx;++ auto it = m_kv_cache_block_managers.find(layer_idx);+ if (it == m_kv_cache_block_managers.end()) {+ continue;+ }++ auto& layer_managers = it->second;+ auto& block_manager = is_key ? layer_managers.key_manager : layer_managers.value_manager;+ const uint32_t kv_dim = (!is_key && v_transposed) ? 3u : kvcache_desc.dim;++ auto src_tensor = request->get_tensor(src_ports.at(output_name));+ uint32_t src_seq_len = static_cast<uint32_t>(src_tensor->get_shape()[kv_dim]);+ OPENVINO_ASSERT(num_tokens <= src_seq_len, "num_tokens (", num_tokens, ") > src_seq_len (", src_seq_len, ")");++ auto src_to_copy = src_tensor;+ if (src_seq_len > num_tokens) {+ src_to_copy = uu::make_tensor_slice(src_tensor, kv_dim, src_seq_len - num_tokens, src_seq_len);+ }++ const uint32_t start_pos = current_kv_position;+ const uint32_t end_pos = current_kv_position + num_tokens;+ const uint32_t start_block_idx = start_pos / m_block_size;+ const uint32_t end_block_idx = (end_pos - 1) / m_block_size;++ // Allocate any blocks that do not yet exist, then fetch the final list once.+ auto allocated_blocks = block_manager->get_allocated_blocks();+ for (uint32_t b = static_cast<uint32_t>(allocated_blocks.size()); b <= end_block_idx; ++b) {+ OPENVINO_ASSERT(block_manager->allocate_block().has_value(),+ "Failed to allocate block for KV cache — pool exhausted");+ }+ allocated_blocks = block_manager->get_allocated_blocks();++ // Write tokens across blocks.+ // The first block may be partially filled: start writing at (start_pos % block_size).+ // Every subsequent block is written from position 0 up to min(remaining, block_size).+ uint32_t tokens_written = 0;+ for (uint32_t block_idx = start_block_idx; block_idx <= end_block_idx; ++block_idx) {+ const uint32_t block_id = allocated_blocks[block_idx];+ const auto block_tensor = block_manager->get_block_tensor(block_id);+ const uint32_t write_start = (block_idx == start_block_idx) ? (start_pos % m_block_size) : 0u;+ const uint32_t write_end = std::min(end_pos - block_idx * m_block_size, m_block_size);+ const uint32_t count = write_end - write_start;+ const auto dst_slice = uu::make_tensor_slice(block_tensor, kv_dim, write_start, write_end);+ const auto src_slice = uu::make_tensor_slice(src_to_copy, kv_dim, tokens_written, tokens_written + count);+ uu::copy_tensor_by_dim(src_slice, dst_slice, kv_dim, kv_dim);+ tokens_written += count;+ block_manager->update_block_tokens(block_id, write_end);+ }+ OPENVINO_ASSERT(tokens_written == num_tokens, "Mismatch: wrote ", tokens_written, " but expected ", num_tokens);+ }+}++// ============================================================================+// Private: initialization helpers+// ============================================================================++void LLMBlockKVCacheStrategy::create_block_managers_and_helpers() {+ const auto& compiled_model = m_req.m_npuw_llm_compiled_model;+ const uint32_t block_size = static_cast<uint32_t>(compiled_model->m_prefill_chunk_size);+ m_block_size = block_size;+ const uint32_t max_blocks = (compiled_model->m_kvcache_desc.total_size + block_size - 1) / block_size;++ LOG_INFO("Block configuration: size=" << block_size << " tokens, max_blocks=" << max_blocks);++ // -------------------------------------------------------------------------+ // Phase 1: Single scan — discover which layers have key/value block ports.+ // Records both numbered blocks and tail ports so Phase 2 can cross-validate.+ // -------------------------------------------------------------------------+ struct LayerKVPresence {+ bool has_key_numbered_block = false; // at least one key_block_N found+ bool has_value_numbered_block = false; // at least one value_block_N found+ bool has_key_tail_block = false; // key_block_tail found+ bool has_value_tail_block = false; // value_block_tail found+ };+ std::map<uint32_t, LayerKVPresence> layer_presence;++ static const std::regex layer_regex(R"(past_key_values\.(\d+)\.)");+ for (const auto& [name, cp] : m_prefill_classified_in_ports) {+ namespace uu = ov::npuw::util;+ if (cp.kind == ov::npuw::BlockParamKind::Skip) {+ continue; // non-KV or contiguous param+ }+ std::smatch match;+ if (!std::regex_search(name, match, layer_regex) || match.size() <= 1) {+ OPENVINO_THROW("NPUW block KV cache: could not parse layer index from port name: ", name);+ }+ const uint32_t layer_idx = static_cast<uint32_t>(std::stoi(match[1].str()));+ auto& presence = layer_presence[layer_idx];++ if (cp.kind == ov::npuw::BlockParamKind::TailBlock) {+ if (uu::isPastKeyParam(name))+ presence.has_key_tail_block = true;+ else+ presence.has_value_tail_block = true;+ } else { // KeyBlock or ValueBlock+ if (cp.kind == ov::npuw::BlockParamKind::KeyBlock)+ presence.has_key_numbered_block = true;+ else+ presence.has_value_numbered_block = true;+ }+ // else: contiguous param — skip+ }++ // -------------------------------------------------------------------------+ // Phase 2: For each layer, validate invariants, create block managers,+ // and pre-compute per-generate-variant binding helpers.+ //+ // Invariants (broken SplitKVCacheIntoBlocks would violate these):+ // A. tail-only layer: has_key_tail without has_key (or same for value)+ // B. missing block_0: has_key/has_value but key/value_block_0 is absent+ // -------------------------------------------------------------------------+ for (const auto& [layer_idx, presence] : layer_presence) {+ const std::string layer_idx_str = std::to_string(layer_idx);++ // Invariant A: tail must not exist without numbered blocks+ OPENVINO_ASSERT(!presence.has_key_tail_block || presence.has_key_numbered_block,+ "NPUW block KV cache: layer ",+ layer_idx,+ " has key_block_tail but no key numbered blocks. "+ "SplitKVCacheIntoBlocks transformation may be broken.");+ OPENVINO_ASSERT(!presence.has_value_tail_block || presence.has_value_numbered_block,+ "NPUW block KV cache: layer ",+ layer_idx,+ " has value_block_tail but no value numbered blocks. "+ "SplitKVCacheIntoBlocks transformation may be broken.");++ LayerBlockManagers layer_managers;++ if (presence.has_key_numbered_block) {+ // Invariant B: numbered blocks must start at block_0+ const std::string key_block0_name = make_numbered_block_input_name("key", layer_idx_str, 0);+ OPENVINO_ASSERT(m_prefill_classified_in_ports.count(key_block0_name),+ "NPUW block KV cache: layer ",+ layer_idx,+ " has key blocks but no key_block_0. "+ "SplitKVCacheIntoBlocks transformation may be broken.");+ auto first_key_port = m_prefill_classified_in_ports.at(key_block0_name).port;+ layer_managers.key_manager = std::make_unique<KVCacheBlockManager>(block_size,+ max_blocks,+ first_key_port.get_shape(),+ first_key_port.get_element_type(),+ m_req.m_pre_alloc_device,+ compiled_model->get_plugin());+ }+ if (presence.has_value_numbered_block) {+ const std::string value_block0_name = make_numbered_block_input_name("value", layer_idx_str, 0);+ OPENVINO_ASSERT(m_prefill_classified_in_ports.count(value_block0_name),+ "NPUW block KV cache: layer ",+ layer_idx,+ " has value blocks but no value_block_0. "+ "SplitKVCacheIntoBlocks transformation may be broken.");+ auto first_value_port = m_prefill_classified_in_ports.at(value_block0_name).port;+ layer_managers.value_manager = std::make_unique<KVCacheBlockManager>(block_size,+ max_blocks,+ first_value_port.get_shape(),+ first_value_port.get_element_type(),+ m_req.m_pre_alloc_device,+ compiled_model->get_plugin());+ }++ m_kv_cache_block_managers[layer_idx] = std::move(layer_managers);+ }++ // Build binding helpers for every generate variant in one scan per variant+ // (no per-layer index enumeration).+ for (const auto& [generate_request, classified] : m_gen_classified_in_ports) {+ m_variant_block_binding_helpers[generate_request] = build_variant_layer_helpers(classified, block_size);+ }+}++} // namespace npuw+} // namespace ovdiff --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.hppnew file mode 100644index 00000000000..002628489eb--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.hpp@@ -0,0 +1,205 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <memory>+#include <optional>+#include <string>+#include <unordered_map>+#include <vector>++#include "kv_cache_block_manager.hpp"+#include "llm_kvcache_strategy.hpp"+#include "openvino/runtime/iasync_infer_request.hpp"+#include "openvino/runtime/itensor.hpp"+#include "openvino/runtime/so_ptr.hpp"++namespace ov {+namespace npuw {++class LLMInferRequest; // forward declaration — avoids circular include++/// @brief Pre-classified kind for a KV block input port, computed once and cached in+/// ClassifiedPortsMap to avoid repeated string operations on every scan.+enum class BlockParamKind {+ KeyBlock, ///< numbered key block (key_block_N)+ ValueBlock, ///< numbered value block (value_block_N)+ TailBlock, ///< block_tail port — use isPastKeyParam() to distinguish key vs value+ Skip, ///< not a block KV param (contiguous KV or unrelated port)+};++/// @brief Pair of key/value block managers for one transformer layer.+struct LayerBlockManagers {+ std::unique_ptr<KVCacheBlockManager> key_manager;+ std::unique_ptr<KVCacheBlockManager> value_manager;+};++/// @brief Helper for block binding: determines whether a block uses zero-copy numbered binding+/// or copy-based tail binding, and stores the pre-parsed input ports for fast access.+struct BlockBindingHelper {+ uint32_t block_size; ///< Tokens per block (e.g., 1024)++ std::vector<ov::Output<const ov::Node>> numbered_input_ports; ///< block_0, block_1, …+ std::optional<ov::Output<const ov::Node>> tail_input_port; ///< block_tail (nullopt if absent)++ static BlockBindingHelper from_ports(std::vector<ov::Output<const ov::Node>> numbered_ports,+ std::optional<ov::Output<const ov::Node>> tail_port,+ uint32_t block_size_param) {+ BlockBindingHelper helper;+ helper.block_size = block_size_param;+ helper.numbered_input_ports = std::move(numbered_ports);+ helper.tail_input_port = std::move(tail_port);+ return helper;+ }++ bool has_tail_input() const {+ return tail_input_port.has_value();+ }++ bool should_treat_as_tail(uint32_t block_idx) const {+ return has_tail_input() && block_idx >= numbered_input_ports.size();+ }++ uint32_t get_block_index_for_position(uint32_t token_position) const {+ return token_position / block_size;+ }+};++/// @brief Pre-computed binding helpers for one transformer layer (key + value).+struct LayerBlockBindingHelpers {+ BlockBindingHelper key_helper;+ BlockBindingHelper value_helper;+};++/**+ * @brief KV cache strategy for the block-based (paged) KV cache implementation.+ *+ * Owns all block KV cache logic:+ * - a pool of fixed-size KV blocks per transformer layer+ * - zero-copy binding of blocks directly to model inputs (prefill + generate)+ * - fallback copy path when zero-copy is not possible+ *+ * The block pool is initialized once (on_initialize) and reset between conversations+ * (on_reset) — no per-chunk buffer copies are needed.+ */+class LLMBlockKVCacheStrategy final : public LLMKVCacheStrategy {+public:+ // PortsMap matches the alias used by LLMInferRequest for consistency.+ using PortsMap = std::unordered_map<std::string, ov::Output<const ov::Node>>;++ // ClassifiedPortsMap embeds the pre-computed BlockParamKind for each port entry,+ // built once at initialization to avoid re-classifying names on every scan.+ struct ClassifiedPort {+ ov::Output<const ov::Node> port;+ BlockParamKind kind;+ };+ using ClassifiedPortsMap = std::unordered_map<std::string, ClassifiedPort>;++ // Dummy tensors shared across all numbered block input ports (key + value).+ struct DummyTensors {+ ov::SoPtr<ov::ITensor> key_tensor;+ ov::SoPtr<ov::ITensor> value_tensor;+ };++ explicit LLMBlockKVCacheStrategy(LLMInferRequest& req) : LLMKVCacheStrategy(req) {}++ // -------------------------------------------------------------------------+ // LLMKVCacheStrategy interface+ // -------------------------------------------------------------------------++ void on_initialize() override;+ void on_reset(uint32_t next_prompt_length = 0) override;+ 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_step_done(uint32_t input_tokens_len) override;++private:+ // -------------------------------------------------------------------------+ // Private helper structs (used only during initialize())+ // -------------------------------------------------------------------------++ // Pre-computed classification for each KV output port (e.g. "present.0.key").+ struct OutputKVInfo {+ uint32_t layer_idx;+ bool is_key;+ };++ // -------------------------------------------------------------------------+ // Initialization helpers+ // -------------------------------------------------------------------------++ // Set dummy tensors on all numbered block input ports of every generate variant and+ // the prefill request. Called once during on_initialize() so every port starts with+ // a valid dummy before any real block tensor is bound.+ void set_dummy_tensors_to_all_requests();++ void create_block_managers_and_helpers();++ // -------------------------------------------------------------------------+ // Core KV copy/bind engine (shared by prefill and generate paths)+ // -------------------------------------------------------------------------++ void copy_outputs_to_blocks(const std::shared_ptr<ov::IAsyncInferRequest>& request,+ const PortsMap& src_ports,+ uint32_t num_tokens,+ bool v_transposed,+ uint32_t current_kv_position);++ void update_generate_bindings(uint32_t old_num_tokens,+ uint32_t new_num_tokens,+ const std::shared_ptr<ov::IAsyncInferRequest>& kvcache_request);++ // -------------------------------------------------------------------------+ // Prefill path primitives+ // -------------------------------------------------------------------------++ void load_past_kv_blocks_to_prefill(const std::shared_ptr<ov::IAsyncInferRequest>& prefill_request,+ const PortsMap& prefill_in_ports);++ bool redirect_prefill_outputs_to_new_blocks(const std::shared_ptr<ov::IAsyncInferRequest>& prefill_request,+ const PortsMap& prefill_out_ports,+ uint32_t num_new_tokens);++ void restore_prefill_output_buffers(const std::shared_ptr<ov::IAsyncInferRequest>& prefill_request,+ const PortsMap& prefill_out_ports);++ // -------------------------------------------------------------------------+ // Data members+ // -------------------------------------------------------------------------++ // Block managers: layer_idx → {key_manager, value_manager}+ std::unordered_map<uint32_t, LayerBlockManagers> m_kv_cache_block_managers;++ // Pre-computed binding helpers: variant_request → layer_idx → {key_helper, value_helper}+ std::unordered_map<std::shared_ptr<ov::IAsyncInferRequest>, std::unordered_map<uint32_t, LayerBlockBindingHelpers>>+ m_variant_block_binding_helpers;++ // output_name → {layer_idx, is_key}: pre-computed in on_initialize()+ std::unordered_map<std::string, OutputKVInfo> m_output_kv_info;++ // Snapshotted original prefill output tensors for restore_prefill_output_buffers()+ std::unordered_map<std::string, ov::SoPtr<ov::ITensor>> m_prefill_original_output_tensors;++ // Dummy tensors shared across all numbered block input ports.+ // Stored here so on_reset() can restore all ports to dummy tensors before clear_all(),+ // releasing any live shared_ptr references held by inference requests.+ DummyTensors m_dummy_tensors;++ // Pre-classified input port maps built once in on_initialize().+ // Avoids re-running classify_block_param() on every scan across the port map.+ ClassifiedPortsMap m_prefill_classified_in_ports;+ std::unordered_map<std::shared_ptr<ov::IAsyncInferRequest>, ClassifiedPortsMap> m_gen_classified_in_ports;++ // Whether the most recent on_prefill_chunk_begin() chose the zero-copy path.+ bool m_zero_copy_last_chunk = false;++ // Block size in tokens — fixed at on_initialize() time, equal to m_prefill_chunk_size.+ // Cached here to avoid repeated map lookups into m_kv_cache_block_managers.+ uint32_t m_block_size = 0;+};++} // namespace npuw+} // namespace ovdiff --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 0a5d0801333..31fa12c095e 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@@ -1150,6 +1150,54 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m}}+ // Apply block-based KV cache transformation for chunk prefill after ShapeOfParameter+ // This ensures ShapeOf nodes are already regularized before transformation+ if (m_cfg.get<::intel_npu::NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE>()) {+ OPENVINO_ASSERT(!m_enable_prefix_caching,+ "NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE and NPUW_LLM_ENABLE_PREFIX_CACHING "+ "cannot be enabled simultaneously — this combination is not yet supported. "+ "Please disable one of the two options.");+ if (m_use_chunk_prefill && !m_is_embedding && (prefill_attn_hfa || prefill_attn_pyramid)) {+ const uint32_t block_size = static_cast<uint32_t>(m_prefill_chunk_size);++ LOG_DEBUG("Applying SplitKVCacheIntoBlocks (block_size=" << block_size << ")");+ LOG_BLOCK();++ bool all_transformed = true;+ auto apply_block_kv_transform =+ [&](std::shared_ptr<ov::Model>& model, bool v_transposed, const std::string& tag) {+ ov::pass::Manager mgr(tag);+ mgr.register_pass<ov::npuw::pass::SplitKVCacheIntoBlocks>(block_size, v_transposed);+ if (mgr.run_passes(model)) {+ LOG_INFO("SplitKVCacheIntoBlocks applied: " << tag);+ } else {+ LOG_WARN("SplitKVCacheIntoBlocks had no effect: " << tag);+ all_transformed = false;+ }+ };++ apply_block_kv_transform(prefill_model, m_kvcache_desc.v_tensors_transposed_pre, "prefill");++ for (size_t i = 0; i < generate_model_variants.size(); ++i) {+ apply_block_kv_transform(generate_model_variants[i],+ m_kvcache_desc.v_tensors_transposed_gen,+ "generate_" + std::to_string(i));+ }++ if (!all_transformed) {+ OPENVINO_THROW("NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE=YES: "+ "SplitKVCacheIntoBlocks had no effect on one or more models. "+ "Ensure the model uses HFA or Pyramid attention pattern.");+ }+ m_is_block_kv_cache = true;+ } else {+ LOG_WARN("NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE=YES was requested but could not be applied. "+ "Block-based KV cache requires: chunk prefill enabled, "+ "HFA or Pyramid attention, and a non-embedding model. "+ "Falling back to monolithic (continuous) KV cache.");+ }+ }+// Compile multiple generate model variants with different sizescompile_generate_model_variants(generate_model_variants, plugin, generate_config);@@ -1267,7 +1315,7 @@ void ov::npuw::LLMCompiledModel::serialize(std::ostream& raw_stream, const ov::nm_kvcache_desc.dim & m_kvcache_desc.max_generation_token_len & m_kvcache_desc.v_tensors_transposed_pre &m_kvcache_desc.v_tensors_transposed_gen & m_prefill_chunk_size & m_use_chunk_prefill & m_max_lora_rank &m_enable_prefix_caching & m_prefix_caching_block_size & m_prefix_caching_max_num_blocks & m_is_whisper &- m_eos_token_id & m_decomposed_sdpa_size & m_is_eagle & m_is_embedding;+ m_eos_token_id & m_decomposed_sdpa_size & m_is_eagle & m_is_embedding & m_is_block_kv_cache;// Write configstream & m_cfg;@@ -1487,7 +1535,7 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::deserialcompiled->m_use_chunk_prefill & compiled->m_max_lora_rank & compiled->m_enable_prefix_caching &compiled->m_prefix_caching_block_size & compiled->m_prefix_caching_max_num_blocks & compiled->m_is_whisper &compiled->m_eos_token_id & compiled->m_decomposed_sdpa_size & compiled->m_is_eagle &- compiled->m_is_embedding;+ compiled->m_is_embedding & compiled->m_is_block_kv_cache;// Deserialize configstream & compiled->m_cfg;@@ -1609,6 +1657,7 @@ void ov::npuw::LLMCompiledModel::implement_properties() {BIND(npuw::llm::optimize_v_tensors, NPUW_LLM_OPTIMIZE_V_TENSORS, get),BIND(npuw::llm::optimize_fp8, NPUW_LLM_OPTIMIZE_FP8, get),BIND(npuw::llm::cache_rope, NPUW_LLM_CACHE_ROPE, get),+ BIND(npuw::llm::enable_block_based_kv_cache, NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE, get),BIND(npuw::llm::prefill_moe_hint, NPUW_LLM_PREFILL_MOE_HINT, get),BIND(npuw::llm::generate_moe_hint, NPUW_LLM_GENERATE_MOE_HINT, get),BIND(npuw::llm::generate_pyramid, NPUW_LLM_GENERATE_PYRAMID, get),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 2a91ee3cfc4..62bf2ec75dc 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@@ -14,6 +14,8 @@ namespace npuw {class LLMInferRequest;class WhisperInferRequest;+class LLMBlockKVCacheStrategy;+class LLMContinuousKVCacheStrategy;struct PrefixCacheRestorationContext;class LLMCompiledModel : public ov::npuw::ICompiledModel {using GetPropertiesMap =@@ -75,6 +77,8 @@ private:friend class LLMInferRequest;friend class WhisperInferRequest;friend class EmbeddingInferRequest;+ friend class LLMBlockKVCacheStrategy;+ friend class LLMContinuousKVCacheStrategy;std::shared_ptr<ov::ISyncInferRequest> create_llm_infer_request();std::shared_ptr<ov::ISyncInferRequest> create_whisper_infer_request();@@ -100,6 +104,7 @@ private:KVCacheDesc m_kvcache_desc;uint64_t m_prefill_chunk_size = 0;bool m_use_chunk_prefill = false;+ bool m_is_block_kv_cache = false;std::shared_ptr<ov::npuw::ICompiledModel_v0> m_kvcache_compiled;std::shared_ptr<ov::npuw::ICompiledModel_v0> m_prefill_compiled;// This model is optional, so can be null.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.cppnew file mode 100644index 00000000000..6df8aee021a--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.cpp@@ -0,0 +1,118 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "llm_continuous_kvcache_strategy.hpp"++#include "llm_infer_request.hpp"+#include "util.hpp"++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).+// 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).+ 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 (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()) {+ const auto& input_name = input_port.get_any_name();+ if (ov::npuw::util::starts_with(input_name, LLMInferRequest::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 shared_tensor =+ ov::SoPtr<ov::ITensor>(ov::make_tensor(input_port.get_element_type(),+ input_port.get_shape(),+ 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));+ }+ }+ }+ }++ // Steps 2–3: bind and zero-fill the shared prefill↔generate KV buffer.+ const bool use_chunk_prefill = m_req.m_npuw_llm_compiled_model->m_use_chunk_prefill;+ if (use_chunk_prefill) {+ m_req.bind_past_kv();+ m_req.clear_chunk_prefill_kv_cache();+ }+}++// on_reset: zero-fill all past KV input tensors in the prefill model.+// next_prompt_length is ignored — continuous strategy has no warm-block concept.+void LLMContinuousKVCacheStrategy::on_reset(uint32_t /*next_prompt_length*/) {+ namespace uu = ov::npuw::util;+ for (const auto& input_name : m_req.m_kvcache_past_names) {+ if (m_req.m_prefill_in_ports.find(input_name) != m_req.m_prefill_in_ports.end()) {+ uu::fill_tensor_bytes(m_req.m_prefill_request->get_tensor(m_req.m_prefill_in_ports.at(input_name)), 0u);+ }+ }+}++// on_prefill_chunk_begin: no-op — continuous KV has no per-chunk setup.+void LLMContinuousKVCacheStrategy::on_prefill_chunk_begin(uint32_t /*current_prompts_len*/) {}++// on_prefill_chunk_done:+// is_last=false: persist just-inferred KV outputs into past inputs for the next chunk.+// is_last=true: leave the KV output in-place in the prefill model's output tensors;+// it will be copied into the generate model by on_generate_kv_init()+// via copy_kvcache() at the start of the first generate step.+void LLMContinuousKVCacheStrategy::on_prefill_chunk_done(uint32_t current_prompts_len, bool is_last) {+ if (is_last) {+ return;+ }+ const bool v_transposed = m_req.m_npuw_llm_compiled_model->m_kvcache_desc.v_tensors_transposed_pre;+ m_req.update_kvcache_for(m_req.m_prefill_request,+ m_req.m_prefill_in_ports,+ m_req.m_prefill_out_ports,+ current_prompts_len,+ v_transposed);+}++// on_generate_kv_init: copy the full accumulated prefill KV into the generate+// model's past input buffer so the first generate step sees the correct context.+void LLMContinuousKVCacheStrategy::on_generate_kv_init() {+ m_req.copy_kvcache();+}++// 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) {+ const bool v_transposed = m_req.m_npuw_llm_compiled_model->m_kvcache_desc.v_tensors_transposed_gen;+ m_req.update_kvcache_for(m_req.m_kvcache_request,+ m_req.m_kvcache_in_ports,+ m_req.m_kvcache_out_ports,+ input_tokens_len,+ v_transposed);+}++} // namespace npuw+} // namespace ovdiff --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.hppnew file mode 100644index 00000000000..dbb949ea55e--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.hpp@@ -0,0 +1,37 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "llm_kvcache_strategy.hpp"++namespace ov {+namespace npuw {++class LLMInferRequest; // forward declaration — avoids circular include++/**+ * @brief KV cache strategy for the classic continuous-buffer implementation.+ *+ * Implements the original single contiguous buffer approach:+ * - prefill KV is accumulated in the prefill model's past_key_values input tensors+ * via update_kvcache_for() after each intermediate chunk+ * - after all chunks, the full KV is copied to the generate model's input buffer+ * via copy_kvcache()+ * - each generate step persists the new token KV via update_kvcache_for()+ */+class LLMContinuousKVCacheStrategy final : public LLMKVCacheStrategy {+public:+ explicit LLMContinuousKVCacheStrategy(LLMInferRequest& req) : LLMKVCacheStrategy(req) {}++ void on_initialize() override;+ void on_reset(uint32_t next_prompt_length = 0) override;+ 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_step_done(uint32_t input_tokens_len) override;+};++} // namespace npuw+} // namespace ovdiff --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 0e88c2d1f19..cb43940802a 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@@ -7,7 +7,9 @@#include <regex>#include "infer_request_utils.hpp"+#include "llm_block_kvcache_strategy.hpp"#include "llm_compiled_model.hpp"+#include "llm_continuous_kvcache_strategy.hpp"#include "logging.hpp"#include "openvino/core/parallel.hpp"#include "openvino/runtime/iasync_infer_request.hpp"@@ -131,8 +133,32 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCom_input_ids_name = layer_names::inputs_embeds;}- // Create and initialize generate request variants with memory sharing- create_generate_request_variants(compiled_model);+ // Create and register all generate model variants.+ auto register_generate_request = [this](const std::shared_ptr<ov::IAsyncInferRequest>& req) {+ m_generate_requests.push_back(req);+ PortsMap in_ports, out_ports;+ for (const auto& p : req->get_compiled_model()->inputs()) {+ in_ports.emplace(p.get_any_name(), p);+ }+ for (const auto& p : req->get_compiled_model()->outputs()) {+ out_ports.emplace(p.get_any_name(), p);+ }+ m_generate_variant_in_ports.emplace(req, std::move(in_ports));+ m_generate_variant_out_ports.emplace(req, std::move(out_ports));+ };+ const size_t num_variants = compiled_model->m_generate_compiled_variants.size();+ m_generate_requests.reserve(num_variants);+ m_generate_base_requests.reserve(num_variants);+ for (size_t i = 0; i < num_variants; ++i) {+ auto base_req = compiled_model->m_generate_compiled_variants[i]->create_base_infer_request();+ m_generate_base_requests.push_back(base_req);+ register_generate_request(compiled_model->m_generate_compiled_variants[i]->wrap_async_infer_request(base_req));+ }+ // Set default to the largest variant for backward compatibility+ m_kvcache_request = m_generate_requests.back();+ // Set ports to ensure tensors aren't empty during bind_past_kv()+ 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_prefill_base_request = compiled_model->m_prefill_compiled->create_base_infer_request();m_prefill_request = compiled_model->m_prefill_compiled->wrap_async_infer_request(m_prefill_base_request);@@ -158,20 +184,21 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCo}}- init_pre_alloc_device();+ m_pre_alloc_device = 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);- const bool use_chunk_prefill = m_npuw_llm_compiled_model->m_use_chunk_prefill;- if (use_chunk_prefill) {- // FIXME: enable w/o chunking as well. Although need to align the paddings beforehand- bind_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();+ // Instantiate the KV cache strategy and run one-time initialization.+ // on_initialize() requires prefill ports, m_generate_requests, and m_pre_alloc_device+ // to be fully populated, so both steps live here at the end of setup.+ if (m_npuw_llm_compiled_model->m_is_block_kv_cache) {+ m_kvcache_strategy = std::make_unique<LLMBlockKVCacheStrategy>(*this);+ } else {+ m_kvcache_strategy = std::make_unique<LLMContinuousKVCacheStrategy>(*this);}+ m_kvcache_strategy->on_initialize();if (m_npuw_llm_compiled_model->m_enable_prefix_caching) {m_prefix_caching_helper = std::make_unique<PrefixCachingHelper>(*this);@@ -281,93 +308,6 @@ void ov::npuw::LLMInferRequest::bind_past_kv() {}}-void ov::npuw::LLMInferRequest::create_generate_request_variants(- const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled_model) {- // Create multiple generate model variants' requests- m_generate_requests.reserve(compiled_model->m_generate_compiled_variants.size());-- // First, create the largest variant request (last one in the list)- auto largest_generate_request = compiled_model->m_generate_compiled_variants.back()->create_infer_request();-- // Store past KV tensors from the largest variant for sharing- 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 (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 tensors- for (size_t i = 0; i < compiled_model->m_generate_compiled_variants.size(); ++i) {- std::shared_ptr<ov::IAsyncInferRequest> generate_request;-- if (i == compiled_model->m_generate_compiled_variants.size() - 1) {- // Use the already created largest variant- generate_request = largest_generate_request;- } else {- // Create smaller variant- generate_request = compiled_model->m_generate_compiled_variants[i]->create_infer_request();-- // Share past KV tensors from the largest variant- for (const auto& input_port : generate_request->get_compiled_model()->inputs()) {- const auto& input_name = input_port.get_any_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);- }- }- }-- m_generate_requests.push_back(generate_request);-- // Build input/output ports mapping for this variant- std::unordered_map<std::string, ov::Output<const ov::Node>> variant_in_ports;- std::unordered_map<std::string, ov::Output<const ov::Node>> variant_out_ports;-- for (const auto& input_port : generate_request->get_compiled_model()->inputs()) {- variant_in_ports.emplace(input_port.get_any_name(), input_port);- }- for (const auto& output_port : generate_request->get_compiled_model()->outputs()) {- variant_out_ports.emplace(output_port.get_any_name(), output_port);- }-- m_generate_variant_in_ports.emplace(generate_request, std::move(variant_in_ports));- m_generate_variant_out_ports.emplace(generate_request, std::move(variant_out_ports));- }-- // Set default to the largest variant for backward compatibility- m_kvcache_request = m_generate_requests.back();-- // Need to set ports to ensure tensors aren't empty during bind_past_kv()- 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);-}-std::shared_ptr<ov::IAsyncInferRequest> ov::npuw::LLMInferRequest::select_generate_request(int64_t prompt_length) {// Select the largest variant if prompt_length is 0 (unknown)if (prompt_length == 0) {@@ -503,12 +443,7 @@ 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);}- 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);- }- }+ m_kvcache_strategy->on_reset(prompt_length > 0 ? static_cast<uint32_t>(prompt_length) : 0u);for (const auto& input_name : m_lincache_past_names) {if (m_prefill_in_ports.find(input_name) != m_prefill_in_ports.end()) {@@ -838,6 +773,9 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inpkvcache_desc.num_stored_tokens,static_cast<uint32_t>(current_prompts_len));}++ // Prepare KV blocks or bind memory for this chunk via strategy.+ m_kvcache_strategy->on_prefill_chunk_begin(static_cast<uint32_t>(current_prompts_len));});m_llm_profile["1/prefill:3b.infer"].record([&]() {@@ -860,31 +798,30 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inp}});+ const bool is_last_chunk = (remaining_prompts - current_prompts_len) <= 0;remaining_prompts -= current_prompts_len;kvcache_desc.num_stored_tokens += static_cast<uint32_t>(current_prompts_len);- // Do not copy last computed chunk and preserve it in present k/v layer- if (remaining_prompts <= 0) {+ m_llm_profile["1/prefill:3d.update_kvcache"].record([&]() {+ // Finalise KV state after inference via strategy.+ m_kvcache_strategy->on_prefill_chunk_done(static_cast<uint32_t>(current_prompts_len), is_last_chunk);+ // Do not copy last computed chunk and preserve it in present k/v layer.+ if (!is_last_chunk) {+ // Attention mask and lincache update for intermediate chunks.+ copy_lincache(m_prefill_request, m_prefill_request, m_prefill_out_ports, m_prefill_in_ports);++ std::copy_n(+ attn_mask_in_tensor->data<int64_t>() + attn_mask_in_tensor->get_size() - current_prompts_len,+ current_prompts_len,+ attn_mask_in_tensor->data<int64_t>() + kvcache_desc.num_stored_tokens - current_prompts_len);+ }+ });++ if (is_last_chunk) {LOG_DEBUG("All prompts have been prefilled in chunks");m_tokens_in_present_chunk = current_prompts_len;break;}-- m_llm_profile["1/prefill:3d.update_kvcache"].record([&]() {- // Copy calculated key/values chunk from present k/v layer to past k/v layer for storage- update_kvcache_for(m_prefill_request,- m_prefill_in_ports,- m_prefill_out_ports,- static_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 iteration- std::copy_n(attn_mask_in_tensor->data<int64_t>() + attn_mask_in_tensor->get_size() - current_prompts_len,- current_prompts_len,- attn_mask_in_tensor->data<int64_t>() + kvcache_desc.num_stored_tokens - current_prompts_len);- });}LOG_DEBUG("Done.");@@ -1040,7 +977,7 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,if (!m_generate_initialized) {LOG_DEBUG("Copy kv-cache from prefill to generate model.");if (kvcache_desc.num_stored_tokens > 0) {- copy_kvcache();+ m_kvcache_strategy->on_generate_kv_init();copy_lincache(m_prefill_request, m_kvcache_request, m_prefill_out_ports, m_kvcache_in_ports);}@@ -1119,18 +1056,19 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,});kvcache_desc.num_stored_tokens += input_tokens_len;- if (m_lm_head_request) {- LOG_DEBUG("Calling inference for LM head model asynchronously");- m_lm_head_request->start_async();+ // Shared post-infer KV cache update for both lm_head and non-lm_head paths.+ auto do_update_kvcache = [&]() {m_llm_profile["N/generate:3.update_kvcache"].record([&]() {if (kvcache_desc.num_stored_tokens < kvcache_desc.total_size) {- update_kvcache_for(m_kvcache_request,- m_kvcache_in_ports,- m_kvcache_out_ports,- input_tokens_len,- kvcache_desc.v_tensors_transposed_gen);+ m_kvcache_strategy->on_generate_step_done(input_tokens_len);}});+ };++ if (m_lm_head_request) {+ LOG_DEBUG("Calling inference for LM head model asynchronously");+ m_lm_head_request->start_async();+ do_update_kvcache();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);});@@ -1141,15 +1079,7 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,m_logits = m_lm_head_request->get_tensor(m_lm_head_logits_port);});} else {- m_llm_profile["N/generate:3.update_kvcache"].record([&]() {- if (kvcache_desc.num_stored_tokens < kvcache_desc.total_size) {- update_kvcache_for(m_kvcache_request,- m_kvcache_in_ports,- m_kvcache_out_ports,- input_tokens_len,- kvcache_desc.v_tensors_transposed_gen);- }- });+ do_update_kvcache();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);});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 8f8576396e7..e5c008b048c 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@@ -10,6 +10,7 @@#include "llm_compiled_model.hpp"#include "llm_eagle3_extension.hpp"#include "llm_infer_base_request.hpp"+#include "llm_kvcache_strategy.hpp"#include "llm_lora_states.hpp"#include "llm_prefix_caching.hpp"#include "llm_stored_tokens_state.hpp"@@ -43,9 +44,6 @@ 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);- // Create and initialize generate variant requests with memory sharing- void create_generate_request_variants(const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled_model);-// 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@@ -88,6 +86,10 @@ protected:// NOTE: This is just a casted pointer for convenience. In fact it points to the// same object as m_prefill_request.std::shared_ptr<ov::npuw::IBaseInferRequest> m_prefill_base_request;+ // Base infer requests for all generate variants, parallel to m_generate_requests.+ // Used to propagate dummy tensors to sub-requests on conversation reset, ensuring that+ // sub-requests also release stale block tensor refs.+ std::vector<std::shared_ptr<ov::npuw::IBaseInferRequest>> m_generate_base_requests;// This infer request is optional, so can be null.std::shared_ptr<ov::IAsyncInferRequest> m_lm_head_request;ov::SoPtr<ov::ITensor> m_logits;@@ -144,7 +146,12 @@ protected:using MS = ov::npuw::perf::metric<ov::npuw::perf::MSec>;ov::npuw::perf::Profile<MS> m_llm_profile;- // Friend declarations for PrefixCachingHelper to access protected members+ // KV cache management strategy (set once in the constructor, valid for the object's lifetime)+ std::unique_ptr<LLMKVCacheStrategy> m_kvcache_strategy;++ // Friend declarations: strategies and PrefixCachingHelper need access to protected members+ friend class LLMContinuousKVCacheStrategy;+ friend class LLMBlockKVCacheStrategy;friend class PrefixCachingHelper;};diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_kvcache_strategy.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_kvcache_strategy.hppnew file mode 100644index 00000000000..a70403ace78--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_kvcache_strategy.hpp@@ -0,0 +1,79 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstdint>+#include <memory>++#include "openvino/runtime/iasync_infer_request.hpp"++namespace ov {+namespace npuw {++class LLMInferRequest; // forward declaration — strategy always outlived by its owning request++/**+ * @brief Abstract strategy interface for LLM KV cache management.+ *+ * Decouples `LLMInferRequest` from the two concrete KV cache implementations:+ * - LLMContinuousKVCacheStrategy — single contiguous buffer, classic copy-on-chunk approach+ * - LLMBlockKVCacheStrategy — fixed-size block pool with zero-copy prefill optimization+ *+ * Lifecycle call sequence:+ * 1. on_initialize() — once after LLMInferRequest construction;+ * allocates block managers, sets up buffer sharing+ * across generate variants (continuous mode), etc.+ * 2. on_reset() — each conversation boundary+ * 3. Per prefill chunk loop:+ * a. on_prefill_chunk_begin() — before infer()+ * b. infer() [called by LLMInferRequest]+ * c. on_prefill_chunk_done() — after infer(); is_last distinguishes the two paths:+ * 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+ * b. infer() [called by LLMInferRequest]+ * c. on_generate_step_done() — after infer(), update KV for next step+ */+class LLMKVCacheStrategy {+public:+ /**+ * @brief Construct the strategy bound to a fully-constructed LLMInferRequest.+ *+ * The reference guarantees the request outlives the strategy (both live inside the+ * same LLMInferRequest object) and can never be null.+ */+ explicit LLMKVCacheStrategy(LLMInferRequest& req) : m_req(req) {}+ virtual ~LLMKVCacheStrategy() = default;++ // One-time setup after LLMInferRequest is fully constructed.+ // May also wire KV tensor sharing across generate variants (continuous mode).+ virtual void on_initialize() = 0;++ // Conversation boundary: free/zero all KV state.+ // next_prompt_length: expected prompt length for the upcoming conversation (0 = unknown).+ // Block-based strategy uses it to decide how many block device tensors to keep warm.+ virtual void on_reset(uint32_t next_prompt_length = 0) = 0;++ // Called before each prefill chunk's infer()+ virtual void on_prefill_chunk_begin(uint32_t current_prompts_len) = 0;++ // Called after each prefill chunk's infer().+ // is_last=false: intermediate chunk — KV outputs must be persisted for the next chunk.+ // is_last=true: final chunk — block mode stores outputs into blocks; continuous is no-op.+ virtual void on_prefill_chunk_done(uint32_t current_prompts_len, bool is_last) = 0;+ // Called once on the first generate step before infer():+ // bind/copy the accumulated prefill KV into the generate model's input ports.+ virtual void on_generate_kv_init() = 0;++ // Called after each generate step's infer(): persist new token KV and update bindings+ virtual void on_generate_step_done(uint32_t input_tokens_len) = 0;++protected:+ LLMInferRequest& m_req;+};++} // namespace npuw+} // namespace ovdiff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex ce81e70a0ac..fc970f3d4c5 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -48,6 +48,8 @@ ov_add_test_target(${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.cpp+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_infer_base_request.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_eagle3_extension.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/whisper/whisper_infer_request.cppdiff --git a/src/plugins/intel_npu/tests/unit/npuw/kv_cache_block_manager_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/kv_cache_block_manager_test.cppindex 8fe4ad70edc..107e2b8f0a0 100644--- a/src/plugins/intel_npu/tests/unit/npuw/kv_cache_block_manager_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/kv_cache_block_manager_test.cpp@@ -142,22 +142,24 @@ TEST_F(KVCacheBlockManagerTest, TokenCountValidation) {<< "Setting tokens beyond capacity should throw exception";}-// Test 6: Memory Reuse After Clear-TEST_F(KVCacheBlockManagerTest, MemoryReuseAfterClear) {- // Allocate a block and record its tensor pointer+// Test 6: Tensor Valid After Clear+// clear_all() drops all SoPtr tensors (releases device memory back to the allocator).+// Re-allocation must produce a fresh valid tensor; the address is not guaranteed to be reused.+TEST_F(KVCacheBlockManagerTest, TensorValidAfterClear) {auto block_id = manager->allocate_block();ASSERT_TRUE(block_id.has_value());- auto tensor_before = manager->get_block_tensor(block_id.value());- ASSERT_NE(tensor_before, nullptr);- void* ptr_before = tensor_before->data();+ ASSERT_NE(manager->get_block_tensor(block_id.value()), nullptr);- // Clear and re-allocate — should reuse the same underlying memory+ // clear_all() releases tensor memory; block state is resetmanager->clear_all();+ EXPECT_TRUE(manager->get_allocated_blocks().empty());++ // Re-allocate: a new tensor must be allocated on demandauto block_id2 = manager->allocate_block();ASSERT_TRUE(block_id2.has_value());auto tensor_after = manager->get_block_tensor(block_id2.value());- ASSERT_NE(tensor_after, nullptr);- EXPECT_EQ(tensor_after->data(), ptr_before) << "Should reuse the same memory buffer after clear";+ ASSERT_NE(tensor_after, nullptr) << "Fresh tensor must be valid after clear + re-allocate";+ EXPECT_EQ(manager->get_block_tokens(block_id2.value()), 0u) << "Token count must be reset to 0";}// Test 7: Allocation and Token State Consistency@@ -263,4 +265,58 @@ TEST_F(KVCacheBlockManagerTest, GetTensorAfterClear) {EXPECT_NE(tensor2, nullptr) << "Tensor should still be valid after clear + re-allocate";}+// Test 12: Invalid Constructor Parameters+TEST_F(KVCacheBlockManagerTest, InvalidConstructorParams) {+ const ov::Shape valid_shape{1, 32, 512, 128};++ // block_size = 0 must throw+ EXPECT_THROW(KVCacheBlockManager(0u, 8u, valid_shape, ov::element::f16, "CPU", nullptr), ov::Exception)+ << "block_size=0 must throw";++ // max_blocks = 0 must throw+ EXPECT_THROW(KVCacheBlockManager(512u, 0u, valid_shape, ov::element::f16, "CPU", nullptr), ov::Exception)+ << "max_blocks=0 must throw";++ // Shape with no dimension equal to block_size must throw+ const ov::Shape bad_shape{1, 32, 256, 128}; // neither dim[2]=256 nor dim[3]=128 equals 512+ EXPECT_THROW(KVCacheBlockManager(512u, 8u, bad_shape, ov::element::f16, "CPU", nullptr), ov::Exception)+ << "Shape not containing block_size must throw";+}++// Test 13: update_block_tokens on a Freed Block+TEST_F(KVCacheBlockManagerTest, UpdateTokensOnFreeBlock) {+ auto block_id = manager->allocate_block();+ ASSERT_TRUE(block_id.has_value());+ manager->update_block_tokens(block_id.value(), 100);++ // clear_all() marks block as free+ manager->clear_all();++ // Updating a free (is_allocated=false) block must throw+ EXPECT_THROW(manager->update_block_tokens(block_id.value(), 100), ov::Exception)+ << "update_block_tokens on a freed block must throw";+}++// Test 14: num_free_blocks Accuracy+TEST_F(KVCacheBlockManagerTest, NumFreeBlocks) {+ // Initially all blocks are free+ EXPECT_EQ(manager->num_free_blocks(), max_blocks);++ // Each allocation reduces the free count by 1+ manager->allocate_block();+ manager->allocate_block();+ manager->allocate_block();+ EXPECT_EQ(manager->num_free_blocks(), max_blocks - 3u);++ // clear_all() restores all blocks to free+ manager->clear_all();+ EXPECT_EQ(manager->num_free_blocks(), max_blocks);++ // Exhaust the pool: free count must reach 0+ for (uint32_t i = 0; i < max_blocks; ++i) {+ manager->allocate_block();+ }+ EXPECT_EQ(manager->num_free_blocks(), 0u);+}+} // namespace