Skip to content

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

[NPUW] Continuous prefill: block-based KV cache continuation (#37149)

Dylan Nevecf2f91155f75
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.cpp
index 8859dbce0b8..cae6e95c9c7 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.cpp
@@ -328,7 +328,10 @@ void LLMBlockKVCacheStrategy::on_reset(uint32_t next_prompt_length) {
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();
+ // The base request is absent when a test factory builds plain sub-requests.
+ if (m_req.m_generate_base_requests[idx]) {
+ m_req.m_generate_base_requests[idx]->propagate_params_to_subrequests();
+ }
}
}
@@ -482,6 +485,93 @@ void LLMBlockKVCacheStrategy::on_generate_step_done(uint32_t input_tokens_len) {
update_generate_bindings(tokens_before, tokens_after, m_req.m_kvcache_request);
}
+// Continuing a prefill on the block pool truncates metadata only, since blocks
+// need no KV movement. Every manager in every layer is validated before any of
+// them changes.
+void LLMBlockKVCacheStrategy::continue_prefill(uint32_t keep, uint32_t delta_len) {
+ OPENVINO_ASSERT(!m_kv_cache_block_managers.empty(), "Continued prefill: block managers are not initialized.");
+ OPENVINO_ASSERT(m_block_size > 0u && keep % m_block_size == 0u,
+ "Continued prefill: keep (",
+ keep,
+ ") must be a multiple of the block size (",
+ m_block_size,
+ ").");
+ const auto& kvcache_desc = m_req.m_npuw_llm_compiled_model->m_kvcache_desc;
+ OPENVINO_ASSERT(keep + delta_len <= kvcache_desc.max_prompt_size,
+ "Continued prefill: keep plus delta exceeds the maximum prompt size.");
+
+ const uint32_t keep_blocks = keep / m_block_size;
+
+ // Each retained block must exist and be completely full, since a partially
+ // filled block would make the continuation prefix incoherent.
+ auto validate = [&](uint32_t layer_idx, KVCacheBlockManager* manager, const char* kv_type) {
+ if (!manager) {
+ return;
+ }
+ const auto allocated = manager->get_allocated_blocks();
+ OPENVINO_ASSERT(allocated.size() >= keep_blocks,
+ "Continued prefill: layer ",
+ layer_idx,
+ " ",
+ kv_type,
+ " has only ",
+ allocated.size(),
+ " allocated blocks, ",
+ keep_blocks,
+ " are required.");
+ for (uint32_t i = 0; i < keep_blocks; ++i) {
+ OPENVINO_ASSERT(manager->get_block_tokens(allocated[i]) == m_block_size,
+ "Continued prefill: retained block ",
+ i,
+ " of layer ",
+ layer_idx,
+ " ",
+ kv_type,
+ " is not full.");
+ }
+ };
+ for (const auto& [layer_idx, layer_managers] : m_kv_cache_block_managers) {
+ validate(layer_idx, layer_managers.key_manager.get(), "key");
+ validate(layer_idx, layer_managers.value_manager.get(), "value");
+ }
+
+ LOG_DEBUG("Continued prefill: truncating block pool to " << keep_blocks << " blocks per layer.");
+
+ // Drop prefill output redirections left over from a previous zero-copy chunk so
+ // the model does not write into a block we are about to release.
+ 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;
+ }
+
+ // Release every input binding that may reference a suffix block. Retained blocks
+ // are rebound by load_past_kv_blocks_to_prefill() at the next chunk begin, and by
+ // on_generate_kv_init() for the generate phase. Dummies go to all variants because
+ // any of them may have been bound during earlier turns.
+ set_dummy_tensors_to_request(m_req.m_prefill_request, m_prefill_classified_in_ports, m_dummy_tensors);
+ for (const auto& generate_request : m_req.m_generate_requests) {
+ set_dummy_tensors_to_request(generate_request, m_gen_classified_in_ports.at(generate_request), m_dummy_tensors);
+ }
+ for (const auto& base_req : m_req.m_generate_base_requests) {
+ // The base request is absent when a test factory builds plain sub-requests.
+ if (base_req) {
+ base_req->propagate_params_to_subrequests();
+ }
+ }
+
+ // Truncate the managers. Stale bytes beyond the retained prefix are inert once no
+ // metadata or binding exposes them, and on_reset() must not run here because it
+ // would release the retained block tensors back to the allocator.
+ for (auto& [layer_idx, layer_managers] : m_kv_cache_block_managers) {
+ if (layer_managers.key_manager) {
+ layer_managers.key_manager->truncate_allocated(keep_blocks);
+ }
+ if (layer_managers.value_manager) {
+ layer_managers.value_manager->truncate_allocated(keep_blocks);
+ }
+ }
+}
+
// ============================================================================
// Private: prefill path primitives
// ============================================================================
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.hpp
index ed6f396ea8a..4621fb6880c 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.hpp
@@ -16,6 +16,14 @@
#include "openvino/runtime/itensor.hpp"
#include "openvino/runtime/so_ptr.hpp"
+namespace ov {
+namespace test {
+namespace npuw {
+struct LLMContinuedPrefillTestAccess;
+} // namespace npuw
+} // namespace test
+} // namespace ov
+
namespace ov {
namespace npuw {
@@ -122,7 +130,14 @@ public:
const PortsMap& new_in_ports) override;
void on_generate_step_done(uint32_t input_tokens_len) override;
+ // Continuous prefill. Blocks need no KV movement, so the plan validates that the
+ // retained prefix is fully covered by allocated blocks and the apply truncates the
+ // block pool to it, releasing all suffix bindings.
+ void continue_prefill(uint32_t keep, uint32_t delta_len) override;
+
private:
+ friend struct ov::test::npuw::LLMContinuedPrefillTestAccess;
+
// -------------------------------------------------------------------------
// Private helper structs (used only during initialize())
// -------------------------------------------------------------------------
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 458ac111399..102c5321493 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
@@ -1849,12 +1849,6 @@ bool ov::npuw::LLMCompiledModel::compute_continuous_prefill_supported() const {
if (position_ids_rank.is_dynamic() || position_ids_rank.get_length() != 2) {
return false;
}
- if (m_is_block_kv_cache) {
- // Only the contiguous strategy can plan a continuation so far, and the block
- // strategy would raise from the base class in preflight. Block support lands
- // in the follow-up change.
- return false;
- }
return true;
}
diff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_continued_prefill_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/llm_continued_prefill_test.cpp
index 426303ceb88..db7cb20b7fe 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/llm_continued_prefill_test.cpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_continued_prefill_test.cpp
@@ -22,6 +22,7 @@
#include <vector>
#include "executor.hpp"
+#include "llm_block_kvcache_strategy.hpp"
#include "llm_compiled_model.hpp"
#include "llm_infer_request.hpp"
#include "llm_kvcache_strategy.hpp"
@@ -65,6 +66,23 @@ struct LLMContinuedPrefillTestAccess {
static void set_strategy(Request& req, std::unique_ptr<ov::npuw::LLMKVCacheStrategy> strategy) {
req.m_kvcache_strategy = std::move(strategy);
}
+
+ static bool is_block_kv_cache(Request& req) {
+ return req.m_npuw_llm_compiled_model->m_is_block_kv_cache;
+ }
+
+ static ov::npuw::LLMBlockKVCacheStrategy* block_strategy(Request& req) {
+ return dynamic_cast<ov::npuw::LLMBlockKVCacheStrategy*>(req.m_kvcache_strategy.get());
+ }
+
+ static const std::unordered_map<uint32_t, ov::npuw::LayerBlockManagers>& block_managers(
+ const ov::npuw::LLMBlockKVCacheStrategy& strategy) {
+ return strategy.m_kv_cache_block_managers;
+ }
+
+ static uint32_t block_size(const ov::npuw::LLMBlockKVCacheStrategy& strategy) {
+ return strategy.m_block_size;
+ }
};
} // namespace ov::test::npuw
@@ -247,19 +265,26 @@ ov::Tensor make_i64_iota(std::initializer_list<size_t> shape, int64_t start) {
class LLMContinuedPrefillTest : public ::testing::Test {
protected:
void SetUp() override {
+ init({});
+ }
+
+ void init(const ov::AnyMap& extra_props) {
m_plugin = std::make_shared<NullPlugin>();
ContinuedPrefillFactory factory;
- m_compiled =
- std::make_shared<ov::npuw::LLMCompiledModel>(build_llm_test_model(),
- m_plugin,
- ov::AnyMap{{"NPUW_LLM", "YES"},
- {"NPUW_DEVICES", "CPU"},
- {"NPUW_LLM_MAX_PROMPT_LEN", "256"},
- {"NPUW_LLM_MIN_RESPONSE_LEN", "64"},
- {"NPUW_LLM_PREFILL_HINT", "DYNAMIC"},
- {"NPUW_LLM_PREFILL_CHUNK_SIZE", "32"},
- {"NPUW_LLM_ENABLE_CONTINUOUS_PREFILL", "YES"}},
- factory.make_factory());
+ ov::AnyMap props{{"NPUW_LLM", "YES"},
+ {"NPUW_DEVICES", "CPU"},
+ {"NPUW_LLM_MAX_PROMPT_LEN", "256"},
+ {"NPUW_LLM_MIN_RESPONSE_LEN", "64"},
+ {"NPUW_LLM_PREFILL_HINT", "DYNAMIC"},
+ {"NPUW_LLM_PREFILL_CHUNK_SIZE", "32"},
+ {"NPUW_LLM_ENABLE_CONTINUOUS_PREFILL", "YES"}};
+ for (const auto& [key, value] : extra_props) {
+ props[key] = value;
+ }
+ m_compiled = std::make_shared<ov::npuw::LLMCompiledModel>(build_llm_test_model(),
+ m_plugin,
+ props,
+ factory.make_factory());
ASSERT_NE(m_compiled, nullptr);
ASSERT_TRUE(m_compiled->get_property("NPUW_LLM_CONTINUOUS_PREFILL_SUPPORTED").as<bool>());
@@ -494,4 +519,102 @@ TEST_F(LLMContinuedPrefillTest, InjectedApplyFailureRecoversAfterReset) {
EXPECT_EQ(stored_tokens(), 81);
}
+// Block-mode variant of the fixture: the same synthetic model compiled with the
+// pyramid attention hint so SplitKVCacheIntoBlocks applies, giving the block
+// strategy a real block pool under the fake factory. Every sub-request comes
+// without a base request, so the whole flow also proves the strategy tolerates
+// absent base requests during reset and continuation.
+class LLMBlockContinuedPrefillTest : public LLMContinuedPrefillTest {
+protected:
+ void SetUp() override {
+ init({{"NPUW_LLM_PREFILL_ATTENTION_HINT", "PYRAMID"},
+ {"NPUW_LLM_GENERATE_ATTENTION_HINT", "PYRAMID"},
+ {"NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE", "YES"}});
+ ASSERT_TRUE(LLMContinuedPrefillTestAccess::is_block_kv_cache(request()));
+ }
+
+ template <typename F>
+ void for_each_manager(const ov::npuw::LLMBlockKVCacheStrategy& strategy, F&& fn) {
+ for (const auto& [layer_idx, layer_managers] : LLMContinuedPrefillTestAccess::block_managers(strategy)) {
+ for (auto* manager : {layer_managers.key_manager.get(), layer_managers.value_manager.get()}) {
+ if (manager) {
+ fn(manager);
+ }
+ }
+ }
+ }
+};
+
+// A granted continuation on the block pool truncates the metadata to the
+// retained prefix without moving a byte: the retained block tensors are the KV
+// storage itself, so their contents surviving the continuation and the delta
+// chunk loop proves the truncate-only design. The delta then appends fresh
+// blocks behind the retained ones and an ordinary generate step follows.
+TEST_F(LLMBlockContinuedPrefillTest, GrantedContinuationTruncatesBlockPoolAndRunsDeltaOnly) {
+ auto& req = request();
+ auto* strategy = LLMContinuedPrefillTestAccess::block_strategy(req);
+ ASSERT_NE(strategy, nullptr);
+
+ run_full_prefill(72);
+ EXPECT_EQ(stored_tokens(), 72);
+ run_generate_step(72);
+ run_generate_step(73);
+ EXPECT_EQ(stored_tokens(), 74);
+ ASSERT_TRUE(LLMContinuedPrefillTestAccess::generate_initialized(req));
+
+ const uint32_t block_size = LLMContinuedPrefillTestAccess::block_size(*strategy);
+ ASSERT_EQ(block_size, 32u);
+ constexpr uint32_t kKeep = 64u;
+ const uint32_t keep_blocks = kKeep / block_size;
+
+ // Stamp the to-be-retained blocks with per-block patterns and remember them.
+ ASSERT_FALSE(LLMContinuedPrefillTestAccess::block_managers(*strategy).empty());
+ std::unordered_map<const ov::npuw::KVCacheBlockManager*, std::vector<std::vector<uint8_t>>> expected_blocks;
+ uint8_t seed = 29u;
+ for_each_manager(*strategy, [&](ov::npuw::KVCacheBlockManager* manager) {
+ const auto allocated = manager->get_allocated_blocks();
+ ASSERT_GE(allocated.size(), keep_blocks);
+ std::vector<std::vector<uint8_t>> bytes;
+ for (uint32_t i = 0; i < keep_blocks; ++i) {
+ ASSERT_EQ(manager->get_block_tokens(allocated[i]), block_size);
+ auto tensor = manager->get_block_tensor(allocated[i]);
+ fill_tensor_pattern(tensor, seed);
+ bytes.push_back(materialize_bytes(tensor));
+ seed = static_cast<uint8_t>(seed + 41u);
+ }
+ expected_blocks.emplace(manager, std::move(bytes));
+ });
+
+ // Propose the whole live history; the watermark is the prefill-produced 72,
+ // so the grant rounds down to the block-aligned 64.
+ propose(74);
+ EXPECT_EQ(stored_tokens(), 64);
+
+ // Second turn: 40 delta tokens (two chunks) on top of the granted keep.
+ run_delta_prefill(kKeep, 40);
+ EXPECT_EQ(stored_tokens(), 104);
+ EXPECT_FALSE(LLMContinuedPrefillTestAccess::generate_initialized(req));
+
+ for_each_manager(*strategy, [&](ov::npuw::KVCacheBlockManager* manager) {
+ // 64 retained + 40 delta = 104 tokens = three full blocks + one 8-token block.
+ const auto allocated = manager->get_allocated_blocks();
+ ASSERT_EQ(allocated.size(), 4u);
+ uint32_t total_tokens = 0;
+ for (const auto block_id : allocated) {
+ total_tokens += manager->get_block_tokens(block_id);
+ }
+ EXPECT_EQ(total_tokens, 104u);
+ // The retained prefix must not have been touched by the truncation or
+ // the delta chunk loop.
+ const auto& bytes = expected_blocks.at(manager);
+ for (uint32_t i = 0; i < keep_blocks; ++i) {
+ EXPECT_EQ(materialize_bytes(manager->get_block_tensor(allocated[i])), bytes[i]) << "block " << i;
+ }
+ });
+
+ // The continuation hands over to an ordinary generate step on the block pool.
+ run_generate_step(104);
+ EXPECT_EQ(stored_tokens(), 105);
+}
+
} // namespace