Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[NPUW]Implement prefix caching. (#31669)

intelgaoxiong9b49fe44630f
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hpp
index 5659011b850..4d184aa060e 100644
--- a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hpp
+++ b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hpp
@@ -148,6 +148,9 @@ DEFINE_OPT(NPUW_LLM_CACHE_ROPE, bool, true, npuw::llm::cache_rope, RunTime);
DEFINE_OPT(NPUW_LLM_PREFILL_CHUNK_SIZE, uint64_t, 1024, npuw::llm::prefill_chunk_size, RunTime);
DEFINE_OPT(NPUW_LLM_SHARED_HEAD, bool, true, npuw::llm::shared_lm_head, RunTime);
DEFINE_OPT(NPUW_LLM_MAX_LORA_RANK, uint32_t, 32, npuw::llm::max_lora_rank, RunTime);
+DEFINE_OPT(NPUW_LLM_ENABLE_PREFIX_CACHING, bool, false, npuw::llm::enable_prefix_caching, RunTime);
+DEFINE_OPT(NPUW_LLM_PREFIX_CACHING_BLOCK_SIZE, uint64_t, 256, npuw::llm::prefix_caching_block_size, RunTime);
+DEFINE_OPT(NPUW_LLM_PREFIX_CACHING_MAX_NUM_BLOCKS, uint64_t, 128, npuw::llm::prefix_caching_max_num_blocks, RunTime);
DEFINE_OPT(NPUW_WHISPER, bool, false, npuw::whisper::enabled, RunTime);
DEFINE_ANYMAP_OPT(NPUW_LLM_PREFILL_CONFIG, npuw::llm::prefill_config);
DEFINE_ANYMAP_OPT(NPUW_LLM_ADDITIONAL_PREFILL_CONFIG, npuw::llm::additional_prefill_config);
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hpp
index 4ffb00b9442..68ac3f2160f 100644
--- a/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hpp
+++ b/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hpp
@@ -498,6 +498,37 @@ static constexpr ov::Property<bool> cache_rope{"NPUW_LLM_CACHE_ROPE"};
*/
static constexpr ov::Property<uint64_t> prefill_chunk_size{"NPUW_LLM_PREFILL_CHUNK_SIZE"};
+/**
+ * @brief
+ * Type: bool.
+ * This toggle enables the prefix caching feature.
+ * When activated, it stores the prefilled key-value pairs (KV) for current prompts in the cache during each
+ * conversation round.
+ * In subsequent rounds, if the prompt's KV is found in the cache, it allows skipping the prefill for certain tokens,
+ * thereby enhancing the latency of the first token.
+ * Default value: false.
+ */
+static constexpr ov::Property<uint64_t> enable_prefix_caching{"NPUW_LLM_ENABLE_PREFIX_CACHING"};
+
+/**
+ * @brief
+ * Type: uint64_t.
+ * Prefilled KV tensors are cached in blocks when prefix caching is enabled.
+ * This value describes the number of tokens in each block.
+ * This value should be not greater than prefill_chunk_size.
+ * Default value: 256.
+ */
+static constexpr ov::Property<uint64_t> prefix_caching_block_size{"NPUW_LLM_PREFIX_CACHING_BLOCK_SIZE"};
+
+/**
+ * @brief
+ * Type: uint64_t.
+ * Prefilled KV tensors are cached in blocks when prefix caching is enabled.
+ * This value describes the maximum number of blocks in cache.
+ * Default value: 128.
+ */
+static constexpr ov::Property<uint64_t> prefix_caching_max_num_blocks{"NPUW_LLM_PREFIX_CACHING_MAX_NUM_BLOCKS"};
+
/**
* @brief
* Type: std::string.
diff --git a/src/plugins/intel_npu/src/al/src/config/npuw.cpp b/src/plugins/intel_npu/src/al/src/config/npuw.cpp
index 8ed46b977c4..ad2cc62b308 100644
--- a/src/plugins/intel_npu/src/al/src/config/npuw.cpp
+++ b/src/plugins/intel_npu/src/al/src/config/npuw.cpp
@@ -69,6 +69,9 @@ void intel_npu::registerNPUWLLMOptions(OptionsDesc& desc) {
desc.add<NPUW_LLM_OPTIMIZE_V_TENSORS>();
desc.add<NPUW_LLM_CACHE_ROPE>();
desc.add<NPUW_LLM_PREFILL_CHUNK_SIZE>();
+ desc.add<NPUW_LLM_ENABLE_PREFIX_CACHING>();
+ desc.add<NPUW_LLM_PREFIX_CACHING_BLOCK_SIZE>();
+ desc.add<NPUW_LLM_PREFIX_CACHING_MAX_NUM_BLOCKS>();
desc.add<NPUW_LLM_MAX_GENERATION_TOKEN_LEN>();
desc.add<NPUW_LLM_PREFILL_HINT>();
desc.add<NPUW_LLM_GENERATE_HINT>();
diff --git a/src/plugins/intel_npu/src/plugin/include/properties.hpp b/src/plugins/intel_npu/src/plugin/include/properties.hpp
index feeeb460a4d..e7b18603470 100644
--- a/src/plugins/intel_npu/src/plugin/include/properties.hpp
+++ b/src/plugins/intel_npu/src/plugin/include/properties.hpp
@@ -119,6 +119,9 @@ private:
ov::intel_npu::npuw::llm::prefill_chunk_size.name(),
ov::intel_npu::npuw::llm::shared_lm_head.name(),
ov::intel_npu::npuw::llm::max_lora_rank.name(),
+ ov::intel_npu::npuw::llm::enable_prefix_caching.name(),
+ ov::intel_npu::npuw::llm::prefix_caching_block_size.name(),
+ ov::intel_npu::npuw::llm::prefix_caching_max_num_blocks.name(),
ov::intel_npu::npuw::llm::prefill_hint.name(),
ov::intel_npu::npuw::llm::prefill_config.name(),
ov::intel_npu::npuw::llm::additional_prefill_config.name(),
diff --git a/src/plugins/intel_npu/src/plugin/npuw/attention.cpp b/src/plugins/intel_npu/src/plugin/npuw/attention.cpp
index e5602400dd8..8542c2e9dc5 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/attention.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/attention.cpp
@@ -161,7 +161,7 @@ ov::npuw::runtime::attention::Selector::Ptr ov::npuw::runtime::attention::Positi
return Selector::Ptr{};
}
-void ov::npuw::runtime::attention::PositionIDs::prepare() {
+void ov::npuw::runtime::attention::PositionIDs::prepare(int64_t past_len) {
const auto& iport = m_rq.get_compiled_model()->inputs()[m_position_ids_idx];
const auto in_tensor = m_rq.get_tensor(iport);
const auto in_dims = in_tensor->get_shape();
@@ -187,7 +187,7 @@ void ov::npuw::runtime::attention::PositionIDs::prepare() {
case Case::PREFILL:
// chunked prefill case. calculate the past_length in full chunks
// FIXME: We know too much about chunking here
- m_past_length = (m_current_length / m_d.query_size) * m_d.query_size;
+ m_past_length = ((past_len + m_d.query_size - 1) / m_d.query_size) * m_d.query_size;
break;
default:
NPUW_ASSERT(false && "Reached the unreachable code");
diff --git a/src/plugins/intel_npu/src/plugin/npuw/attention.hpp b/src/plugins/intel_npu/src/plugin/npuw/attention.hpp
index 7da6762f5ea..f271d1668a2 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/attention.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/attention.hpp
@@ -139,7 +139,7 @@ public:
using Ptr = std::shared_ptr<Selector>;
virtual ~Selector() = default;
- virtual void prepare() = 0;
+ virtual void prepare(int64_t past_len) = 0;
virtual int64_t length() const = 0;
virtual int64_t past_length() const = 0;
@@ -153,7 +153,7 @@ protected:
// No dynamic dispatch - just run over the whole range
class All final : public Selector {
- void prepare() override {}
+ void prepare(int64_t past_len) override {}
int64_t length() const override {
return -1;
}
@@ -172,7 +172,7 @@ class PositionIDs final : public Selector {
const ov::ISyncInferRequest& m_rq;
PositionIDs(std::size_t param_idx, const compiled::Attention& d, const ov::ISyncInferRequest& rq);
- void prepare() override;
+ void prepare(int64_t past_len) override;
int64_t length() const override;
int64_t past_length() const override;
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.hpp
index c17765261ca..7a988a6b555 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
@@ -69,7 +69,17 @@ public:
virtual std::size_t total_subrequests() const;
virtual bool supports_async_pipeline() const = 0;
+ void update_history_size(int64_t history_size) {
+ m_history_size = history_size;
+ }
+
+ int64_t get_history_size() const {
+ return m_history_size;
+ }
+
protected:
+ int64_t m_history_size = 0;
+
using RqPtr = ov::SoPtr<ov::IAsyncInferRequest>;
using RqPtrs = std::vector<RqPtr>;
diff --git a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
index 54196c48539..08df11c19ba 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
@@ -1554,7 +1554,7 @@ void ov::npuw::CompiledModel::dump_on_fail(std::size_t id, const std::string& de
}
}
-std::shared_ptr<ov::ISyncInferRequest> ov::npuw::CompiledModel::create_sync_infer_request() const {
+std::shared_ptr<ov::npuw::IBaseInferRequest> ov::npuw::CompiledModel::create_base_infer_request() const {
// Synchronous infer request implementation may vary based on the
// selected strategy
auto* non_const_this = const_cast<ov::npuw::CompiledModel*>(this); // because of const in API
@@ -1582,21 +1582,29 @@ std::shared_ptr<ov::ISyncInferRequest> ov::npuw::CompiledModel::create_sync_infe
return true; // no spatial & subgraphs requiring unpack found
};
- std::shared_ptr<ov::ISyncInferRequest> result;
+ std::shared_ptr<ov::npuw::IBaseInferRequest> result;
if (m_cfg.get<::intel_npu::NPUW_UNFOLD_IREQS>() && no_spatial_unpack()) {
- result.reset(new ov::npuw::UnfoldInferRequest(non_const_this_sptr));
+ result = std::make_shared<ov::npuw::UnfoldInferRequest>(non_const_this_sptr);
} else {
- result.reset(new ov::npuw::JustInferRequest(non_const_this_sptr));
+ result = std::make_shared<ov::npuw::JustInferRequest>(non_const_this_sptr);
}
NPUW_ASSERT(result);
return result;
}
-std::shared_ptr<ov::IAsyncInferRequest> ov::npuw::CompiledModel::create_infer_request() const {
- auto internal_request = create_sync_infer_request();
+std::shared_ptr<ov::ISyncInferRequest> ov::npuw::CompiledModel::create_sync_infer_request() const {
+ return create_base_infer_request();
+}
+
+std::shared_ptr<ov::IAsyncInferRequest> ov::npuw::CompiledModel ::wrap_async_infer_request(
+ std::shared_ptr<ov::npuw::IBaseInferRequest> internal_request) const {
return std::make_shared<ov::IAsyncInferRequest>(internal_request, get_task_executor(), get_callback_executor());
}
+std::shared_ptr<ov::IAsyncInferRequest> ov::npuw::CompiledModel::create_infer_request() const {
+ return wrap_async_infer_request(create_base_infer_request());
+}
+
void ov::npuw::CompiledModel::set_property(const ov::AnyMap& properties) {
OPENVINO_NOT_IMPLEMENTED;
}
diff --git a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp
index a783b5b0a99..81af4c7b276 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp
@@ -7,6 +7,7 @@
#include <optional>
#include "attention.hpp"
+#include "base_sync_infer_request.hpp"
#include "common.hpp"
#include "intel_npu/config/config.hpp"
#include "intel_npu/config/npuw.hpp"
@@ -94,6 +95,11 @@ private:
std::shared_ptr<const ::intel_npu::Plugin> get_npuw_plugin() const;
std::shared_ptr<ov::ISyncInferRequest> create_sync_infer_request() const override;
+ // API for easily create and manage NPUW infer-requests
+ std::shared_ptr<ov::npuw::IBaseInferRequest> create_base_infer_request() const;
+ std::shared_ptr<ov::IAsyncInferRequest> wrap_async_infer_request(
+ std::shared_ptr<ov::npuw::IBaseInferRequest> internal_request) const;
+
std::string submodel_device(const std::size_t idx) const;
bool is_gather_closure(const std::size_t idx, const std::size_t cidx) const;
bool unpack_required(const std::size_t idx) const;
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.cpp
index 0844624680b..36a4de68367 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
@@ -509,7 +509,7 @@ void ov::npuw::JustInferRequest::prepare_for_infer() {
// So do the dynamic range
if (m_attention_selector) {
- m_attention_selector->prepare();
+ m_attention_selector->prepare(get_history_size());
}
// FIXME: attention-specific, needs to be moved out after refactoring
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp
index 8e1c30137d2..13a4b6cdef9 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
@@ -401,6 +401,10 @@ uint32_t align_to(uint32_t value, uint32_t alignment) {
return (value + alignment - 1) & ~(alignment - 1);
}
+bool is_aligned_to(uint32_t value, uint32_t alignment) {
+ return value % alignment == 0;
+}
+
std::shared_ptr<ov::Model> cvt_kvcache_to_fp16(const std::shared_ptr<ov::Model>& model) {
ov::preprocess::PrePostProcessor ppp(model);
@@ -420,8 +424,8 @@ std::shared_ptr<ov::Model> cvt_kvcache_to_fp16(const std::shared_ptr<ov::Model>&
}
std::shared_ptr<ov::Model> redirect_new_kv_to_output(const std::shared_ptr<ov::Model>& model) {
- const auto kStartOutputKVCacheLayers = 1u;
- for (std::size_t i = kStartOutputKVCacheLayers; i < model->outputs().size(); ++i) {
+ for (std::size_t i = ov::npuw::LLMInferRequest::layer_ids::kStartOutputKVCacheLayers; i < model->outputs().size();
+ ++i) {
auto kvout = model->output(i);
auto kvrslt = kvout.get_node();
auto kvcat = kvrslt->inputs()[0].get_source_output().get_node();
@@ -1054,6 +1058,20 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
}
max_prompt_len = align_to(max_prompt_len, static_cast<uint32_t>(m_prefill_chunk_size));
}
+
+ m_enable_prefix_caching = m_cfg.get<::intel_npu::NPUW_LLM_ENABLE_PREFIX_CACHING>();
+ if (m_enable_prefix_caching) {
+ LOG_INFO("Prefix caching is enabled");
+ m_prefix_caching_block_size = m_cfg.get<::intel_npu::NPUW_LLM_PREFIX_CACHING_BLOCK_SIZE>();
+ if (!is_aligned_to(static_cast<uint32_t>(m_prefill_chunk_size),
+ static_cast<uint32_t>(m_prefix_caching_block_size))) {
+ LOG_INFO("Prefix caching block size is adjusted to " << m_prefill_chunk_size);
+ m_prefix_caching_block_size = m_prefill_chunk_size;
+ }
+ m_prefix_caching_max_num_blocks = m_cfg.get<::intel_npu::NPUW_LLM_PREFIX_CACHING_MAX_NUM_BLOCKS>();
+ LOG_INFO("Prefix caching block size: " << m_prefix_caching_block_size);
+ LOG_INFO("Prefix caching maximum number of blocks: " << m_prefix_caching_max_num_blocks);
+ }
}
LOG_VERB("Enabled prefill chunking: " << m_use_chunk_prefill);
@@ -1363,6 +1381,9 @@ void ov::npuw::LLMCompiledModel::serialize(std::ostream& stream, const ov::npuw:
write(model_stream, m_prefill_chunk_size);
write(model_stream, m_use_chunk_prefill);
write(model_stream, m_max_lora_rank);
+ write(model_stream, m_enable_prefix_caching);
+ write(model_stream, m_prefix_caching_block_size);
+ write(model_stream, m_prefix_caching_max_num_blocks);
write(model_stream, m_gemma_sliding_window_size);
write(model_stream, m_is_whisper);
@@ -1575,6 +1596,9 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::deserial
read(model_stream, compiled->m_prefill_chunk_size);
read(model_stream, compiled->m_use_chunk_prefill);
read(model_stream, compiled->m_max_lora_rank);
+ read(model_stream, compiled->m_enable_prefix_caching);
+ read(model_stream, compiled->m_prefix_caching_block_size);
+ read(model_stream, compiled->m_prefix_caching_max_num_blocks);
read(model_stream, compiled->m_gemma_sliding_window_size);
read(model_stream, compiled->m_is_whisper);
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.hpp
index c831f0919ae..f3888ebf254 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
@@ -13,6 +13,7 @@ namespace npuw {
class LLMInferRequest;
class WhisperInferRequest;
+struct PrefixCacheRestorationContext;
class LLMCompiledModel : public ov::npuw::ICompiledModel {
using GetPropertiesMap =
std::map<std::string, std::tuple<ov::PropertyMutability, std::function<ov::Any(const ::intel_npu::Config&)>>>;
@@ -89,6 +90,14 @@ private:
void convert_stateful_lora_to_stateless(std::shared_ptr<ov::Model>& model);
uint32_t m_max_lora_rank = 32;
+ // Support prefix caching
+ bool m_enable_prefix_caching = false;
+ uint64_t m_prefix_caching_block_size = 0;
+ uint64_t m_prefix_caching_max_num_blocks = 0;
+
+ // Friend declarations for PrefixCachingHelper to access protected members
+ friend class PrefixCachingHelper;
+
void gemma_transformations(const std::shared_ptr<ov::Model>& model);
int32_t m_gemma_sliding_window_size = 0;
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp
index 4227abd5dff..8a70c0e0d0a 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
@@ -144,10 +144,6 @@ void fill_sliding_mask(const ov::SoPtr<ov::ITensor>& mask, int64_t curr_pos, int
mask_data[mask->get_size() - 1] = true;
}
-constexpr uint32_t INPUT_IDS_SEQ_LEN_DIM = 1;
-
-constexpr std::size_t kStartOutputKVCacheLayers = 1;
-
} // anonymous namespace
void ov::npuw::LLMInferRequest::init_lora_states() {
@@ -183,7 +179,9 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCo
}
m_kvcache_request = compiled_model->m_kvcache_compiled->create_infer_request();
- m_prefill_request = compiled_model->m_prefill_compiled->create_infer_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);
for (const auto& input_port : m_prefill_request->get_compiled_model()->inputs()) {
m_prefill_in_ports.emplace(input_port.get_any_name(), input_port);
@@ -206,6 +204,10 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCo
clear_chunk_prefill_kv_cache();
}
+ if (m_npuw_llm_compiled_model->m_enable_prefix_caching) {
+ m_prefix_caching_helper = std::make_unique<PrefixCachingHelper>(*this);
+ }
+
if (compiled_model->m_lm_head_compiled) {
m_lm_head_request = compiled_model->m_lm_head_compiled->create_infer_request();
OPENVINO_ASSERT(m_lm_head_request);
@@ -239,7 +241,7 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCo
if (enable_cpu_wa) {
const auto& kvcache_compiled = m_kvcache_request->get_compiled_model();
// FIXME: Find only matching by names outputs and copy them, having previously checked that such inputs exist
- for (std::size_t i = kStartOutputKVCacheLayers; i < kvcache_compiled->outputs().size(); ++i) {
+ for (std::size_t i = layer_ids::kStartOutputKVCacheLayers; i < kvcache_compiled->outputs().size(); ++i) {
const auto& output_name = kvcache_compiled->outputs()[i].get_any_name();
const auto& input_name =
std::regex_replace(output_name, std::regex("present"), layer_names::past_key_values);
@@ -391,8 +393,8 @@ void ov::npuw::LLMInferRequest::copy_kvcache() {
auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;
const auto& kvcache_compiled = m_kvcache_request->get_compiled_model();
// FIXME: Find only matching by names outputs and copy them, having previously checked that such inputs exist
- ov::parallel_for(kvcache_compiled->outputs().size() - kStartOutputKVCacheLayers, [&](size_t out_idx) {
- const std::size_t i = kStartOutputKVCacheLayers + out_idx;
+ ov::parallel_for(kvcache_compiled->outputs().size() - layer_ids::kStartOutputKVCacheLayers, [&](size_t out_idx) {
+ const std::size_t i = layer_ids::kStartOutputKVCacheLayers + out_idx;
const auto& output_name = kvcache_compiled->outputs()[i].get_any_name();
auto prefill_out_tensor = m_prefill_request->get_tensor(m_prefill_out_ports.at(output_name));
@@ -420,11 +422,8 @@ void ov::npuw::LLMInferRequest::copy_kvcache() {
// The task is to copy both parts into the KV-cache input tensor for the decoding process
// Copy part 1 KV results
- auto tokens_in_present_chunk = kvcache_desc.num_stored_tokens % prefill_chunk_size;
- tokens_in_present_chunk = tokens_in_present_chunk ? tokens_in_present_chunk : prefill_chunk_size;
-
// tokens_in_past_chunks may be 0 in case short prompts are prefilled in single chunk
- auto tokens_in_past_chunks = kvcache_desc.num_stored_tokens - tokens_in_present_chunk;
+ auto tokens_in_past_chunks = kvcache_desc.num_stored_tokens - m_tokens_in_present_chunk;
if (tokens_in_past_chunks > 0) {
auto prefill_past_kv = m_prefill_request->get_tensor(m_prefill_in_ports.at(input_name));
auto prefill_past_kv_chunks = uu::make_tensor_slice(prefill_past_kv,
@@ -444,7 +443,7 @@ void ov::npuw::LLMInferRequest::copy_kvcache() {
auto prefill_present_kv_chunk =
uu::make_tensor_slice(prefill_out_tensor,
pre_kv_dim,
- static_cast<uint32_t>(prefill_chunk_size - tokens_in_present_chunk),
+ static_cast<uint32_t>(prefill_chunk_size - m_tokens_in_present_chunk),
static_cast<uint32_t>(prefill_chunk_size));
auto kvcache_last_kv_chunk = uu::make_tensor_slice(kvcache_in_tensor,
@@ -482,7 +481,7 @@ void ov::npuw::LLMInferRequest::update_kvcache_for(
auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;
auto& compiled = request->get_compiled_model();
// FIXME: Find only matching by names outputs and copy them, having previously checked that such inputs exist
- for (std::size_t i = kStartOutputKVCacheLayers; i < compiled->outputs().size(); ++i) {
+ for (std::size_t i = layer_ids::kStartOutputKVCacheLayers; i < compiled->outputs().size(); ++i) {
const auto& output_name = compiled->outputs()[i].get_any_name();
const auto& input_name = std::regex_replace(output_name, std::regex("present"), layer_names::past_key_values);
if (in_ports.find(input_name) == in_ports.end()) {
@@ -528,7 +527,7 @@ void ov::npuw::LLMInferRequest::trim_kvcache_for_speculative_decoding(ov::SoPtr<
void ov::npuw::LLMInferRequest::clear_chunk_prefill_kv_cache() {
const auto& prefill_compiled = m_prefill_request->get_compiled_model();
- for (std::size_t i = kStartOutputKVCacheLayers; i < prefill_compiled->outputs().size(); ++i) {
+ for (std::size_t i = layer_ids::kStartOutputKVCacheLayers; i < prefill_compiled->outputs().size(); ++i) {
const auto& output_name = prefill_compiled->outputs()[i].get_any_name();
const auto& input_name = std::regex_replace(output_name, std::regex("present"), "past_key_values");
if (m_prefill_in_ports.find(input_name) == m_prefill_in_ports.end()) {
@@ -549,7 +548,7 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inp
LOG_DEBUG("Calling chunked inference for prefill model.");
LOG_BLOCK();
- const auto input_prompt_len = input_ids->get_shape()[INPUT_IDS_SEQ_LEN_DIM];
+ const auto input_prompt_len = input_ids->get_shape()[layer_ids::INPUT_IDS_SEQ_LEN_DIM];
// For LLM, model accepts 2d inputs_embeds[BATCH, SEQ_LEN]
// For VLM, model accepts 3d inputs_ids[BATCH, SEQ_LEN, EMB_SIZE]
@@ -557,20 +556,42 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inp
const auto input_ids_elem_size = input_ids->get_element_type().size();
auto input_ids_in_tensor = m_prefill_request->get_tensor(m_prefill_in_ports.at(m_input_ids_name));
- const int64_t chunk_prompt_len = m_npuw_llm_compiled_model->m_prefill_chunk_size;
+ const uint64_t chunk_prompt_len = m_npuw_llm_compiled_model->m_prefill_chunk_size;
auto attn_mask_in_tensor = m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::attention_mask));
auto pos_ids_in_tensor = m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::position_ids));
auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;
- int64_t remaining_prompts = input_prompt_len;
+ uint64_t remaining_prompts = input_prompt_len;
+
+ const bool enable_prefix_caching = m_npuw_llm_compiled_model->m_enable_prefix_caching;
+ PrefixCacheRestorationContext cache_context;
+ if (enable_prefix_caching) {
+ // Prepare and restore prefix cache using helper
+ cache_context = m_prefix_caching_helper->prepare_and_restore(input_ids, input_prompt_len);
+ remaining_prompts = cache_context.remaining_prompts;
+ }
+
while (remaining_prompts > 0) {
// NB: input_ids can be either fp32(VLM) or i64(LLM)
// The last chunk may not be completely filled if the actual length of the prompts is not evenly divisible by
// the chunk size
auto current_prompts_len = std::min(remaining_prompts, chunk_prompt_len);
+ // Handle first chunk with prefix caching: adjust chunk size and populate attention mask for restored cache
+ if (enable_prefix_caching && cache_context.restore_prefix_cache) {
+ if (current_prompts_len == chunk_prompt_len) {
+ auto token_num_to_a_full_chunk =
+ m_prefix_caching_helper->adjust_chunk_size(kvcache_desc.num_stored_tokens, chunk_prompt_len);
+ current_prompts_len = token_num_to_a_full_chunk;
+ }
+ m_prefix_caching_helper->populate_attention_mask_for_restored_cache(attention_mask,
+ attn_mask_in_tensor,
+ kvcache_desc.num_stored_tokens);
+ cache_context.restore_prefix_cache = false;
+ }
+
// Populate the attention mask for the present chunk
// For the already processed tokens, they will be added into the attention mask after inference call
size_t last_chunk_offset = attn_mask_in_tensor->get_size() - chunk_prompt_len;
@@ -580,6 +601,7 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inp
// clear the last chunk of the attention mask to ensure non-relevant tokens are masked
ov::npuw::util::fill_tensor<int64_t>(attn_mask_in_tensor, 0, last_chunk_offset);
}
+
std::copy_n(attention_mask->data<int64_t>() + kvcache_desc.num_stored_tokens,
current_prompts_len,
attn_mask_in_tensor->data<int64_t>() + attn_mask_in_tensor->get_size() - current_prompts_len);
@@ -607,14 +629,25 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inp
kvcache_desc.num_stored_tokens + static_cast<uint32_t>(current_prompts_len));
pad_position_ids(pos_ids_in_tensor, actual_position_ids_slice);
+ // Update history size for dynamic context:
+ // dynamic attention selector needs history size to determin the past KV shape and attention mask shape
+ m_prefill_base_request->update_history_size(kvcache_desc.num_stored_tokens);
+
m_prefill_request->infer();
+ if (enable_prefix_caching) {
+ m_prefix_caching_helper->store_computed_blocks(current_prompts_len,
+ cache_context.prompt_hashes,
+ cache_context.token_idx);
+ }
+
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) {
LOG_DEBUG("All prompts have been prefilled in chunks");
+ m_tokens_in_present_chunk = current_prompts_len;
break;
}
@@ -632,6 +665,10 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inp
}
LOG_DEBUG("Done.");
+
+ if (enable_prefix_caching) {
+ m_prefix_caching_helper->print_cache_status();
+ }
}
void ov::npuw::LLMInferRequest::infer_whole_prefill(ov::SoPtr<ov::ITensor> input_ids,
@@ -666,7 +703,7 @@ void ov::npuw::LLMInferRequest::infer_whole_prefill(ov::SoPtr<ov::ITensor> input
m_prefill_request->infer();
auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;
- kvcache_desc.num_stored_tokens += static_cast<uint32_t>(input_ids->get_shape()[INPUT_IDS_SEQ_LEN_DIM]);
+ kvcache_desc.num_stored_tokens += static_cast<uint32_t>(input_ids->get_shape()[layer_ids::INPUT_IDS_SEQ_LEN_DIM]);
LOG_DEBUG("Done");
}
@@ -679,7 +716,7 @@ void ov::npuw::LLMInferRequest::infer_prefill(ov::SoPtr<ov::ITensor> input_ids,
LOG_BLOCK();
auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;
- if (input_ids->get_shape()[INPUT_IDS_SEQ_LEN_DIM] > kvcache_desc.max_prompt_size) {
+ if (input_ids->get_shape()[layer_ids::INPUT_IDS_SEQ_LEN_DIM] > kvcache_desc.max_prompt_size) {
OPENVINO_THROW("Input prompt is longer than configured \"NPUW_LLM_MAX_PROMPT_LEN\": ",
kvcache_desc.max_prompt_size,
".\nPlease either setup bigger "
@@ -718,7 +755,7 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,
LOG_DEBUG("Calling inference for generate model...");
LOG_BLOCK();
auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;
- uint32_t input_tokens_len = static_cast<uint32_t>(input_ids->get_shape()[INPUT_IDS_SEQ_LEN_DIM]);
+ uint32_t input_tokens_len = static_cast<uint32_t>(input_ids->get_shape()[layer_ids::INPUT_IDS_SEQ_LEN_DIM]);
if (input_tokens_len > kvcache_desc.max_generation_token_len) {
OPENVINO_THROW("Input prompt length is greater than output \"NPUW_LLM_MAX_GENERATION_TOKEN_LEN\": ",
kvcache_desc.max_generation_token_len,
@@ -876,7 +913,8 @@ void ov::npuw::LLMInferRequest::infer() {
// The outcome of two items is that prefill and generate stages
// can be safely differentiated by start position id for
// both main and draft models.
- if (input_ids->get_shape()[INPUT_IDS_SEQ_LEN_DIM] > 1 && position_ids->data<int64_t>()[0] == m_first_position_id) {
+ if (input_ids->get_shape()[layer_ids::INPUT_IDS_SEQ_LEN_DIM] > 1 &&
+ position_ids->data<int64_t>()[0] == m_first_position_id) {
infer_prefill(input_ids, attention_mask, position_ids, token_type_ids);
} else {
auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;
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.hpp
index 0b1a3a02de3..461c28b7cc6 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
@@ -6,8 +6,10 @@
#include <memory>
+#include "base_sync_infer_request.hpp"
#include "llm_compiled_model.hpp"
#include "llm_lora_states.hpp"
+#include "llm_prefix_caching.hpp"
#include "openvino/core/descriptor/output.hpp"
#include "openvino/runtime/isync_infer_request.hpp"
@@ -28,6 +30,11 @@ public:
static constexpr const char* gemma_sliding_mask = "npuw_gemma_sliding_mask";
};
+ struct layer_ids {
+ static constexpr uint32_t INPUT_IDS_SEQ_LEN_DIM = 1;
+ static constexpr std::size_t kStartOutputKVCacheLayers = 1;
+ };
+
explicit LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled_model);
void infer() override;
@@ -78,6 +85,10 @@ protected:
std::shared_ptr<ov::IAsyncInferRequest> m_kvcache_request;
std::shared_ptr<ov::IAsyncInferRequest> m_prefill_request;
+ // Base infer request for prefill, used to update history size for dynamic context.
+ // 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;
// This infer request is optional, so can be null.
std::shared_ptr<ov::IAsyncInferRequest> m_lm_head_request;
std::shared_ptr<LLMCompiledModel> m_npuw_llm_compiled_model;
@@ -99,9 +110,17 @@ protected:
int64_t m_first_position_id = 0;
int32_t m_gemma_sliding_window_size = 0;
+ uint64_t m_tokens_in_present_chunk = 0;
+
// Support LoRA
std::vector<ov::SoPtr<ov::IVariableState>> m_variableStates;
void init_lora_states();
+
+ // Support prefix caching
+ std::unique_ptr<PrefixCachingHelper> m_prefix_caching_helper;
+
+ // Friend declarations for PrefixCachingHelper to access protected members
+ friend class PrefixCachingHelper;
};
} // namespace npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_prefix_caching.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_prefix_caching.cpp
new file mode 100644
index 00000000000..0e2a37d1561
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_prefix_caching.cpp
@@ -0,0 +1,572 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "llm_prefix_caching.hpp"
+
+#include "infer_request_utils.hpp"
+#include "llm_infer_request.hpp"
+#include "logging.hpp"
+#include "openvino/core/parallel.hpp"
+#include "openvino/runtime/iasync_infer_request.hpp"
+#include "util.hpp"
+
+namespace ov {
+namespace npuw {
+
+bool KVBlock::add_block(const std::vector<uint64_t>& token_hashes, const KVData& kv_tensors) {
+ // Check input validity
+ if (token_hashes.empty()) {
+ return false;
+ }
+
+ // Check if the block size exceeds capacity
+ if (token_hashes.size() > m_block_size) {
+ return false;
+ }
+
+ m_token_hashes = token_hashes;
+ m_kv_data = kv_tensors;
+ m_is_full = (token_hashes.size() == m_block_size);
+
+ // Compute the block's hash value
+ m_block_hash = compute_block_hash(token_hashes);
+
+ return true;
+}
+
+void KVBlock::link_blocks(std::shared_ptr<KVBlock> prev_block) {
+ prev_block->m_child_block_hashes.insert(m_block_hash);
+
+ m_parent_block_hash = prev_block->m_block_hash;
+}
+
+void KVBlock::unlink_blocks(std::shared_ptr<KVBlock> prev_block) {
+ prev_block->m_child_block_hashes.erase(m_block_hash);
+
+ m_parent_block_hash = 0;
+}
+
+uint64_t KVBlock::compute_block_hash(const std::vector<uint64_t>& token_hashes) const {
+ // Use the last token hash as the block hash, given token hash is calculated with preceding tokens
+ return m_token_hashes.back();
+}
+
+void KVBlock::print_block_info(bool verbose) const {
+ constexpr size_t BYTES_IN_MB = 1024 * 1024;
+
+ LOG_VERB("Block information: ");
+ LOG_VERB(" Block size: " << m_block_size);
+ LOG_VERB(" Block hash: " << m_block_hash);
+ LOG_VERB(" Token count: " << m_token_hashes.size());
+ LOG_VERB(" Status: " << (m_is_full ? "Full" : "Not Full"));
+ LOG_VERB(" Token start: " << m_token_start);
+
+ LOG_VERB(" Children blocks: ");
+ if (m_child_block_hashes.empty()) {
+ LOG_VERB(" Null");
+ } else {
+ size_t index = 0;
+ for (auto it = m_child_block_hashes.begin(); it != m_child_block_hashes.end(); ++it, ++index) {
+ LOG_VERB(" hash [" << index << "]: " << *it);
+ }
+ }
+
+ if (verbose) {
+ LOG_VERB(" KV cache stored in block: ");
+ }
+ size_t total_size = 0;
+ for (const auto& pair : m_kv_data) {
+ const std::string& name = pair.first;
+ const ov::SoPtr<ov::ITensor>& tensor = pair.second;
+
+ total_size += tensor->get_byte_size();
+
+ if (!verbose) {
+ continue;
+ }
+
+ // Print KV cache stored in block verbosely
+ LOG_VERB("Name: " << name);
+ if (tensor) {
+ LOG_VERB("Tensor Shape: " << tensor->get_shape().to_string());
+ } else {
+ LOG_VERB("Tensor is null");
+ }
+ LOG_VERB("----------------------------------------");
+ }
+
+ LOG_VERB(" KV cache tensor total size: " << total_size / BYTES_IN_MB << " MB");
+}
+
+bool PrefixCacheManager::put_block(const std::shared_ptr<KVBlock>& block, uint64_t prev_block_hash) {
+ // Do not cache incomplete blocks
+ if (!block->is_full()) {
+ LOG_VERB("[Cache store] Block rejected: not full");
+ return false;
+ }
+
+ {
+ std::lock_guard<std::mutex> lock(m_mutex);
+
+ // Check if the block is already cached
+ const auto curr_block = get_block_unsafe(block->get_block_hash());
+ if (curr_block != nullptr) {
+ // Update LRU position if block is evictable
+ update_evictable_lru_unsafe(curr_block->get_block_hash(), true);
+ LOG_VERB("[Cache store] Block already cached, updated LRU");
+ return true; // Already cached counts as success
+ }
+
+ // Link current block with previous block
+ const auto prev_block = get_block_unsafe(prev_block_hash);
+ if (prev_block != nullptr) {
+ // Link the current block with the previous block before attempting eviction.
+ // When the cache is full and all preceding blocks have child dependencies (e.g., A -> B -> C -> D),
+ // linking ensures no eviction candidates are available, preventing block E from being added.
+ block->link_blocks(prev_block);
+ // Previous block now has a child, so it's no longer evictable
+ update_evictable_lru_unsafe(prev_block_hash, false);
+ } else if (prev_block_hash != 0) {
+ // If the previous block wasn't added due to full cache capacity,
+ // there's no need to add the current block, as it won't be accessed in the cache.
+ LOG_VERB("[Cache store] Block rejected: previous block missing");
+ return false;
+ }
+
+ if (m_cache_map.size() >= m_max_cache_size) {
+ if (!evict_lru_block_unsafe()) {
+ // New block is not added into the cache
+ if (prev_block != nullptr) {
+ block->unlink_blocks(prev_block);
+ // Restore previous block's evictable status if it has no other children
+ if (prev_block->get_child_block_hashes().empty()) {
+ update_evictable_lru_unsafe(prev_block_hash, true);
+ }
+ }
+ LOG_VERB("[Cache store] Block rejected: cache full, no eviction candidate");
+ return false;
+ }
+ }
+
+ m_cache_map[block->get_block_hash()] = block;
+ // New added block is a leaf node - mark as evictable (automatically adds to LRU list)
+ update_evictable_lru_unsafe(block->get_block_hash(), true);
+
+ LOG_VERB("[Cache store] Successfully added block. Token start: " << block->get_token_start()
+ << " block hash: " << block->get_block_hash());
+ }
+
+ return true;
+}
+
+void PrefixCacheManager::update_evictable_lru_unsafe(uint64_t block_hash, bool is_evictable) {
+ auto evictable_iter_it = m_evictable_lru_iter_map.find(block_hash);
+ bool currently_evictable = (evictable_iter_it != m_evictable_lru_iter_map.end());
+
+ // Case 1: Block should not be evictable
+ if (!is_evictable) {
+ if (currently_evictable) {
+ // Remove from evictable LRU list
+ m_evictable_lru_list.erase(evictable_iter_it->second);
+ m_evictable_lru_iter_map.erase(evictable_iter_it);
+ }
+ return; // Nothing to do if already non-evictable
+ }
+
+ // Case 2: Block should be evictable
+ if (currently_evictable) {
+ // Already evictable - remove from current position to move to front
+ m_evictable_lru_list.erase(evictable_iter_it->second);
+ }
+ // Add/move block to front (most recently used)
+ m_evictable_lru_list.push_front(block_hash);
+ m_evictable_lru_iter_map[block_hash] = m_evictable_lru_list.begin();
+}
+
+bool PrefixCacheManager::evict_lru_block_unsafe() {
+ // O(1) eviction: directly access the least recently used evictable block
+ if (m_evictable_lru_list.empty()) {
+ return false; // No evictable blocks available
+ }
+
+ // Get LRU evictable block (from back of list)
+ uint64_t lru_block_hash = m_evictable_lru_list.back();
+
+ const auto lru_block = get_block_unsafe(lru_block_hash);
+ if (lru_block == nullptr) {
+ // Data inconsistency - clean up and return false
+ m_evictable_lru_list.pop_back();
+ m_evictable_lru_iter_map.erase(lru_block_hash);
+ return false;
+ }
+
+ LOG_VERB("Cache is full, evict LRU block");
+
+ lru_block->print_block_info(false);
+
+ // Unlink from parent block and update parent's evictable status
+ const auto lru_prev_block_hash = lru_block->get_parent_block_hash();
+ if (lru_prev_block_hash != 0) {
+ const auto lru_prev_block = get_block_unsafe(lru_prev_block_hash);
+ if (lru_prev_block != nullptr) {
+ lru_block->unlink_blocks(lru_prev_block);
+ // Parent might now be evictable if it has no other children
+ if (lru_prev_block->get_child_block_hashes().empty()) {
+ update_evictable_lru_unsafe(lru_prev_block_hash, true);
+ }
+ }
+ }
+
+ // Remove from cache
+ m_cache_map.erase(lru_block_hash); // O(1)
+
+ // Remove from evictable LRU list
+ m_evictable_lru_list.pop_back(); // O(1) - we know it's at the back
+ m_evictable_lru_iter_map.erase(lru_block_hash); // O(1)
+
+ return true; // Successfully evicted one block
+}
+
+std::shared_ptr<KVBlock> PrefixCacheManager::get_block(uint64_t combined_hash) {
+ std::lock_guard<std::mutex> lock(m_mutex);
+ auto block = get_block_unsafe(combined_hash);
+ if (block != nullptr) {
+ // Update LRU position if block is evictable
+ update_evictable_lru_unsafe(block->get_block_hash(), true);
+ }
+ return block;
+}
+
+std::shared_ptr<KVBlock> PrefixCacheManager::get_block_unsafe(uint64_t combined_hash) const {
+ auto it = m_cache_map.find(combined_hash);
+ if (it != m_cache_map.end()) {
+ return it->second;
+ }
+
+ return nullptr;
+}
+
+void PrefixCacheManager::print_cache_status(bool verbose) const {
+ LOG_VERB("Cache Status:");
+ LOG_VERB("Max Cache Size: " << m_max_cache_size);
+ LOG_VERB("Number of Cached Blocks: " << m_cache_map.size());
+ LOG_VERB("----------------------------------------");
+
+ // Print information of all blocks in cache
+ for (const auto& pair : m_cache_map) {
+ uint64_t key = pair.first;
+ std::shared_ptr<KVBlock> block = pair.second;
+
+ LOG_VERB("Key Hash: " << key);
+ if (block) {
+ block->print_block_info(verbose);
+ } else {
+ LOG_VERB(" Block is null");
+ }
+ LOG_VERB("----------------------------------------");
+ }
+}
+
+// ============================================================================
+// PrefixCachingHelper Implementation
+// ============================================================================
+
+PrefixCachingHelper::PrefixCachingHelper(LLMInferRequest& request)
+ : m_request(request),
+ m_cache_manager(
+ std::make_shared<PrefixCacheManager>(request.m_npuw_llm_compiled_model->m_prefix_caching_max_num_blocks)) {
+ // Initialize name mapping once during construction
+ create_name_mapping();
+}
+
+PrefixCacheRestorationContext PrefixCachingHelper::prepare_and_restore(const ov::SoPtr<ov::ITensor>& input_ids,
+ uint64_t input_prompt_len) {
+ PrefixCacheRestorationContext context;
+
+ auto& kvcache_desc = m_request.m_npuw_llm_compiled_model->m_kvcache_desc;
+
+ // Calculate input prompts hash
+ context.prompt_hashes = calculate_hashes(input_ids);
+
+ // Try to restore prefilled prompts from cache
+ context.restored_token_num = restore_blocks(input_ids, context.prompt_hashes);
+
+ uint64_t scheduled_token_num = input_prompt_len - context.restored_token_num;
+ LOG_VERB("[PrefixCache] Successfully restored " << context.restored_token_num
+ << " tokens from cache. "
+ "Will compute "
+ << scheduled_token_num << " tokens out of total input length "
+ << input_prompt_len << ".");
+
+ context.remaining_prompts = scheduled_token_num;
+ context.token_idx = context.restored_token_num;
+ context.restore_prefix_cache = (scheduled_token_num < input_prompt_len);
+
+ // Update kvcache state
+ kvcache_desc.num_stored_tokens = static_cast<uint32_t>(context.restored_token_num);
+
+ return context;
+}
+
+void PrefixCachingHelper::store_computed_blocks(size_t chunk_size,
+ const std::vector<uint64_t>& prompt_hashes,
+ size_t& token_idx) {
+ store_blocks(chunk_size, prompt_hashes, token_idx);
+}
+
+size_t PrefixCachingHelper::adjust_chunk_size(size_t restored_token_num, size_t chunk_len) {
+ // This function calculates the number of tokens needed to complete a full chunk
+ // based on the current restored token number and the chunk prompt length.
+
+ // Ensure that the past KV in the inference request can accommodate a full chunk after the first inference run.
+ // Consider the scenario when prefix caching is enabled:
+ // - The input prompt length is 1024, and the chunk size is 256. Initially, the present KV length in the inference
+ // request is 256, and the past KV length is 768.
+ // - Initially, 128 tokens have been restored from the cache, leaving 1024 - 128 = 896 tokens that need to be
+ // computed.
+ // Round 1:
+ // - 128 tokens are stored in the past KV.
+ // - Infer for 256 tokens in the present KV.
+ // - After updating the KV cache, the past KV will hold 128 + 256 tokens, leaving 896 - 256 = 640 tokens.
+ // Round 2:
+ // - 128 + 256 tokens are stored in the past KV.
+ // - Infer for another 256 tokens in the present KV.
+ // - After updating the KV cache, the past KV will hold 128 + 256 + 256 tokens, leaving 896 - 256 - 256 = 384
+ // tokens.
+ // Round 3:
+ // - 128 + 256 + 256 tokens are stored in the past KV.
+ // - Infer for another 256 tokens in the present KV.
+ // - KV cache update would fail because the past KV cannot accommodate 128 + 256 + 256 + 256 tokens.
+
+ // To address this issue, ensure that the past KV can hold a full chunk after round 1:
+ // Round 1:
+ // - 128 tokens are stored in the past KV.
+ // - Infer for 128 tokens in the present KV.
+ // - After updating the KV cache, the past KV will hold 128 + 128 tokens, leaving 896 - 128 = 768 tokens.
+ // Round 2:
+ // - 256 tokens are stored in the past KV.
+ // - Infer for 256 tokens in the present KV.
+ // - After updating the KV cache, the past KV will hold 128 + 128 + 256 tokens, leaving 896 - 128 - 256 = 512
+ // tokens. Round 3:
+ // - 256 + 256 tokens are stored in the past KV.
+ // - Infer for 256 tokens in the present KV.
+ // - After updating the KV cache, the past KV will hold 128 + 128 + 256 + 256 tokens, leaving 896 - 128 - 256 - 256
+ // = 256 tokens. Round 4:
+ // - 128 + 128 + 256 + 256 tokens are stored in the past KV.
+ // - Infer for the last 256 tokens in the present KV, completing the prefill for all prompts.
+
+ return chunk_len - restored_token_num % chunk_len;
+}
+
+void PrefixCachingHelper::print_cache_status(bool verbose) const {
+ if (m_cache_manager) {
+ m_cache_manager->print_cache_status(verbose);
+ }
+}
+
+void PrefixCachingHelper::populate_attention_mask_for_restored_cache(const ov::SoPtr<ov::ITensor>& attention_mask,
+ const ov::SoPtr<ov::ITensor>& attn_mask_in_tensor,
+ size_t num_restored_tokens) {
+ // Populate the attention mask for prefix caching:
+ // num_restored_tokens have been prefilled already from cache
+ // The calculated key/values blocks will be copied from cache to past k/v inputs for inference
+ std::copy_n(attention_mask->data<int64_t>(), num_restored_tokens, attn_mask_in_tensor->data<int64_t>());
+}
+
+std::vector<uint64_t> PrefixCachingHelper::calculate_hashes(const ov::SoPtr<ov::ITensor>& input_ids) {
+ // For LLM, model accepts 2d inputs_embeds[BATCH, SEQ_LEN]
+ // For VLM, model accepts 3d inputs_ids[BATCH, SEQ_LEN, EMB_SIZE]
+ bool is_input_embeds = input_ids->get_shape().size() == 2 ? false : true;
+
+ const auto data_elem_size = input_ids->get_element_type().size();
+ size_t total_size = input_ids->get_shape()[LLMInferRequest::layer_ids::INPUT_IDS_SEQ_LEN_DIM];
+
+ std::vector<uint64_t> prompt_hashes(total_size);
+
+ uint64_t prefix_hash = 0;
+ for (size_t i = 0; i < total_size; ++i) {
+ size_t offset = i * data_elem_size;
+ size_t size = data_elem_size;
+ if (is_input_embeds) {
+ offset *= input_ids->get_shape().back();
+ size *= input_ids->get_shape().back();
+ }
+ const char* token_data = reinterpret_cast<const char*>(input_ids->data()) + offset;
+ uint64_t token_hash = std::hash<std::string_view>{}(std::string_view(token_data, size));
+ prefix_hash = prefix_hash * 31 + token_hash;
+ prompt_hashes[i] = prefix_hash;
+ }
+
+ return prompt_hashes;
+}
+
+void PrefixCachingHelper::create_name_mapping() {
+ const auto& prefill_compiled = m_request.m_prefill_request->get_compiled_model();
+
+ // Pre-compile regex pattern (static to avoid recompilation)
+ static const std::regex present_regex("present");
+
+ for (std::size_t i = LLMInferRequest::layer_ids::kStartOutputKVCacheLayers; i < prefill_compiled->outputs().size();
+ ++i) {
+ const auto& output_name = prefill_compiled->outputs()[i].get_any_name();
+ std::string input_name = std::regex_replace(output_name, present_regex, "past_key_values");
+ if (m_request.m_prefill_in_ports.find(input_name) == m_request.m_prefill_in_ports.end()) {
+ LOG_DEBUG("Input name " << input_name << " doesn't contain kv cache. Skipping.");
+ continue;
+ }
+
+ m_cached_input_name_map[output_name] = std::move(input_name);
+ }
+}
+
+uint64_t PrefixCachingHelper::restore_blocks(const ov::SoPtr<ov::ITensor>& input_ids,
+ const std::vector<uint64_t>& prompt_hashes) {
+ const uint64_t block_size = m_request.m_npuw_llm_compiled_model->m_prefix_caching_block_size;
+ auto& kvcache_desc = m_request.m_npuw_llm_compiled_model->m_kvcache_desc;
+
+ size_t actual_token_num = input_ids->get_shape()[LLMInferRequest::layer_ids::INPUT_IDS_SEQ_LEN_DIM];
+ size_t num_blocks = (actual_token_num + block_size - 1) / block_size;
+
+ uint64_t restored_token_num = 0;
+ size_t token_idx = 0;
+
+ uint64_t max_restored_token_num =
+ kvcache_desc.max_prompt_size - m_request.m_npuw_llm_compiled_model->m_prefill_chunk_size;
+
+ for (size_t block_index = 0; block_index < num_blocks; ++block_index) {
+ if ((actual_token_num - block_index * block_size) < block_size) {
+ break; // Not a full block
+ }
+
+ std::vector<uint64_t> token_hashes(block_size);
+ for (size_t i = 0; i < block_size; ++i) {
+ token_hashes[i] = prompt_hashes[token_idx];
+ token_idx++;
+ }
+
+ uint64_t block_hash = token_hashes.back();
+
+ auto retrieved_block = m_cache_manager->get_block(block_hash);
+ if (!retrieved_block) {
+ LOG_VERB("[PrefixCache] No cache block found for hash " << block_hash);
+ break;
+ }
+
+ // Cache hit - restore KV tensors
+ auto token_start = retrieved_block->get_token_start();
+ const KVData& block_kv_data = retrieved_block->get_block_kv_data();
+ LOG_VERB("[PrefixCache] Cache hit for block hash " << block_hash << ", restored tokens start from position "
+ << token_start);
+
+ ov::parallel_for(block_kv_data.size(), [&](size_t idx) {
+ auto kv_per_layer = block_kv_data[idx];
+ auto kv_out_name = kv_per_layer.first;
+ const auto& kv_in_name = m_cached_input_name_map.at(kv_out_name);
+
+ auto kv_tensor = kv_per_layer.second;
+ const auto& kv_dim =
+ (kv_out_name.find("value") != std::string::npos && kvcache_desc.v_tensors_transposed_pre)
+ ? 3u
+ : kvcache_desc.dim;
+
+ auto kv_dst_tensor = m_request.m_prefill_request->get_tensor(m_request.m_prefill_in_ports.at(kv_in_name));
+ auto kv_dst_slice = ov::npuw::util::view(kv_dst_tensor, kv_dim, token_start, block_size);
+ ov::npuw::util::copy_tensor_by_dim(kv_tensor, kv_dst_slice, kv_dim, kv_dim);
+ });
+
+ restored_token_num += block_size;
+
+ // Ensure the cached tokens can be loaded into infer request
+ if (restored_token_num + block_size > max_restored_token_num) {
+ break;
+ }
+
+ // At least we should infer "1" token to generate "logit"
+ if (restored_token_num == actual_token_num) {
+ restored_token_num -= block_size;
+ break;
+ }
+ }
+
+ return restored_token_num;
+}
+
+void PrefixCachingHelper::store_blocks(size_t chunk_size,
+ const std::vector<uint64_t>& prompt_hashes,
+ size_t& token_idx) {
+ const uint64_t block_size = m_request.m_npuw_llm_compiled_model->m_prefix_caching_block_size;
+
+ if (chunk_size < block_size) {
+ return;
+ }
+
+ auto& kvcache_desc = m_request.m_npuw_llm_compiled_model->m_kvcache_desc;
+ const auto& prefill_compiled = m_request.m_prefill_request->get_compiled_model();
+ const uint64_t chunk_prompt_len = m_request.m_npuw_llm_compiled_model->m_prefill_chunk_size;
+ size_t offset = chunk_size < chunk_prompt_len ? chunk_prompt_len - chunk_size : 0;
+
+ const size_t num_kv_layers =
+ prefill_compiled->outputs().size() - LLMInferRequest::layer_ids::kStartOutputKVCacheLayers;
+ std::vector<bool> is_value_tensor(prefill_compiled->outputs().size(), false);
+ for (std::size_t i = LLMInferRequest::layer_ids::kStartOutputKVCacheLayers; i < prefill_compiled->outputs().size();
+ ++i) {
+ is_value_tensor[i] = (prefill_compiled->outputs()[i].get_any_name().find("value") != std::string::npos);
+ }
+
+ for (size_t block_start = offset; block_start < chunk_prompt_len; block_start += block_size) {
+ if ((chunk_prompt_len - block_start) < block_size) {
+ break; // Not a full block
+ }
+
+ // Get token hashes for this block
+ std::vector<size_t> token_hashes(block_size);
+ for (size_t i = 0; i < block_size; ++i) {
+ token_hashes[i] = prompt_hashes[token_idx];
+ token_idx++;
+ }
+
+ // Allocate KV cache tensors for this block
+ auto kvcache_data = KVData();
+ kvcache_data.reserve(num_kv_layers);
+
+ for (std::size_t i = LLMInferRequest::layer_ids::kStartOutputKVCacheLayers;
+ i < prefill_compiled->outputs().size();
+ ++i) {
+ const auto& output_name = prefill_compiled->outputs()[i].get_any_name();
+
+ const auto& kv_dim = (is_value_tensor[i] && kvcache_desc.v_tensors_transposed_pre) ? 3u : kvcache_desc.dim;
+
+ auto kv_src_tensor = m_request.m_prefill_request->get_tensor(m_request.m_prefill_out_ports.at(output_name));
+ auto kv_src_slice = ov::npuw::util::view(kv_src_tensor, kv_dim, block_start, block_size);
+
+ auto new_tensor_elem_type = kv_src_slice->get_element_type();
+ auto new_tensor_shape = kv_src_slice->get_shape();
+ auto new_kv_tensor = ov::get_tensor_impl(ov::Tensor(new_tensor_elem_type, new_tensor_shape));
+ ov::npuw::util::copy_tensor_by_dim(kv_src_slice, new_kv_tensor, kv_dim, kv_dim);
+
+ kvcache_data.emplace_back(output_name, new_kv_tensor);
+ }
+
+ // Create KVBlock and store in cache
+ auto block = std::make_shared<KVBlock>(block_size);
+ block->set_token_start(token_idx - block_size);
+ block->add_block(token_hashes, kvcache_data);
+
+ uint64_t prev_block_hash = 0;
+ if (block->get_token_start() > 0) {
+ size_t last_token_id_in_prev_block = block->get_token_start() - 1;
+ prev_block_hash = prompt_hashes[last_token_id_in_prev_block];
+ }
+
+ // Note: put_block returns bool but we don't need to check it here.
+ // The block's lifetime is managed by shared_ptr reference counting.
+ // If cache accepts it, both cache and this function hold references.
+ // If cache rejects it, only this function holds reference and block will be destroyed
+ // when it goes out of scope, which is the expected behavior.
+ m_cache_manager->put_block(block, prev_block_hash);
+ }
+}
+
+} // namespace npuw
+} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_prefix_caching.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_prefix_caching.hpp
new file mode 100644
index 00000000000..5913870c3a6
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_prefix_caching.hpp
@@ -0,0 +1,243 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <list>
+#include <memory>
+#include <mutex>
+#include <regex>
+#include <unordered_map>
+
+#include "openvino/runtime/icompiled_model.hpp"
+#include "openvino/runtime/itensor.hpp"
+#include "openvino/runtime/so_ptr.hpp"
+
+namespace ov {
+namespace npuw {
+
+/**
+ * @brief KV cache data container for storing tensor pairs per layer
+ *
+ * This type alias defines a container that stores KV cache tensors organized by layer.
+ * Each element in the vector represents one layer's KV cache data as a pair of:
+ * - string: Tensor name/identifier (e.g., "past_key_values.0.key", "past_key_values.0.values")
+ * - ov::SoPtr<ov::ITensor>: Smart pointer to the actual KV cache tensor data
+ *
+ * The container holds all KV cache tensors for a specific block of tokens,
+ * enabling efficient storage and retrieval of cached computation results
+ * in the prefix caching system.
+ */
+using KVData = std::vector<std::pair<std::string, ov::SoPtr<ov::ITensor>>>;
+
+class KVBlock {
+public:
+ // block_size is number of tokens per block
+ explicit KVBlock(size_t block_size)
+ : m_block_size(block_size),
+ m_is_full(false),
+ m_token_start(0),
+ m_block_hash(0),
+ m_parent_block_hash(0) {
+ m_token_hashes.reserve(m_block_size);
+ }
+
+ bool is_full() const {
+ return m_is_full;
+ }
+
+ void set_token_start(size_t token_start) {
+ m_token_start = token_start;
+ }
+
+ size_t get_token_start() const {
+ return m_token_start;
+ }
+
+ uint64_t get_block_hash() const {
+ return m_block_hash;
+ }
+
+ const std::unordered_set<uint64_t>& get_child_block_hashes() const {
+ return m_child_block_hashes;
+ }
+
+ uint64_t get_parent_block_hash() const {
+ return m_parent_block_hash;
+ }
+
+ const KVData& get_block_kv_data() const {
+ return m_kv_data;
+ }
+
+ /**
+ * @brief Add the entire block's token data
+ * @param token_hashes Hash values of all tokens in the block
+ * @param kv_tensors KV cache data for all tokens in the block
+ * @return Whether the addition was successful
+ */
+ bool add_block(const std::vector<uint64_t>& token_hashes, const KVData& kv_tensors);
+ void link_blocks(std::shared_ptr<KVBlock> prev_block);
+ void unlink_blocks(std::shared_ptr<KVBlock> prev_block);
+ void print_block_info(bool verbose) const;
+
+private:
+ /**
+ * @brief Compute the block's hash value
+ * @param token_hashes Hash values of all tokens in the block
+ * @return The block's hash value
+ *
+ * Note: The block hash is derived from the last token hash in the sequence,
+ * as each token hash is calculated based on preceding tokens, ensuring
+ * a cumulative representation of the block's content.
+ */
+ uint64_t compute_block_hash(const std::vector<uint64_t>& token_hashes) const;
+
+ size_t m_block_size;
+ std::vector<uint64_t> m_token_hashes;
+ bool m_is_full;
+ size_t m_token_start;
+ uint64_t m_block_hash;
+ // One block may have multiply child blocks
+ std::unordered_set<uint64_t> m_child_block_hashes;
+ // One block only has single parent block
+ uint64_t m_parent_block_hash;
+ KVData m_kv_data;
+};
+
+class PrefixCacheManager {
+public:
+ PrefixCacheManager(size_t max_cache_size) : m_max_cache_size(max_cache_size) {}
+
+ /**
+ * @brief Add a block to the cache
+ * @param block The KV block to cache
+ * @param prev_block_hash Hash of the previous block for linking
+ * @return true if the block was successfully added to the cache, false otherwise
+ *
+ * @note This method does not take ownership of the block. The cache and caller
+ * both hold shared_ptr references. The block's lifetime is managed by
+ * the shared_ptr reference counting mechanism.
+ *
+ * Reasons for rejection:
+ * - Block is not full (!block->is_full())
+ * - Block already exists in cache (duplicate)
+ * - Previous block is missing and prev_block_hash != 0
+ * - Cache is full and no LRU block can be evicted
+ */
+ bool put_block(const std::shared_ptr<KVBlock>& block, uint64_t prev_block_hash);
+
+ /**
+ * @brief Retrieve a block from the cache by hash
+ * @param combined_hash Hash value to look up
+ * @return Shared pointer to the KVBlock if found, nullptr otherwise
+ */
+ std::shared_ptr<KVBlock> get_block(uint64_t combined_hash);
+
+ // Print the current status of the cache
+ void print_cache_status(bool verbose = false) const;
+
+private:
+ size_t m_max_cache_size;
+ std::mutex m_mutex;
+ // Mapping from hash to KV blocks
+ std::unordered_map<uint64_t, std::shared_ptr<KVBlock>> m_cache_map;
+ // LRU list for evictable blocks only (leaf nodes with no children, most recent at front)
+ std::list<uint64_t> m_evictable_lru_list;
+ // Mapping from hash to evictable LRU list iterator for O(1) access
+ std::unordered_map<uint64_t, std::list<uint64_t>::iterator> m_evictable_lru_iter_map;
+
+ // Retrieve a block from the cache by hash without holding a mutex
+ std::shared_ptr<KVBlock> get_block_unsafe(uint64_t combined_hash) const;
+ // Update evictable LRU list: mark block as evictable/non-evictable and update its LRU position
+ void update_evictable_lru_unsafe(uint64_t block_hash, bool is_evictable);
+ // Evict the least recently used blocks with no children
+ bool evict_lru_block_unsafe();
+};
+
+/**
+ * @brief Context structure for prefix caching restoration
+ *
+ * This structure holds the necessary state and metadata for restoring cached blocks
+ * during chunked prefill inference.
+ */
+struct PrefixCacheRestorationContext {
+ std::vector<uint64_t> prompt_hashes;
+ size_t token_idx = 0;
+ bool restore_prefix_cache = false;
+ uint64_t restored_token_num = 0;
+ uint64_t remaining_prompts = 0;
+};
+
+class LLMInferRequest;
+
+/**
+ * @brief Helper class for coordinating prefix caching operations during inference
+ *
+ * This class encapsulates all prefix caching coordination logic, including:
+ * - Hash calculation for token sequences
+ * - Cache restoration and storage
+ * - Chunk size adjustment for optimal caching
+ * - Coordination between inference request and cache manager
+ *
+ * It serves as a bridge between the LLMInferRequest and PrefixCacheManager,
+ * handling all the complex logic required to integrate prefix caching into
+ * the inference workflow.
+ */
+class PrefixCachingHelper {
+public:
+ /**
+ * @brief Construct a PrefixCachingHelper
+ * @param request Reference to the LLMInferRequest that owns this helper
+ */
+ explicit PrefixCachingHelper(LLMInferRequest& request);
+
+ /**
+ * @brief Prepare and restore prefix cache before inference
+ *
+ * This high-level method coordinates the entire cache restoration process.
+ */
+ PrefixCacheRestorationContext prepare_and_restore(const ov::SoPtr<ov::ITensor>& input_ids,
+ uint64_t input_prompt_len);
+
+ /**
+ * @brief Store computed KV cache blocks after inference
+ */
+ void store_computed_blocks(size_t chunk_size, const std::vector<uint64_t>& prompt_hashes, size_t& token_idx);
+
+ /**
+ * @brief Adjust chunk size for optimal prefix caching alignment
+ */
+ size_t adjust_chunk_size(size_t restored_token_num, size_t chunk_len);
+
+ /**
+ * @brief Print the current status of the prefix cache
+ */
+ void print_cache_status(bool verbose = false) const;
+
+ /**
+ * @brief Populate attention mask for restored prefix cache blocks
+ * @param attention_mask Original full attention mask from user input
+ * @param attn_mask_in_tensor Attention mask tensor for the current inference chunk
+ * @param num_restored_tokens Number of tokens that have been restored from cache
+ */
+ void populate_attention_mask_for_restored_cache(const ov::SoPtr<ov::ITensor>& attention_mask,
+ const ov::SoPtr<ov::ITensor>& attn_mask_in_tensor,
+ size_t num_restored_tokens);
+
+private:
+ LLMInferRequest& m_request;
+ std::shared_ptr<PrefixCacheManager> m_cache_manager;
+
+ // Cached name mapping from output to input ports (initialized once in constructor)
+ std::unordered_map<std::string, std::string> m_cached_input_name_map;
+
+ std::vector<uint64_t> calculate_hashes(const ov::SoPtr<ov::ITensor>& input_ids);
+ void create_name_mapping();
+ uint64_t restore_blocks(const ov::SoPtr<ov::ITensor>& input_ids, const std::vector<uint64_t>& prompt_hashes);
+ void store_blocks(size_t chunk_size, const std::vector<uint64_t>& prompt_hashes, size_t& token_idx);
+};
+
+} // namespace npuw
+} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
index c7575991920..64f08aa7c17 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
@@ -34,7 +34,7 @@ const constexpr ov::npuw::s11n::IndicatorType NPUW_COMPILED_MODEL_INDICATOR =
const constexpr ov::npuw::s11n::IndicatorType NPUW_LLM_COMPILED_MODEL_INDICATOR =
{char{0x4c}, char{0x4c}, char{0x4d}, char{0x43}, char{0x4d}, char{0x4f}};
-const constexpr char* NPUW_SERIALIZATION_VERSION = "0.12";
+const constexpr char* NPUW_SERIALIZATION_VERSION = "0.13";
// Forward declaration
namespace intel_npu {
diff --git a/src/plugins/intel_npu/src/plugin/src/plugin.cpp b/src/plugins/intel_npu/src/plugin/src/plugin.cpp
index 8633bc5454b..01085db9e53 100644
--- a/src/plugins/intel_npu/src/plugin/src/plugin.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/plugin.cpp
@@ -356,6 +356,9 @@ void Plugin::init_options() {
REGISTER_OPTION(NPUW_LLM_PREFILL_CHUNK_SIZE);
REGISTER_OPTION(NPUW_LLM_SHARED_HEAD);
REGISTER_OPTION(NPUW_LLM_MAX_LORA_RANK);
+ REGISTER_OPTION(NPUW_LLM_ENABLE_PREFIX_CACHING);
+ REGISTER_OPTION(NPUW_LLM_PREFIX_CACHING_BLOCK_SIZE);
+ REGISTER_OPTION(NPUW_LLM_PREFIX_CACHING_MAX_NUM_BLOCKS);
REGISTER_OPTION(NPUW_WHISPER);
REGISTER_OPTION(NPUW_LLM_PREFILL_HINT);
REGISTER_OPTION(NPUW_LLM_PREFILL_CONFIG);
diff --git a/src/plugins/intel_npu/src/plugin/src/properties.cpp b/src/plugins/intel_npu/src/plugin/src/properties.cpp
index 255301b625f..0432b69af2b 100644
--- a/src/plugins/intel_npu/src/plugin/src/properties.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/properties.cpp
@@ -463,6 +463,11 @@ void Properties::registerPluginProperties() {
TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::prefill_chunk_size, NPUW_LLM_PREFILL_CHUNK_SIZE);
TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::shared_lm_head, NPUW_LLM_SHARED_HEAD);
TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::max_lora_rank, NPUW_LLM_MAX_LORA_RANK);
+ TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::enable_prefix_caching, NPUW_LLM_ENABLE_PREFIX_CACHING);
+ TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::prefix_caching_block_size,
+ NPUW_LLM_PREFIX_CACHING_BLOCK_SIZE);
+ TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::prefix_caching_max_num_blocks,
+ NPUW_LLM_PREFIX_CACHING_MAX_NUM_BLOCKS);
TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::prefill_hint, NPUW_LLM_PREFILL_HINT);
TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::prefill_config, NPUW_LLM_PREFILL_CONFIG);
TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::additional_prefill_config,
diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
index b85ca206b29..03b3a7d8c41 100644
--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
@@ -35,6 +35,8 @@ ov_add_test_target(
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/src/metadata.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/logging.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_prefix_caching.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/infer_request_utils.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/util.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/util_xarch.cpp
diff --git a/src/plugins/intel_npu/tests/unit/npuw/prefix_caching.cpp b/src/plugins/intel_npu/tests/unit/npuw/prefix_caching.cpp
new file mode 100644
index 00000000000..a2d5d1a61a0
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/npuw/prefix_caching.cpp
@@ -0,0 +1,288 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <gtest/gtest.h>
+
+#include "llm_prefix_caching.hpp"
+
+TEST(PrefixCacheManagerTest, AddAndGetBlock) {
+ constexpr size_t cache_capability = 10;
+ ov::npuw::PrefixCacheManager cache(cache_capability);
+
+ constexpr size_t block_size = 2;
+
+ auto block1 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block1->set_token_start(0);
+ block1->add_block({0x1, 0x2}, {});
+
+ auto block2 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block2->set_token_start(2);
+ block2->add_block({0x3, 0x4}, {});
+
+ auto block3 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block3->set_token_start(4);
+ block3->add_block({0x5, 0x6}, {});
+
+ cache.put_block(block1, 0x0);
+ cache.put_block(block2, block1->get_block_hash());
+ cache.put_block(block3, block2->get_block_hash());
+
+ // Retrieve block from cache adn check block hash
+ auto retrieved_block = cache.get_block(block1->get_block_hash());
+ EXPECT_NE(retrieved_block, nullptr);
+ EXPECT_EQ(block1->get_block_hash(), 0x2);
+
+ retrieved_block = cache.get_block(block2->get_block_hash());
+ EXPECT_NE(retrieved_block, nullptr);
+ EXPECT_EQ(block2->get_block_hash(), 0x4);
+
+ retrieved_block = cache.get_block(block3->get_block_hash());
+ EXPECT_NE(retrieved_block, nullptr);
+ EXPECT_EQ(block3->get_block_hash(), 0x6);
+}
+
+TEST(PrefixCacheManagerTest, LinkBlocks) {
+ constexpr size_t cache_capability = 10;
+ ov::npuw::PrefixCacheManager cache(cache_capability);
+
+ constexpr size_t block_size = 2;
+
+ auto block1 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block1->add_block({0x1, 0x2}, {});
+
+ auto block2 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block2->add_block({0x3, 0x4}, {});
+
+ cache.put_block(block1, 0);
+ cache.put_block(block2, block1->get_block_hash());
+
+ // Check if block1 points to block2
+ auto retrieved_block = cache.get_block(block1->get_block_hash());
+ EXPECT_NE(retrieved_block, nullptr);
+ EXPECT_EQ(retrieved_block->get_child_block_hashes().size(), 1);
+ EXPECT_EQ(*retrieved_block->get_child_block_hashes().begin(), block2->get_block_hash());
+
+ // Check if block2 points back to block1
+ retrieved_block = cache.get_block(block2->get_block_hash());
+ EXPECT_NE(retrieved_block, nullptr);
+ EXPECT_EQ(retrieved_block->get_parent_block_hash(), block1->get_block_hash());
+}
+
+TEST(PrefixCacheManagerTest, EvictLRUBlock) {
+ /*
+ Test Purpose: Verify that the PrefixCacheManager's evict_lru_block_unsafe method correctly removes the least
+ recently used block.
+
+ Initial Cache State (Capacity is 5):
+ 1
+ |
+ 2
+ / | \
+ 3 4 5
+ |
+ [6]
+
+ Operation: Attempt to add block 6 to the cache.
+
+ Expected Result: Block 3 is evicted because it is the least recently used and has no child blocks, then block 6
+ is successfully added to the cache.
+
+ Final Cache State:
+ 1
+ |
+ 2
+ / | \
+ 4 5
+ |
+ 6
+ */
+ constexpr size_t cache_capability = 5;
+ ov::npuw::PrefixCacheManager cache(cache_capability);
+
+ constexpr size_t block_size = 2;
+
+ auto block1 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block1->add_block({0x1, 0x2}, {});
+
+ auto block2 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block2->add_block({0x3, 0x4}, {});
+
+ auto block3 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block3->add_block({0x5, 0x6}, {});
+
+ auto block4 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block4->add_block({0x7, 0x8}, {});
+
+ auto block5 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block5->add_block({0x9, 0xa}, {});
+
+ cache.put_block(block1, 0);
+ cache.put_block(block2, block1->get_block_hash());
+ cache.put_block(block3, block2->get_block_hash());
+ cache.put_block(block4, block2->get_block_hash());
+ cache.put_block(block5, block2->get_block_hash());
+
+ auto block6 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block6->add_block({0xb, 0xc}, {});
+
+ // This should evict block3 as it is the least recently used and has no children
+ cache.put_block(block6, block5->get_block_hash());
+
+ EXPECT_NE(cache.get_block(block1->get_block_hash()), nullptr);
+
+ EXPECT_NE(cache.get_block(block2->get_block_hash()), nullptr);
+
+ EXPECT_EQ(cache.get_block(block3->get_block_hash()), nullptr);
+
+ EXPECT_NE(cache.get_block(block4->get_block_hash()), nullptr);
+
+ EXPECT_NE(cache.get_block(block5->get_block_hash()), nullptr);
+
+ EXPECT_NE(cache.get_block(block6->get_block_hash()), nullptr);
+}
+
+TEST(PrefixCacheManagerTest, UpdateLRUList) {
+ /*
+ Test Purpose: Verify that accessing a block updates the LRU list correctly, and ensure the least recently used
+ block without children is evicted when the cache is full.
+
+ Initial Cache State (Capacity is 5):
+ 1
+ |
+ 2
+ / | \
+ 3 4 5
+ |
+ [6]
+
+ Operation:
+ 1. Access block 3 to update its position in the LRU list.
+ 2. Attempt to add block 6 to the cache.
+
+ Expected Result:
+ - Accessing block 3 updates its position, making block 4 the least recently used.
+ - Block 4 is evicted because it is the least recently used and has no child blocks.
+ - Block 6 is successfully added to the cache.
+
+ Final Cache State:
+ 1
+ |
+ 2
+ / | \
+ 3 5
+ |
+ 6
+ */
+ constexpr size_t cache_capability = 5;
+ ov::npuw::PrefixCacheManager cache(cache_capability);
+
+ constexpr size_t block_size = 2;
+
+ auto block1 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block1->add_block({0x1, 0x2}, {});
+
+ auto block2 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block2->add_block({0x3, 0x4}, {});
+
+ auto block3 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block3->add_block({0x5, 0x6}, {});
+
+ auto block4 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block4->add_block({0x7, 0x8}, {});
+
+ auto block5 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block5->add_block({0x9, 0xa}, {});
+
+ cache.put_block(block1, 0);
+ cache.put_block(block2, block1->get_block_hash());
+ cache.put_block(block3, block2->get_block_hash());
+ cache.put_block(block4, block2->get_block_hash());
+ cache.put_block(block5, block2->get_block_hash());
+
+ // Get block 3 from the cache to update LRU list
+ auto retrieved_block = cache.get_block(block3->get_block_hash());
+ EXPECT_NE(retrieved_block, nullptr);
+
+ auto block6 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block6->add_block({0xb, 0xc}, {});
+
+ // This should evict block4 as it is the least recently used and has no children
+ cache.put_block(block6, block5->get_block_hash());
+
+ EXPECT_NE(cache.get_block(block1->get_block_hash()), nullptr);
+
+ EXPECT_NE(cache.get_block(block2->get_block_hash()), nullptr);
+
+ EXPECT_NE(cache.get_block(block3->get_block_hash()), nullptr);
+
+ EXPECT_EQ(cache.get_block(block4->get_block_hash()), nullptr);
+
+ EXPECT_NE(cache.get_block(block5->get_block_hash()), nullptr);
+
+ EXPECT_NE(cache.get_block(block6->get_block_hash()), nullptr);
+}
+
+TEST(PrefixCacheManagerTest, PreventAddingBlock) {
+ /*
+ Test Purpose: Verify that the cache prevents adding new blocks when the cache is full and no eviction
+ candidates are available.
+
+ Initial Cache State (Capacity is 4):
+ 1 -> 2 -> 3 -> 4
+
+ Operation:
+ - Attempt to add block 5 and block 6 to the cache.
+
+ Expected Result:
+ - Since the cache is at full capacity and all blocks have child dependencies, there are no eviction candidates.
+ - Block 5 and block 6 should not be added to the cache.
+
+ Final Cache State:
+ 1 -> 2 -> 3 -> 4
+ - Block 5 and block 6 are not present in the cache.
+ */
+ constexpr size_t cache_capability = 4;
+ ov::npuw::PrefixCacheManager cache(cache_capability);
+
+ constexpr size_t block_size = 2;
+
+ auto block1 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block1->add_block({0x1, 0x2}, {});
+
+ auto block2 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block2->add_block({0x3, 0x4}, {});
+
+ auto block3 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block3->add_block({0x5, 0x6}, {});
+
+ auto block4 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block4->add_block({0x7, 0x8}, {});
+
+ cache.put_block(block1, 0);
+ cache.put_block(block2, block1->get_block_hash());
+ cache.put_block(block3, block2->get_block_hash());
+ cache.put_block(block4, block3->get_block_hash());
+
+ auto block5 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block5->add_block({0x9, 0xa}, {});
+
+ auto block6 = std::make_shared<ov::npuw::KVBlock>(block_size);
+ block6->add_block({0xb, 0xc}, {});
+
+ // Block 5 and block 6 should not be put into the cache successfully
+ cache.put_block(block5, block4->get_block_hash());
+ cache.put_block(block6, block5->get_block_hash());
+
+ EXPECT_NE(cache.get_block(block1->get_block_hash()), nullptr);
+
+ EXPECT_NE(cache.get_block(block2->get_block_hash()), nullptr);
+
+ EXPECT_NE(cache.get_block(block3->get_block_hash()), nullptr);
+
+ EXPECT_NE(cache.get_block(block4->get_block_hash()), nullptr);
+
+ EXPECT_EQ(cache.get_block(block5->get_block_hash()), nullptr);
+
+ EXPECT_EQ(cache.get_block(block6->get_block_hash()), nullptr);
+}