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 SplitKVCacheIntoBlocks model transformation. (#35012)
intelgaoxiong424fe81a89f1
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/split_kvcache_into_blocks.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/split_kvcache_into_blocks.cppnew file mode 100644index 00000000000..ba0b2228b27--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/split_kvcache_into_blocks.cpp@@ -0,0 +1,213 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "split_kvcache_into_blocks.hpp"++#include <vector>++#include "../logging.hpp"+#include "../util.hpp"+#include "openvino/core/graph_util.hpp"+#include "openvino/core/node.hpp"+#include "openvino/core/rt_info.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/parameter.hpp"++namespace ov {+namespace npuw {+namespace pass {++namespace {++// Information collected in the scan phase; all fields are pre-computed so the+// transform phase never needs to re-query the parameter name.+struct KVCacheTransformInfo {+ std::shared_ptr<ov::op::v0::Parameter> param;+ std::shared_ptr<ov::op::v0::Concat> concat;+ ov::Output<ov::Node> present_kv_input;+ std::shared_ptr<ov::Node> convert_node; // nullptr when Parameter→Concat directly+ bool is_key; // true = K tensor+ bool is_value; // true = V tensor+ int64_t concat_axis; // sequence dimension index in the concat+};++// Walk a parameter's consumers to find the Concat it feeds (directly or via Convert).+// Returns {concat, convert_node}; concat is nullptr if the pattern is not found.+std::pair<std::shared_ptr<ov::op::v0::Concat>, std::shared_ptr<ov::Node>> find_concat_for_param(+ const std::shared_ptr<ov::op::v0::Parameter>& param) {+ for (const auto& output : param->outputs()) {+ for (const auto& target : output.get_target_inputs()) {+ auto node = target.get_node()->shared_from_this();+ if (auto concat = ov::as_type_ptr<ov::op::v0::Concat>(node)) {+ return {concat, nullptr};+ }+ if (ov::is_type<ov::op::v0::Convert>(node)) {+ for (const auto& cvt_out : node->outputs()) {+ for (const auto& cvt_target : cvt_out.get_target_inputs()) {+ auto next = cvt_target.get_node()->shared_from_this();+ if (auto concat = ov::as_type_ptr<ov::op::v0::Concat>(next)) {+ return {concat, node};+ }+ }+ }+ }+ }+ }+ return {nullptr, nullptr};+}++// Build a 4D block shape. seq_dim is the axis holding the sequence (2 or 3);+// all other dims are copied from orig_shape.+ov::Shape make_block_shape(const ov::PartialShape& orig_shape, int64_t seq_dim, size_t seq_size) {+ ov::Shape s(4);+ for (int i = 0; i < 4; ++i) {+ s[i] = (i == seq_dim) ? seq_size : static_cast<size_t>(orig_shape[i].get_length());+ }+ return s;+}++} // namespace++SplitKVCacheIntoBlocks::SplitKVCacheIntoBlocks(uint32_t block_size, bool v_transposed)+ : m_block_size(block_size),+ m_v_transposed(v_transposed) {}++bool SplitKVCacheIntoBlocks::run_on_model(const std::shared_ptr<ov::Model>& model) {+ bool model_changed = false;++ // --- Phase 1: Scan — collect parameters that need to be split ----------+ std::vector<KVCacheTransformInfo> params_to_transform;++ for (const auto& param : model->get_parameters()) {+ const std::string& name = param->get_friendly_name();++ const bool is_key = ov::npuw::util::isPastKeyValuesKeyContiguous(name).has_value();+ const bool is_value = ov::npuw::util::isPastKeyValuesValueContiguous(name).has_value();+ if (!is_key && !is_value) {+ continue; // not a contiguous KV cache parameter+ }++ // Shape must be 4D and fully static before we can proceed.+ const auto& orig_shape = param->get_partial_shape();+ if (orig_shape.rank().is_dynamic() || orig_shape.rank().get_length() != 4) {+ LOG_WARN("SplitKVCacheIntoBlocks: Skipping " << name << " — expected 4D shape, got " << orig_shape);+ continue;+ }+ if (!orig_shape[0].is_static() || !orig_shape[1].is_static() || !orig_shape[2].is_static() ||+ !orig_shape[3].is_static()) {+ LOG_WARN("SplitKVCacheIntoBlocks: Skipping " << name << " — dynamic dimensions not supported");+ continue;+ }++ // Locate the Concat this parameter feeds (directly or via Convert).+ auto [concat, convert_node] = find_concat_for_param(param);+ if (!concat) {+ continue;+ }++ // Locate the "present_kv" input — the non-param input of the Concat.+ ov::Output<ov::Node> present_kv_input;+ bool found = false;+ for (size_t i = 0; i < concat->get_input_size(); ++i) {+ auto src = concat->input(i).get_source_output().get_node_shared_ptr();+ bool from_param = (src == param) || (ov::is_type<ov::op::v0::Convert>(src) &&+ src->input(0).get_source_output().get_node_shared_ptr() == param);+ if (!from_param) {+ present_kv_input = concat->input(i).get_source_output();+ found = true;+ break;+ }+ }+ if (!found) {+ continue;+ }++ // Pre-compute the concat axis (sequence dimension) once.+ const int64_t concat_axis = (is_key || (is_value && !m_v_transposed)) ? 2 : 3;++ params_to_transform.push_back({param, concat, present_kv_input, convert_node, is_key, is_value, concat_axis});+ }++ // --- Phase 2: Transform — replace each collected parameter with blocks --+ for (auto& info : params_to_transform) {+ auto& param = info.param;+ auto& concat = info.concat;++ const auto& orig_shape = param->get_partial_shape();+ const int64_t seq_len = orig_shape[info.concat_axis].get_length();+ const uint32_t num_full_blocks = static_cast<uint32_t>(seq_len) / m_block_size;+ const uint32_t tail_size = static_cast<uint32_t>(seq_len) % m_block_size;+ const uint32_t total_blocks = num_full_blocks + (tail_size > 0 ? 1 : 0);++ LOG_INFO("SplitKVCacheIntoBlocks: Transforming " << param->get_friendly_name() << " shape=" << orig_shape+ << " → " << total_blocks << " blocks (tail=" << tail_size+ << ")");++ // Build block Parameter nodes.+ ov::OutputVector block_outputs;+ std::vector<std::shared_ptr<ov::op::v0::Parameter>> new_params;+ block_outputs.reserve(total_blocks);+ new_params.reserve(total_blocks);++ auto make_block_param = [&](const std::string& suffix, size_t seq_size) {+ auto block_shape = make_block_shape(orig_shape, info.concat_axis, seq_size);+ auto p = std::make_shared<ov::op::v0::Parameter>(param->get_element_type(), block_shape);+ const std::string block_name = param->get_friendly_name() + suffix;+ p->set_friendly_name(block_name);+ p->output(0).set_names({block_name});+ return p;+ };++ for (uint32_t i = 0; i < num_full_blocks; ++i) {+ new_params.push_back(make_block_param("_block_" + std::to_string(i), m_block_size));+ block_outputs.push_back(new_params.back());+ }+ if (tail_size > 0) {+ new_params.push_back(make_block_param("_block_tail", tail_size));+ block_outputs.push_back(new_params.back());+ }++ model->add_parameters(new_params);++ // If the original path had a Convert, insert one after each block param.+ ov::OutputVector inputs_for_concat;+ inputs_for_concat.reserve(total_blocks + 1);++ if (info.convert_node) {+ const auto target_type = info.convert_node->get_output_element_type(0);+ for (const auto& blk : block_outputs) {+ auto cvt = std::make_shared<ov::op::v0::Convert>(blk, target_type);+ cvt->set_friendly_name(blk.get_node()->get_friendly_name() + "_convert");+ inputs_for_concat.push_back(cvt);+ }+ } else {+ inputs_for_concat = block_outputs;+ }+ inputs_for_concat.push_back(info.present_kv_input);++ // Replace the old Concat.+ auto new_concat = std::make_shared<ov::op::v0::Concat>(inputs_for_concat, info.concat_axis);+ new_concat->set_friendly_name(concat->get_friendly_name());++ ov::NodeVector new_nodes{new_concat};+ for (const auto& p : new_params) {+ new_nodes.push_back(p);+ }+ copy_runtime_info({param, concat}, new_nodes);++ concat->output(0).replace(new_concat->output(0));+ model->remove_parameter(param);++ LOG_DEBUG("SplitKVCacheIntoBlocks: new concat shape " << new_concat->get_output_partial_shape(0));++ model_changed = true;+ }++ return model_changed;+}++} // namespace pass+} // namespace npuw+} // namespace ovdiff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/split_kvcache_into_blocks.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/split_kvcache_into_blocks.hppnew file mode 100644index 00000000000..9126614e489--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/split_kvcache_into_blocks.hpp@@ -0,0 +1,73 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/pass.hpp"++namespace ov {+namespace npuw {+namespace pass {++/**+ * @brief Transformation pass to split KV cache access into block-based pattern+ *+ * This pass identifies KV cache parameters in the model and transforms their access+ * pattern from continuous memory (batch, num_heads, seq_len, head_dim) to block-based+ * layout (num_blocks, batch, num_heads, block_size, head_dim).+ *+ * Transformation pattern:+ * Before:+ * Parameter(past_key) [1, 32, 2048, 128] \+ * Parameter(present_key) [1, 32, 1, 128] |-> Concat(axis=2) -> SDPA+ *+ * Parameter(past_value) [1, 32, 128, 2048] \+ * Parameter(present_value)[1, 32, 128, 1] |-> Concat(axis=3) -> SDPA (if v_transposed=true)+ *+ * After (block_size=1024, seq_len=2048):+ * Parameter(past_key_block_0) [1, 32, 1024, 128] \+ * Parameter(past_key_block_1) [1, 32, 1024, 128] |+ * Parameter(present_key) [1, 32, 1, 128] |-> Concat(axis=2) -> SDPA+ *+ * Parameter(past_value_block_0) [1, 32, 128, 1024] \+ * Parameter(past_value_block_1) [1, 32, 128, 1024] |+ * Parameter(present_value) [1, 32, 128, 1] |-> Concat(axis=3) -> SDPA (if v_transposed=true)+ *+ * Note: Number of blocks is auto-calculated from original seq_len and block_size.+ * If seq_len % block_size != 0, a tail block with remaining tokens is created.+ *+ * Benefits:+ * - Reduces memory allocation (only allocate needed blocks)+ * - Enables memory sharing across sequences+ * - Improves memory locality for attention operations+ *+ * Note: This transformation is applied to both prefill and generate (decode) models+ * where KV cache parameters are identified by naming convention+ * (e.g., "past_key", "past_value", "past_key_values.X.key", "past_key_values.X.value").+ */+class SplitKVCacheIntoBlocks : public ov::pass::ModelPass {+public:+ OPENVINO_RTTI("ov::npuw::pass::SplitKVCacheIntoBlocks", "0");++ /**+ * @brief Construct transformation with block configuration+ *+ * @param block_size Number of tokens per block (default: 1024 for efficiency)+ * @param v_transposed Whether V tensor is transposed (true: [B,H,D,S], false: [B,H,S,D])+ *+ * The number of blocks is automatically calculated from the original past_key shape.+ * If the sequence length is not evenly divisible by block_size, a tail block is created.+ */+ explicit SplitKVCacheIntoBlocks(uint32_t block_size = 1024, bool v_transposed = true);++ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;++private:+ uint32_t m_block_size;+ bool m_v_transposed;+};++} // namespace pass+} // namespace npuw+} // namespace ovdiff --git a/src/plugins/intel_npu/src/plugin/npuw/util.cpp b/src/plugins/intel_npu/src/plugin/npuw/util.cppindex 13fa215954f..ec4faddbd5d 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util.cpp@@ -919,7 +919,22 @@ void ov::npuw::util::fill_tensor_bytes(ov::SoPtr<ov::ITensor> tensor, uint8_t fistd::memset(tensor_data, fill_val, byte_size);}-std::optional<int> ov::npuw::util::isPastKeyValuesKey(const std::string& str) {+bool ov::npuw::util::isPastKeyParam(const std::string& str) {+ // Match any past key param: contiguous or block-split (e.g. key_block_3, key_block_tail).+ static const std::regex pattern(R"(past_key_values\.\d+\.key(_block_(\d+|tail))?)");+ return std::regex_match(str, pattern);+}++bool ov::npuw::util::isPastValueParam(const std::string& str) {+ // Match any past value param: contiguous or block-split.+ static const std::regex pattern(R"(past_key_values\.\d+\.value(_block_(\d+|tail))?)");+ return std::regex_match(str, pattern);+}++std::optional<int> ov::npuw::util::isPastKeyValuesKeyContiguous(const std::string& str) {+ // Match only the single contiguous past key param (no _block_ suffix).+ // Allows optional intermediate parts like "encoder" or "decoder" (for Whisper).+ // Returns the layer index if matched.std::regex pattern(R"(past_key_values\.(\d+)(?:\.[^.]+)*\.key)");std::smatch match;if (std::regex_match(str, match, pattern)) {@@ -929,7 +944,10 @@ std::optional<int> ov::npuw::util::isPastKeyValuesKey(const std::string& str) {return std::nullopt;}-std::optional<int> ov::npuw::util::isPastKeyValuesValue(const std::string& str) {+std::optional<int> ov::npuw::util::isPastKeyValuesValueContiguous(const std::string& str) {+ // Match only the single contiguous past value param (no _block_ suffix).+ // Allows optional intermediate parts like "encoder" or "decoder" (for Whisper).+ // Returns the layer index if matched.std::regex pattern(R"(past_key_values\.(\d+)(?:\.[^.]+)*\.value)");std::smatch match;if (std::regex_match(str, match, pattern)) {@@ -1073,4 +1091,4 @@ ov::npuw::util::SDPAPatternNodes ov::npuw::util::find_sdpa_pattern_nodes(const sreturn {};}return internal_nodes.front();-}\ No newline at end of file+}diff --git a/src/plugins/intel_npu/src/plugin/npuw/util.hpp b/src/plugins/intel_npu/src/plugin/npuw/util.hppindex b800a14d477..d5359e0aa39 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util.hpp@@ -275,11 +275,28 @@ private:mutable bool done = false;};-std::optional<int> isPastKeyValuesKey(const std::string& str);-std::optional<int> isPastKeyValuesValue(const std::string& str);+// Matches only the contiguous (non-block-split) past key param. Returns the layer index if matched.+std::optional<int> isPastKeyValuesKeyContiguous(const std::string& str);+// Matches only the contiguous (non-block-split) past value param. Returns the layer index if matched.+std::optional<int> isPastKeyValuesValueContiguous(const std::string& str);++// Backward compatibility: Alias for isPastKeyValuesKeyContiguous+inline std::optional<int> isPastKeyValuesKey(const std::string& str) {+ return isPastKeyValuesKeyContiguous(str);+}+// Backward compatibility: Alias for isPastKeyValuesValueContiguous+inline std::optional<int> isPastKeyValuesValue(const std::string& str) {+ return isPastKeyValuesValueContiguous(str);+}+std::optional<int> isPresentKeyValuesKey(const std::string& str);std::optional<int> isPresentKeyValuesValue(const std::string& str);+// Matches any past key param: contiguous (past_key_values.N.key) or block-split (key_block_M).+bool isPastKeyParam(const std::string& str);+// Matches any past value param: contiguous or block-split.+bool isPastValueParam(const std::string& str);+} // namespace util} // namespace npuw} // namespace ovdiff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex da124833203..cc80704c97e 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -67,6 +67,7 @@ ov_add_test_target(${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/v1/elements/accuracy_checked.cpp${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/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/split_kvcache_into_blocks_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/split_kvcache_into_blocks_test.cppnew file mode 100644index 00000000000..6c31aed9cf8--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/split_kvcache_into_blocks_test.cpp@@ -0,0 +1,413 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "npuw_transformations/split_kvcache_into_blocks.hpp"++#include <gtest/gtest.h>++#include "openvino/op/concat.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/result.hpp"+#include "openvino/pass/manager.hpp"++using namespace ov;+using namespace ov::npuw::pass;++class SplitKVCacheIntoBlocksTest : public ::testing::Test {+protected:+ void SetUp() override {+ // Common test setup+ }++ // Helper: Create a simple model with KV cache parameter -> Concat+ std::shared_ptr<ov::Model> create_kv_cache_model(const std::string& param_name,+ const ov::Shape& shape,+ int64_t concat_axis) {+ // Create KV cache parameter+ auto kv_param = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, shape);+ kv_param->set_friendly_name(param_name);++ // Create new token parameter (to concatenate with)+ ov::Shape new_token_shape = shape;+ new_token_shape[concat_axis] = 1; // Single token+ auto new_token = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, new_token_shape);+ new_token->set_friendly_name("new_token");++ // Create Concat+ auto concat = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{kv_param, new_token}, concat_axis);++ // Create Result+ auto result = std::make_shared<ov::op::v0::Result>(concat);++ return std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{kv_param, new_token});+ }+};++TEST_F(SplitKVCacheIntoBlocksTest, TransformKeyParameter) {+ // Test: Transform past_key parameter with axis=2+ // Original: past_key [1, 32, 64, 128] + new_token [1, 32, 1, 128]+ // After: 4 blocks of 16 tokens each + new_token+ const uint32_t block_size = 16;+ const ov::Shape orig_shape{1, 32, 64, 128}; // [B, H, S=64, D]+ const uint32_t expected_blocks = 64 / block_size; // 4 blocks++ auto model = create_kv_cache_model("past_key_values.0.key", orig_shape, 2);++ // Apply transformation (max_blocks removed, auto-calculated from shape)+ ov::pass::Manager manager;+ manager.register_pass<SplitKVCacheIntoBlocks>(block_size, true);+ manager.run_passes(model);++ // Verify: Should have expected_blocks + 1 parameters (blocks + new_token)+ EXPECT_EQ(model->get_parameters().size(), expected_blocks + 1);++ // Verify: Each block parameter has correct shape [1, 32, 16, 128]+ uint32_t block_count = 0;+ for (const auto& param : model->get_parameters()) {+ if (param->get_friendly_name().find("_block_") != std::string::npos) {+ block_count++;+ auto block_shape = param->get_shape();+ EXPECT_EQ(block_shape[0], 1); // batch+ EXPECT_EQ(block_shape[1], 32); // num_heads+ EXPECT_EQ(block_shape[2], block_size); // block_size+ EXPECT_EQ(block_shape[3], 128); // head_dim+ }+ }+ EXPECT_EQ(block_count, expected_blocks);++ // Verify: Concat has blocks + new_token input (CRITICAL: present_key preserved!)+ bool found_concat = false;+ for (const auto& op : model->get_ops()) {+ if (ov::is_type<ov::op::v0::Concat>(op)) {+ found_concat = true;+ auto concat = ov::as_type_ptr<ov::op::v0::Concat>(op);+ EXPECT_EQ(concat->get_axis(), 2);+ EXPECT_EQ(concat->get_input_size(), expected_blocks + 1); // blocks + present_key+ }+ }+ EXPECT_TRUE(found_concat);+}++TEST_F(SplitKVCacheIntoBlocksTest, TransformValueParameterTransposed) {+ // Test: Transform past_value parameter with v_transposed=true (axis=3)+ const uint32_t block_size = 16;+ const ov::Shape orig_shape{1, 32, 128, 64}; // [B, H, D, S] - transposed++ auto model = create_kv_cache_model("past_key_values.0.value", orig_shape, 3);++ // Apply transformation with v_transposed=true+ ov::pass::Manager manager;+ manager.register_pass<SplitKVCacheIntoBlocks>(block_size, true);+ manager.run_passes(model);++ const uint32_t expected_blocks = 64 / block_size; // 4 blocks++ // Verify: Block parameters have correct shape [1, 32, 128, 16]+ uint32_t block_count = 0;+ for (const auto& param : model->get_parameters()) {+ if (param->get_friendly_name().find("_block_") != std::string::npos) {+ block_count++;+ auto block_shape = param->get_shape();+ EXPECT_EQ(block_shape[0], 1); // batch+ EXPECT_EQ(block_shape[1], 32); // num_heads+ EXPECT_EQ(block_shape[2], 128); // head_dim+ EXPECT_EQ(block_shape[3], block_size); // block_size+ }+ }+ EXPECT_EQ(block_count, expected_blocks);++ // Verify: Concat axis=3 and has blocks + present_value+ for (const auto& op : model->get_ops()) {+ if (ov::is_type<ov::op::v0::Concat>(op)) {+ auto concat = ov::as_type_ptr<ov::op::v0::Concat>(op);+ EXPECT_EQ(concat->get_axis(), 3);+ EXPECT_EQ(concat->get_input_size(), expected_blocks + 1);+ }+ }+}++TEST_F(SplitKVCacheIntoBlocksTest, TransformValueParameterNotTransposed) {+ // Test: Transform past_value parameter with v_transposed=false (axis=2)+ const uint32_t block_size = 16;+ const ov::Shape orig_shape{1, 32, 64, 128}; // [B, H, S, D] - same as K++ auto model = create_kv_cache_model("past_key_values.0.value", orig_shape, 2);++ // Apply transformation with v_transposed=false+ ov::pass::Manager manager;+ manager.register_pass<SplitKVCacheIntoBlocks>(block_size, false);+ manager.run_passes(model);++ const uint32_t expected_blocks = 64 / block_size; // 4 blocks++ // Verify: Block parameters have correct shape [1, 32, 16, 128]+ uint32_t block_count = 0;+ for (const auto& param : model->get_parameters()) {+ if (param->get_friendly_name().find("_block_") != std::string::npos) {+ block_count++;+ auto block_shape = param->get_shape();+ EXPECT_EQ(block_shape[0], 1); // batch+ EXPECT_EQ(block_shape[1], 32); // num_heads+ EXPECT_EQ(block_shape[2], block_size); // block_size (at axis=2)+ EXPECT_EQ(block_shape[3], 128); // head_dim+ }+ }+ EXPECT_EQ(block_count, expected_blocks);++ // Verify: Concat axis=2 (same as K) and has blocks + present_value+ for (const auto& op : model->get_ops()) {+ if (ov::is_type<ov::op::v0::Concat>(op)) {+ auto concat = ov::as_type_ptr<ov::op::v0::Concat>(op);+ EXPECT_EQ(concat->get_axis(), 2);+ EXPECT_EQ(concat->get_input_size(), expected_blocks + 1);+ }+ }+}++TEST_F(SplitKVCacheIntoBlocksTest, AlternativeNaming) {+ // Test: Transform past_key_values.0.key naming convention+ const uint32_t block_size = 16;+ const ov::Shape orig_shape{1, 32, 64, 128};++ auto model = create_kv_cache_model("past_key_values.0.key", orig_shape, 2);++ const uint32_t expected_blocks = 64 / block_size; // 4 blocks++ // Apply transformation+ ov::pass::Manager manager;+ manager.register_pass<SplitKVCacheIntoBlocks>(block_size, true);+ manager.run_passes(model);++ // Verify: Should have transformed+ EXPECT_EQ(model->get_parameters().size(), expected_blocks + 1);++ bool found_blocks = false;+ for (const auto& param : model->get_parameters()) {+ if (param->get_friendly_name().find("_block_") != std::string::npos) {+ found_blocks = true;+ }+ }+ EXPECT_TRUE(found_blocks);+}++TEST_F(SplitKVCacheIntoBlocksTest, SkipNonKVCacheParameter) {+ // Test: Should NOT transform non-KV cache parameters+ const uint32_t block_size = 16;+ const ov::Shape orig_shape{1, 32, 64, 128};++ auto model = create_kv_cache_model("hidden_states", orig_shape, 2);++ size_t orig_param_count = model->get_parameters().size();++ // Apply transformation+ ov::pass::Manager manager;+ manager.register_pass<SplitKVCacheIntoBlocks>(block_size, true);+ manager.run_passes(model);++ // Verify: Parameter count unchanged (not transformed)+ EXPECT_EQ(model->get_parameters().size(), orig_param_count);++ // Verify: No block parameters created+ for (const auto& param : model->get_parameters()) {+ EXPECT_EQ(param->get_friendly_name().find("_block_"), std::string::npos);+ }+}++TEST_F(SplitKVCacheIntoBlocksTest, InvalidRank) {+ // Test: Should skip parameters with invalid rank (not 4D)+ const uint32_t block_size = 16;+ const ov::Shape invalid_shape{1, 32, 64}; // 3D instead of 4D++ auto kv_param = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, invalid_shape);+ kv_param->set_friendly_name("past_key.0");++ ov::Shape new_token_shape{1, 32, 1};+ auto new_token = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, new_token_shape);++ auto concat = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{kv_param, new_token}, 2);+ auto result = std::make_shared<ov::op::v0::Result>(concat);+ auto model = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{kv_param, new_token});++ size_t orig_param_count = model->get_parameters().size();++ // Apply transformation+ ov::pass::Manager manager;+ manager.register_pass<SplitKVCacheIntoBlocks>(block_size, true);+ manager.run_passes(model);++ // Verify: Not transformed due to invalid rank+ EXPECT_EQ(model->get_parameters().size(), orig_param_count);+}++TEST_F(SplitKVCacheIntoBlocksTest, MultipleKVParameters) {+ // Test: Transform multiple KV cache parameters in one model+ const uint32_t block_size = 16;+ const uint32_t expected_blocks = 64 / block_size; // 4 blocks per parameter++ // Create model with both past_key and past_value+ auto key_param = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 32, 64, 128});+ key_param->set_friendly_name("past_key_values.0.key");++ auto value_param = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 32, 128, 64});+ value_param->set_friendly_name("past_key_values.0.value");++ auto new_k = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 32, 1, 128});+ auto new_v = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 32, 128, 1});++ auto concat_k = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{key_param, new_k}, 2);+ auto concat_v = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{value_param, new_v}, 3);++ auto result_k = std::make_shared<ov::op::v0::Result>(concat_k);+ auto result_v = std::make_shared<ov::op::v0::Result>(concat_v);++ auto model = std::make_shared<ov::Model>(ov::ResultVector{result_k, result_v},+ ov::ParameterVector{key_param, value_param, new_k, new_v});++ // Apply transformation+ ov::pass::Manager manager;+ manager.register_pass<SplitKVCacheIntoBlocks>(block_size, true);+ manager.run_passes(model);++ // Verify: Should have (expected_blocks * 2) + 2 parameters (K blocks + V blocks + new_k + new_v)+ EXPECT_EQ(model->get_parameters().size(), (expected_blocks * 2) + 2);++ // Count block parameters+ size_t key_blocks = 0, value_blocks = 0;+ for (const auto& param : model->get_parameters()) {+ if (param->get_friendly_name().find(".key") != std::string::npos &&+ param->get_friendly_name().find("_block_") != std::string::npos) {+ key_blocks++;+ }+ if (param->get_friendly_name().find(".value") != std::string::npos &&+ param->get_friendly_name().find("_block_") != std::string::npos) {+ value_blocks++;+ }+ }++ EXPECT_EQ(key_blocks, expected_blocks);+ EXPECT_EQ(value_blocks, expected_blocks);+}++TEST_F(SplitKVCacheIntoBlocksTest, TailBlockHandling) {+ // Test: Handle non-evenly divisible seq_len (creates tail block)+ // seq_len=70, block_size=16 -> 4 full blocks (64 tokens) + 1 tail block (6 tokens)+ const uint32_t block_size = 16;+ const ov::Shape orig_shape{1, 32, 70, 128}; // [B, H, S=70, D]+ const uint32_t expected_full_blocks = 70 / block_size; // 4+ const uint32_t expected_tail_size = 70 % block_size; // 6+ const uint32_t expected_total_blocks = expected_full_blocks + (expected_tail_size > 0 ? 1 : 0); // 5++ auto model = create_kv_cache_model("past_key_values.0.key", orig_shape, 2);++ // Apply transformation+ ov::pass::Manager manager;+ manager.register_pass<SplitKVCacheIntoBlocks>(block_size, true);+ manager.run_passes(model);++ // Verify: Should have 5 block parameters + 1 new_token = 6 total+ EXPECT_EQ(model->get_parameters().size(), expected_total_blocks + 1);++ // Verify: 4 full blocks + 1 tail block+ uint32_t full_block_count = 0;+ bool found_tail_block = false;+ for (const auto& param : model->get_parameters()) {+ if (param->get_friendly_name().find("_block_tail") != std::string::npos) {+ found_tail_block = true;+ auto tail_shape = param->get_shape();+ EXPECT_EQ(tail_shape[2], expected_tail_size); // tail block has 6 tokens+ } else if (param->get_friendly_name().find("_block_") != std::string::npos) {+ full_block_count++;+ auto block_shape = param->get_shape();+ EXPECT_EQ(block_shape[2], block_size); // full block has 16 tokens+ }+ }+ EXPECT_EQ(full_block_count, expected_full_blocks);+ EXPECT_TRUE(found_tail_block);++ // Verify: Concat has all blocks + present_key+ for (const auto& op : model->get_ops()) {+ if (ov::is_type<ov::op::v0::Concat>(op)) {+ auto concat = ov::as_type_ptr<ov::op::v0::Concat>(op);+ EXPECT_EQ(concat->get_input_size(), expected_total_blocks + 1); // 5 blocks + present_key+ }+ }+}++TEST_F(SplitKVCacheIntoBlocksTest, WithConvertNode) {+ // Test: Transform KV cache with Convert node between Parameter and Concat+ // Pattern: Parameter(f16) -> Convert(f32) -> Concat+ const uint32_t block_size = 16;+ const ov::Shape orig_shape{1, 32, 64, 128}; // [B, H, S=64, D]++ // Create KV cache parameter+ auto kv_param = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, orig_shape);+ kv_param->set_friendly_name("past_key_values.0.key");++ // Create Convert node (f16 -> f32)+ auto convert = std::make_shared<ov::op::v0::Convert>(kv_param, ov::element::f32);++ // Create new token parameter+ ov::Shape new_token_shape = orig_shape;+ new_token_shape[2] = 1; // Single token+ auto new_token = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, new_token_shape);+ new_token->set_friendly_name("new_token");++ // Create Concat with Convert output and new_token+ auto concat = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{convert, new_token}, 2);++ // Create Result+ auto result = std::make_shared<ov::op::v0::Result>(concat);++ auto model = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{kv_param, new_token});++ // Apply transformation+ ov::pass::Manager manager;+ manager.register_pass<SplitKVCacheIntoBlocks>(block_size, true);+ manager.run_passes(model);++ // Verify: Should have 4 block parameters + 1 new_token+ EXPECT_EQ(model->get_parameters().size(), 5);++ // Verify: Each block parameter should be followed by a Convert node+ uint32_t block_count = 0;+ uint32_t convert_count = 0;+ for (const auto& param : model->get_parameters()) {+ if (param->get_friendly_name().find("_block_") != std::string::npos) {+ block_count++;+ // Check that parameter is f16+ EXPECT_EQ(param->get_element_type(), ov::element::f16);++ // Check that it's followed by a Convert node+ for (const auto& output : param->outputs()) {+ for (const auto& input : output.get_target_inputs()) {+ auto node = input.get_node()->shared_from_this();+ if (ov::is_type<ov::op::v0::Convert>(node)) {+ auto cvt = ov::as_type_ptr<ov::op::v0::Convert>(node);+ EXPECT_EQ(cvt->get_destination_type(), ov::element::f32);+ convert_count++;+ }+ }+ }+ }+ }+ EXPECT_EQ(block_count, 4);+ EXPECT_EQ(convert_count, 4); // Each block should have a Convert++ // Verify: Concat receives f32 inputs from Convert nodes+ bool found_concat = false;+ for (const auto& op : model->get_ops()) {+ if (ov::is_type<ov::op::v0::Concat>(op)) {+ found_concat = true;+ auto concat_node = ov::as_type_ptr<ov::op::v0::Concat>(op);+ EXPECT_EQ(concat_node->get_input_size(), 5); // 4 blocks + new_token++ // Verify all concat inputs are f32+ for (size_t i = 0; i < concat_node->get_input_size(); ++i) {+ EXPECT_EQ(concat_node->get_input_element_type(i), ov::element::f32);+ }+ }+ }+ EXPECT_TRUE(found_concat);+}