Skip to content

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

[NPUW] Add KVCacheBlockManager::truncate_allocated (#37146)

Dylan Neveaf308c25d490
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.cpp
index 80a3e3aef41..df01095ff49 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
@@ -166,16 +166,46 @@ void KVCacheBlockManager::release(uint32_t keep_warm_count) {
<< keep_warm_count << " warm");
}
- // Rebuild free stack (push in reverse order so block 0 is on top)
+ rebuild_free_block_ids();
+}
+
+void KVCacheBlockManager::clear_all() {
+ release(0);
+}
+
+void KVCacheBlockManager::rebuild_free_block_ids() {
+ // Push in descending ID order so the smallest free ID ends up on top of the stack
+ // and is handed out first. Allocation order then follows block ID order, which is
+ // what keeps a truncated prefix contiguous when the freed suffix is reacquired.
std::stack<uint32_t> empty;
free_block_ids_.swap(empty);
for (uint32_t i = max_blocks_; i > 0; --i) {
- free_block_ids_.push(i - 1);
+ if (!blocks_[i - 1].is_allocated) {
+ free_block_ids_.push(i - 1);
+ }
}
}
-void KVCacheBlockManager::clear_all() {
- release(0);
+void KVCacheBlockManager::truncate_allocated(uint32_t keep_count) {
+ const auto allocated = get_allocated_blocks();
+ OPENVINO_ASSERT(keep_count <= allocated.size(),
+ "KVCacheBlockManager: cannot truncate to ",
+ keep_count,
+ " blocks, only ",
+ allocated.size(),
+ " are allocated");
+
+ // Deallocate the suffix, keeping device tensors warm for quick reuse.
+ for (size_t i = keep_count; i < allocated.size(); ++i) {
+ auto& block = blocks_[allocated[i]];
+ block.is_allocated = false;
+ block.num_tokens = 0;
+ }
+
+ rebuild_free_block_ids();
+
+ LOG_DEBUG("KVCacheBlockManager: truncated to " << keep_count << " blocks, " << (allocated.size() - keep_count)
+ << " suffix block(s) freed");
}
void KVCacheBlockManager::validate_block_id(uint32_t block_id) const {
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.hpp
index 7c831b38038..c07768ff6b3 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
@@ -127,6 +127,20 @@ public:
*/
void clear_all();
+ /**
+ * @brief Truncate the allocated block list to its first keep_count blocks.
+ *
+ * Used by continuous prefill to discard the suffix of a previous turn while
+ * retaining the shared prefix. Retained blocks keep their IDs, order, token
+ * counts and tensors. Suffix blocks are deallocated with token counts zeroed
+ * and their device tensors kept warm, and subsequent allocations return the
+ * freed IDs in ascending order so logical append order is preserved.
+ *
+ * @param keep_count Number of leading allocated blocks to retain. Must not
+ * exceed the current allocated count.
+ */
+ void truncate_allocated(uint32_t keep_count);
+
/**
* @brief Get block size (tokens per block)
*/
@@ -168,6 +182,16 @@ private:
std::string device_; ///< Target device
std::shared_ptr<const ov::IPlugin> plugin_; ///< Plugin for memory allocation
+ /**
+ * @brief Rebuild the free block ID stack from the current allocation flags.
+ *
+ * Pushes in descending ID order so the smallest free ID is handed out first,
+ * keeping allocation order aligned with block ID order. Shared by every path
+ * that changes allocation state, since the ordering is what keeps a retained
+ * prefix contiguous once freed IDs are reacquired.
+ */
+ void rebuild_free_block_ids();
+
/**
* @brief Validate block ID
*/
diff --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.cpp
index 107e2b8f0a0..a5879a55693 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
@@ -248,6 +248,82 @@ TEST_F(KVCacheBlockManagerTest, InvalidBlockID) {
<< "Updating invalid block ID should throw";
}
+// Truncation for continuous prefill keeps the leading blocks and frees the suffix.
+TEST_F(KVCacheBlockManagerTest, TruncateAllocatedKeepsPrefix) {
+ std::vector<uint32_t> ids;
+ for (int i = 0; i < 5; ++i) {
+ auto id = manager->allocate_block();
+ ASSERT_TRUE(id.has_value());
+ manager->update_block_tokens(id.value(), block_size);
+ ids.push_back(id.value());
+ }
+
+ manager->truncate_allocated(2);
+
+ auto allocated = manager->get_allocated_blocks();
+ ASSERT_EQ(allocated.size(), 2u);
+ EXPECT_EQ(allocated[0], ids[0]);
+ EXPECT_EQ(allocated[1], ids[1]);
+ // Retained blocks keep their token counts and tensors.
+ EXPECT_EQ(manager->get_block_tokens(ids[0]), block_size);
+ EXPECT_EQ(manager->get_block_tokens(ids[1]), block_size);
+ EXPECT_NE(manager->get_block_tensor(ids[0]), nullptr);
+ EXPECT_EQ(manager->num_free_blocks(), max_blocks - 2);
+}
+
+TEST_F(KVCacheBlockManagerTest, TruncateAllocatedPreservesAppendOrder) {
+ std::vector<uint32_t> ids;
+ for (int i = 0; i < 4; ++i) {
+ auto id = manager->allocate_block();
+ ASSERT_TRUE(id.has_value());
+ ids.push_back(id.value());
+ }
+
+ manager->truncate_allocated(1);
+
+ // Freed suffix IDs come back in ascending order so logical append order holds.
+ auto first = manager->allocate_block();
+ auto second = manager->allocate_block();
+ ASSERT_TRUE(first.has_value() && second.has_value());
+ EXPECT_EQ(first.value(), ids[1]);
+ EXPECT_EQ(second.value(), ids[2]);
+ // Reacquired blocks start empty.
+ EXPECT_EQ(manager->get_block_tokens(first.value()), 0u);
+}
+
+TEST_F(KVCacheBlockManagerTest, TruncateAllocatedKeepsSuffixTensorsWarm) {
+ std::vector<uint32_t> ids;
+ std::vector<void*> data_before;
+ for (int i = 0; i < 3; ++i) {
+ auto id = manager->allocate_block();
+ ASSERT_TRUE(id.has_value());
+ ids.push_back(id.value());
+ data_before.push_back(manager->get_block_tensor(id.value())->data());
+ }
+
+ manager->truncate_allocated(1);
+
+ // Retained prefix keeps its tensor untouched.
+ EXPECT_EQ(manager->get_block_tensor(ids[0])->data(), data_before[0]);
+
+ // Suffix tensors are kept warm, so reacquiring those IDs must not re-allocate.
+ // Without this the first prefill chunk of a continuation pays allocation latency.
+ for (size_t i = 1; i < ids.size(); ++i) {
+ auto reacquired = manager->allocate_block();
+ ASSERT_TRUE(reacquired.has_value());
+ EXPECT_EQ(reacquired.value(), ids[i]);
+ EXPECT_EQ(manager->get_block_tensor(reacquired.value())->data(), data_before[i]);
+ }
+}
+
+TEST_F(KVCacheBlockManagerTest, TruncateAllocatedRejectsOverKeep) {
+ ASSERT_TRUE(manager->allocate_block().has_value());
+ EXPECT_THROW(manager->truncate_allocated(2), ov::Exception);
+ // Truncating to the full allocated count is a no-op.
+ manager->truncate_allocated(1);
+ EXPECT_EQ(manager->get_allocated_blocks().size(), 1u);
+}
+
// Test 11: Get Tensor After Clear (memory kept, state reset)
TEST_F(KVCacheBlockManagerTest, GetTensorAfterClear) {
auto block_id = manager->allocate_block();