Skip to content

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

[NPUW] Fix K/V Reshape targets in Pyramid attention variants (#38351)

xiaodong8b6419ae6bd3
diff --git a/src/plugins/intel_npu/src/plugin/npuw/attention.cpp b/src/plugins/intel_npu/src/plugin/npuw/attention.cpp
index 2f977554c48..8322b9cc583 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/attention.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/attention.cpp
@@ -4,6 +4,7 @@
#include "attention.hpp"
+#include "openvino/core/validation_util.hpp"
#include "openvino/op/broadcast.hpp"
#include "openvino/op/matmul.hpp"
#include "openvino/op/reshape.hpp"
@@ -44,62 +45,63 @@ void ov::npuw::function::patch_broadcast_constants(const std::shared_ptr<ov::Mod
}
}
-// Helper function to patch reshape constants for pre-reshape (-1 substitution)
+// Preserve folded K/V sequence lengths as inferred dimensions before reshaping a pyramid variant.
void ov::npuw::function::patch_reshape_constants(const std::shared_ptr<ov::Model>& model,
- const std::map<std::string, size_t>& past_value_sequence_dims) {
- for (auto&& op : model->get_ordered_ops()) {
- if (!ov::is_type<ov::op::v1::Reshape>(op)) {
- continue;
- }
-
- // Check if Reshape's single consumer is MatMul
- auto target_inputs = op->output(0).get_target_inputs();
- if (target_inputs.size() != 1) {
- continue; // Reshape should have exactly one consumer
- }
-
- auto matmul_node = target_inputs.begin()->get_node()->shared_from_this();
- if (!ov::is_type<ov::op::v0::MatMul>(matmul_node)) {
- continue;
- }
-
- // Check if MatMul's input 0 is from Softmax
- auto matmul_input0 = matmul_node->input(0).get_source_output().get_node_shared_ptr();
- if (!ov::is_type<ov::op::v8::Softmax>(matmul_input0)) {
- continue;
- }
-
- LOG_INFO("Found Reshape -> MatMul pattern where MatMul input 0 is from Softmax, "
- "patching Reshape constant");
-
- // Inspect the reshape constant (shape input)
- auto shape_source = op->input(1).get_source_output().get_node_shared_ptr();
- if (!ov::is_type<ov::op::v0::Constant>(shape_source)) {
- LOG_WARN("Reshape's shape input is not Const: " << shape_source << ", skipping");
- continue;
- }
-
- auto shape_const = std::dynamic_pointer_cast<ov::op::v0::Constant>(shape_source);
- auto shape_values = shape_const->cast_vector<int32_t>();
+ const std::map<std::string, size_t>& past_key_sequence_dims,
+ const std::map<std::string, size_t>& past_value_sequence_dims,
+ size_t full_context_length) {
+ if (past_key_sequence_dims.empty() || past_value_sequence_dims.empty()) {
+ LOG_WARN("Missing K/V sequence dimensions for Reshape patching");
+ return;
+ }
- // Find the first past value sequence dimension from the map
- // All past value parameters should have the same sequence dimension
- if (past_value_sequence_dims.empty()) {
- LOG_WARN("No past value sequence dimensions provided for reshape patching");
+ // All past K/V parameters in this attention subgraph use the same Concat sequence axis.
+ const auto key_sequence_dim = past_key_sequence_dims.begin()->second;
+ const auto value_sequence_dim = past_value_sequence_dims.begin()->second;
+ for (const auto& pattern : ov::npuw::util::find_all_sdpa_pattern_nodes(model)) {
+ if (!pattern.is_valid()) {
continue;
}
- size_t value_seq_dim = past_value_sequence_dims.begin()->second;
- NPUW_ASSERT(value_seq_dim < shape_values.size());
- shape_values[value_seq_dim] = -1;
-
- auto new_const = std::make_shared<ov::op::v0::Constant>(shape_const->get_element_type(),
- shape_const->get_shape(),
- shape_values);
- op->input(1).replace_source_output(new_const);
+ auto patch_input = [&](const std::shared_ptr<ov::Node>& node, size_t sequence_axis) {
+ const auto matmul = ov::as_type_ptr<ov::op::v0::MatMul>(node);
+ auto current = matmul->input_value(1).get_node_shared_ptr();
+ while (current && !ov::is_type<ov::op::v1::Reshape>(current)) {
+ if (!ov::is_type<ov::op::v1::Transpose>(current) && !ov::is_type<ov::op::v0::Convert>(current) &&
+ !ov::is_type<ov::op::v1::Multiply>(current)) {
+ return;
+ }
+ current = current->input_value(0).get_node_shared_ptr();
+ }
- LOG_INFO("Done");
- return;
+ const auto reshape = ov::as_type_ptr<ov::op::v1::Reshape>(current);
+ if (!reshape) {
+ return;
+ }
+ const auto shape_source = reshape->input_value(1);
+ const auto shape_const = ov::util::get_constant_from_source(shape_source);
+ if (!shape_const) {
+ LOG_WARN("KV Reshape's shape input is not constant-foldable: " << reshape->get_friendly_name());
+ return;
+ }
+ auto shape_values = shape_const->cast_vector<int64_t>();
+ if (sequence_axis >= shape_values.size() ||
+ shape_values[sequence_axis] != static_cast<int64_t>(full_context_length)) {
+ return;
+ }
+ if (std::find(shape_values.begin(), shape_values.end(), -1) != shape_values.end()) {
+ LOG_WARN("KV Reshape already has an inferred dimension: " << reshape->get_friendly_name());
+ return;
+ }
+ shape_values[sequence_axis] = -1;
+ auto new_const = std::make_shared<ov::op::v0::Constant>(shape_source.get_element_type(),
+ shape_const->get_shape(),
+ shape_values);
+ reshape->input(1).replace_source_output(new_const);
+ };
+
+ patch_input(pattern.matmul1_node, key_sequence_dim);
+ patch_input(pattern.matmul2_node, value_sequence_dim);
}
}
diff --git a/src/plugins/intel_npu/src/plugin/npuw/attention.hpp b/src/plugins/intel_npu/src/plugin/npuw/attention.hpp
index bdf3c0a70d2..f199ae5111c 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/attention.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/attention.hpp
@@ -68,9 +68,11 @@ struct Attention {
// Helper function to patch broadcast constants (set to 1 for dynamic handling)
void patch_broadcast_constants(const std::shared_ptr<ov::Model>& model, size_t target_length);
-// Helper function to patch reshape constants (-1 substitution)
+// Preserve inferred K/V sequence dimensions when reshaping an attention context.
void patch_reshape_constants(const std::shared_ptr<ov::Model>& model,
- const std::map<std::string, size_t>& past_value_sequence_dims);
+ const std::map<std::string, size_t>& past_key_sequence_dims,
+ const std::map<std::string, size_t>& past_value_sequence_dims,
+ size_t full_context_length);
} // namespace function
diff --git a/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp b/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp
index bbc57bc1439..4c15af1f72a 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp
@@ -377,13 +377,6 @@ std::optional<PyramidModelResult> process_pyramid_model(const std::shared_ptr<ov
return std::nullopt;
}
- // Capture value Concat axis before shrinking — needed for patch_reshape_constants below.
- int64_t value_concat_axis = 0;
- if (auto vc = std::dynamic_pointer_cast<ov::op::v0::Concat>(cloned_pattern.past_value_concat_node)) {
- const auto& out_shape = vc->get_output_partial_shape(0);
- value_concat_axis = ov::util::try_normalize_axis(vc->get_axis(), out_shape.rank(), *vc);
- }
-
auto shrunk_key = shrink_concat_inputs(cloned_pattern.past_key_concat_node);
auto shrunk_value = shrink_concat_inputs(cloned_pattern.past_value_concat_node);
if (!shrunk_key || !shrunk_value) {
@@ -393,15 +386,27 @@ std::optional<PyramidModelResult> process_pyramid_model(const std::shared_ptr<ov
LOG_DEBUG(" Concat nodes shrunk successfully for model[" << model_idx << "]");
- // Apply the same pre-reshape patching + reshape sequence as the non-block path:
+ // Apply the same pre-reshape patching as the non-block path:
// 1. patch_broadcast_constants — fix Broadcast shape constants referencing full_context_length
- // 2. patch_reshape_constants — set seq dim to -1 in value-path Reshape shape constant
- // (pattern: value_Concat → Reshape → MatMul2 ← Softmax)
- // 3. reshape(new_shapes) — apply mask shape update and propagate all shapes
+ // 2. patch_reshape_constants — use the K/V Concat sequence dimensions
+ // 3. set_partial_shape — apply the mask shape update
// 4. validate_nodes_and_infer_types
+ const auto key_concat = ov::as_type_ptr<ov::op::v0::Concat>(shrunk_key);
+ const auto value_concat = ov::as_type_ptr<ov::op::v0::Concat>(shrunk_value);
+ const auto key_sequence_dim =
+ static_cast<size_t>(ov::util::try_normalize_axis(key_concat->get_axis(),
+ key_concat->get_output_partial_shape(0).rank(),
+ *key_concat));
+ const auto value_sequence_dim =
+ static_cast<size_t>(ov::util::try_normalize_axis(value_concat->get_axis(),
+ value_concat->get_output_partial_shape(0).rank(),
+ *value_concat));
ov::npuw::function::patch_broadcast_constants(cloned_model, full_context_length);
- // The map key is unused by patch_reshape_constants; only the dim-index value matters.
- ov::npuw::function::patch_reshape_constants(cloned_model, {{"", static_cast<size_t>(value_concat_axis)}});
+ // Block mode has no contiguous parameter names; the patcher only uses the map values.
+ ov::npuw::function::patch_reshape_constants(cloned_model,
+ {{"", key_sequence_dim}},
+ {{"", value_sequence_dim}},
+ full_context_length);
// Directly set partial shape on the Parameter node — bypasses reshape() name/pointer
// lookup entirely. reshape(Output<Node>) can silently miss, reshape(string) uses
@@ -523,8 +528,15 @@ std::optional<PyramidModelResult> process_pyramid_model(const std::shared_ptr<ov
}
// Apply pre-reshape patching using helper functions
+ if (past_key_sequence_dims.empty() || past_value_sequence_dims.empty()) {
+ LOG_WARN("Missing K/V sequence dimensions for pyramid model " << model_idx);
+ return std::nullopt;
+ }
ov::npuw::function::patch_broadcast_constants(cloned_model, full_context_length);
- ov::npuw::function::patch_reshape_constants(cloned_model, past_value_sequence_dims);
+ ov::npuw::function::patch_reshape_constants(cloned_model,
+ past_key_sequence_dims,
+ past_value_sequence_dims,
+ full_context_length);
cloned_model->reshape(new_shapes);
cloned_model->validate_nodes_and_infer_types();
diff --git a/src/plugins/intel_npu/tests/unit/npuw/pyramid_attention_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pyramid_attention_test.cpp
index b0acacc2bda..c5ed5308788 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/pyramid_attention_test.cpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/pyramid_attention_test.cpp
@@ -10,6 +10,7 @@
#include <map>
#include <memory>
#include <string>
+#include <utility>
#include <variant>
#include <vector>
@@ -18,12 +19,15 @@
#include "npuw_transformations/convert_kvcache_to_precision.hpp"
#include "npuw_transformations/split_kvcache_into_blocks.hpp"
#include "openvino/op/add.hpp"
+#include "openvino/op/broadcast.hpp"
#include "openvino/op/concat.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/matmul.hpp"
#include "openvino/op/parameter.hpp"
+#include "openvino/op/reshape.hpp"
#include "openvino/op/result.hpp"
#include "openvino/op/softmax.hpp"
+#include "openvino/op/unsqueeze.hpp"
#include "openvino/openvino.hpp"
#include "serialization.hpp"
#include "util.hpp"
@@ -109,6 +113,57 @@ std::shared_ptr<ov::Model> build_isolated_attention_model(const AttentionModelCo
return model;
}
+std::shared_ptr<ov::Model> build_reshaped_attention_model(size_t query_len, size_t past_len, size_t head_dim) {
+ using namespace ov;
+ const size_t context_len = query_len + past_len;
+ auto query = ov::test::utils::make_param(element::f32, Shape{1, 8, query_len, head_dim}, "query.0");
+ auto past_key = ov::test::utils::make_param(element::f32, Shape{1, 2, past_len, head_dim}, "past_key_values.0.key");
+ auto new_key = ov::test::utils::make_param(element::f32, Shape{1, 2, query_len, head_dim}, "new_key.0");
+ auto past_value =
+ ov::test::utils::make_param(element::f32, Shape{1, 2, head_dim, past_len}, "past_key_values.0.value");
+ auto new_value = ov::test::utils::make_param(element::f32, Shape{1, 2, head_dim, query_len}, "new_value.0");
+ auto mask = ov::test::utils::make_param(element::f32, Shape{1, 1, query_len, context_len}, "mask.0");
+
+ auto key_concat = std::make_shared<op::v0::Concat>(OutputVector{past_key, new_key}, 2);
+ auto value_concat = std::make_shared<op::v0::Concat>(OutputVector{past_value, new_value}, 3);
+ auto axis = op::v0::Constant::create(element::i64, Shape{1}, {2});
+ auto key_unsqueeze = std::make_shared<op::v0::Unsqueeze>(key_concat, axis);
+ auto value_unsqueeze = std::make_shared<op::v0::Unsqueeze>(value_concat, axis);
+ auto key_broadcast_shape = op::v0::Constant::create(
+ element::i64,
+ Shape{5},
+ std::vector<int64_t>{1, 2, 4, static_cast<int64_t>(context_len), static_cast<int64_t>(head_dim)});
+ auto value_broadcast_shape = op::v0::Constant::create(
+ element::i32,
+ Shape{5},
+ std::vector<int32_t>{1, 2, 4, static_cast<int32_t>(head_dim), static_cast<int32_t>(context_len)});
+ auto key_broadcast =
+ std::make_shared<op::v3::Broadcast>(key_unsqueeze, key_broadcast_shape, op::BroadcastType::BIDIRECTIONAL);
+ auto value_broadcast =
+ std::make_shared<op::v3::Broadcast>(value_unsqueeze, value_broadcast_shape, op::BroadcastType::BIDIRECTIONAL);
+ auto key_shape = op::v0::Constant::create(
+ element::i64,
+ Shape{4},
+ std::vector<int64_t>{1, 8, static_cast<int64_t>(context_len), static_cast<int64_t>(head_dim)});
+ auto value_shape = op::v0::Constant::create(
+ element::i32,
+ Shape{4},
+ std::vector<int32_t>{1, 8, static_cast<int32_t>(head_dim), static_cast<int32_t>(context_len)});
+ auto key_reshape = std::make_shared<op::v1::Reshape>(key_broadcast, key_shape, false);
+ auto value_reshape = std::make_shared<op::v1::Reshape>(value_broadcast, value_shape, false);
+ key_reshape->set_friendly_name("key_reshape");
+ value_reshape->set_friendly_name("value_reshape");
+
+ auto qk = std::make_shared<op::v0::MatMul>(query, key_reshape, false, true);
+ auto add = std::make_shared<op::v1::Add>(qk, mask);
+ auto softmax = std::make_shared<op::v8::Softmax>(add, 3);
+ auto attention = std::make_shared<op::v0::MatMul>(softmax, value_reshape, false, true);
+ auto model = std::make_shared<Model>(ResultVector{std::make_shared<op::v0::Result>(attention)},
+ ParameterVector{query, past_key, new_key, past_value, new_value, mask});
+ model->validate_nodes_and_infer_types();
+ return model;
+}
+
// Helper function to extract contiguous result from validation variant
const ov::npuw::function::PyramidValidationContiguousResult& get_contiguous_result(
const ov::npuw::function::PyramidValidationResult& validation) {
@@ -122,10 +177,11 @@ const ov::npuw::function::PyramidValidationBlockResult& get_block_result(
}
// Helper function to apply SplitKVCacheIntoBlocks transformation
std::shared_ptr<ov::Model> apply_split_kvcache_into_blocks(const std::shared_ptr<ov::Model>& model,
- uint32_t block_size = 32) {
+ uint32_t block_size = 32,
+ bool v_transposed = false) {
auto cloned = model->clone();
- // Use v_transposed=false to match test model structure where both key and value use axis 2
- ov::npuw::pass::SplitKVCacheIntoBlocks(block_size, false).run_on_model(cloned);
+ // Most existing test models use axis 2 for both K and V; transposed-V fixtures pass true.
+ ov::npuw::pass::SplitKVCacheIntoBlocks(block_size, v_transposed).run_on_model(cloned);
return cloned;
}
// --- Tests for validate_and_setup_pyramid_attention (Contiguous KV Cache) ---
@@ -332,6 +388,91 @@ TEST(PyramidAttentionTest, ProcessPyramidModelSucceedsForPrefillCase) {
}
}
+TEST(PyramidAttentionTest, PrefillSpecializesBothKVReshapeSequenceAxes) {
+ for (const auto& [query_len, past_len] : {std::pair<size_t, size_t>{64, 128}, {128, 128}}) {
+ const size_t full_context = query_len + past_len;
+ SCOPED_TRACE("full context: " + std::to_string(full_context));
+ auto model = build_reshaped_attention_model(query_len, past_len, full_context);
+ auto validation = ov::npuw::function::validate_and_setup_pyramid_attention(model);
+ ASSERT_TRUE(validation.has_value());
+ const auto& info = get_contiguous_result(*validation);
+
+ auto variant = ov::npuw::function::process_pyramid_model(model,
+ 0,
+ query_len,
+ info.query_length,
+ info.past_kv_length,
+ info.full_context_length,
+ info.past_key_sequence_dims,
+ info.past_value_sequence_dims);
+ ASSERT_TRUE(variant.has_value());
+ EXPECT_EQ(variant->model->output(0).get_shape(), (ov::Shape{1, 8, query_len, full_context}));
+ size_t patched_reshapes = 0;
+ for (const auto& op : variant->model->get_ordered_ops()) {
+ auto reshape = ov::as_type_ptr<ov::op::v1::Reshape>(op);
+ if (!reshape) {
+ continue;
+ }
+ if (reshape->get_friendly_name() == "key_reshape") {
+ EXPECT_EQ(reshape->get_output_shape(0), (ov::Shape{1, 8, query_len, full_context}));
+ ++patched_reshapes;
+ } else if (reshape->get_friendly_name() == "value_reshape") {
+ EXPECT_EQ(reshape->get_output_shape(0), (ov::Shape{1, 8, full_context, query_len}));
+ ++patched_reshapes;
+ }
+ }
+ EXPECT_EQ(patched_reshapes, 2u);
+ }
+}
+
+TEST(PyramidAttentionTest, BlockPrefillSpecializesBothKVReshapeSequenceAxes) {
+ constexpr size_t query_len = 64;
+ constexpr size_t past_len = 128;
+ constexpr size_t head_dim = 16;
+ constexpr size_t block_size = query_len;
+ constexpr size_t expected_context_length = 2 * query_len;
+
+ auto model = build_reshaped_attention_model(query_len, past_len, head_dim);
+ // V is stored as [B, H, D, S], so its sequence axis is 3 in this fixture.
+ auto block_model = apply_split_kvcache_into_blocks(model, block_size, /*v_transposed=*/true);
+
+ auto validation = ov::npuw::function::validate_and_setup_pyramid_attention(block_model);
+ ASSERT_TRUE(validation.has_value());
+ const auto& info = get_block_result(*validation);
+ ASSERT_EQ(info.query_length, query_len);
+ ASSERT_EQ(info.past_kv_length, past_len);
+ ASSERT_EQ(info.full_context_length, query_len + past_len);
+
+ // Variant 1 retains one 64-token past block and the 64-token present KV.
+ auto variant = ov::npuw::function::process_pyramid_model(block_model,
+ 1,
+ block_size,
+ info.query_length,
+ info.past_kv_length,
+ info.full_context_length,
+ {},
+ {},
+ true);
+ ASSERT_TRUE(variant.has_value());
+ EXPECT_EQ(variant->attention.context_len(), expected_context_length);
+
+ size_t patched_reshapes = 0;
+ for (const auto& op : variant->model->get_ordered_ops()) {
+ auto reshape = ov::as_type_ptr<ov::op::v1::Reshape>(op);
+ if (!reshape) {
+ continue;
+ }
+ if (reshape->get_friendly_name() == "key_reshape") {
+ EXPECT_EQ(reshape->get_output_shape(0), (ov::Shape{1, 8, expected_context_length, head_dim}));
+ ++patched_reshapes;
+ } else if (reshape->get_friendly_name() == "value_reshape") {
+ EXPECT_EQ(reshape->get_output_shape(0), (ov::Shape{1, 8, head_dim, expected_context_length}));
+ ++patched_reshapes;
+ }
+ }
+ EXPECT_EQ(patched_reshapes, 2u);
+}
+
TEST(PyramidAttentionTest, ProcessPyramidModelProducesCorrectAttentionInfo) {
AttentionModelConfig cfg;
cfg.query_len = 1;