OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[NPUW] Introduce KVCacheBlockManager for block-based KV cache. (#35013)
intelgaoxiong7fe2854a671f
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.cppnew file mode 100644index 00000000000..b55a3a55c81--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/kv_cache_block_manager.cpp@@ -0,0 +1,168 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "kv_cache_block_manager.hpp"++#include "logging.hpp"+#include "util.hpp"++namespace ov {+namespace npuw {++KVCacheBlockManager::KVCacheBlockManager(uint32_t block_size,+ uint32_t max_blocks,+ const ov::Shape& base_shape,+ ov::element::Type elem_type,+ const std::string& device,+ const std::shared_ptr<const ov::IPlugin>& plugin)+ : block_size_(block_size),+ max_blocks_(max_blocks),+ element_type_(elem_type),+ block_shape_(base_shape),+ device_(device),+ plugin_(plugin) {+ OPENVINO_ASSERT(block_size_ > 0 && max_blocks_ > 0,+ "KVCacheBlockManager: block_size and max_blocks must be > 0, got block_size=",+ block_size_,+ " max_blocks=",+ max_blocks_);+ OPENVINO_ASSERT(device_ == "CPU" || plugin_ != nullptr,+ "KVCacheBlockManager: plugin must be non-null for non-CPU device '",+ device_,+ "'");+ // Check that the sequence dimension (dim 2 for K/non-transposed-V, dim 3 for transposed V)+ // equals block_size.+ OPENVINO_ASSERT(base_shape.size() == 4 && (base_shape[2] == block_size || base_shape[3] == block_size),+ "KVCacheBlockManager: base_shape ",+ base_shape,+ " does not have block_size=",+ block_size,+ " in sequence dimension (expected at dim 2 or 3)");++ // Initialize block pool (tensors allocated on-demand, not here)+ blocks_.reserve(max_blocks);+ for (uint32_t i = 0; i < max_blocks; ++i) {+ blocks_.push_back({});+ }++ // Push block IDs to stack in reverse order (so block 0 is on top).+ for (uint32_t i = max_blocks; i > 0; --i) {+ free_block_ids_.push(i - 1);+ }++ LOG_INFO("KVCacheBlockManager initialized: " << "block_size=" << block_size << ", max_blocks=" << max_blocks+ << ", total_capacity=" << (block_size * max_blocks) << " tokens"+ << ", device=" << device);+}++std::optional<uint32_t> KVCacheBlockManager::allocate_block() {+ if (free_block_ids_.empty()) {+ LOG_WARN("KVCacheBlockManager: No free blocks available! " << "All " << max_blocks_ << " blocks are in use.");+ return std::nullopt;+ }++ uint32_t block_id = free_block_ids_.top();+ free_block_ids_.pop();++ auto& block = blocks_[block_id];++ // Allocate actual memory on-demand+ if (!block.tensor) {+ block.tensor = ov::npuw::util::allocMem(element_type_, block_shape_, device_, plugin_);+ LOG_DEBUG("KVCacheBlockManager: Allocated memory for block " << block_id << " (shape=" << block_shape_+ << ", device=" << device_ << ")");+ }++ // Reset block state+ block.num_tokens = 0;+ block.is_allocated = true;++ LOG_VERB("KVCacheBlockManager: Allocated block " << block_id+ << " (free blocks remaining: " << free_block_ids_.size() << ")");++ return block_id;+}++ov::SoPtr<ov::ITensor> KVCacheBlockManager::get_block_tensor(uint32_t block_id) const {+ validate_block_id(block_id);++ auto& block = blocks_[block_id];++ if (!block.tensor) {+ OPENVINO_THROW("KVCacheBlockManager: Block ",+ block_id,+ " has no allocated tensor. "+ "Call allocate_block() first.");+ }++ return block.tensor;+}++void KVCacheBlockManager::update_block_tokens(uint32_t block_id, uint32_t num_tokens) {+ validate_block_id(block_id);++ if (!blocks_[block_id].is_allocated) {+ OPENVINO_THROW("KVCacheBlockManager: Cannot update tokens on free block ",+ block_id,+ ". Call allocate_block() first.");+ }++ if (num_tokens > block_size_) {+ OPENVINO_THROW("KVCacheBlockManager: Cannot set ",+ num_tokens,+ " tokens in block ",+ block_id,+ " (capacity: ",+ block_size_,+ ")");+ }++ auto& block = blocks_[block_id];+ block.num_tokens = num_tokens;++ LOG_VERB("KVCacheBlockManager: Updated block " << block_id << " tokens: " << num_tokens << "/" << block_size_);+}++uint32_t KVCacheBlockManager::get_block_tokens(uint32_t block_id) const {+ validate_block_id(block_id);+ return blocks_[block_id].num_tokens;+}++std::vector<uint32_t> KVCacheBlockManager::get_allocated_blocks() const {+ std::vector<uint32_t> allocated;+ allocated.reserve(max_blocks_ - free_block_ids_.size());++ for (uint32_t i = 0; i < blocks_.size(); ++i) {+ if (blocks_[i].is_allocated) {+ allocated.push_back(i);+ }+ }++ return allocated;+}++void KVCacheBlockManager::clear_all() {+ LOG_DEBUG("KVCacheBlockManager: Clearing all blocks");++ for (auto& block : blocks_) {+ block.num_tokens = 0;+ block.is_allocated = false;+ }++ // Rebuild free stack (push in reverse order so block 0 is on top)+ 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);+ }+}++void KVCacheBlockManager::validate_block_id(uint32_t block_id) const {+ if (block_id >= max_blocks_) {+ OPENVINO_THROW("KVCacheBlockManager: Invalid block ID ", block_id, " (valid range: 0-", max_blocks_ - 1, ")");+ }+}++} // namespace npuw+} // namespace ovdiff --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.hppnew file mode 100644index 00000000000..65b82d9f820--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/kv_cache_block_manager.hpp@@ -0,0 +1,163 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstdint>+#include <memory>+#include <optional>+#include <stack>+#include <string>+#include <vector>++#include "openvino/runtime/iplugin.hpp"+#include "openvino/runtime/itensor.hpp"+#include "openvino/runtime/so_ptr.hpp"++namespace ov {+namespace npuw {++/**+ * @brief Block-based KV Cache Manager+ *+ * Manages KV cache memory using fixed-size blocks instead of a single continuous buffer.+ * This approach significantly reduces memory waste when actual prompt length is much smaller+ * than the configured max_prompt_size.+ *+ * Key benefits:+ * - Memory efficiency: Only allocate blocks as needed+ * - Flexible allocation: Adapt to variable-length prompts without pre-allocating max buffer+ *+ * Example usage:+ * KVCacheBlockManager manager(512, 16, shape, type, "NPU", plugin);+ * auto block_id = manager.allocate_block();+ * auto tensor = manager.get_block_tensor(block_id.value());+ * manager.update_block_tokens(block_id.value(), 256);+ * manager.clear_all();+ */+class KVCacheBlockManager {+public:+ /**+ * @brief Construct a new KV Cache Block Manager+ *+ * @param block_size Number of tokens per block+ * @param max_blocks Maximum number of blocks in the pool+ * @param base_shape Base shape for block tensors [batch, num_heads, seq_len, head_dim]+ * @param elem_type Element type (e.g., fp16, fp32)+ * @param device Target device for memory allocation ("NPU", "CPU")+ * @param plugin Plugin instance for memory allocation+ */+ KVCacheBlockManager(uint32_t block_size,+ uint32_t max_blocks,+ const ov::Shape& base_shape,+ ov::element::Type elem_type,+ const std::string& device,+ const std::shared_ptr<const ov::IPlugin>& plugin);++ ~KVCacheBlockManager() = default;++ // Disable copy+ KVCacheBlockManager(const KVCacheBlockManager&) = delete;+ KVCacheBlockManager& operator=(const KVCacheBlockManager&) = delete;++ // Allow move+ KVCacheBlockManager(KVCacheBlockManager&&) = default;+ KVCacheBlockManager& operator=(KVCacheBlockManager&&) = default;++ /**+ * @brief Allocate a new block from the free pool+ *+ * @return Block ID if successful, std::nullopt if no free blocks available+ */+ std::optional<uint32_t> allocate_block();++ /**+ * @brief Get the tensor associated with a block+ *+ * @param block_id Block ID+ * @return Tensor for the block+ */+ ov::SoPtr<ov::ITensor> get_block_tensor(uint32_t block_id) const;++ /**+ * @brief Update the number of tokens stored in a block+ *+ * @param block_id Block ID+ * @param num_tokens New token count (must be <= block_size)+ */+ void update_block_tokens(uint32_t block_id, uint32_t num_tokens);++ /**+ * @brief Get the number of tokens in a block+ *+ * @param block_id Block ID+ * @return Number of tokens+ */+ uint32_t get_block_tokens(uint32_t block_id) const;++ /**+ * @brief Get list of all currently allocated block IDs+ *+ * @return Vector of block IDs+ */+ std::vector<uint32_t> get_allocated_blocks() const;++ /**+ * @brief Reset all blocks to FREE state and clear token counts.+ *+ * Note: tensor memory is retained in the pool for reuse; no device+ * deallocation occurs. Individual block release is not supported —+ * use this method to reset the entire pool between requests.+ */+ void clear_all();++ /**+ * @brief Get block size (tokens per block)+ */+ uint32_t get_block_size() const {+ return block_size_;+ }++ /**+ * @brief Get maximum number of blocks+ */+ uint32_t get_max_blocks() const {+ return max_blocks_;+ }++ /**+ * @brief Get number of currently free (unallocated) blocks+ */+ uint32_t num_free_blocks() const {+ return static_cast<uint32_t>(free_block_ids_.size());+ }++private:+ /**+ * @brief Represents a single block of KV cache memory+ */+ struct Block {+ ov::SoPtr<ov::ITensor> tensor; ///< Block memory tensor (allocated on-demand)+ uint32_t num_tokens = 0; ///< Number of tokens stored in this block+ bool is_allocated = false; ///< True when block is in use; false = free+ };++ uint32_t block_size_; ///< Number of tokens per block+ uint32_t max_blocks_; ///< Maximum blocks in pool+ std::vector<Block> blocks_; ///< All blocks (free + allocated)+ std::stack<uint32_t> free_block_ids_; ///< Stack of free block IDs (LIFO for better reuse)++ ov::element::Type element_type_; ///< Element type for tensors+ ov::Shape block_shape_; ///< Shape for block tensors+ std::string device_; ///< Target device+ std::shared_ptr<const ov::IPlugin> plugin_; ///< Plugin for memory allocation++ /**+ * @brief Validate block ID+ */+ void validate_block_id(uint32_t block_id) const;+};++} // namespace npuw+} // namespace ovdiff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex cec8f0e9d5f..cbd054beda4 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -68,6 +68,7 @@ ov_add_test_target(${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/v1/elements/failsafe.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/split_kvcache_into_blocks.cpp+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/kv_cache_block_manager.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/attention.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cppdiff --git a/src/plugins/intel_npu/tests/unit/npuw/kv_cache_block_manager_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/kv_cache_block_manager_test.cppnew file mode 100644index 00000000000..8fe4ad70edc--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/kv_cache_block_manager_test.cpp@@ -0,0 +1,266 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "kv_cache_block_manager.hpp"++#include <gtest/gtest.h>++#include <algorithm>+#include <set>++#include "openvino/core/shape.hpp"+#include "openvino/core/type/element_type.hpp"++using namespace ov::npuw;++namespace {++// Test fixture for KVCacheBlockManager tests+class KVCacheBlockManagerTest : public ::testing::Test {+protected:+ void SetUp() override {+ // Common test parameters+ block_size = 512;+ max_blocks = 8;+ base_shape = ov::Shape{1, 32, block_size, 128}; // [batch, num_heads, seq_len=block_size, head_dim]+ elem_type = ov::element::f16;+ device = "CPU"; // Use CPU for unit tests++ // Pass nullptr for plugin since CPU device doesn't need it in allocMem+ manager = std::make_unique<KVCacheBlockManager>(block_size, max_blocks, base_shape, elem_type, device, nullptr);+ }++ void TearDown() override {+ manager.reset();+ }++ uint32_t block_size;+ uint32_t max_blocks;+ ov::Shape base_shape;+ ov::element::Type elem_type;+ std::string device;+ std::unique_ptr<KVCacheBlockManager> manager;+};++// Test 1: Basic Allocation+TEST_F(KVCacheBlockManagerTest, BasicAllocation) {+ // Allocate a block+ auto block_id = manager->allocate_block();+ ASSERT_TRUE(block_id.has_value()) << "Block allocation should succeed";+ EXPECT_EQ(block_id.value(), 0u) << "First block should have ID 0";++ // Get block tensor+ auto tensor = manager->get_block_tensor(block_id.value());+ ASSERT_NE(tensor, nullptr) << "Block tensor should not be null";++ // Check tensor shape+ auto shape = tensor->get_shape();+ EXPECT_EQ(shape[0], base_shape[0]) << "Batch dimension should match";+ EXPECT_EQ(shape[1], base_shape[1]) << "Num_heads dimension should match";+ EXPECT_EQ(shape[2], block_size) << "Seq_len should be block_size";+ EXPECT_EQ(shape[3], base_shape[3]) << "Head_dim should match";++ // Check token count+ EXPECT_EQ(manager->get_block_tokens(block_id.value()), 0u) << "Newly allocated block should have 0 tokens";+}++// Test 2: Multiple Allocations+TEST_F(KVCacheBlockManagerTest, MultipleAllocations) {+ std::vector<uint32_t> allocated_blocks;++ // Allocate half of available blocks+ for (uint32_t i = 0; i < max_blocks / 2; ++i) {+ auto block_id = manager->allocate_block();+ ASSERT_TRUE(block_id.has_value()) << "Allocation " << i << " should succeed";+ allocated_blocks.push_back(block_id.value());+ }++ // Verify unique block IDs+ std::set<uint32_t> unique_ids(allocated_blocks.begin(), allocated_blocks.end());+ EXPECT_EQ(unique_ids.size(), allocated_blocks.size()) << "All allocated blocks should have unique IDs";++ // Verify counts via get_allocated_blocks()+ auto all_allocated = manager->get_allocated_blocks();+ EXPECT_EQ(all_allocated.size(), max_blocks / 2);+}++// Test 3: Block Exhaustion+TEST_F(KVCacheBlockManagerTest, BlockExhaustion) {+ // Allocate all blocks+ for (uint32_t i = 0; i < max_blocks; ++i) {+ auto block_id = manager->allocate_block();+ ASSERT_TRUE(block_id.has_value()) << "Allocation " << i << " should succeed";+ }++ // All blocks should be allocated+ EXPECT_EQ(manager->get_allocated_blocks().size(), static_cast<size_t>(max_blocks));++ // Try to allocate one more - should fail+ auto extra_block = manager->allocate_block();+ EXPECT_FALSE(extra_block.has_value()) << "Allocation should fail when all blocks are in use";++ // Clear all, then allocation should succeed again+ manager->clear_all();+ EXPECT_TRUE(manager->get_allocated_blocks().empty());++ auto new_block = manager->allocate_block();+ ASSERT_TRUE(new_block.has_value()) << "Allocation should succeed after clearing all blocks";+}++// Test 4: Token Tracking+TEST_F(KVCacheBlockManagerTest, TokenTracking) {+ auto block_id = manager->allocate_block();+ ASSERT_TRUE(block_id.has_value());++ // Initially 0 tokens+ EXPECT_EQ(manager->get_block_tokens(block_id.value()), 0u);++ // Update to 256 tokens+ manager->update_block_tokens(block_id.value(), 256);+ EXPECT_EQ(manager->get_block_tokens(block_id.value()), 256u);++ // Update to full capacity+ manager->update_block_tokens(block_id.value(), block_size);+ EXPECT_EQ(manager->get_block_tokens(block_id.value()), block_size);++ // Allocate a second block and verify its tokens are tracked independently+ auto block_id2 = manager->allocate_block();+ ASSERT_TRUE(block_id2.has_value());+ manager->update_block_tokens(block_id2.value(), 100);+ EXPECT_EQ(manager->get_block_tokens(block_id2.value()), 100u);+ EXPECT_EQ(manager->get_block_tokens(block_id.value()), block_size) << "First block tokens should be unchanged";+}++// Test 5: Token Count Validation+TEST_F(KVCacheBlockManagerTest, TokenCountValidation) {+ auto block_id = manager->allocate_block();+ ASSERT_TRUE(block_id.has_value());++ // Try to set more tokens than capacity - should throw+ EXPECT_THROW(manager->update_block_tokens(block_id.value(), block_size + 1), ov::Exception)+ << "Setting tokens beyond capacity should throw exception";+}++// Test 6: Memory Reuse After Clear+TEST_F(KVCacheBlockManagerTest, MemoryReuseAfterClear) {+ // Allocate a block and record its tensor pointer+ auto block_id = manager->allocate_block();+ ASSERT_TRUE(block_id.has_value());+ auto tensor_before = manager->get_block_tensor(block_id.value());+ ASSERT_NE(tensor_before, nullptr);+ void* ptr_before = tensor_before->data();++ // Clear and re-allocate — should reuse the same underlying memory+ manager->clear_all();+ auto block_id2 = manager->allocate_block();+ ASSERT_TRUE(block_id2.has_value());+ auto tensor_after = manager->get_block_tensor(block_id2.value());+ ASSERT_NE(tensor_after, nullptr);+ EXPECT_EQ(tensor_after->data(), ptr_before) << "Should reuse the same memory buffer after clear";+}++// Test 7: Allocation and Token State Consistency+TEST_F(KVCacheBlockManagerTest, AllocationAndTokenConsistency) {+ // Initially no blocks allocated+ EXPECT_TRUE(manager->get_allocated_blocks().empty());++ // Allocate 2 blocks with different token counts+ auto block1 = manager->allocate_block();+ auto block2 = manager->allocate_block();+ ASSERT_TRUE(block1.has_value());+ ASSERT_TRUE(block2.has_value());++ manager->update_block_tokens(block1.value(), block_size); // full block+ manager->update_block_tokens(block2.value(), 256); // half-full block++ EXPECT_EQ(manager->get_allocated_blocks().size(), 2u);+ EXPECT_EQ(manager->get_block_tokens(block1.value()), block_size);+ EXPECT_EQ(manager->get_block_tokens(block2.value()), 256u);++ // After clear, tokens and allocations reset+ manager->clear_all();+ EXPECT_TRUE(manager->get_allocated_blocks().empty());+ // Re-allocate and verify tokens are reset to 0+ auto block3 = manager->allocate_block();+ ASSERT_TRUE(block3.has_value());+ EXPECT_EQ(manager->get_block_tokens(block3.value()), 0u);+}++// Test 8: Clear All+TEST_F(KVCacheBlockManagerTest, ClearAll) {+ // Allocate several blocks with token counts+ for (uint32_t i = 0; i < 5; ++i) {+ auto block_id = manager->allocate_block();+ ASSERT_TRUE(block_id.has_value());+ manager->update_block_tokens(block_id.value(), 100 * (i + 1));+ }++ // Verify blocks allocated+ EXPECT_EQ(manager->get_allocated_blocks().size(), 5u);++ // Clear all+ manager->clear_all();++ // Verify all blocks freed+ EXPECT_TRUE(manager->get_allocated_blocks().empty());++ // Should be able to allocate again, and tokens reset to 0+ auto new_block = manager->allocate_block();+ ASSERT_TRUE(new_block.has_value());+ EXPECT_EQ(manager->get_block_tokens(new_block.value()), 0u);+}++// Test 9: Get Allocated Blocks+TEST_F(KVCacheBlockManagerTest, GetAllocatedBlocks) {+ // Initially empty+ auto allocated = manager->get_allocated_blocks();+ EXPECT_TRUE(allocated.empty());++ // Allocate some blocks+ std::vector<uint32_t> expected_blocks;+ expected_blocks.push_back(manager->allocate_block().value());+ expected_blocks.push_back(manager->allocate_block().value());+ expected_blocks.push_back(manager->allocate_block().value());++ // Get allocated blocks+ allocated = manager->get_allocated_blocks();+ EXPECT_EQ(allocated.size(), expected_blocks.size());++ // Verify all expected blocks are in the list+ for (auto block_id : expected_blocks) {+ EXPECT_TRUE(std::find(allocated.begin(), allocated.end(), block_id) != allocated.end())+ << "Block " << block_id << " should be in allocated list";+ }+}++// Test 10: Invalid Block ID+TEST_F(KVCacheBlockManagerTest, InvalidBlockID) {+ // Try to access block with ID >= max_blocks+ EXPECT_THROW(manager->get_block_tensor(max_blocks), ov::Exception) << "Accessing invalid block ID should throw";++ EXPECT_THROW(manager->get_block_tokens(max_blocks + 10), ov::Exception)+ << "Accessing invalid block ID should throw";++ EXPECT_THROW(manager->update_block_tokens(max_blocks, 100), ov::Exception)+ << "Updating invalid block ID should throw";+}++// Test 11: Get Tensor After Clear (memory kept, state reset)+TEST_F(KVCacheBlockManagerTest, GetTensorAfterClear) {+ auto block_id = manager->allocate_block();+ ASSERT_TRUE(block_id.has_value());++ // Tensor is allocated on first allocate_block()+ auto tensor = manager->get_block_tensor(block_id.value());+ EXPECT_NE(tensor, nullptr) << "Tensor should be valid after allocation";++ // clear_all() resets state but keeps memory for reuse+ manager->clear_all();+ auto block_id2 = manager->allocate_block();+ ASSERT_TRUE(block_id2.has_value());+ auto tensor2 = manager->get_block_tensor(block_id2.value());+ EXPECT_NE(tensor2, nullptr) << "Tensor should still be valid after clear + re-allocate";+}++} // namespace