Skip to content

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

[NPUW] Support gemma4 26B A4B MoE with Block KV Cache (#37020)

Guoliang Shid0b153af2b2e
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 c09b045b0b4..8859dbce0b8 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
@@ -52,20 +52,43 @@ ov::npuw::LLMBlockKVCacheStrategy::ClassifiedPortsMap build_classified_ports_map
return result;
}
+using DummyTensorVec = std::vector<ov::npuw::LLMBlockKVCacheStrategy::DummyTensorEntry>;
+
+// Locate the dummy tensor whose shape and element type both match the query.
+// Returns nullptr only if on_initialize() missed an entry (should not happen).
+const ov::SoPtr<ov::ITensor>* find_dummy_tensor(const DummyTensorVec& dummies,
+ const ov::Shape& shape,
+ const ov::element::Type& elem_type) {
+ for (const auto& entry : dummies) {
+ if (entry.shape == shape && entry.elem_type == elem_type) {
+ return &entry.tensor;
+ }
+ }
+ return nullptr;
+}
+
// Set dummy tensors on all numbered block inputs in a classified ports map.
+// Each port is matched by exact (shape, element_type) — both dimensions are required
// Returns the count of block inputs that were set.
template <typename SetTensorFn>
size_t set_dummy_block_tensors(const ov::npuw::LLMBlockKVCacheStrategy::ClassifiedPortsMap& ports_map,
SetTensorFn&& set_tensor_fn,
- const ov::SoPtr<ov::ITensor>& dummy_key_tensor,
- const ov::SoPtr<ov::ITensor>& dummy_value_tensor) {
+ const DummyTensorVec& dummies) {
using ov::npuw::BlockParamKind;
size_t block_count = 0;
for (const auto& [name, cp] : ports_map) {
if (cp.kind == BlockParamKind::Skip || cp.kind == BlockParamKind::TailBlock) {
continue; // skip non-block ports and tail ports (tail is copy-filled separately)
}
- set_tensor_fn(cp.port, cp.kind == BlockParamKind::KeyBlock ? dummy_key_tensor : dummy_value_tensor);
+ const auto* dummy = find_dummy_tensor(dummies, cp.port.get_shape(), cp.port.get_element_type());
+ OPENVINO_ASSERT(dummy != nullptr,
+ "No dummy tensor registered for block port '",
+ name,
+ "' with shape ",
+ cp.port.get_shape(),
+ " type ",
+ cp.port.get_element_type());
+ set_tensor_fn(cp.port, *dummy);
block_count++;
}
return block_count;
@@ -156,54 +179,38 @@ void copy_block_to_tail_input(const ov::SoPtr<ov::ITensor>& block_tensor,
uu::copy_tensor_by_dim(src_slice, dst_slice, kv_dim, kv_dim);
}
-// Shapes and element type of one key/value block pair — derived from the first
-// numbered block port found during initialization.
-struct BlockShapeInfo {
- ov::Shape key_shape;
- ov::Shape value_shape;
- ov::element::Type elem_type;
- bool found_key = false;
- bool found_value = false;
-};
-
-// Scan classified prefill input ports to discover the shape and element type of block tensors.
-BlockShapeInfo find_block_shapes(const ov::npuw::LLMBlockKVCacheStrategy::ClassifiedPortsMap& classified_ports) {
+// Collect all unique (shape, element_type) pairs from classified block input ports.
+// Returns a DummyTensorVec with tensor fields left empty (filled in on_initialize()).
+// In typical LLM models this returns 1 entry; Gemma4 26B A4B MoE returns 2.
+DummyTensorVec collect_unique_block_tensor_entries(
+ const ov::npuw::LLMBlockKVCacheStrategy::ClassifiedPortsMap& classified_ports) {
using ov::npuw::BlockParamKind;
- BlockShapeInfo shapes;
+ DummyTensorVec result;
for (const auto& [name, cp] : classified_ports) {
if (cp.kind == BlockParamKind::Skip || cp.kind == BlockParamKind::TailBlock) {
continue;
}
- const bool is_key = cp.kind == BlockParamKind::KeyBlock;
- if (!shapes.found_key && is_key) {
- shapes.key_shape = cp.port.get_shape();
- shapes.elem_type = cp.port.get_element_type();
- shapes.found_key = true;
- LOG_DEBUG("Detected key block shape: " << shapes.key_shape << ", type: " << shapes.elem_type);
- }
- if (!shapes.found_value && !is_key) {
- shapes.value_shape = cp.port.get_shape();
- shapes.found_value = true;
- LOG_DEBUG("Detected value block shape: " << shapes.value_shape);
- }
- if (shapes.found_key && shapes.found_value) {
- break;
+ const ov::Shape shape = cp.port.get_shape();
+ const ov::element::Type elem_type = cp.port.get_element_type();
+ if (find_dummy_tensor(result, shape, elem_type) == nullptr) {
+ result.push_back({shape, elem_type, {}});
+ LOG_DEBUG("collect_unique_block_tensor_entries: port='" << name << "' shape=" << shape
+ << " type=" << elem_type);
}
}
- return shapes;
+ return result;
}
// Set dummy tensors on all numbered block input ports of a single inference request.
size_t set_dummy_tensors_to_request(const std::shared_ptr<ov::IAsyncInferRequest>& request,
const ov::npuw::LLMBlockKVCacheStrategy::ClassifiedPortsMap& classified_ports,
- const ov::npuw::LLMBlockKVCacheStrategy::DummyTensors& dummies) {
+ const DummyTensorVec& dummies) {
return set_dummy_block_tensors(
classified_ports,
[&request](const ov::Output<const ov::Node>& port, const ov::SoPtr<ov::ITensor>& tensor) {
request->set_tensor(port, tensor);
},
- dummies.key_tensor,
- dummies.value_tensor);
+ dummies);
}
} // anonymous namespace
@@ -221,32 +228,24 @@ void LLMBlockKVCacheStrategy::on_initialize() {
const auto& prefill_in_ports = m_req.m_prefill_in_ports;
const auto& prefill_out_ports = m_req.m_prefill_out_ports;
- // Pre-classify all port names once — reused by find_block_shapes,
+ // Pre-classify all port names once — reused by collect_unique_block_shapes,
// set_dummy_block_tensors, and the phase-1 layer scan.
m_prefill_classified_in_ports = build_classified_ports_map(prefill_in_ports);
for (const auto& [request, ports] : m_req.m_generate_variant_in_ports) {
m_gen_classified_in_ports.emplace(request, build_classified_ports_map(ports));
}
- auto block_shapes = find_block_shapes(m_prefill_classified_in_ports);
- if (block_shapes.found_key) {
- // Dummy tensor optimization: share one dummy tensor per shape across all block inputs.
- // Store in m_dummy_tensors so on_reset() can restore ports to release block tensor refs.
+ auto dummy_entries = collect_unique_block_tensor_entries(m_prefill_classified_in_ports);
+ if (!dummy_entries.empty()) {
+ // Allocate one dummy tensor per distinct (shape, element_type) pair.
+ // Keying on both dimensions prevents type-mismatch errors in mixed-precision models.
const auto& plugin = m_req.m_npuw_llm_compiled_model->get_plugin();
- m_dummy_tensors.key_tensor =
- ov::npuw::util::allocMem(block_shapes.elem_type, block_shapes.key_shape, m_req.m_pre_alloc_device, plugin);
- LOG_INFO("Allocated shared dummy key tensor: " << block_shapes.key_shape << " ("
- << m_dummy_tensors.key_tensor->get_byte_size() << " bytes)");
- if (block_shapes.found_value && block_shapes.value_shape != block_shapes.key_shape) {
- m_dummy_tensors.value_tensor = ov::npuw::util::allocMem(block_shapes.elem_type,
- block_shapes.value_shape,
- m_req.m_pre_alloc_device,
- plugin);
- LOG_INFO("Allocated shared dummy value tensor: "
- << block_shapes.value_shape << " (" << m_dummy_tensors.value_tensor->get_byte_size() << " bytes)");
- } else {
- m_dummy_tensors.value_tensor = m_dummy_tensors.key_tensor;
+ for (auto& entry : dummy_entries) {
+ entry.tensor = ov::npuw::util::allocMem(entry.elem_type, entry.shape, m_req.m_pre_alloc_device, plugin);
+ LOG_INFO("Allocated dummy block tensor shape=" << entry.shape << " type=" << entry.elem_type << " ("
+ << entry.tensor->get_byte_size() << " bytes)");
}
+ m_dummy_tensors = std::move(dummy_entries);
set_dummy_tensors_to_all_requests();
}
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 62b771f90d2..ed6f396ea8a 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
@@ -97,10 +97,12 @@ public:
};
using ClassifiedPortsMap = std::unordered_map<std::string, ClassifiedPort>;
- // Dummy tensors shared across all numbered block input ports (key + value).
- struct DummyTensors {
- ov::SoPtr<ov::ITensor> key_tensor;
- ov::SoPtr<ov::ITensor> value_tensor;
+ // One dummy tensor entry: (shape, element_type) + pre-allocated tensor.
+ // Kept as a small vector (usually LLM with 1~2 entries) for simple and fast linear lookup.
+ struct DummyTensorEntry {
+ ov::Shape shape;
+ ov::element::Type elem_type;
+ ov::SoPtr<ov::ITensor> tensor;
};
explicit LLMBlockKVCacheStrategy(LLMInferRequest& req) : LLMKVCacheStrategy(req) {}
@@ -187,10 +189,11 @@ private:
// Snapshotted original prefill output tensors for restore_prefill_output_buffers()
std::unordered_map<std::string, ov::SoPtr<ov::ITensor>> m_prefill_original_output_tensors;
- // Dummy tensors shared across all numbered block input ports.
- // Stored here so on_reset() can restore all ports to dummy tensors before clear_all(),
+ // Dummy tensors, one per distinct (shape, element_type) pair found across all block
+ // input ports. Keying on both dimensions is required.
+ // Stored here so on_reset() can restore all ports to dummies before clear_all(),
// releasing any live shared_ptr references held by inference requests.
- DummyTensors m_dummy_tensors;
+ std::vector<DummyTensorEntry> m_dummy_tensors;
// Pre-classified input port maps built once in on_initialize().
// Avoids re-running classify_block_param() on every scan across the port map.
diff --git a/src/plugins/intel_npu/tests/unit/npuw/split_kvcache_into_blocks_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/split_kvcache_into_blocks_test.cpp
index 6c31aed9cf8..effedfbe247 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/split_kvcache_into_blocks_test.cpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/split_kvcache_into_blocks_test.cpp
@@ -411,3 +411,59 @@ TEST_F(SplitKVCacheIntoBlocksTest, WithConvertNode) {
}
EXPECT_TRUE(found_concat);
}
+
+TEST_F(SplitKVCacheIntoBlocksTest, HeterogeneousKVShapesAcrossLayers) {
+ // Test: MoE model with two KV layer groups that have different shapes.
+ // Layer 0: [1, 8, 512, 256] (8 heads, head_dim=256)
+ // Layer 1: [1, 2, 512, 512] (2 heads, head_dim=512)
+ // block_size=128 -> 4 blocks per layer.
+ // After transformation each group must produce blocks with ITS OWN shape,
+ // not the shape of the first group encountered.
+ const uint32_t block_size = 128;
+ const uint32_t expected_blocks = 512 / block_size; // 4 blocks per layer
+
+ // --- Layer 0 ---
+ auto key0 = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 8, 512, 256});
+ key0->set_friendly_name("past_key_values.0.key");
+ auto new_k0 = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 8, 1, 256});
+ auto concat_k0 = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{key0, new_k0}, 2);
+
+ // --- Layer 1 ---
+ auto key1 = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 2, 512, 512});
+ key1->set_friendly_name("past_key_values.1.key");
+ auto new_k1 = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 2, 1, 512});
+ auto concat_k1 = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{key1, new_k1}, 2);
+
+ auto model = std::make_shared<ov::Model>(ov::ResultVector{std::make_shared<ov::op::v0::Result>(concat_k0),
+ std::make_shared<ov::op::v0::Result>(concat_k1)},
+ ov::ParameterVector{key0, key1, new_k0, new_k1});
+
+ ov::pass::Manager manager;
+ manager.register_pass<SplitKVCacheIntoBlocks>(block_size, true);
+ manager.run_passes(model);
+
+ // 4 blocks per layer * 2 layers + 2 new_token params = 10
+ EXPECT_EQ(model->get_parameters().size(), expected_blocks * 2 + 2);
+
+ // Verify each layer's block params have the correct per-layer shape.
+ size_t layer0_blocks = 0, layer1_blocks = 0;
+ for (const auto& param : model->get_parameters()) {
+ const auto& name = param->get_friendly_name();
+ if (name.find("_block_") == std::string::npos)
+ continue;
+ const auto& s = param->get_shape();
+ if (name.find("past_key_values.0") != std::string::npos) {
+ layer0_blocks++;
+ EXPECT_EQ(s[1], 8u) << "Layer 0 block must have 8 heads";
+ EXPECT_EQ(s[2], block_size) << "Layer 0 block_size axis";
+ EXPECT_EQ(s[3], 256u) << "Layer 0 head_dim must be 256";
+ } else if (name.find("past_key_values.1") != std::string::npos) {
+ layer1_blocks++;
+ EXPECT_EQ(s[1], 2u) << "Layer 1 block must have 2 heads";
+ EXPECT_EQ(s[2], block_size) << "Layer 1 block_size axis";
+ EXPECT_EQ(s[3], 512u) << "Layer 1 head_dim must be 512";
+ }
+ }
+ EXPECT_EQ(layer0_blocks, expected_blocks);
+ EXPECT_EQ(layer1_blocks, expected_blocks);
+}