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
[CPU] Tree attention (#35352)
yanlan song53582cfa6fc9
diff --git a/docs/articles_en/documentation/openvino-ir-format/operation-sets/operation-specs/internal/pa-kv-reorder.rst b/docs/articles_en/documentation/openvino-ir-format/operation-sets/operation-specs/internal/pa-kv-reorder.rstnew file mode 100644index 00000000000..396f2bac139--- /dev/null+++ b/docs/articles_en/documentation/openvino-ir-format/operation-sets/operation-specs/internal/pa-kv-reorder.rst@@ -0,0 +1,182 @@+.. {#openvino_docs_ops_internal_PaKVReorder}++PaKVReorder+===========++.. meta::+ :description: Learn about PaKVReorder - a key-value cache reordering operation for paged attention in autoregressive models.++**Versioned name**: *PaKVReorder*++**Category**: *Internal*++**Short description**:+The *PaKVReorder* operation reorders tokens within the key-value (KV) cache blocks used by paged attention mechanisms,+enabling efficient token management for speculative decoding after draft token verification+in autoregressive language models.++**Detailed description**++*PaKVReorder* processes paged KV cache blocks by moving tokens from source positions to destination positions+according to the provided update indices. The operation is kv manipulation for speculative decoding, when draft tokens are verified, accepted tokens need to be kept while rejected ones+are discarded, requiring reordering of the KV cache to maintain sequence consistency.++The KV cache may use quantization (by-channel or by-token) for memory efficiency. The operation handles:++- **Non-quantized caches** (fp32, bf16, fp16): Direct memory copy of token embeddings.+- **By-token quantized caches** (u8, u4): Direct copy of quantized data with scale/zero-point parameters.+- **By-channel quantized caches** (u8, u4): Requires dequantization, token movement in float space, and requantization+ with updated per-channel scale/zero-point parameters when the block's data distribution changes.++Signed ``int8`` KV cache is not supported by this operation.++**Paged memory organization**++The KV cache is organized into non-contiguous pages (blocks). Each physical block stores a fixed number of token states+(``block_size``). The memory layout depends on the quantization mode within different plugins.++**Reordering algorithm**++For each update operation ``(src_token_idx, dst_token_idx)``:++1. Convert logical token indices to ``(block_idx, token_in_block)`` pairs.+2. copy operations:++ - **By-channel quantized**: Dequantize entire block → move tokens in float space → requantize with new statistics.+ - **By-token quantized or non-quantized**: Direct data copy within the block. Parameters, if any, should be copied based on how they are stored (interleaved or separate).++.. code-block:: py+ :force:++ # Parallel processing across sequences+ for s in parallel(num_sequences):+ # Get update operations for this sequence+ op_start = block_update_indices_begins[s]+ op_end = block_update_indices_begins[s + 1]++ # Get block mapping for this sequence+ blk_start = block_indices_begins[s]+ blk_end = block_indices_begins[s + 1]+ seq_blocks = block_indices[blk_start:blk_end]++ # Process operations in batches with same (src_block, dst_block) pair+ op_idx = op_start+ while op_idx < op_end:+ src_logical = block_update_indices[op_idx * 2 + 0]+ dst_logical = block_update_indices[op_idx * 2 + 1]++ # Convert to (block, token) pairs+ src_block_local = src_logical // block_size+ dst_block_local = dst_logical // block_size+ src_block = seq_blocks[src_block_local]+ dst_block = seq_blocks[dst_block_local]++ # Collect all operations with same (src_block, dst_block) into batch+ batch_end = op_idx + 1+ while batch_end < op_end:+ next_src = block_update_indices[batch_end * 2 + 0]+ next_dst = block_update_indices[batch_end * 2 + 1]+ next_src_block = seq_blocks[next_src // block_size]+ next_dst_block = seq_blocks[next_dst // block_size]+ if next_src_block != src_block or next_dst_block != dst_block:+ break+ batch_end += 1++ # Process batch: [op_idx, batch_end)+ same_block = (src_block == dst_block)++ # Parallel processing across heads+ for h in parallel(num_kv_heads):+ if by_channel_quantized:+ if same_block:+ # Same block: direct copy without requantization+ for op in range(op_idx, batch_end):+ src_token = block_update_indices[op * 2 + 0] % block_size+ dst_token = block_update_indices[op * 2 + 1] % block_size+ key_cache[src_block, h, dst_token] = key_cache[src_block, h, src_token]+ value_cache[src_block, h, dst_token] = value_cache[src_block, h, src_token]+ else:+ # Cross-block: dequantize dst once, copy all, requantize once+ # Key cache+ dst_block_data = dequantize_by_channel(key_cache[dst_block, h])+ for op in range(op_idx, batch_end):+ src_token = block_update_indices[op * 2 + 0] % block_size+ dst_token = block_update_indices[op * 2 + 1] % block_size+ src_token_data = dequantize_by_channel(key_cache[src_block, h, src_token])+ dst_block_data[dst_token] = src_token_data+ key_cache[dst_block, h] = quantize_by_channel(dst_block_data)++ # Value cache (same process)+ dst_block_data = dequantize_by_channel(value_cache[dst_block, h])+ for op in range(op_idx, batch_end):+ src_token = block_update_indices[op * 2 + 0] % block_size+ dst_token = block_update_indices[op * 2 + 1] % block_size+ src_token_data = dequantize_by_channel(value_cache[src_block, h, src_token])+ dst_block_data[dst_token] = src_token_data+ value_cache[dst_block, h] = quantize_by_channel(dst_block_data)+ else:+ # Non-by-channel: direct copy for all operations in batch+ for op in range(op_idx, batch_end):+ src_token = block_update_indices[op * 2 + 0] % block_size+ dst_token = block_update_indices[op * 2 + 1] % block_size+ key_cache[dst_block, h, dst_token] = key_cache[src_block, h, src_token]+ value_cache[dst_block, h, dst_token] = value_cache[src_block, h, src_token]++ # Move to next batch+ op_idx = batch_end+++**Attributes**: *PaKVReorder* operation has no attributes.+++**Inputs**++* **0**: ``key_cache``+ A 4D tensor of type *T* with shape ``[num_blocks, num_kv_heads, block_size, key_hidden]`` for non-quantized,+ or ``[num_blocks, num_kv_heads, block_size + params_size, key_hidden]`` for by-channel quantization.+ Paged key cache storing attention keys. Updated in-place during reordering. **Required.**++* **1**: ``value_cache``+ A 4D tensor of type *T* with shape ``[num_blocks, num_kv_heads, block_size, value_hidden]`` for non-quantized,+ or ``[num_blocks, num_kv_heads, block_size + params_size, value_hidden]`` for by-channel quantization.+ Paged value cache storing attention values. Updated in-place during reordering. **Required.**++* **2**: ``block_indices``+ A 1D tensor of type *T_IND* with shape ``[total_num_blocks]``.+ Physical block indices for all sequences. Maps logical block indices to physical block addresses in the cache.+ ``total_num_blocks = block_indices_begins[-1]``. **Required.**++* **3**: ``block_indices_begins``+ A 1D tensor of type *T_IND* with shape ``[num_sequences + 1]``.+ Splits ``block_indices`` among sequences. Sequence ``s`` uses blocks from+ ``block_indices[block_indices_begins[s] : block_indices_begins[s+1]]``. **Required.**++* **4**: ``block_update_indices``+ A 1D tensor of type *T_IND* with shape ``[total_updates * 2]``.+ Pairs of ``(src_logical_token_idx, dst_logical_token_idx)`` specifying token movements.+ Each pair represents one reorder operation. Indices are logical (sequence-relative) token positions.+ ``total_updates = block_update_indices_begins[-1]``. **Required.**++* **5**: ``block_update_indices_begins``+ A 1D tensor of type *T_IND* with shape ``[num_sequences + 1]``.+ Splits ``block_update_indices`` among sequences. Sequence ``s`` has operations from+ ``block_update_indices[block_update_indices_begins[s]*2 : block_update_indices_begins[s+1]*2]``.+ **Required.**+++**Outputs**++* **0**: ``status``+ A 1D tensor of type *u8* with shape ``[1]``.+ Status indicator (always 0 for success). The actual output is the in-place modification of ``key_cache``+ and ``value_cache``.+++**Types**++* **T**: ``float32``, ``bfloat16``, ``float16``, ``uint8``, ``uint4``.+ Determines the data type of KV cache. Quantized types (``uint8``, ``uint4``) require scale/zero-point parameters.+ Signed ``int8`` KV cache is not supported.++* **T_IND**: ``int32``.+ Index type for all index tensors.diff --git a/src/common/transformations/tests/pa_kv_reorder_fusion_test.cpp b/src/common/transformations/tests/pa_kv_reorder_fusion_test.cppnew file mode 100644index 00000000000..f55357eaae4--- /dev/null+++ b/src/common/transformations/tests/pa_kv_reorder_fusion_test.cpp@@ -0,0 +1,333 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/pass/pa_kv_reorder_fusion.hpp"++#include <gtest/gtest.h>++#include <memory>++#include "common_test_utils/ov_test_utils.hpp"+#include "openvino/core/model.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/pa_kv_reorder.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/result.hpp"+#include "openvino/op/scatter_update.hpp"+#include "openvino/pass/manager.hpp"++namespace ov::test {++TEST(PaKVReorderFusionTest, PassInstantiation) {+ auto pass = std::make_shared<pass::PaKVReorderFusion>();+ ASSERT_NE(pass, nullptr);+}++TEST(PaKVReorderFusionTest, EmptyModel) {+ auto model = std::make_shared<Model>(ResultVector{}, ParameterVector{});++ pass::Manager manager;+ manager.register_pass<pass::PaKVReorderFusion>();+ manager.run_passes(model);++ ASSERT_EQ(model->get_results().size(), 0);+}++TEST(PaKVReorderFusionTest, NoPatternToFuse) {+ auto input = std::make_shared<op::v0::Parameter>(element::f32, Shape{1, 3, 224, 224});+ auto result = std::make_shared<op::v0::Result>(input);+ auto model = std::make_shared<Model>(ResultVector{result}, ParameterVector{input});++ size_t ops_before = model->get_ops().size();++ pass::Manager manager;+ manager.register_pass<pass::PaKVReorderFusion>();+ manager.run_passes(model);++ size_t ops_after = model->get_ops().size();+ ASSERT_EQ(ops_before, ops_after);+}++TEST(PaKVReorderFusionTest, FusionPattern) {+ auto key_cache = std::make_shared<op::v0::Parameter>(element::f32, Shape{4, 8, 32, 64});+ key_cache->set_friendly_name("key_cache.0_clone_for_k_update");++ auto value_cache = std::make_shared<op::v0::Parameter>(element::f32, Shape{4, 8, 32, 64});+ value_cache->set_friendly_name("value_cache.0_clone_for_v_update");++ auto block_update_indices = std::make_shared<op::v0::Parameter>(element::i32, Shape{4});+ block_update_indices->set_friendly_name("block_update_indices");++ auto block_indices = std::make_shared<op::v0::Parameter>(element::i32, Shape{4});+ block_indices->set_friendly_name("block_indices");++ auto block_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, Shape{2});+ block_indices_begins->set_friendly_name("block_indices_begins");++ auto block_update_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, Shape{2});+ block_update_indices_begins->set_friendly_name("block_update_indices_begins");++ auto axis = op::v0::Constant::create(element::i32, Shape{}, {0});++ auto key_gather = std::make_shared<op::v8::Gather>(key_cache, block_update_indices, axis);+ auto key_scatter = std::make_shared<op::v3::ScatterUpdate>(key_cache, block_indices, key_gather, axis);+ key_scatter->set_friendly_name("updated_key_cache_0");++ auto value_gather = std::make_shared<op::v8::Gather>(value_cache, block_update_indices, axis);+ auto value_scatter = std::make_shared<op::v3::ScatterUpdate>(value_cache, block_indices, value_gather, axis);+ value_scatter->set_friendly_name("updated_value_cache_0");++ auto concat = std::make_shared<op::v0::Concat>(OutputVector{key_scatter, value_scatter}, 0);+ auto result = std::make_shared<op::v0::Result>(concat);++ auto model = std::make_shared<Model>(ResultVector{result},+ ParameterVector{key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins});++ pass::Manager manager;+ manager.register_pass<pass::PaKVReorderFusion>();+ manager.run_passes(model);++ bool found_pa_kv_reorder = false;+ int gather_count = 0;+ int scatter_count = 0;++ for (const auto& op : model->get_ops()) {+ if (std::dynamic_pointer_cast<op::internal::PaKVReorder>(op)) {+ found_pa_kv_reorder = true;+ }+ if (std::dynamic_pointer_cast<op::v8::Gather>(op)) {+ gather_count++;+ }+ if (std::dynamic_pointer_cast<op::v3::ScatterUpdate>(op)) {+ scatter_count++;+ }+ }++ ASSERT_TRUE(found_pa_kv_reorder) << "PaKVReorder op should be created after fusion";+ ASSERT_EQ(gather_count, 0) << "Gather ops should be removed after fusion";+ ASSERT_EQ(scatter_count, 0) << "ScatterUpdate ops should be removed after fusion";+}++TEST_F(TransformationTestsF, PaKVReorderFusion_basic) {+ disable_result_friendly_names_check();+ {+ auto key_cache = std::make_shared<op::v0::Parameter>(element::f16, PartialShape::dynamic(4));+ key_cache->set_friendly_name("key_cache.0_clone_for_k_update");+ auto value_cache = std::make_shared<op::v0::Parameter>(element::f16, PartialShape::dynamic(4));+ value_cache->set_friendly_name("value_cache.0_clone_for_v_update");++ auto block_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{2});+ block_indices->set_friendly_name("block_indices");+ auto block_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{2});+ block_indices_begins->set_friendly_name("block_indices_begins");++ auto block_update_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{2});+ block_update_indices->set_friendly_name("block_update_indices");+ auto block_update_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{2});+ block_update_indices_begins->set_friendly_name("block_update_indices_begins");++ auto gather_axis = op::v0::Constant::create(element::i64, Shape{}, {0});+ auto scatter_axis = op::v0::Constant::create(element::i64, Shape{}, {0});++ auto key_gather = std::make_shared<op::v8::Gather>(key_cache, block_update_indices, gather_axis);+ auto value_gather = std::make_shared<op::v8::Gather>(value_cache, block_update_indices, gather_axis);++ auto key_scatter = std::make_shared<op::v3::ScatterUpdate>(key_cache, block_indices, key_gather, scatter_axis);+ auto value_scatter =+ std::make_shared<op::v3::ScatterUpdate>(value_cache, block_indices, value_gather, scatter_axis);++ auto concat = std::make_shared<op::v0::Concat>(OutputVector{key_scatter, value_scatter}, 0);+ auto result = std::make_shared<op::v0::Result>(concat);++ model = std::make_shared<Model>(ResultVector{result},+ ParameterVector{key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins});++ manager.register_pass<pass::PaKVReorderFusion>();+ }++ {+ auto key_cache = std::make_shared<op::v0::Parameter>(element::f16, PartialShape::dynamic(4));+ key_cache->set_friendly_name("key_cache.0_clone_for_k_update");+ auto value_cache = std::make_shared<op::v0::Parameter>(element::f16, PartialShape::dynamic(4));+ value_cache->set_friendly_name("value_cache.0_clone_for_v_update");++ auto block_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{2});+ block_indices->set_friendly_name("block_indices");+ auto block_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{2});+ block_indices_begins->set_friendly_name("block_indices_begins");++ auto block_update_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{2});+ block_update_indices->set_friendly_name("block_update_indices");+ auto block_update_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{2});+ block_update_indices_begins->set_friendly_name("block_update_indices_begins");++ auto pa_kv_reorder = std::make_shared<op::internal::PaKVReorder>(key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins);+ pa_kv_reorder->set_friendly_name("pa_kv_reorder_0");+ auto result = std::make_shared<op::v0::Result>(pa_kv_reorder);++ model_ref = std::make_shared<Model>(ResultVector{result},+ ParameterVector{key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins});+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ }+}++TEST_F(TransformationTestsF, PaKVReorderFusion_skip_on_mismatched_block_indices) {+ disable_result_friendly_names_check();+ auto key_cache = std::make_shared<op::v0::Parameter>(element::f16, PartialShape::dynamic(4));+ key_cache->set_friendly_name("key_cache.0_clone_for_k_update");+ auto value_cache = std::make_shared<op::v0::Parameter>(element::f16, PartialShape::dynamic(4));+ value_cache->set_friendly_name("value_cache.0_clone_for_v_update");++ auto block_indices_k = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{2});+ block_indices_k->set_friendly_name("block_indices_k");+ auto block_indices_v = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{2});+ block_indices_v->set_friendly_name("block_indices_v");++ auto block_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{2});+ block_indices_begins->set_friendly_name("block_indices_begins");+ auto block_update_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{2});+ block_update_indices->set_friendly_name("block_update_indices");+ auto block_update_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{2});+ block_update_indices_begins->set_friendly_name("block_update_indices_begins");++ auto gather_axis = op::v0::Constant::create(element::i64, Shape{}, {0});+ auto scatter_axis = op::v0::Constant::create(element::i64, Shape{}, {0});++ auto key_gather = std::make_shared<op::v8::Gather>(key_cache, block_update_indices, gather_axis);+ auto value_gather = std::make_shared<op::v8::Gather>(value_cache, block_update_indices, gather_axis);++ auto key_scatter = std::make_shared<op::v3::ScatterUpdate>(key_cache, block_indices_k, key_gather, scatter_axis);+ auto value_scatter =+ std::make_shared<op::v3::ScatterUpdate>(value_cache, block_indices_v, value_gather, scatter_axis);++ auto concat = std::make_shared<op::v0::Concat>(OutputVector{key_scatter, value_scatter}, 0);+ auto result = std::make_shared<op::v0::Result>(concat);++ model = std::make_shared<Model>(ResultVector{result},+ ParameterVector{key_cache,+ value_cache,+ block_indices_k,+ block_indices_v,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins});++ manager.register_pass<pass::PaKVReorderFusion>();++ model_ref = model->clone();+ comparator.enable(FunctionsComparator::ATTRIBUTES);+}++TEST(PaKVReorderOpTest, OpCreation) {+ auto key_cache = std::make_shared<op::v0::Parameter>(element::f32, Shape{4, 8, 32, 64});+ auto value_cache = std::make_shared<op::v0::Parameter>(element::f32, Shape{4, 8, 32, 64});+ auto block_indices = std::make_shared<op::v0::Parameter>(element::i32, Shape{8});+ auto block_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, Shape{2});+ auto block_update_indices = std::make_shared<op::v0::Parameter>(element::i32, Shape{4});+ auto block_update_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, Shape{2});++ auto pa_kv_reorder = std::make_shared<op::internal::PaKVReorder>(key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins);++ ASSERT_NE(pa_kv_reorder, nullptr);+ ASSERT_EQ(pa_kv_reorder->get_input_size(), 6);+ ASSERT_EQ(pa_kv_reorder->get_output_size(), 1);+}++TEST(PaKVReorderOpTest, ModelWithOp) {+ auto key_cache = std::make_shared<op::v0::Parameter>(element::f32, Shape{4, 8, 32, 64});+ key_cache->set_friendly_name("key_cache");++ auto value_cache = std::make_shared<op::v0::Parameter>(element::f32, Shape{4, 8, 32, 64});+ value_cache->set_friendly_name("value_cache");++ auto block_indices = std::make_shared<op::v0::Parameter>(element::i32, Shape{8});+ block_indices->set_friendly_name("block_indices");++ auto block_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, Shape{2});+ block_indices_begins->set_friendly_name("block_indices_begins");++ auto block_update_indices = std::make_shared<op::v0::Parameter>(element::i32, Shape{4});+ block_update_indices->set_friendly_name("block_update_indices");++ auto block_update_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, Shape{2});+ block_update_indices_begins->set_friendly_name("block_update_indices_begins");++ auto pa_kv_reorder = std::make_shared<op::internal::PaKVReorder>(key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins);++ auto result = std::make_shared<op::v0::Result>(pa_kv_reorder->output(0));++ auto model = std::make_shared<Model>(ResultVector{result},+ ParameterVector{key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins});++ ASSERT_NE(model, nullptr);+ ASSERT_EQ(model->get_parameters().size(), 6);+ ASSERT_EQ(model->get_results().size(), 1);++ bool found_pa_kv_reorder = false;+ for (const auto& op : model->get_ops()) {+ if (std::dynamic_pointer_cast<op::internal::PaKVReorder>(op)) {+ found_pa_kv_reorder = true;+ break;+ }+ }+ ASSERT_TRUE(found_pa_kv_reorder) << "PaKVReorder op not found in model";+}++TEST(PaKVReorderOpTest, TypeInfo) {+ auto key_cache = std::make_shared<op::v0::Parameter>(element::f32, Shape{4, 8, 32, 64});+ auto value_cache = std::make_shared<op::v0::Parameter>(element::f32, Shape{4, 8, 32, 64});+ auto block_indices = std::make_shared<op::v0::Parameter>(element::i32, Shape{8});+ auto block_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, Shape{2});+ auto block_update_indices = std::make_shared<op::v0::Parameter>(element::i32, Shape{4});+ auto block_update_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, Shape{2});++ auto pa_kv_reorder = std::make_shared<op::internal::PaKVReorder>(key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins);++ auto type_info = pa_kv_reorder->get_type_info();+ ASSERT_STREQ(type_info.name, "PaKVReorder");+}++} // namespace ov::testdiff --git a/src/core/dev_api/openvino/op/pa_kv_reorder.hpp b/src/core/dev_api/openvino/op/pa_kv_reorder.hppnew file mode 100644index 00000000000..01a772ecfe8--- /dev/null+++ b/src/core/dev_api/openvino/op/pa_kv_reorder.hpp@@ -0,0 +1,35 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/op/op.hpp"++namespace ov {+namespace op {+namespace internal {++class OPENVINO_API PaKVReorder : public ov::op::Op {+public:+ OPENVINO_OP("PaKVReorder");++ PaKVReorder() = default;++ PaKVReorder(const Output<Node>& key_cache,+ const Output<Node>& value_cache,+ const Output<Node>& block_indices,+ const Output<Node>& block_indices_begins,+ const Output<Node>& block_update_indices,+ const Output<Node>& block_update_indices_begins);++ bool visit_attributes(ov::AttributeVisitor& visitor) override;++ void validate_and_infer_types() override;++ std::shared_ptr<Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;+};++} // namespace internal+} // namespace op+} // namespace ovdiff --git a/src/core/include/openvino/pass/pa_kv_reorder_fusion.hpp b/src/core/include/openvino/pass/pa_kv_reorder_fusion.hppnew file mode 100644index 00000000000..639e91d8776--- /dev/null+++ b/src/core/include/openvino/pass/pa_kv_reorder_fusion.hpp@@ -0,0 +1,30 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/core/type/element_type.hpp"+#include "openvino/pass/pass.hpp"++namespace ov {+namespace pass {++/// Fuses paired key/value cache reorder paths into a single PaKVReorder op.+///+/// This transformation performs graph pattern matching and replacement.+/// An optional cache_precision parameter can be provided to set the element type+/// of the key/value cache Parameters during fusion.+class OPENVINO_API PaKVReorderFusion : public ov::pass::ModelPass {+public:+ OPENVINO_MODEL_PASS_RTTI("PaKVReorderFusion");+ PaKVReorderFusion() = default;+ explicit PaKVReorderFusion(ov::element::Type cache_precision);+ bool run_on_model(const std::shared_ptr<ov::Model>& m) override;++private:+ ov::element::Type m_cache_precision = ov::element::dynamic;+};++} // namespace pass+} // namespace ovdiff --git a/src/core/shape_inference/include/pa_kv_reorder_shape_inference.hpp b/src/core/shape_inference/include/pa_kv_reorder_shape_inference.hppnew file mode 100644index 00000000000..a4bbca3f45f--- /dev/null+++ b/src/core/shape_inference/include/pa_kv_reorder_shape_inference.hpp@@ -0,0 +1,23 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/op/pa_kv_reorder.hpp"+#include "utils.hpp"++namespace ov::op::internal {+template <class T, class TRShape = result_shape_t<T>>+std::vector<TRShape> shape_infer(const PaKVReorder* op, const std::vector<T>& input_shapes) {+ NODE_VALIDATION_CHECK(op, input_shapes.size() == 6);++ NODE_SHAPE_INFER_CHECK(op, input_shapes, input_shapes[0].rank().compatible(4));+ NODE_SHAPE_INFER_CHECK(op, input_shapes, input_shapes[1].rank().compatible(4));+ for (size_t i = 2; i < 6; ++i) {+ NODE_SHAPE_INFER_CHECK(op, input_shapes, input_shapes[i].rank().compatible(1));+ }++ return {TRShape{1}};+}+} // namespace ov::op::internaldiff --git a/src/core/src/op/pa_kv_reorder.cpp b/src/core/src/op/pa_kv_reorder.cppnew file mode 100644index 00000000000..6d7a4f048f9--- /dev/null+++ b/src/core/src/op/pa_kv_reorder.cpp@@ -0,0 +1,59 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/op/pa_kv_reorder.hpp"++#include "itt.hpp"+#include "openvino/core/validation_util.hpp"+#include "pa_kv_reorder_shape_inference.hpp"++namespace ov::op::internal {++PaKVReorder::PaKVReorder(const Output<Node>& key_cache,+ const Output<Node>& value_cache,+ const Output<Node>& block_indices,+ const Output<Node>& block_indices_begins,+ const Output<Node>& block_update_indices,+ const Output<Node>& block_update_indices_begins)+ : Op({key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins}) {+ constructor_validate_and_infer_types();+}++bool PaKVReorder::visit_attributes(ov::AttributeVisitor& /*visitor*/) {+ return true;+}++void PaKVReorder::validate_and_infer_types() {+ OV_OP_SCOPE(PaKVReorder_validate_and_infer_types);++ for (size_t i = 2; i < 6; ++i) {+ NODE_VALIDATION_CHECK(this,+ get_input_element_type(i).is_dynamic() || get_input_element_type(i) == ov::element::i32,+ "Input ",+ i,+ " (indices) must be i32, got ",+ get_input_element_type(i));+ }++ const auto output_shapes = shape_infer(this, ov::util::get_node_input_partial_shapes(*this));+ set_output_type(0, ov::element::u8, output_shapes[0]);+}++std::shared_ptr<Node> PaKVReorder::clone_with_new_inputs(const ov::OutputVector& new_args) const {+ OV_OP_SCOPE(PaKVReorder_clone_with_new_inputs);+ check_new_args_count(this, new_args);+ return std::make_shared<PaKVReorder>(new_args.at(0),+ new_args.at(1),+ new_args.at(2),+ new_args.at(3),+ new_args.at(4),+ new_args.at(5));+}++} // namespace ov::op::internaldiff --git a/src/plugins/intel_gpu/src/plugin/transformations/pa_kv_reorder_fusion.cpp b/src/core/src/pass/pa_kv_reorder_fusion.cppsimilarity index 67%rename from src/plugins/intel_gpu/src/plugin/transformations/pa_kv_reorder_fusion.cpprename to src/core/src/pass/pa_kv_reorder_fusion.cppindex c2c687c0075..8e406ae23bb 100644--- a/src/plugins/intel_gpu/src/plugin/transformations/pa_kv_reorder_fusion.cpp+++ b/src/core/src/pass/pa_kv_reorder_fusion.cpp@@ -2,7 +2,7 @@// SPDX-License-Identifier: Apache-2.0//-#include "pa_kv_reorder_fusion.hpp"+#include "openvino/pass/pa_kv_reorder_fusion.hpp"#include <optional>#include <regex>@@ -10,17 +10,18 @@#include <unordered_map>#include <vector>-#include "intel_gpu/op/pa_kv_reorder.hpp"#include "openvino/core/graph_util.hpp"#include "openvino/core/rt_info.hpp"#include "openvino/op/concat.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/gather.hpp"+#include "openvino/op/pa_kv_reorder.hpp"#include "openvino/op/parameter.hpp"+#include "openvino/op/result.hpp"#include "openvino/op/scatter_update.hpp"-#include "transformations/utils/utils.hpp"-namespace ov::intel_gpu {+namespace ov {+namespace pass {namespace {struct CacheReorderPath {@@ -96,6 +97,11 @@ std::optional<CacheReorderPath> parse_cache_reorder_path(const std::shared_ptr<oreturn std::nullopt;}+ // PaKVReorder only supports reordering along the block dimension (axis 0)+ if (gather_axis.value() != 0) {+ return std::nullopt;+ }+auto role_and_index = parse_cache_role_and_index(cache->get_friendly_name());if (!role_and_index.has_value()) {role_and_index = parse_cache_role_and_index(scatter->get_friendly_name());@@ -116,7 +122,8 @@ std::optional<CacheReorderPath> parse_cache_reorder_path(const std::shared_ptr<oreturn path;}-std::shared_ptr<ov::op::v0::Parameter> get_parameter_by_name(const std::shared_ptr<ov::Model>& m, const std::string& parameter_name) {+std::shared_ptr<ov::op::v0::Parameter> get_parameter_by_name(const std::shared_ptr<ov::Model>& m,+ const std::string& parameter_name) {for (const auto& parameter : m->get_parameters()) {if (parameter && parameter->get_friendly_name() == parameter_name) {return parameter;@@ -126,28 +133,9 @@ std::shared_ptr<ov::op::v0::Parameter> get_parameter_by_name(const std::shared_preturn nullptr;}-ov::element::Type format_cache_precision(const ov::element::Type& cache_precision, const ov::element::Type& infer_precision) {- return cache_precision == ov::element::f16 && infer_precision == ov::element::bf16 ? infer_precision : cache_precision;-}--bool is_compressed_cache_type(const ov::element::Type& type) {- return type == ov::element::i8 || type == ov::element::u8 || type == ov::element::i4 || type == ov::element::u4;-}--size_t infer_scales_zp_size(const ov::element::Type& cache_type, const ov::element::Type& infer_precision) {- if (!is_compressed_cache_type(cache_type)) {- return 0;- }-- OPENVINO_ASSERT(cache_type.size() > 0 && infer_precision.size() > 0, "[GPU] Invalid element size for pa_kv_reorder metadata inference");- if (cache_type == ov::element::i4 || cache_type == ov::element::u4) {- return 4 * infer_precision.size();- }- return (2 * infer_precision.size()) / cache_type.size();-}--std::vector<std::shared_ptr<ov::op::v0::Concat>> get_joint_concat_consumers(const ov::Output<ov::Node>& key_scatter_output,- const ov::Output<ov::Node>& value_scatter_output) {+std::vector<std::shared_ptr<ov::op::v0::Concat>> get_joint_concat_consumers(+ const ov::Output<ov::Node>& key_scatter_output,+ const ov::Output<ov::Node>& value_scatter_output) {std::vector<std::shared_ptr<ov::op::v0::Concat>> concats;for (const auto& target_input : key_scatter_output.get_target_inputs()) {auto concat = ov::as_type_ptr<ov::op::v0::Concat>(target_input.get_node()->shared_from_this());@@ -166,15 +154,15 @@ std::vector<std::shared_ptr<ov::op::v0::Concat>> get_joint_concat_consumers(conscontinue;}- bool has_result_consumer = false;+ bool all_consumers_are_results = true;for (const auto& concat_target : concat->output(0).get_target_inputs()) {- if (ov::as_type_ptr<ov::op::v0::Result>(concat_target.get_node()->shared_from_this())) {- has_result_consumer = true;+ if (!ov::as_type_ptr<ov::op::v0::Result>(concat_target.get_node()->shared_from_this())) {+ all_consumers_are_results = false;break;}}- if (has_result_consumer) {+ if (all_consumers_are_results) {concats.push_back(concat);}}@@ -184,6 +172,8 @@ std::vector<std::shared_ptr<ov::op::v0::Concat>> get_joint_concat_consumers(cons} // namespace+PaKVReorderFusion::PaKVReorderFusion(ov::element::Type cache_precision) : m_cache_precision(cache_precision) {}+bool PaKVReorderFusion::run_on_model(const std::shared_ptr<ov::Model>& m) {auto block_indices_begins = get_parameter_by_name(m, "block_indices_begins");auto block_update_indices_begins = get_parameter_by_name(m, "block_update_indices_begins");@@ -216,45 +206,28 @@ bool PaKVReorderFusion::run_on_model(const std::shared_ptr<ov::Model>& m) {}const auto& value_path = value_paths.at(index);- if (!same_output(key_path.block_indices, value_path.block_indices) || !same_output(key_path.block_update_indices, value_path.block_update_indices)) {+ if (!same_output(key_path.block_indices, value_path.block_indices) ||+ !same_output(key_path.block_update_indices, value_path.block_update_indices)) {continue;}- const auto concat_consumers = get_joint_concat_consumers(key_path.scatter->output(0), value_path.scatter->output(0));+ const auto concat_consumers =+ get_joint_concat_consumers(key_path.scatter->output(0), value_path.scatter->output(0));if (concat_consumers.empty()) {continue;}- auto pa_kv_reorder = std::make_shared<ov::intel_gpu::op::PA_KV_Reorder>(key_path.cache->output(0),- value_path.cache->output(0),- key_path.block_indices,- block_indices_begins->output(0),- key_path.block_update_indices,- block_update_indices_begins->output(0));-- constexpr const char* rt_is_key_by_channel = "pa_kv_reorder.is_key_by_channel";- constexpr const char* rt_scales_zp_size = "pa_kv_reorder.scales_zp_size";- constexpr const char* rt_key_dim_order = "pa_kv_reorder.key_cache_dim_order";- constexpr const char* rt_value_dim_order = "pa_kv_reorder.value_cache_dim_order";-- const auto key_cache_type = format_cache_precision(m_key_cache_precision, m_inference_precision);- const auto value_cache_type = format_cache_precision(m_value_cache_precision, m_inference_precision);- const auto key_scales_zp_size = infer_scales_zp_size(key_cache_type, m_inference_precision);- const auto value_scales_zp_size = infer_scales_zp_size(value_cache_type, m_inference_precision);- OPENVINO_ASSERT(key_scales_zp_size == value_scales_zp_size,- "[GPU] PaKVReorderFusion expects equal scales/zp size for key/value cache, but got ",- key_scales_zp_size,- " and ",- value_scales_zp_size);- // update key/value type- key_path.cache->set_element_type(key_cache_type);- value_path.cache->set_element_type(value_cache_type);- const bool is_key_by_channel = m_key_cache_quant_by_channel;-- pa_kv_reorder->get_rt_info()[rt_is_key_by_channel] = is_key_by_channel;- pa_kv_reorder->get_rt_info()[rt_scales_zp_size] = key_scales_zp_size;- pa_kv_reorder->get_rt_info()[rt_key_dim_order] = m_key_cache_dim_order;- pa_kv_reorder->get_rt_info()[rt_value_dim_order] = m_value_cache_dim_order;+ if (m_cache_precision != ov::element::dynamic) {+ key_path.cache->set_element_type(m_cache_precision);+ value_path.cache->set_element_type(m_cache_precision);+ }++ auto pa_kv_reorder = std::make_shared<ov::op::internal::PaKVReorder>(key_path.cache->output(0),+ value_path.cache->output(0),+ key_path.block_indices,+ block_indices_begins->output(0),+ key_path.block_update_indices,+ block_update_indices_begins->output(0));ov::copy_runtime_info(key_path.cache, pa_kv_reorder);pa_kv_reorder->set_friendly_name("pa_kv_reorder_" + index);@@ -280,4 +253,5 @@ bool PaKVReorderFusion::run_on_model(const std::shared_ptr<ov::Model>& m) {return rewritten;}-} // namespace ov::intel_gpu+} // namespace pass+} // namespace ovdiff --git a/src/core/tests/type_prop/pa_kv_reorder.cpp b/src/core/tests/type_prop/pa_kv_reorder.cppnew file mode 100644index 00000000000..d5018342f45--- /dev/null+++ b/src/core/tests/type_prop/pa_kv_reorder.cpp@@ -0,0 +1,191 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/op/pa_kv_reorder.hpp"++#include <gtest/gtest.h>++#include "common_test_utils/test_assertions.hpp"+#include "common_test_utils/type_prop.hpp"+#include "openvino/op/parameter.hpp"++namespace ov::test {++class TypePropPaKVReorderTest : public TypePropOpTest<op::internal::PaKVReorder> {};++TEST_F(TypePropPaKVReorderTest, static_shapes) {+ const auto key_cache = std::make_shared<op::v0::Parameter>(element::f16, PartialShape{100, 8, 64, 16});+ const auto value_cache = std::make_shared<op::v0::Parameter>(element::f16, PartialShape{100, 8, 16, 64});+ const auto block_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{50});+ const auto block_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{4});+ const auto block_update_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{50});+ const auto block_update_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{4});++ const auto op = make_op(key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins);++ EXPECT_EQ(op->get_output_element_type(0), element::u8);+ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{1}));+ EXPECT_EQ(op->get_output_size(), 1);+}++TEST_F(TypePropPaKVReorderTest, dynamic_batch) {+ const auto key_cache =+ std::make_shared<op::v0::Parameter>(element::f32, PartialShape{Dimension::dynamic(), 8, 64, 16});+ const auto value_cache =+ std::make_shared<op::v0::Parameter>(element::f32, PartialShape{Dimension::dynamic(), 8, 16, 64});+ const auto block_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{Dimension::dynamic()});+ const auto block_indices_begins =+ std::make_shared<op::v0::Parameter>(element::i32, PartialShape{Dimension::dynamic()});+ const auto block_update_indices =+ std::make_shared<op::v0::Parameter>(element::i32, PartialShape{Dimension::dynamic()});+ const auto block_update_indices_begins =+ std::make_shared<op::v0::Parameter>(element::i32, PartialShape{Dimension::dynamic()});++ const auto op = make_op(key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins);++ EXPECT_EQ(op->get_output_element_type(0), element::u8);+ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{1}));+}++TEST_F(TypePropPaKVReorderTest, fully_dynamic_shapes) {+ const auto key_cache = std::make_shared<op::v0::Parameter>(element::f16, PartialShape::dynamic(4));+ const auto value_cache = std::make_shared<op::v0::Parameter>(element::f16, PartialShape::dynamic(4));+ const auto block_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape::dynamic(1));+ const auto block_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape::dynamic(1));+ const auto block_update_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape::dynamic(1));+ const auto block_update_indices_begins =+ std::make_shared<op::v0::Parameter>(element::i32, PartialShape::dynamic(1));++ const auto op = make_op(key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins);++ EXPECT_EQ(op->get_output_element_type(0), element::u8);+ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{1}));+}++TEST_F(TypePropPaKVReorderTest, dynamic_rank) {+ const auto key_cache = std::make_shared<op::v0::Parameter>(element::f16, PartialShape::dynamic());+ const auto value_cache = std::make_shared<op::v0::Parameter>(element::f16, PartialShape::dynamic());+ const auto block_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape::dynamic());+ const auto block_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape::dynamic());+ const auto block_update_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape::dynamic());+ const auto block_update_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape::dynamic());++ const auto op = make_op(key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins);++ EXPECT_EQ(op->get_output_element_type(0), element::u8);+ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{1}));+}++TEST_F(TypePropPaKVReorderTest, invalid_key_cache_rank) {+ const auto key_cache = std::make_shared<op::v0::Parameter>(element::f16, PartialShape{100, 8, 64});+ const auto value_cache = std::make_shared<op::v0::Parameter>(element::f16, PartialShape{100, 8, 16, 64});+ const auto block_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{50});+ const auto block_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{4});+ const auto block_update_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{50});+ const auto block_update_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{4});++ OV_EXPECT_THROW(std::ignore = make_op(key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins),+ NodeValidationFailure,+ testing::HasSubstr("input_shapes[0].rank().compatible(4)"));+}++TEST_F(TypePropPaKVReorderTest, invalid_value_cache_rank) {+ const auto key_cache = std::make_shared<op::v0::Parameter>(element::f16, PartialShape{100, 8, 64, 16});+ const auto value_cache = std::make_shared<op::v0::Parameter>(element::f16, PartialShape{100, 8, 64});+ const auto block_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{50});+ const auto block_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{4});+ const auto block_update_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{50});+ const auto block_update_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{4});++ OV_EXPECT_THROW(std::ignore = make_op(key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins),+ NodeValidationFailure,+ testing::HasSubstr("input_shapes[1].rank().compatible(4)"));+}++TEST_F(TypePropPaKVReorderTest, invalid_indices_rank) {+ const auto key_cache = std::make_shared<op::v0::Parameter>(element::f16, PartialShape{100, 8, 64, 16});+ const auto value_cache = std::make_shared<op::v0::Parameter>(element::f16, PartialShape{100, 8, 16, 64});+ const auto block_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{5, 10});+ const auto block_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{4});+ const auto block_update_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{50});+ const auto block_update_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{4});++ OV_EXPECT_THROW(std::ignore = make_op(key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins),+ NodeValidationFailure,+ testing::HasSubstr("input_shapes[i].rank().compatible(1)"));+}++TEST_F(TypePropPaKVReorderTest, invalid_indices_type) {+ const auto key_cache = std::make_shared<op::v0::Parameter>(element::f16, PartialShape{100, 8, 64, 16});+ const auto value_cache = std::make_shared<op::v0::Parameter>(element::f16, PartialShape{100, 8, 16, 64});+ const auto block_indices = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{50});+ const auto block_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{4});+ const auto block_update_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{50});+ const auto block_update_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{4});++ OV_EXPECT_THROW(std::ignore = make_op(key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins),+ NodeValidationFailure,+ testing::HasSubstr("(indices) must be i32"));+}++TEST_F(TypePropPaKVReorderTest, i8_cache) {+ const auto key_cache = std::make_shared<op::v0::Parameter>(element::i8, PartialShape{100, 8, 64, 16});+ const auto value_cache = std::make_shared<op::v0::Parameter>(element::i8, PartialShape{100, 8, 16, 64});+ const auto block_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{50});+ const auto block_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{4});+ const auto block_update_indices = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{50});+ const auto block_update_indices_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{4});++ const auto op = make_op(key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins);++ EXPECT_EQ(op->get_output_element_type(0), element::u8);+ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{1}));+}++} // namespace ov::testdiff --git a/src/plugins/intel_cpu/src/cpu_types.cpp b/src/plugins/intel_cpu/src/cpu_types.cppindex 673338fd661..87869b397bc 100644--- a/src/plugins/intel_cpu/src/cpu_types.cpp+++ b/src/plugins/intel_cpu/src/cpu_types.cpp@@ -252,6 +252,7 @@ static const TypeToNameMap& get_type_to_name_tbl() {{"ScaledDotProductAttentionWithKVCache", Type::ScaledDotProductAttention},{"SDPAWithTransposeReshape", Type::ScaledDotProductAttention},{"PagedAttentionExtension", Type::PagedAttention},+ {"PaKVReorder", Type::PaKVReorder},{"RoPE", Type::RoPE},{"GatherCompressed", Type::Gather},{"CausalMaskPreprocess", Type::CausalMaskPreprocess},@@ -393,6 +394,7 @@ std::string NameFromType(const Type type) {CASE(Ngram);CASE(ScaledDotProductAttention);CASE(PagedAttention);+ CASE(PaKVReorder);CASE(RoPE);CASE(CausalMaskPreprocess);CASE(LLMMLP);diff --git a/src/plugins/intel_cpu/src/cpu_types.h b/src/plugins/intel_cpu/src/cpu_types.hindex e25678b27f8..c8c62da0f07 100644--- a/src/plugins/intel_cpu/src/cpu_types.h+++ b/src/plugins/intel_cpu/src/cpu_types.h@@ -130,6 +130,7 @@ enum class Type : uint8_t {Ngram,ScaledDotProductAttention,PagedAttention,+ PaKVReorder,RoPE,CausalMaskPreprocess,LLMMLP,diff --git a/src/plugins/intel_cpu/src/graph.cpp b/src/plugins/intel_cpu/src/graph.cppindex 56786eac259..0853daf9b3a 100644--- a/src/plugins/intel_cpu/src/graph.cpp+++ b/src/plugins/intel_cpu/src/graph.cpp@@ -2142,6 +2142,10 @@ void Graph::EnforceInferencePrecision() const {if (node->getType() == Type::PagedAttention && any_of(inPort, 3U, 4U)) {return true;}+ // kv cache of PaKVReorder should be written directly+ if (node->getType() == Type::PaKVReorder && any_of(inPort, 0U, 1U)) {+ return true;+ }const auto& parent = node->getParentEdgeAt(inPort)->getParent();/* Skip BF16 enforcement for nodes after Constant Inputs for maintaining precision for fusing.* Element type conversion to bf16 is done automatically, if convolution follows up after Constantdiff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/attn_quant_kernel.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/attn_quant_kernel.hppindex b2394824de0..c9fec70ba46 100644--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/attn_quant_kernel.hpp+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/attn_quant_kernel.hpp@@ -11,6 +11,7 @@# include <immintrin.h>#endif+#include <cfloat>#include <cstddef>#include <cstdint>#if defined(HAVE_SVE)@@ -186,11 +187,11 @@ void quant_u8(const T* src, uint8_t* dst, size_t n, float& scale, float& zp) {find_minmax(src, n, min, max);scale = (max - min) / 255;if (scale == 0) {- scale = 0.0001f;+ scale = 0.0001F;#ifdef __ARM_FEATURE_FP16_VECTOR_ARITHMETIC// For FP16 in ARM we use FP16 accumulatorif constexpr (std::is_same_v<T, ov::float16>) {- scale = std::max(0.05f, std::abs(min) / 65504.0f);+ scale = std::max(0.05F, std::abs(min) / 65504.0F);}#endif}@@ -225,7 +226,7 @@ void quant_u8(const T* src, uint8_t* dst, size_t n, float& scale, float& zp) {#endiffor (; i < n; i++) {float tmp = src[i];- tmp = std::max(tmp / scale + zp, 0.0f);+ tmp = std::max(tmp / scale + zp, 0.0F);dst[i] = static_cast<uint8_t>(std::round(tmp));}}@@ -239,7 +240,7 @@ void quant_i8(const T* src, int8_t* dst, size_t n, float& scale) {float max_abs = std::max(std::abs(min), std::abs(max));scale = max_abs / ((1 << 7) - 1);if (scale == 0) {- scale = 0.0001f;+ scale = 0.0001F;}#if defined(HAVE_AVX512F)auto v_scale = _mm512_set1_ps(1 / scale);@@ -274,8 +275,8 @@ void quant_i8(const T* src, int8_t* dst, size_t n, float& scale) {for (; i < n; i++) {float tmp = src[i];tmp = std::round(tmp / scale);- tmp = std::max(tmp, -128.0f);- tmp = std::min(tmp, 127.0f);+ tmp = std::max(tmp, -128.0F);+ tmp = std::min(tmp, 127.0F);dst[i] = static_cast<int8_t>(tmp);}}@@ -285,12 +286,12 @@ void find_params_by_channel(const T* src,size_t seq_dim,size_t hidden_dims,size_t src_stride,- size_t dst_stride,+ [[maybe_unused]] size_t dst_stride,float* scale,float* zp,size_t bits) {size_t j = 0;- float integer_range = static_cast<float>((1 << bits) - 1);+ auto integer_range = static_cast<float>((1 << bits) - 1);#if defined(HAVE_AVX512F)for (; j + vec_len_f32_avx512 <= hidden_dims; j += vec_len_f32_avx512) {auto v_max = _mm512_set1_ps(-std::numeric_limits<float>::max());@@ -303,8 +304,8 @@ void find_params_by_channel(const T* src,auto v_scale = _mm512_sub_ps(v_max, v_min);v_scale = _mm512_mul_ps(v_scale, _mm512_set1_ps(1 / integer_range));auto v_mask = _mm512_cmp_ps_mask(v_scale, _mm512_setzero_ps(), _CMP_EQ_OQ);- v_scale = _mm512_mask_add_ps(v_scale, v_mask, v_scale, _mm512_set1_ps(0.0001f));- auto v_zp = _mm512_mul_ps(v_min, _mm512_set1_ps(-1.0f));+ v_scale = _mm512_mask_add_ps(v_scale, v_mask, v_scale, _mm512_set1_ps(0.0001F));+ auto v_zp = _mm512_mul_ps(v_min, _mm512_set1_ps(-1.0F));v_zp = _mm512_div_ps(v_zp, v_scale);_mm512_storeu_ps(scale + j, v_scale);@@ -323,9 +324,9 @@ void find_params_by_channel(const T* src,auto v_scale = _mm256_sub_ps(v_max, v_min);v_scale = _mm256_mul_ps(v_scale, _mm256_set1_ps(1 / integer_range));auto v_cond = _mm256_cmp_ps(v_scale, _mm256_setzero_ps(), _CMP_EQ_OQ);- auto v_comp = _mm256_and_ps(v_cond, _mm256_set1_ps(0.0001f));+ auto v_comp = _mm256_and_ps(v_cond, _mm256_set1_ps(0.0001F));v_scale = _mm256_add_ps(v_scale, v_comp);- auto v_zp = _mm256_mul_ps(v_min, _mm256_set1_ps(-1.0f));+ auto v_zp = _mm256_mul_ps(v_min, _mm256_set1_ps(-1.0F));v_zp = _mm256_div_ps(v_zp, v_scale);_mm256_storeu_ps(scale + j, v_scale);_mm256_storeu_ps(zp + j, v_zp);@@ -341,7 +342,7 @@ void find_params_by_channel(const T* src,}float temp_scale = (max - min) / integer_range;if (temp_scale == 0) {- temp_scale = 0.0001f;+ temp_scale = 0.0001F;}float temp_zp = -min / temp_scale;scale[j] = temp_scale;@@ -364,7 +365,7 @@ void quantize_by_channel(const T* src,#if defined(HAVE_AVX512F)for (; j + vec_len_f32_avx512 <= hidden_dims; j += vec_len_f32_avx512) {auto v_scale = mm512_uni_loadu_ps(scale + j);- v_scale = _mm512_div_ps(_mm512_set1_ps(1.0f), v_scale);+ v_scale = _mm512_div_ps(_mm512_set1_ps(1.0F), v_scale);auto v_zero = _mm512_setzero_epi32();auto v_zp = mm512_uni_loadu_ps(zp + j);for (size_t i = 0; i < seq_dim; i++) {@@ -380,7 +381,7 @@ void quantize_by_channel(const T* src,#if defined(HAVE_AVX2)for (; j + vec_len_f32_avx2 <= hidden_dims; j += vec_len_f32_avx2) {auto v_scale = mm256_uni_loadu_ps(scale + j);- v_scale = _mm256_div_ps(_mm256_set1_ps(1.0f), v_scale);+ v_scale = _mm256_div_ps(_mm256_set1_ps(1.0F), v_scale);auto v_zp = mm256_uni_loadu_ps(zp + j);auto v_zero = _mm256_setzero_si256();for (size_t i = 0; i < seq_dim; i++) {@@ -400,7 +401,7 @@ void quantize_by_channel(const T* src,for (; j < hidden_dims; j++) {for (size_t i = 0; i < seq_dim; ++i) {float tmp = src[i * src_stride + j];- tmp = std::max(tmp / scale[j] + zp[j], 0.0f);+ tmp = std::max(tmp / scale[j] + zp[j], 0.0F);dst[i * dst_stride + j] = static_cast<uint8_t>(std::round(tmp));}}@@ -420,9 +421,9 @@ void quantize_by_channel(const T* src,#if defined(HAVE_AVX512F)for (; j + vec_len_f32_avx512 * 2 <= hidden_dims; j += vec_len_f32_avx512 * 2) {auto v_scale0 = mm512_uni_loadu_ps(scale + j);- v_scale0 = _mm512_div_ps(_mm512_set1_ps(1.0f), v_scale0);+ v_scale0 = _mm512_div_ps(_mm512_set1_ps(1.0F), v_scale0);auto v_scale1 = mm512_uni_loadu_ps(scale + j + vec_len_f32_avx512);- v_scale1 = _mm512_div_ps(_mm512_set1_ps(1.0f), v_scale1);+ v_scale1 = _mm512_div_ps(_mm512_set1_ps(1.0F), v_scale1);auto v_zero = _mm512_setzero_epi32();auto v_upper = _mm512_set1_epi32(15);@@ -447,9 +448,9 @@ void quantize_by_channel(const T* src,#if defined(HAVE_AVX2)for (; j + vec_len_f32_avx2 * 2 <= hidden_dims; j += vec_len_f32_avx2 * 2) {auto v_scale0 = mm256_uni_loadu_ps(scale + j);- v_scale0 = _mm256_div_ps(_mm256_set1_ps(1.0f), v_scale0);+ v_scale0 = _mm256_div_ps(_mm256_set1_ps(1.0F), v_scale0);auto v_scale1 = mm256_uni_loadu_ps(scale + j + vec_len_f32_avx2);- v_scale1 = _mm256_div_ps(_mm256_set1_ps(1.0f), v_scale1);+ v_scale1 = _mm256_div_ps(_mm256_set1_ps(1.0F), v_scale1);auto v_zero = _mm256_setzero_si256();auto v_upper = _mm256_set1_epi32(15);@@ -493,10 +494,10 @@ void quant_u4(const T* src, void* dst, size_t n, float& scale, float& zp) {float max = -FLT_MAX;float min = FLT_MAX;find_minmax(src, n, min, max);- auto dst_ptr = reinterpret_cast<uint8_t*>(dst);+ auto* dst_ptr = reinterpret_cast<uint8_t*>(dst);scale = (max - min) / ((1 << 4) - 1);if (scale == 0) {- scale = 0.0001f;+ scale = 0.0001F;}zp = -min / scale;#if defined(HAVE_AVX512F)@@ -551,16 +552,19 @@ void quant_u4(const T* src, void* dst, size_t n, float& scale, float& zp) {}template <typename T, ov::element::Type_t DST_PREC, std::enable_if_t<DST_PREC == ov::element::u8, bool> = true>+// NOLINTNEXTLINE(readability-non-const-parameter) scale_zp stores quantization outputs.void quantize(const T* src, uint8_t* dst, size_t n, float* scale_zp) {quant_u8(src, dst, n, *scale_zp, *(scale_zp + 1));}template <typename T, ov::element::Type_t DST_PREC, std::enable_if_t<DST_PREC == ov::element::i8, bool> = true>+// NOLINTNEXTLINE(readability-non-const-parameter) scale_zp stores quantization outputs.void quantize(const T* src, uint8_t* dst, size_t n, float* scale_zp) {quant_i8(src, reinterpret_cast<int8_t*>(dst), n, *scale_zp);}template <typename T, ov::element::Type_t DST_PREC, std::enable_if_t<DST_PREC == ov::element::u4, bool> = true>+// NOLINTNEXTLINE(readability-non-const-parameter) scale_zp stores quantization outputs.void quantize(const T* src, void* dst, size_t n, float* scale_zp) {quant_u4(src, dst, n, *scale_zp, *(scale_zp + 1));}@@ -581,9 +585,9 @@ void quantize_q_by_dims(const ov::intel_cpu::PlainTensor& src,size_t m = 0;for (size_t src_offset = 0, dst_offset = 0; src_offset < S;src_offset += group_size, dst_offset += group_size / sub_byte_multiplier + param_size) {- auto base = dst.ptr<uint8_t, DST_PREC>(b, h, 0);+ auto* base = dst.ptr<uint8_t, DST_PREC>(b, h, 0);base += dst_offset;- auto p = reinterpret_cast<float*>(base);+ auto* p = reinterpret_cast<float*>(base);uint8_t* ptr = base + param_size;quantize<T, DST_PREC>(src.ptr<T>(b, h, m, src_offset), ptr, group_size, p);}@@ -592,17 +596,16 @@ void quantize_q_by_dims(const ov::intel_cpu::PlainTensor& src,template <typename TDST,ov::element::Type_t SRC_PREC,typename std::enable_if_t<SRC_PREC == ov::element::u8, bool> = true>-void attn_dequant_kernel(const void* src, TDST* dst, size_t n, float* params) {+void attn_dequant_kernel(const void* src, TDST* dst, size_t n, const float* params) {size_t i = 0;- // loadu_si128/epi64 does not support const qualifier- uint8_t* src_nc = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(src));+ const auto* src_nc = reinterpret_cast<const uint8_t*>(src);float scale = params[0];float zp = params[1];#if defined(HAVE_AVX512F)auto v_zp = _mm512_set1_ps(zp);auto v_scale = _mm512_set1_ps(scale);for (; i + vec_len_f32_avx512 <= n; i += vec_len_f32_avx512) {- auto v0_128 = _mm_loadu_si128(reinterpret_cast<__m128i*>(src_nc + i));+ auto v0_128 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(src_nc + i));auto v0_512 = _mm512_cvtepu8_epi32(v0_128);auto v0_value = _mm512_cvtepi32_ps(v0_512);v0_value = _mm512_sub_ps(v0_value, v_zp);@@ -613,7 +616,7 @@ void attn_dequant_kernel(const void* src, TDST* dst, size_t n, float* params) {auto v_zp = _mm256_set1_ps(zp);auto v_scale = _mm256_set1_ps(scale);for (; i + vec_len_f32_avx2 <= n; i += vec_len_f32_avx2) {- auto v0_128 = _mm_loadl_epi64(reinterpret_cast<__m128i*>(src_nc + i));+ auto v0_128 = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(src_nc + i));auto v0_256 = _mm256_cvtepu8_epi32(v0_128);auto v0_value = _mm256_cvtepi32_ps(v0_256);v0_value = _mm256_sub_ps(v0_value, v_zp);@@ -631,15 +634,14 @@ void attn_dequant_kernel(const void* src, TDST* dst, size_t n, float* params) {template <typename TDST,ov::element::Type_t SRC_PREC,typename std::enable_if_t<SRC_PREC == ov::element::i8, bool> = true>-void attn_dequant_kernel(const void* src, TDST* dst, size_t n, float* params) {+void attn_dequant_kernel(const void* src, TDST* dst, size_t n, const float* params) {size_t i = 0;- // loadu_si128/epi64 does not support const qualifier- int8_t* src_nc = const_cast<int8_t*>(reinterpret_cast<const int8_t*>(src));+ const auto* src_nc = reinterpret_cast<const int8_t*>(src);float scale = params[0];#if defined(HAVE_AVX512F)auto v_scale = _mm512_set1_ps(scale);for (; i + vec_len_f32_avx512 <= n; i += vec_len_f32_avx512) {- auto v0_128 = _mm_loadu_si128(reinterpret_cast<__m128i*>(src_nc + i));+ auto v0_128 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(src_nc + i));auto v0_512 = _mm512_cvtepi8_epi32(v0_128);auto v0_value = _mm512_cvtepi32_ps(v0_512);auto v0_out = _mm512_mul_ps(v0_value, v_scale);@@ -648,7 +650,7 @@ void attn_dequant_kernel(const void* src, TDST* dst, size_t n, float* params) {#elif defined(HAVE_AVX2)auto v_scale = _mm256_set1_ps(scale);for (; i + vec_len_f32_avx2 <= n; i += vec_len_f32_avx2) {- auto v0_128 = _mm_loadl_epi64(reinterpret_cast<__m128i*>(src_nc + i));+ auto v0_128 = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(src_nc + i));auto v0_256 = _mm256_cvtepi8_epi32(v0_128);auto v0_value = _mm256_cvtepi32_ps(v0_256);auto v0_out = _mm256_mul_ps(v0_value, v_scale);@@ -664,8 +666,8 @@ void attn_dequant_kernel(const void* src, TDST* dst, size_t n, float* params) {template <typename TDST,ov::element::Type_t SRC_PREC,- typename std::enable_if<SRC_PREC == ov::element::u4, bool>::type = true>-void attn_dequant_kernel(const void* src, TDST* dst, size_t n, float* params) {+ typename std::enable_if_t<SRC_PREC == ov::element::u4, bool> = true>+void attn_dequant_kernel(const void* src, TDST* dst, size_t n, const float* params) {// 2 4bit data form a byte/* 0,1|2,3|4,5|6,7/ \@@ -676,14 +678,14 @@ void attn_dequant_kernel(const void* src, TDST* dst, size_t n, float* params) {0,1,2,3,4,5,6,7*/size_t i = 0;- uint8_t* src_nc = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(src));+ const auto* src_nc = reinterpret_cast<const uint8_t*>(src);float scale = params[0];float zp = params[1];#if defined(HAVE_AVX512F)auto v_scale = _mm512_set1_ps(scale);auto v_zp_scale = _mm512_set1_ps(zp * scale);for (; i + vec_len_f32_avx512 * 2 <= n; i += vec_len_f32_avx512 * 2) {- auto data = _mm_loadu_si128(reinterpret_cast<__m128i*>(src_nc + i / 2));+ auto data = _mm_loadu_si128(reinterpret_cast<const __m128i*>(src_nc + i / 2));auto v_i32 = _mm512_cvtepu8_epi32(data);auto v_512_low_half = _mm512_srli_epi32(v_i32, 4);@@ -706,7 +708,7 @@ void attn_dequant_kernel(const void* src, TDST* dst, size_t n, float* params) {auto v256_zp = _mm256_set1_ps(zp);auto v256_scale = _mm256_set1_ps(scale);for (; i + vec_len_f32_avx2 * 2 <= n; i += vec_len_f32_avx2 * 2) {- auto data = _mm_loadl_epi64(reinterpret_cast<__m128i*>(src_nc + i / 2));+ auto data = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(src_nc + i / 2));auto v_i32 = _mm256_cvtepu8_epi32(data);auto v_256_low_half = _mm256_srli_epi32(v_i32, 4);@@ -751,15 +753,15 @@ void attn_dequant_by_channel_kernel(const void* src,size_t hidden_dims,size_t src_stride,size_t dst_stride,- float* scale,- float* zp) {- uint8_t* src_nc = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(src));+ const float* scale,+ const float* zp) {+ const auto* src_nc = reinterpret_cast<const uint8_t*>(src);for (size_t i = 0; i < seq_dim; ++i) {size_t j = 0;#if defined(HAVE_AVX512F)while (j + vec_len_f32_avx512 <= hidden_dims) {- auto v0_128 = _mm_loadu_si128(reinterpret_cast<__m128i*>(src_nc + j + i * src_stride));+ auto v0_128 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(src_nc + j + i * src_stride));auto v0_512 = _mm512_cvtepu8_epi32(v0_128);auto v0_value = _mm512_cvtepi32_ps(v0_512);v0_value = _mm512_sub_ps(v0_value, _mm512_loadu_ps(zp + j));@@ -770,7 +772,7 @@ void attn_dequant_by_channel_kernel(const void* src,#endif#if defined(HAVE_AVX2)while (j + vec_len_f32_avx2 <= hidden_dims) {- auto v0_128 = _mm_loadl_epi64(reinterpret_cast<__m128i*>(src_nc + j + i * src_stride));+ auto v0_128 = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(src_nc + j + i * src_stride));auto v0_256 = _mm256_cvtepu8_epi32(v0_128);auto v0_value = _mm256_cvtepi32_ps(v0_256);v0_value = _mm256_sub_ps(v0_value, _mm256_loadu_ps(zp + j));@@ -795,9 +797,9 @@ void attn_dequant_by_channel_kernel(const void* src,size_t hidden_dims,size_t src_stride,size_t dst_stride,- float* scale,- float* zp) {- uint8_t* src_nc = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(src));+ const float* scale,+ const float* zp) {+ const auto* src_nc = reinterpret_cast<const uint8_t*>(src);size_t j = 0;#if defined(HAVE_AVX512F)for (; j + vec_len_f32_avx512 * 2 <= hidden_dims; j += vec_len_f32_avx512 * 2) {@@ -846,9 +848,9 @@ void attn_dequant_by_channel_kernel(const void* src,}#if defined(HAVE_SVE)-void inline attn_dequant_u8_kernel(const uint8_t* src, float* dst, size_t n, float* params) {+void inline attn_dequant_u8_kernel(const uint8_t* src, float* dst, size_t n, const float* params) {size_t i = 0;- uint8_t* src_nc = const_cast<uint8_t*>(src);+ const auto* src_nc = src;float scale = params[0];float zp = params[1];size_t nvec = n / svcntw();diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/cache_reorder.cpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/cache_reorder.cppnew file mode 100644index 00000000000..ebd54a03a4d--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/cache_reorder.cpp@@ -0,0 +1,534 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "cache_reorder.hpp"++#include <cstddef>+#include <cstdint>+#include <cstring>+#include <vector>++#include "attn_quant_kernel.hpp"+#include "common.hpp"+#include "cpu_parallel.hpp"+#include "openvino/core/except.hpp"+#include "openvino/core/type/element_type.hpp"+#include "openvino/core/type/element_type_traits.hpp"+#include "utils/plain_tensor.hpp"+namespace ov::Extensions::Cpu::XARCH {++using ov::intel_cpu::CpuParallelPtr;+using ov::intel_cpu::PlainTensor;++namespace {++void validate_begin_offsets(const int32_t* begins_ptr,+ size_t begins_count,+ size_t upper_bound,+ const char* tensor_name) {+ for (size_t i = 0; i < begins_count; i++) {+ const int32_t begin = begins_ptr[i];+ OPENVINO_ASSERT(begin >= 0, tensor_name, " contains a negative offset at index ", i, ": ", begin, ".");+ OPENVINO_ASSERT(static_cast<size_t>(begin) <= upper_bound,+ tensor_name,+ " offset at index ",+ i,+ " is out of range: ",+ begin,+ " > ",+ upper_bound,+ ".");+ if (i + 1 == begins_count) {+ continue;+ }++ const int32_t next_begin = begins_ptr[i + 1];+ OPENVINO_ASSERT(next_begin >= begin,+ tensor_name,+ " must be monotonic, but offsets at indices ",+ i,+ " and ",+ i + 1,+ " are ",+ begin,+ " and ",+ next_begin,+ ".");+ }+}++/**+ * @brief Batch reorder context for collecting operations with same block pair+ */+struct BatchReorderContext {+ size_t src_block = 0;+ size_t dst_block = 0;+ int32_t op_begin = 0;+ int32_t op_end = 0;+ size_t block_size = 0;+ size_t dst_actual_tokens = 0;+ const int32_t* update_ptr = nullptr;+ size_t hidden = 0;+ bool same_block = false;+};++/**+ * @brief Process cache batch for quantized types+ */+template <ov::element::Type_t PREC>+void process_cache_batch_quantized(PlainTensor& cache,+ const BatchReorderContext& ctx,+ bool by_channel,+ size_t kv_heads,+ const CpuParallelPtr& cpu_parallel) {+ using value_type = typename ov::element_type_traits<PREC>::value_type;+ static constexpr size_t elem_size = sizeof(value_type);+ static constexpr size_t sub_byte = get_sub_byte_multiplier(PREC);+ const size_t token_bytes = ctx.hidden * elem_size / sub_byte;++ auto process_head = [&](size_t h) {+ if (by_channel) {+ std::vector<float> local_block_buf(ctx.block_size * ctx.hidden);+ std::vector<float> local_row_buf(ctx.hidden);++ auto* src_base = reinterpret_cast<uint8_t*>(cache.ptr_v(ctx.src_block, h, 0, 0));+ auto* dst_base = reinterpret_cast<uint8_t*>(cache.ptr_v(ctx.dst_block, h, 0, 0));+ auto* src_scales = reinterpret_cast<float*>(src_base);+ auto* src_zps = src_scales + ctx.hidden;+ auto* dst_scales = reinterpret_cast<float*>(dst_base);+ auto* dst_zps = dst_scales + ctx.hidden;++ const size_t params_offset = 2 * sizeof(float) * ctx.hidden;+ auto* src_data = src_base + params_offset;+ auto* dst_data = dst_base + params_offset;+ const size_t data_stride = cache.stride_bytes(2);++ if (ctx.same_block) {+ for (int32_t batch_op = ctx.op_begin; batch_op < ctx.op_end; batch_op++) {+ const int32_t b_pair_base = batch_op * 2;+ const int32_t b_src_logical = ctx.update_ptr[b_pair_base + 0];+ const int32_t b_dst_logical = ctx.update_ptr[b_pair_base + 1];+ if (b_src_logical < 0 || b_dst_logical < 0) {+ continue;+ }++ const auto b_src_token = static_cast<size_t>(b_src_logical) % ctx.block_size;+ const auto b_dst_token = static_cast<size_t>(b_dst_logical) % ctx.block_size;++ std::memcpy(dst_data + b_dst_token * data_stride,+ src_data + b_src_token * data_stride,+ token_bytes);+ }+ } else {+ attn_dequant_by_channel_kernel<float, PREC>(dst_data,+ local_block_buf.data(),+ ctx.dst_actual_tokens,+ ctx.hidden,+ data_stride,+ ctx.hidden,+ dst_scales,+ dst_zps);++ for (int32_t batch_op = ctx.op_begin; batch_op < ctx.op_end; batch_op++) {+ const int32_t b_pair_base = batch_op * 2;+ const int32_t b_src_logical = ctx.update_ptr[b_pair_base + 0];+ const int32_t b_dst_logical = ctx.update_ptr[b_pair_base + 1];+ if (b_src_logical < 0 || b_dst_logical < 0) {+ continue;+ }++ const auto b_src_token = static_cast<size_t>(b_src_logical) % ctx.block_size;+ const auto b_dst_token = static_cast<size_t>(b_dst_logical) % ctx.block_size;++ attn_dequant_by_channel_kernel<float, PREC>(src_data + b_src_token * data_stride,+ local_row_buf.data(),+ 1,+ ctx.hidden,+ data_stride,+ ctx.hidden,+ src_scales,+ src_zps);++ std::memcpy(local_block_buf.data() + b_dst_token * ctx.hidden,+ local_row_buf.data(),+ ctx.hidden * sizeof(float));+ }++ quantize_by_channel<float, PREC>(local_block_buf.data(),+ dst_data,+ ctx.dst_actual_tokens,+ ctx.hidden,+ ctx.hidden,+ data_stride,+ dst_scales,+ dst_zps);+ }+ } else {+ for (int32_t batch_op = ctx.op_begin; batch_op < ctx.op_end; batch_op++) {+ const int32_t b_pair_base = batch_op * 2;+ const int32_t b_src_logical = ctx.update_ptr[b_pair_base + 0];+ const int32_t b_dst_logical = ctx.update_ptr[b_pair_base + 1];+ if (b_src_logical < 0 || b_dst_logical < 0) {+ continue;+ }++ const auto b_src_token = static_cast<size_t>(b_src_logical) % ctx.block_size;+ const auto b_dst_token = static_cast<size_t>(b_dst_logical) % ctx.block_size;++ auto* src_ptr = reinterpret_cast<uint8_t*>(cache.ptr_v(ctx.src_block, h, b_src_token, 0));+ auto* dst_ptr = reinterpret_cast<uint8_t*>(cache.ptr_v(ctx.dst_block, h, b_dst_token, 0));+ std::memcpy(dst_ptr, src_ptr, token_bytes);+ }+ }+ };++ cpu_parallel->parallel_for(kv_heads, process_head);+}++/**+ * @brief Process cache batch for non-quantized types+ */+template <ov::element::Type_t PREC>+void process_cache_batch_non_quantized(PlainTensor& cache,+ const BatchReorderContext& ctx,+ size_t kv_heads,+ const CpuParallelPtr& cpu_parallel) {+ using value_type = typename ov::element_type_traits<PREC>::value_type;+ static constexpr size_t elem_size = sizeof(value_type);+ static constexpr size_t sub_byte = get_sub_byte_multiplier(PREC);+ const size_t token_bytes = ctx.hidden * elem_size / sub_byte;++ auto process_head = [&](size_t h) {+ for (int32_t batch_op = ctx.op_begin; batch_op < ctx.op_end; batch_op++) {+ const int32_t b_pair_base = batch_op * 2;+ const int32_t b_src_logical = ctx.update_ptr[b_pair_base + 0];+ const int32_t b_dst_logical = ctx.update_ptr[b_pair_base + 1];+ if (b_src_logical < 0 || b_dst_logical < 0) {+ continue;+ }++ const auto b_src_token = static_cast<size_t>(b_src_logical) % ctx.block_size;+ const auto b_dst_token = static_cast<size_t>(b_dst_logical) % ctx.block_size;++ auto* src_ptr = reinterpret_cast<uint8_t*>(cache.ptr_v(ctx.src_block, h, b_src_token, 0));+ auto* dst_ptr = reinterpret_cast<uint8_t*>(cache.ptr_v(ctx.dst_block, h, b_dst_token, 0));+ std::memcpy(dst_ptr, src_ptr, token_bytes);+ }+ };++ cpu_parallel->parallel_for(kv_heads, process_head);+}++void dispatch_and_process_cache(ov::element::Type_t prec,+ PlainTensor& cache,+ const BatchReorderContext& ctx,+ bool by_channel,+ size_t kv_heads,+ const CpuParallelPtr& cpu_parallel) {+ if (prec == ov::element::u8) {+ process_cache_batch_quantized<ov::element::u8>(cache, ctx, by_channel, kv_heads, cpu_parallel);+ } else if (prec == ov::element::u4) {+ process_cache_batch_quantized<ov::element::u4>(cache, ctx, by_channel, kv_heads, cpu_parallel);+ } else if (prec == ov::element::f32) {+ process_cache_batch_non_quantized<ov::element::f32>(cache, ctx, kv_heads, cpu_parallel);+ } else if (prec == ov::element::bf16) {+ process_cache_batch_non_quantized<ov::element::bf16>(cache, ctx, kv_heads, cpu_parallel);+ } else if (prec == ov::element::f16) {+ process_cache_batch_non_quantized<ov::element::f16>(cache, ctx, kv_heads, cpu_parallel);+ } else {+ OPENVINO_THROW("PaKVReorder supports only f32, bf16, f16, u8, and u4 KV cache precisions. ",+ "Received cache element type: ",+ prec,+ ".",+ prec == ov::element::i8 ? " int8 KV cache is not supported." : "");+ }+}++// Reorder a single cache tensor (either K or V). The loop over sequences and the per-sequence+// batch grouping are run independently for K and V so that one full tensor is processed before+// the other, which keeps the active working set on a single tensor and lets hardware prefetchers+// and the L2/L3 working set stay focused. The cost is that the bookkeeping (max-dst scan and+// batch grouping) is recomputed once per pass.+void reorder_one_cache(PlainTensor& cache,+ ov::element::Type_t prec,+ bool by_channel,+ size_t hidden,+ size_t kv_heads,+ size_t block_size,+ size_t seq_count,+ const int32_t* block_idx_ptr,+ const int32_t* block_idx_begins_ptr,+ const int32_t* update_ptr,+ const int32_t* update_begins_ptr,+ const CpuParallelPtr& cpu_parallel) {+ cpu_parallel->parallel_for(seq_count, [&](size_t seq) {+ const int32_t op_begin = update_begins_ptr[seq];+ const int32_t op_end = update_begins_ptr[seq + 1];+ if (op_end <= op_begin) {+ return;+ }++ const int32_t block_indices_base = block_idx_begins_ptr[seq];+ const int32_t blocks_in_seq = block_idx_begins_ptr[seq + 1] - block_indices_base;+ if (blocks_in_seq <= 0) {+ return;+ }++ int32_t max_dst_logical = -1;+ size_t max_dst_block_local = 0;+ size_t max_dst_token = 0;+ for (int32_t op = op_begin; op < op_end; op++) {+ const int32_t dst_logical = update_ptr[op * 2 + 1];+ if (dst_logical > max_dst_logical) {+ max_dst_logical = dst_logical;+ max_dst_block_local = static_cast<size_t>(dst_logical) / block_size;+ max_dst_token = static_cast<size_t>(dst_logical) % block_size;+ }+ }++ auto get_block_actual_tokens = [&](size_t block_local) -> size_t {+ if (block_local < max_dst_block_local) {+ return block_size;+ }+ if (block_local == max_dst_block_local) {+ return max_dst_token + 1;+ }+ return block_size;+ };++ for (int32_t op = op_begin; op < op_end;) {+ const int32_t pair_base = op * 2;+ const int32_t src_logical = update_ptr[pair_base + 0];+ const int32_t dst_logical = update_ptr[pair_base + 1];++ if (src_logical < 0 || dst_logical < 0) {+ op++;+ continue;+ }++ const auto src_block_local = static_cast<size_t>(src_logical) / block_size;+ const auto dst_block_local = static_cast<size_t>(dst_logical) / block_size;++ if (src_block_local >= static_cast<size_t>(blocks_in_seq) ||+ dst_block_local >= static_cast<size_t>(blocks_in_seq)) {+ op++;+ continue;+ }++ const auto src_block = static_cast<size_t>(block_idx_ptr[block_indices_base + src_block_local]);+ const auto dst_block = static_cast<size_t>(block_idx_ptr[block_indices_base + dst_block_local]);++ int32_t batch_end = op + 1;+ while (batch_end < op_end) {+ const int32_t n_pair_base = batch_end * 2;+ const int32_t n_src_logical = update_ptr[n_pair_base + 0];+ const int32_t n_dst_logical = update_ptr[n_pair_base + 1];++ if (n_src_logical < 0 || n_dst_logical < 0) {+ batch_end++;+ continue;+ }++ const auto n_src_block_local = static_cast<size_t>(n_src_logical) / block_size;+ const auto n_dst_block_local = static_cast<size_t>(n_dst_logical) / block_size;++ if (n_src_block_local >= static_cast<size_t>(blocks_in_seq) ||+ n_dst_block_local >= static_cast<size_t>(blocks_in_seq)) {+ batch_end++;+ continue;+ }++ const auto n_src_block = static_cast<size_t>(block_idx_ptr[block_indices_base + n_src_block_local]);+ const auto n_dst_block = static_cast<size_t>(block_idx_ptr[block_indices_base + n_dst_block_local]);++ if (n_src_block != src_block || n_dst_block != dst_block) {+ break;+ }+ batch_end++;+ }++ BatchReorderContext ctx;+ ctx.src_block = src_block;+ ctx.dst_block = dst_block;+ ctx.same_block = (src_block == dst_block);+ ctx.op_begin = op;+ ctx.op_end = batch_end;+ ctx.block_size = block_size;+ ctx.dst_actual_tokens = get_block_actual_tokens(dst_block_local);+ ctx.update_ptr = update_ptr;+ ctx.hidden = hidden;++ dispatch_and_process_cache(prec, cache, ctx, by_channel, kv_heads, cpu_parallel);++ op = batch_end;+ }+ });+}++} // namespace++// Reorders KV cache tokens within each sequence after logical token positions change.+//+// Layout:+// * block_indices stores the physical KV-cache block ids for all sequences.+// * block_indices_begins is a prefix-sum array over block_indices, so+// block_indices[block_indices_begins[seq] : block_indices_begins[seq + 1]]+// is the block list for one sequence.+// * block_update_indices stores flattened (src_logical_token, dst_logical_token)+// pairs for all sequences.+// * block_update_indices_begins is a prefix-sum array over update pairs, so+// block_update_indices[2 * begin : 2 * end] is the update list for one+// sequence, where begin = block_update_indices_begins[seq] and+// end = block_update_indices_begins[seq + 1].+//+// For logical token t in sequence seq:+// seq_block_base = block_indices_begins[seq]+// block_local = t / block_size+// token_in_block = t % block_size+// physical_block = block_indices[seq_block_base + block_local]+// So the physical KV-cache location is (physical_block, token_in_block).+//+// Multi-sequence example with block_size = 4:+// block_indices = [100, 101, 102, 200, 201, 300]+// block_indices_begins = [0, 3, 5, 6]+// seq0 uses blocks [100, 101, 102]+// seq1 uses blocks [200, 201]+// seq2 uses blocks [300]+//+// block_update_indices = [0, 3, 7, 8, 0, 1]+// block_update_indices_begins = [0, 2, 2, 3]+// seq0 updates logical tokens (0 -> 3) and (7 -> 8)+// seq1 has no updates because begin == end == 2+// seq2 updates logical token (0 -> 1)+//+// Physical index calculation:+// seq0, 0 -> 3:+// 0: block_local = 0 / 4 = 0, token_in_block = 0 % 4 = 0,+// physical_block = block_indices[0 + 0] = 100 => (100, 0)+// 3: block_local = 3 / 4 = 0, token_in_block = 3 % 4 = 3,+// physical_block = block_indices[0 + 0] = 100 => (100, 3)+//+// seq0, 7 -> 8:+// 7: block_local = 7 / 4 = 1, token_in_block = 7 % 4 = 3,+// physical_block = block_indices[0 + 1] = 101 => (101, 3)+// 8: block_local = 8 / 4 = 2, token_in_block = 8 % 4 = 0,+// physical_block = block_indices[0 + 2] = 102 => (102, 0)+//+// seq2, 0 -> 1:+// 0: block_local = 0 / 4 = 0, token_in_block = 0 % 4 = 0,+// physical_block = block_indices[5 + 0] = 300 => (300, 0)+// 1: block_local = 1 / 4 = 0, token_in_block = 1 % 4 = 1,+// physical_block = block_indices[5 + 0] = 300 => (300, 1)+//+// Note that a sequence may have many blocks but no updates, or only a few+// updates; the number of update pairs is independent from the number of blocks.+//+// Cache payload handling for each update pair:+// * Non-quantized cache (f32/bf16/f16): copy the token payload bytes directly.+// * Quantized cache with by_channel == false (per-token / per-group params):+// each token row already carries its own scale/zp groups, so reorder copies+// the full token record as-is. No explicit dequant/requant is needed because+// the quant params move together with the token payload.+// Example: if one token row stores+// [scale0, zp0, q(group0), scale1, zp1, q(group1)],+// then seq2's 0 -> 1 update copies that whole row from (300, 0) to (300, 1).+// * Quantized cache with by_channel == true:+// each physical block stores shared per-channel scales/zps at the front of+// the block, and all token payloads inside that block are encoded with those+// shared params.+// - same physical block: raw quantized token bytes can be copied directly,+// because src and dst use the same scales/zps.+// - different physical blocks: raw byte copy is incorrect because src_block+// and dst_block may have different scales/zps. The implementation+// dequantizes the destination block into a float buffer using dst_block's+// params, dequantizes each moved source token using src_block's params,+// overwrites the destination float row, then requantizes the destination+// block back with dst_block's params.+// Example with seq0 above:+// - 0 -> 3 stays inside physical block 100, so the quantized token bytes+// move directly from (100, 0) to (100, 3).+// - 7 -> 8 crosses from (101, 3) to (102, 0), so token 7 is first+// dequantized with block 101's scales/zps, written into dst token 0 of a+// float buffer initialized from block 102, and then block 102 is+// requantized with block 102's own scales/zps.+void reorder_kv_cache(PlainTensor& key_cache,+ PlainTensor& value_cache,+ const PlainTensor& block_indices,+ const PlainTensor& block_indices_begins,+ const PlainTensor& block_update_indices,+ const PlainTensor& block_update_indices_begins,+ bool key_by_channel,+ bool value_by_channel,+ const CpuParallelPtr& cpu_parallel) {+ if (!block_update_indices || !block_update_indices_begins || block_update_indices.size(0) == 0 ||+ block_update_indices_begins.size(0) == 0) {+ return;+ }++ const size_t kv_heads = key_cache.size(1);+ const size_t key_hidden = key_cache.size(3);+ const size_t value_hidden = value_cache.size(3);+ const size_t key_sub_byte = get_sub_byte_multiplier(key_cache.get_precision());+ const size_t block_size =+ key_by_channel ? (key_cache.size(2) - 2 * sizeof(float) * key_sub_byte) : key_cache.size(2);+ const size_t seq_count = block_update_indices_begins.size(0) - 1;++ const auto* block_idx_ptr = block_indices.ptr<int32_t>();+ const auto* block_idx_begins_ptr = block_indices_begins.ptr<int32_t>();+ const auto* update_ptr = block_update_indices.ptr<int32_t>();+ const auto* update_begins_ptr = block_update_indices_begins.ptr<int32_t>();++ OPENVINO_ASSERT(block_indices_begins.size(0) == block_update_indices_begins.size(0),+ "block_indices_begins and block_update_indices_begins must have the same length, but got ",+ block_indices_begins.size(0),+ " and ",+ block_update_indices_begins.size(0),+ ".");+ OPENVINO_ASSERT(block_update_indices.size(0) % 2 == 0,+ "block_update_indices must contain src/dst pairs, but got ",+ block_update_indices.size(0),+ " elements.");+ validate_begin_offsets(block_idx_begins_ptr,+ block_indices_begins.size(0),+ block_indices.size(0),+ "block_indices_begins");+ validate_begin_offsets(update_begins_ptr,+ block_update_indices_begins.size(0),+ block_update_indices.size(0) / 2,+ "block_update_indices_begins");++ const auto key_prec = key_cache.get_precision();+ const auto value_prec = value_cache.get_precision();++ // Process the whole K tensor first, then the whole V tensor. K and V are independent address+ // ranges, so handling them in separate passes keeps each pass focused on a single tensor's+ // working set instead of bouncing between two large buffers per batch group.+ reorder_one_cache(key_cache,+ key_prec,+ key_by_channel,+ key_hidden,+ kv_heads,+ block_size,+ seq_count,+ block_idx_ptr,+ block_idx_begins_ptr,+ update_ptr,+ update_begins_ptr,+ cpu_parallel);++ reorder_one_cache(value_cache,+ value_prec,+ value_by_channel,+ value_hidden,+ kv_heads,+ block_size,+ seq_count,+ block_idx_ptr,+ block_idx_begins_ptr,+ update_ptr,+ update_begins_ptr,+ cpu_parallel);+}++} // namespace ov::Extensions::Cpu::XARCHdiff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/cache_reorder.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/cache_reorder.hppnew file mode 100644index 00000000000..c109ab9c133--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/cache_reorder.hpp@@ -0,0 +1,21 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+#pragma once++#include "cpu_parallel.hpp"+#include "utils/plain_tensor.hpp"++namespace ov::Extensions::Cpu::XARCH {++void reorder_kv_cache(ov::intel_cpu::PlainTensor& key_cache,+ ov::intel_cpu::PlainTensor& value_cache,+ const ov::intel_cpu::PlainTensor& block_indices,+ const ov::intel_cpu::PlainTensor& block_indices_begins,+ const ov::intel_cpu::PlainTensor& block_update_indices,+ const ov::intel_cpu::PlainTensor& block_update_indices_begins,+ bool key_by_channel,+ bool value_by_channel,+ const ov::intel_cpu::CpuParallelPtr& cpu_parallel);++} // namespace ov::Extensions::Cpu::XARCHdiff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/common.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/common.hppindex 666bb4ea98c..1a5e87a1bc1 100644--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/common.hpp+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/common.hpp@@ -40,9 +40,9 @@namespace ov::Extensions::Cpu::XARCH {// avx512/avx2 register length in byte-static constexpr size_t vec_len_avx512 = 64LU;-static constexpr size_t vec_len_avx2 = 32LU;-static constexpr size_t vec_len_neon = 16LU;+static constexpr size_t vec_len_avx512 = 64UL;+static constexpr size_t vec_len_avx2 = 32UL;+static constexpr size_t vec_len_neon = 16UL;// avx512/avx2 register length in floatstatic constexpr size_t vec_len_f32_avx512 = vec_len_avx512 / sizeof(float);static constexpr size_t vec_len_f32_avx2 = vec_len_avx2 / sizeof(float);@@ -406,16 +406,16 @@ inline svfloat32_t exp_ps_sve(svbool_t& pg, svfloat32_t& src) {const auto c5 = svreinterpret_f32_u32(svdup_n_u32(0x3c072010));const auto shift = svreinterpret_f32_u32(svdup_n_u32(0x4b00007f)); // 2^23 + 127 = 0x1.0000fep23f- const auto one = svdup_n_f32(1.0f); // 1- const auto two = svdup_n_f32(2.0f); // 2+ const auto one = svdup_n_f32(1.0F); // 1+ const auto two = svdup_n_f32(2.0F); // 2const auto inv_ln2 = svreinterpret_f32_u32(svdup_n_u32(0x3fb8aa3b));const auto neg_ln2_hi = svreinterpret_f32_u32(svdup_n_u32(0xbf317200));const auto neg_ln2_lo = svreinterpret_f32_u32(svdup_n_u32(0xb5bfbe8e));const auto inf = svdup_n_f32(std::numeric_limits<float>::infinity());- const auto max_input = svdup_n_f32(88.37f); // Approximately ln(2^127.5)+ const auto max_input = svdup_n_f32(88.37F); // Approximately ln(2^127.5)const auto zero = svdup_n_f32(0.F);- const auto min_input = svdup_n_f32(-86.64f); // Approximately ln(2^-125)+ const auto min_input = svdup_n_f32(-86.64F); // Approximately ln(2^-125)auto x = svmin_f32_z(pg, src, max_input);x = svmax_f32_z(pg, x, min_input);@@ -498,27 +498,27 @@ inline float32x4_t exp_ps_neon_f32(const float32x4_t& src) {return poly;}-inline float32x4_t _vld1q_f32(const ov::bfloat16* a) {+inline float32x4_t loadq_f32(const ov::bfloat16* a) {uint16x4_t vec_bf16 = vld1_u16(reinterpret_cast<const uint16_t*>(a));float32x4_t vec_f32 = vcvtq_f32_u32(vmovl_u16(vec_bf16));return vec_f32;}-inline float32x4_t _vld1q_f32(const float* a) {+inline float32x4_t loadq_f32(const float* a) {return vld1q_f32(a);}-inline float32x4_t _vld1q_f32(const ov::float16* a) {- const auto* _a = reinterpret_cast<const float16_t*>(a);- return vcvt_f32_f16(vld1_f16(_a));+inline float32x4_t loadq_f32(const ov::float16* a) {+ const auto* a_fp16 = reinterpret_cast<const float16_t*>(a);+ return vcvt_f32_f16(vld1_f16(a_fp16));}-inline void _vst1q_f32(float* a, float32x4_t b) {+inline void storeq_f32(float* a, float32x4_t b) {vst1q_f32(a, b);}-inline void _vst1q_f32(ov::float16* a, float32x4_t b) {+inline void storeq_f32(ov::float16* a, float32x4_t b) {float16x4_t v_f16 = vcvt_f16_f32(b);vst1_f16(reinterpret_cast<float16_t*>(a), v_f16);}-inline void _vst1q_f32(ov::bfloat16* a, float32x4_t b) {+inline void storeq_f32(ov::bfloat16* a, float32x4_t b) {uint32x4_t v_int32 = vreinterpretq_u32_f32(b);uint16x4_t v_bf16 = vshrn_n_u32(v_int32, 16);@@ -614,7 +614,7 @@ void cvt_add(TDST* dst, TA* a, TB* b, size_t m, size_t n, size_t a_stride, size_}template <typename TA, typename TB>-float dot_product(TA* a,+float dot_product(const TA* a,const TB* b,size_t n,[[maybe_unused]] const float* scale,@@ -666,10 +666,10 @@ float dot_product(TA* a,vsum0 = _mm512_add_ps(vsum0, vsum2);sum = _mm512_reduce_add_ps(vsum0);#elif defined(HAVE_AVX2)- auto vsum0 = _mm256_set1_ps(0.0f);- auto vsum1 = _mm256_set1_ps(0.0f);- auto vsum2 = _mm256_set1_ps(0.0f);- auto vsum3 = _mm256_set1_ps(0.0f);+ auto vsum0 = _mm256_set1_ps(0.0F);+ auto vsum1 = _mm256_set1_ps(0.0F);+ auto vsum2 = _mm256_set1_ps(0.0F);+ auto vsum3 = _mm256_set1_ps(0.0F);for (; i + 4 * vec_len_f32_avx2 <= n; i += vec_len_f32_avx2 * 4) {auto va0 = mm256_uni_loadu_ps(a + i);auto va1 = mm256_uni_loadu_ps(a + i + vec_len_f32_avx2);@@ -715,25 +715,25 @@ float dot_product(TA* a,# if defined(HAVE_SVE)if constexpr (std::is_same_v<TA, float> && std::is_same_v<TB, float>) {svbool_t pg = svptrue_b32();- svfloat32_t sum0 = svdup_n_f32(0.0f);- svfloat32_t sum1 = svdup_n_f32(0.0f);- svfloat32_t sum2 = svdup_n_f32(0.0f);- svfloat32_t sum3 = svdup_n_f32(0.0f);+ svfloat32_t sum0 = svdup_n_f32(0.0F);+ svfloat32_t sum1 = svdup_n_f32(0.0F);+ svfloat32_t sum2 = svdup_n_f32(0.0F);+ svfloat32_t sum3 = svdup_n_f32(0.0F);auto vec_len = vec_len_f32_sve();- auto _a = reinterpret_cast<float32_t*>(a);- const auto* _b = reinterpret_cast<const float32_t*>(b);+ const auto* a_ptr = reinterpret_cast<const float32_t*>(a);+ const auto* b_ptr = reinterpret_cast<const float32_t*>(b);for (; i + 4 * vec_len <= n; i += 4 * vec_len) {- svfloat32_t a0 = svld1_f32(pg, _a + i);- svfloat32_t a1 = svld1_f32(pg, _a + i + vec_len);- svfloat32_t a2 = svld1_f32(pg, _a + i + vec_len * 2);- svfloat32_t a3 = svld1_f32(pg, _a + i + vec_len * 3);+ svfloat32_t a0 = svld1_f32(pg, a_ptr + i);+ svfloat32_t a1 = svld1_f32(pg, a_ptr + i + vec_len);+ svfloat32_t a2 = svld1_f32(pg, a_ptr + i + vec_len * 2);+ svfloat32_t a3 = svld1_f32(pg, a_ptr + i + vec_len * 3);- svfloat32_t b0 = svld1_f32(pg, _b + i);- svfloat32_t b1 = svld1_f32(pg, _b + i + vec_len);- svfloat32_t b2 = svld1_f32(pg, _b + i + vec_len * 2);- svfloat32_t b3 = svld1_f32(pg, _b + i + vec_len * 3);+ svfloat32_t b0 = svld1_f32(pg, b_ptr + i);+ svfloat32_t b1 = svld1_f32(pg, b_ptr + i + vec_len);+ svfloat32_t b2 = svld1_f32(pg, b_ptr + i + vec_len * 2);+ svfloat32_t b3 = svld1_f32(pg, b_ptr + i + vec_len * 3);sum0 = svmla_f32_z(pg, sum0, a0, b0);sum1 = svmla_f32_z(pg, sum1, a1, b1);@@ -741,27 +741,27 @@ float dot_product(TA* a,sum3 = svmla_f32_z(pg, sum3, a3, b3);}if (i + 2 * vec_len <= n) {- svfloat32_t a0 = svld1_f32(pg, _a + i);- svfloat32_t a1 = svld1_f32(pg, _a + i + vec_len);+ svfloat32_t a0 = svld1_f32(pg, a_ptr + i);+ svfloat32_t a1 = svld1_f32(pg, a_ptr + i + vec_len);- svfloat32_t b0 = svld1_f32(pg, _b + i);- svfloat32_t b1 = svld1_f32(pg, _b + i + vec_len);+ svfloat32_t b0 = svld1_f32(pg, b_ptr + i);+ svfloat32_t b1 = svld1_f32(pg, b_ptr + i + vec_len);sum0 = svmla_f32_z(pg, sum0, a0, b0);sum1 = svmla_f32_z(pg, sum1, a1, b1);i += 2 * vec_len;}if (i + vec_len <= n) {- svfloat32_t a0 = svld1_f32(pg, _a + i);- svfloat32_t b0 = svld1_f32(pg, _b + i);+ svfloat32_t a0 = svld1_f32(pg, a_ptr + i);+ svfloat32_t b0 = svld1_f32(pg, b_ptr + i);sum0 = svmla_f32_z(pg, sum0, a0, b0);i += vec_len;}// Process the tail elements parallely as well (if any)if (i != n) {svbool_t pg_rem = svwhilelt_b32(0, static_cast<int>(n - i));- svfloat32_t a0 = svld1_f32(pg_rem, _a + i);- svfloat32_t b0 = svld1_f32(pg_rem, _b + i);+ svfloat32_t a0 = svld1_f32(pg_rem, a_ptr + i);+ svfloat32_t b0 = svld1_f32(pg_rem, b_ptr + i);sum0 = svmla_f32_m(pg_rem, sum0, a0, b0);i = n;}@@ -779,15 +779,15 @@ float dot_product(TA* a,float32x4_t vsum3 = vdupq_n_f32(0.0F);for (; i + 4 * vec_len_f32_neon <= n; i += vec_len_f32_neon * 4) {- float32x4_t va0 = _vld1q_f32(a + i);- float32x4_t va1 = _vld1q_f32(a + i + vec_len_f32_neon);- float32x4_t va2 = _vld1q_f32(a + i + vec_len_f32_neon * 2);- float32x4_t va3 = _vld1q_f32(a + i + vec_len_f32_neon * 3);+ float32x4_t va0 = loadq_f32(a + i);+ float32x4_t va1 = loadq_f32(a + i + vec_len_f32_neon);+ float32x4_t va2 = loadq_f32(a + i + vec_len_f32_neon * 2);+ float32x4_t va3 = loadq_f32(a + i + vec_len_f32_neon * 3);- float32x4_t vb0 = _vld1q_f32(b + i);- float32x4_t vb1 = _vld1q_f32(b + i + vec_len_f32_neon);- float32x4_t vb2 = _vld1q_f32(b + i + vec_len_f32_neon * 2);- float32x4_t vb3 = _vld1q_f32(b + i + vec_len_f32_neon * 3);+ float32x4_t vb0 = loadq_f32(b + i);+ float32x4_t vb1 = loadq_f32(b + i + vec_len_f32_neon);+ float32x4_t vb2 = loadq_f32(b + i + vec_len_f32_neon * 2);+ float32x4_t vb3 = loadq_f32(b + i + vec_len_f32_neon * 3);vsum0 = vmlaq_f32(vsum0, va0, vb0);vsum1 = vmlaq_f32(vsum1, va1, vb1);@@ -795,19 +795,19 @@ float dot_product(TA* a,vsum3 = vmlaq_f32(vsum3, va3, vb3);}if (i + 2 * vec_len_f32_neon <= n) {- float32x4_t va0 = _vld1q_f32(a + i);- float32x4_t va1 = _vld1q_f32(a + i + vec_len_f32_neon);+ float32x4_t va0 = loadq_f32(a + i);+ float32x4_t va1 = loadq_f32(a + i + vec_len_f32_neon);- float32x4_t vb0 = _vld1q_f32(b + i);- float32x4_t vb1 = _vld1q_f32(b + i + vec_len_f32_neon);+ float32x4_t vb0 = loadq_f32(b + i);+ float32x4_t vb1 = loadq_f32(b + i + vec_len_f32_neon);vsum0 = vmlaq_f32(vsum0, va0, vb0);vsum1 = vmlaq_f32(vsum1, va1, vb1);i += 2 * vec_len_f32_neon;}if (i + vec_len_f32_neon <= n) {- float32x4_t va0 = _vld1q_f32(a + i);- float32x4_t vb0 = _vld1q_f32(b + i);+ float32x4_t va0 = loadq_f32(a + i);+ float32x4_t vb0 = loadq_f32(b + i);vsum0 = vmlaq_f32(vsum0, va0, vb0);i += vec_len_f32_neon;}@@ -828,7 +828,7 @@ float dot_product(TA* a,}template <typename TA>-float dot_product(TA* a,+float dot_product(const TA* a,const uint8_t* b,size_t n,const float* scale,@@ -839,10 +839,10 @@ float dot_product(TA* a,size_t group_id = 0;#if defined(HAVE_AVX512F)while (group_id < n / group_size) {- auto vsum0 = _mm512_set1_ps(0.0f);- auto vsum1 = _mm512_set1_ps(0.0f);- auto vsum2 = _mm512_set1_ps(0.0f);- auto vsum3 = _mm512_set1_ps(0.0f);+ auto vsum0 = _mm512_set1_ps(0.0F);+ auto vsum1 = _mm512_set1_ps(0.0F);+ auto vsum2 = _mm512_set1_ps(0.0F);+ auto vsum3 = _mm512_set1_ps(0.0F);float group_scale = *(scale + group_id * 2);float group_zp = *(zp + group_id * 2);auto v_zp = _mm512_set1_ps(group_zp);@@ -926,10 +926,10 @@ float dot_product(TA* a,float group_zp = *(zp + group_id * 2);size_t offset = group_id * group_size;size_t i = 0;- auto vsum0 = _mm256_set1_ps(0.0f);- auto vsum1 = _mm256_set1_ps(0.0f);- auto vsum2 = _mm256_set1_ps(0.0f);- auto vsum3 = _mm256_set1_ps(0.0f);+ auto vsum0 = _mm256_set1_ps(0.0F);+ auto vsum1 = _mm256_set1_ps(0.0F);+ auto vsum2 = _mm256_set1_ps(0.0F);+ auto vsum3 = _mm256_set1_ps(0.0F);for (; i + 4 * vec_len_f32_avx2 <= group_size; i += vec_len_f32_avx2 * 4) {auto va0 = mm256_uni_loadu_ps(a + offset + i);auto va1 = mm256_uni_loadu_ps(a + offset + i + vec_len_f32_avx2);@@ -1209,9 +1209,9 @@ inline void multiply_scalar_f32(ov::float16* a, ov::float16* a_dst, const ov::flfloat32x4_t v_val = vdupq_n_f32(val);size_t i = 0;for (; i + vec_len_f32_neon <= size; i += vec_len_f32_neon) {- v_a = _vld1q_f32((a + i));+ v_a = loadq_f32((a + i));v_res = vmulq_f32(v_a, v_val);- _vst1q_f32(a_dst + i, v_res);+ storeq_f32(a_dst + i, v_res);}auto val_f32 = static_cast<float>(val);for (; i < size; ++i) {@@ -1256,7 +1256,7 @@ inline void multiply_scalar(ov::float16* a, ov::float16* a_dst, const ov::float1#endifinline float reduce_sum(const float* data, size_t n) {- float s = 0.0f;+ float s = 0.0F;size_t i = 0;#if defined(HAVE_AVX512F){diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cppindex bd60694d6f9..6a0a4354996 100644--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cpp+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cpp@@ -8,8 +8,10 @@#include <cpu/x64/cpu_isa_traits.hpp>#include <cstdint>#include <cstring>+#include <limits>#include <memory>#include <type_traits>+#include <unordered_map>#include <vector>#include "cpu_memory.h"@@ -399,7 +401,10 @@ struct ScoreAggregationInfo {int32_t score_buf_num; // tmp buffer number for current headint32_t kv_len_aligned; // tmp buffer length for current block};-+struct QueryToQueryBiasInfo {+ size_t qq_begin_offset = 0; // offset into flattened qq_bias matrix+ size_t spec_num = 0; // number of draft tokens (matrix side length)+};template <typename DATA_TYPE, ov::element::Type_t KEY_PREC, ov::element::Type_t VALUE_PREC>struct MHAHelper {// initialize once@@ -454,6 +459,10 @@ struct MHAHelper {std::vector<int32_t> _image_group_end; // for image token i, the exclusive end of its groupstd::vector<int32_t> _image_group_begin; // for image token i, the inclusive start of its group+ // Speculative tree mask (qq_bias)+ PlainTensor _qq_bias;+ std::vector<QueryToQueryBiasInfo> _qq_bias_infos; // Precomputed info for each sequence+// Precompute image group boundaries from token_type_ids.// For each image token:// _image_group_end[i] = index past the last contiguous image token in the same group@@ -514,6 +523,96 @@ struct MHAHelper {return default_ncausal;}+ void clear_qq_bias() {+ _qq_bias = PlainTensor();+ _qq_bias_infos.clear();+ }++ // Initialize per-sequence metadata for speculative query-to-query masks.+ //+ // qq_bias stores one flattened square mask per scheduled sequence, concatenated back-to-back.+ // qq_bias_begins is the prefix-sum array that selects the slice for each sequence:+ // seq i -> qq_bias[qq_bias_begins[i] : qq_bias_begins[i + 1])+ //+ // Each non-empty slice must contain spec_num * spec_num elements, where spec_num is the number of+ // speculative tokens for that sequence. A value of 1 means "keep this speculative query->key edge",+ // and 0 means "mask it out". Empty slices are allowed and mean that the sequence has no speculative+ // query-to-query mask for this step.+ //+ // Example with three scheduled sequences:+ // qq_bias_begins = [0, 4, 4, 13]+ // seq0 -> qq_bias[0:4] -> 2 x 2 mask for 2 speculative tokens+ // seq1 -> qq_bias[4:4] -> empty, so no extra query-to-query masking+ // seq2 -> qq_bias[4:13] -> 3 x 3 mask for 3 speculative tokens+ //+ // If seq2 has:+ // qq_bias[4:13] = [+ // 1, 1, 0,+ // 1, 1, 1,+ // 1, 0, 1+ // ]+ // then for seq2:+ // - query_spec_idx = 0 and key_idx = past_len + 2 reads qq_bias[4 + 0 * 3 + 2] = 0, so that+ // speculative query cannot attend to the 3rd speculative key.+ // - query_spec_idx = 2 and key_idx = past_len + 1 reads qq_bias[4 + 2 * 3 + 1] = 0, so that+ // speculative query cannot attend to the 2nd speculative key.+ //+ // init_query_to_query_mask() only validates the per-sequence ranges and caches:+ // - qq_begin_offset: the starting offset in the flattened qq_bias tensor+ // - spec_num: the square side length used later by query_to_query_is_masked()+ // During attention, only key_idx >= past_len participates in this lookup; prompt/past KV tokens are+ // unaffected by qq_bias.+ void init_query_to_query_mask(const PlainTensor& qq_bias, const PlainTensor& qq_bias_begins) {+ _qq_bias = qq_bias;++ // Precompute QueryToQueryBiasInfo for each sequence+ const auto num_seqs = qq_bias_begins.m_dims[0] - 1;+ _qq_bias_infos.resize(num_seqs);++ for (size_t batch_in_seq = 0; batch_in_seq < num_seqs; batch_in_seq++) {+ QueryToQueryBiasInfo qq_bias_info;++ const auto qq_begin = static_cast<size_t>(qq_bias_begins.ptr<int32_t>()[batch_in_seq]);+ const auto qq_end = static_cast<size_t>(qq_bias_begins.ptr<int32_t>()[batch_in_seq + 1]);++ OPENVINO_ASSERT(qq_begin <= qq_end && qq_end <= qq_bias.size(0),+ "PagedAttention: qq_bias_begins contains invalid range");++ const auto qq_num = qq_end - qq_begin;+ if (qq_num > 0) {+ const auto spec_num = static_cast<size_t>(std::sqrt(static_cast<float>(qq_num)));++ OPENVINO_ASSERT(spec_num * spec_num == qq_num, "PagedAttention: qq_bias range length incorrect ");++ qq_bias_info.qq_begin_offset = qq_begin;+ qq_bias_info.spec_num = spec_num;+ }++ _qq_bias_infos[batch_in_seq] = qq_bias_info;+ }+ }++ bool query_to_query_is_masked(const QueryToQueryBiasInfo* cache,+ size_t query_spec_idx,+ size_t key_idx,+ size_t past_len) const {+ if (!_qq_bias || key_idx < past_len || cache == nullptr || cache->spec_num == 0) {+ return false;+ }++ if (query_spec_idx >= cache->spec_num) {+ return false;+ }++ const auto key_spec_idx = key_idx - past_len;+ if (key_spec_idx >= cache->spec_num) {+ return false;+ }++ const auto qq_off = cache->qq_begin_offset + query_spec_idx * cache->spec_num + key_spec_idx;+ return _qq_bias.ptr<uint8_t>()[qq_off] == 0;+ }+[[nodiscard]] size_t get_sliding_start_idx(size_t q_global_idx, size_t default_ncausal) const {const size_t sw_start = default_ncausal > _sliding_window ? default_ncausal - _sliding_window : 0UL;if (!_has_image_tokens || q_global_idx >= _image_group_begin.size()) {@@ -784,13 +883,16 @@ struct MHAHelper {const PlainTensor& sinks,size_t batch_in_seq = 0,const std::vector<PlainTensor>& sparse_attention_mask = {},- size_t q_token_start = 0) {+ size_t q_token_start = 0,+ const QueryToQueryBiasInfo* query_to_query_info_ptr = nullptr) {auto q_start = q_blk * _block_size;auto q_end = std::min(q_start + _block_size, q_len);auto q_cnt = q_end - q_start;constexpr bool q_is_xf16 = any_of(precision_of<DATA_TYPE>::value, ov::element::bf16, ov::element::f16);constexpr bool q_cache_is_same = precision_of<DATA_TYPE>::value == VALUE_PREC;auto cur_kv_len_blocks = div_up(cur_kv_len, _block_size);+ const size_t past_len = cur_kv_len - (q_blk * _block_size + q_cnt);+[[maybe_unused]] size_t sparse_scale = 1;[[maybe_unused]] std::function<std::pair<size_t, size_t>(size_t, size_t)> map_to_mask_idx =[](size_t q_blk_rt, size_t k_blk_rt) {@@ -866,6 +968,13 @@ struct MHAHelper {const auto causal_pos = cur_kv_len - q_cnt + (m - q_start) + 1;const auto ncausal = get_ncausal(q_token_start + m, causal_pos, cur_kv_len);auto* score = _weight.ptr<float>(ithr, h - hq_beg, m - q_start);+ if (query_to_query_info_ptr != nullptr) {+ for (size_t key_idx = past_len; key_idx < cur_kv_len; key_idx++) {+ if (query_to_query_is_masked(query_to_query_info_ptr, m, key_idx, past_len)) {+ score[key_idx] = -FLT_MAX;+ }+ }+ }// dequantization of q matrix could be fused with _d_scale since softmax is done by rowfloat revised_d_scale =_params.is_sage_attn@@ -1030,10 +1139,12 @@ struct MHAHelper {float* score_output,size_t q_start_idx_score,const ScoreAggregationInfo* score_info_ptr,- size_t q_token_start = 0) {+ size_t q_token_start = 0,+ const QueryToQueryBiasInfo* query_to_query_info_ptr = nullptr) {auto q_start = q_blk * _block_size;auto q_end = std::min(q_start + _block_size, q_len);auto q_cnt = q_end - q_start;+ const size_t past_len = cur_kv_len - (q_blk * _block_size + q_cnt);constexpr bool q_is_xf16 = any_of(precision_of<DATA_TYPE>::value, ov::element::bf16, ov::element::f16);auto cur_kv_len_blocks = div_up(cur_kv_len, _block_size);auto _score_stride = _weight.stride_bytes(2) / 2;@@ -1073,6 +1184,15 @@ struct MHAHelper {const auto ncausal = get_ncausal(q_token_start + m, causal_pos, cur_kv_len);auto soft_in = _weight.ptr<float>(ithr, h - hq_beg, m - q_start);auto score = _weight.ptr<float>(ithr, h - hq_beg, m - q_start);++ // Apply qq_bias mask+ if (query_to_query_info_ptr != nullptr) {+ for (size_t key_idx = past_len; key_idx < cur_kv_len; key_idx++) {+ if (query_to_query_is_masked(query_to_query_info_ptr, m, key_idx, past_len)) {+ score[key_idx] = -FLT_MAX;+ }+ }+ }PlainTensor f32_cvt;if (q_is_xf16) {f32_cvt.resize<float>({size_t{rnd_up(cur_kv_len, _block_size)}});@@ -1225,6 +1345,7 @@ struct MHAHelper {const auto ncausal = get_ncausal(q_token_start + pq, cur_kv_len, cur_kv_len);float* score = _weight.ptr<float>(ithr, h - hq_beg, pq);OPENVINO_DEBUG_ASSERT(score != nullptr, "PagedAttention: _weight buffer must be allocated");+float* alibi_lookup = nullptr;float alibi_slope = 0.F;if (alibi_slopes) {@@ -1780,6 +1901,11 @@ struct MHA {sub_query.resize({q_len, _helper.H, _helper.S}, q.ptr<DATA_TYPE>(batch_in_token));// physical layout (B_in_tokens, H, S)sub_query = sub_query.permute({1, 0, 2});++ QueryToQueryBiasInfo* query_to_query_info_ptr = nullptr;+ if (_helper._qq_bias && static_cast<size_t>(batch_in_seq) < _helper._qq_bias_infos.size()) {+ query_to_query_info_ptr = &_helper._qq_bias_infos[batch_in_seq];+ }# if defined(OPENVINO_ARCH_ARM64)if constexpr (q_is_xf16) {_helper.exec_kernel_multiple_kai(@@ -1801,7 +1927,8 @@ struct MHA {score_output,q_start_idx_score,score_info_ptr,- static_cast<size_t>(batch_in_token));+ static_cast<size_t>(batch_in_token),+ query_to_query_info_ptr);} else {_helper.exec_kernel_multiple(sub_query,@@ -1825,7 +1952,8 @@ struct MHA {PlainTensor(),0,{},- static_cast<size_t>(batch_in_token));+ static_cast<size_t>(batch_in_token),+ query_to_query_info_ptr);}# else_helper.exec_kernel_multiple(@@ -1850,7 +1978,8 @@ struct MHA {sinks,batch_in_seq,sparse_attention_mask,- static_cast<size_t>(batch_in_token));+ static_cast<size_t>(batch_in_token),+ query_to_query_info_ptr);# endif}});@@ -1889,13 +2018,19 @@ struct MHA {const PlainTensor& alibi_slopes,const PlainTensor& score_aggregation_window,const PlainTensor& sinks,- const std::vector<PlainTensor>& sparse_attention_mask) {+ const std::vector<PlainTensor>& sparse_attention_mask,+ const PlainTensor& qq_bias,+ const PlainTensor& qq_bias_begins) {_workitems.reset(query, past_lens, subsequence_begins, block_indices, block_indices_begins, _helper._block_size);if (output_score) {_helper.init_score_buffers(past_lens, subsequence_begins, score_aggregation_window);}-+ if (qq_bias) {+ _helper.init_query_to_query_mask(qq_bias, qq_bias_begins);+ } else {+ _helper.clear_qq_bias();+ }auto nthr = static_cast<size_t>(parallel_get_max_threads());if (past_lens.m_dims[0] >= nthr || _workitems.get_reorder_max_batch_size() > 0) {@@ -2058,8 +2193,12 @@ struct AttentionExecutor : public PagedAttentionExecutor {}}- OPENVINO_ASSERT(inputs[ID_QQ_BIAS]->getShape().hasZeroDims(),- "CPU plugin doesn't support qq_bias (tree mask) in paged attention yet");+ if (!inputs[ID_QQ_BIAS]->getShape().hasZeroDims()) {+ qq_bias.reset(inputs[ID_QQ_BIAS]);+ OPENVINO_ASSERT(!inputs[ID_QQ_BIAS_BEGINS]->getShape().hasZeroDims(),+ "PagedAttention: qq_bias_begins must be provided with qq_bias");+ qq_bias_begins.reset(inputs[ID_QQ_BIAS_BEGINS]);+ }output_emb.reset(outputs[0]);if (outputs.size() >= 2) {@@ -2217,6 +2356,11 @@ struct AttentionExecutor : public PagedAttentionExecutor {token_type_ids.assert_dims({B_token});}+ if (qq_bias) {+ qq_bias.assert_dims({0}, true);+ qq_bias_begins.assert_dims({B_seq + 1});+ }+output_emb.assert_dims({B_token, H * SV});output_emb = output_emb.reshape({B_token, 1, H * SV});@@ -2615,7 +2759,9 @@ struct AttentionExecutor : public PagedAttentionExecutor {alibi_slopes,score_aggregation_window,sinks,- sparse_attention_mask);+ sparse_attention_mask,+ qq_bias,+ qq_bias_begins);if (adaptive_rkv_evictable_sizes && adaptive_rkv_diversity_block_set_indices) {compute_adaptive_rkv_diversity(k_cache,diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_single_token.cpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_single_token.cppindex 28e25dbc8c4..ce83c00ca1c 100644--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_single_token.cpp+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_single_token.cpp@@ -107,8 +107,8 @@ template <>void cvt_copy(float* dst, float* src, size_t n) {size_t i = 0;for (; i + vec_len_f32_neon <= n; i += vec_len_f32_neon) {- float32x4_t vb1 = _vld1q_f32(src + i);- _vst1q_f32(dst + i, vb1);+ float32x4_t vb1 = loadq_f32(src + i);+ storeq_f32(dst + i, vb1);}for (; i < n; i++) {dst[i] = src[i];@@ -160,10 +160,10 @@ static void attn_acc_value(float* out, float weight, T* v, size_t S, float* scal# elsefloat32x4_t attn_w_vec_fp32 = vdupq_n_f32(weight);for (; i + vec_len_f32_neon <= S; i += vec_len_f32_neon) {- float32x4_t v_value = _vld1q_f32(v + i);- float32x4_t v_out = _vld1q_f32(out + i);+ float32x4_t v_value = loadq_f32(v + i);+ float32x4_t v_out = loadq_f32(out + i);v_out = vmlaq_f32(v_out, attn_w_vec_fp32, v_value);- _vst1q_f32(out + i, v_out);+ storeq_f32(out + i, v_out);}# endif#endif@@ -1150,11 +1150,11 @@ static void attn_reduce(T* dst, float* temp, size_t M, size_t S, size_t temp_strauto* src = temp + i;auto result_vec_fp32 = vdupq_n_f32(0.0f);for (size_t m = 0; m < M; m++) {- auto o_vec_fp32 = _vld1q_f32(src);+ auto o_vec_fp32 = loadq_f32(src);result_vec_fp32 = vaddq_f32(result_vec_fp32, o_vec_fp32);src += temp_stride;}- _vst1q_f32(dst + i, result_vec_fp32);+ storeq_f32(dst + i, result_vec_fp32);}# endif#endifdiff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/softmax_kernel.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/softmax_kernel.hppindex 8fa70edc297..6325881f8cb 100644--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/softmax_kernel.hpp+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/softmax_kernel.hpp@@ -557,7 +557,7 @@ inline void scale_add2_reduce_max(float* a,}if (has_attn_mask) {- float32x4_t v_mask = _vld1q_f32(attn_mask + i);+ float32x4_t v_mask = loadq_f32(attn_mask + i);v_a = vaddq_f32(v_a, v_mask);}@@ -1407,4 +1407,4 @@ inline void attn_softmax_kernel<ov::float16>(ov::float16* a,}#endif-} // namespace ov::Extensions::Cpu::XARCH\ No newline at end of file+} // namespace ov::Extensions::Cpu::XARCHdiff --git a/src/plugins/intel_cpu/src/nodes/pa_kv_reorder.cpp b/src/plugins/intel_cpu/src/nodes/pa_kv_reorder.cppnew file mode 100644index 00000000000..4f0cd5e5b2a--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/pa_kv_reorder.cpp@@ -0,0 +1,152 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "pa_kv_reorder.hpp"++#include <cstring>+#include <memory>+#include <oneapi/dnnl/dnnl.hpp>+#include <string>++#include "config.h"+#include "cpu_types.h"+#include "graph_context.h"+#include "memory_desc/cpu_memory_desc.h"+#include "node.h"+#include "nodes/kernels/scaled_attn/cache_reorder.hpp"+#include "nodes/paged_attn.h"+#include "onednn/iml_type_mapper.h"+#include "openvino/core/except.hpp"+#include "openvino/core/node.hpp"+#include "openvino/core/type.hpp"+#include "openvino/core/type/element_type.hpp"+#include "openvino/op/pa_kv_reorder.hpp"+#include "shape_inference/shape_inference_cpu.hpp"+#include "utils/plain_tensor.hpp"++namespace ov::intel_cpu::node {++bool PaKVReorder::isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept {+ try {+ if (!ov::is_type<ov::op::internal::PaKVReorder>(op)) {+ errorMessage = "Unsupported operation type for PaKVReorder CPU node: " + std::string(op->get_type_name());+ return false;+ }++ if (op->get_input_size() != 6) {+ errorMessage = "PaKVReorder expects 6 inputs.";+ return false;+ }++ if (op->get_output_size() != 1) {+ errorMessage = "PaKVReorder expects 1 output.";+ return false;+ }+ } catch (...) {+ return false;+ }++ return true;+}++PaKVReorder::PaKVReorder(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context)+ : Node(op, context, NgraphShapeInferFactory(op)) {+ std::string errorMessage;+ if (!isSupportedOperation(op, errorMessage)) {+ OPENVINO_THROW_NOT_IMPLEMENTED(errorMessage);+ }+}++void PaKVReorder::getSupportedDescriptors() {+ if (getParentEdges().size() != 6) {+ CPU_NODE_THROW("has incorrect number of input edges.");+ }+ if (getChildEdges().empty()) {+ CPU_NODE_THROW("has incorrect number of output edges.");+ }+}++void PaKVReorder::initSupportedPrimitiveDescriptors() {+ if (!supportedPrimitiveDescriptors.empty()) {+ return;+ }++ const auto key_cache_precision = getOriginalInputPrecisionAtPort(0);+ const auto value_cache_precision = getOriginalInputPrecisionAtPort(1);++ addSupportedPrimDesc({{LayoutType::ncsp, key_cache_precision},+ {LayoutType::ncsp, value_cache_precision},+ {LayoutType::ncsp, ov::element::i32},+ {LayoutType::ncsp, ov::element::i32},+ {LayoutType::ncsp, ov::element::i32},+ {LayoutType::ncsp, ov::element::i32}},+ {{LayoutType::ncsp, ov::element::u8}},+ impl_desc_type::ref_any);+}++void PaKVReorder::createPrimitive() {+ // Determine quantization mode once at primitive creation time+ const auto& cpuConfig = context->getConfig();+ auto keyCachePrecision = getOriginalInputPrecisionAtPort(0);+ auto valueCachePrecision = getOriginalInputPrecisionAtPort(1);++ m_key_by_channel = PagedAttention::isQuantByChannel(cpuConfig.keyCacheQuantMode, keyCachePrecision, true);+ m_value_by_channel = PagedAttention::isQuantByChannel(cpuConfig.valueCacheQuantMode, valueCachePrecision, false);+}++void PaKVReorder::execute([[maybe_unused]] const dnnl::stream& strm) {+ PlainTensor key_cache(getSrcMemoryAtPort(0));+ PlainTensor value_cache(getSrcMemoryAtPort(1));+ PlainTensor block_indices(getSrcMemoryAtPort(2));+ PlainTensor block_indices_begins(getSrcMemoryAtPort(3));+ PlainTensor block_update_indices(getSrcMemoryAtPort(4));+ PlainTensor block_update_indices_begins(getSrcMemoryAtPort(5));++ block_indices.assert_dims({0}, true);+ block_indices_begins.assert_dims({0}, true);+ block_update_indices.assert_dims({0}, true);+ block_update_indices_begins.assert_dims({0}, true);++ CPU_NODE_ASSERT(key_cache.m_rank == 4, "expects 4D key cache tensor");+ CPU_NODE_ASSERT(value_cache.m_rank == 4, "expects 4D value cache tensor");++ CPU_NODE_ASSERT(key_cache.size(1) == value_cache.size(1),+ "expects key/value cache to have identical kv head count");++ CPU_NODE_ASSERT(block_indices_begins.size(0) == block_update_indices_begins.size(0),+ "expects block_indices_begins and block_update_indices_begins to have same length");++ // The KV cache tensors are modified in-place: PaKVReorder rewrites tokens within key_cache and+ // value_cache and produces only a dummy [1] u8 status output. This violates the usual immutable-input+ // contract and is a special case intended exclusively for the GenAI paged-attention backend, where the+ // cache is owned by the runtime and the reorder is applied between main/draft decoding steps.+ ov::Extensions::Cpu::XARCH::reorder_kv_cache(key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins,+ m_key_by_channel,+ m_value_by_channel,+ context->getCpuParallel());++ if (getChildEdges().empty()) {+ return;+ }++ auto* out = getDstDataAtPort(0);+ if (out != nullptr && !getDstMemoryAtPort(0)->getShape().hasZeroDims()) {+ std::memset(out, 0, getDstMemoryAtPort(0)->getDesc().getCurrentMemSize());+ }+}++void PaKVReorder::executeDynamicImpl(const dnnl::stream& strm) {+ execute(strm);+}++bool PaKVReorder::created() const {+ return getType() == Type::PaKVReorder;+}++} // namespace ov::intel_cpu::nodediff --git a/src/plugins/intel_cpu/src/nodes/pa_kv_reorder.hpp b/src/plugins/intel_cpu/src/nodes/pa_kv_reorder.hppnew file mode 100644index 00000000000..b72af127e71--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/pa_kv_reorder.hpp@@ -0,0 +1,41 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <node.h>++#include <vector>++namespace ov::intel_cpu::node {++class PaKVReorder : public Node {+public:+ PaKVReorder(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context);++ void getSupportedDescriptors() override;++ void initSupportedPrimitiveDescriptors() override;++ void createPrimitive() override;++ void execute(const dnnl::stream& strm) override;++ void executeDynamicImpl(const dnnl::stream& strm) override;++ bool created() const override;++ bool needPrepareParams() const override {+ return false;+ }++ static bool isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept;++private:+ // Quantization configuration (determined at createPrimitive time)+ bool m_key_by_channel = false;+ bool m_value_by_channel = false;+};++} // namespace ov::intel_cpu::nodediff --git a/src/plugins/intel_cpu/src/nodes_factory.cpp b/src/plugins/intel_cpu/src/nodes_factory.cppindex d8a4bcac6af..f26e5a1578d 100644--- a/src/plugins/intel_cpu/src/nodes_factory.cpp+++ b/src/plugins/intel_cpu/src/nodes_factory.cpp@@ -66,6 +66,7 @@#include "nodes/non_zero.h"#include "nodes/normalize.h"#include "nodes/one_hot.h"+#include "nodes/pa_kv_reorder.hpp"#include "nodes/pad.h"#include "nodes/paged_causal_conv1d.h"#include "nodes/paged_gated_delta_net.h"@@ -241,6 +242,7 @@ Node::NodesFactory::NodesFactory() : Factory("NodesFactory") {INTEL_CPU_NODE(Subgraph, Type::Subgraph);INTEL_CPU_NODE(Composite, Type::SubModel);INTEL_CPU_NODE(ScaledDotProductAttention, Type::ScaledDotProductAttention);+ INTEL_CPU_NODE(PaKVReorder, Type::PaKVReorder);INTEL_CPU_NODE(SearchSorted, Type::SearchSorted);INTEL_CPU_NODE(SegmentMax, Type::SegmentMax);INTEL_CPU_NODE(LoRA, Type::LoRA);diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn_qq_bias.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn_qq_bias.cppnew file mode 100644index 00000000000..bc27d2537aa--- /dev/null+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn_qq_bias.cpp@@ -0,0 +1,517 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "common_test_utils/include/common_test_utils/ov_tensor_utils.hpp"+#include "common_test_utils/node_builders/constant.hpp"+#include "internal_properties.hpp"+#include "openvino/core/type/bfloat16.hpp"+#include "openvino/core/type/float16.hpp"+#include "openvino/op/paged_attention.hpp"+#include "openvino/op/parameter.hpp"+#include "shared_test_classes/base/ov_subgraph.hpp"+#include "utils/cpu_test_utils.hpp"++using namespace ov::test;+using namespace CPUTestUtils;+using namespace ov::op;++namespace ov {+namespace test {++struct QQBiasPattern {+ std::string name;+ std::vector<uint8_t> matrix; // N×N matrix for N draft tokens+ int32_t num_draft_tokens;+};++using PagedAttnQQBiasParams = std::tuple<ElementType, size_t, size_t, size_t, QQBiasPattern>;++class PagedAttnQQBiasTest : public testing::WithParamInterface<PagedAttnQQBiasParams>,+ virtual public ov::test::SubgraphBaseTest,+ public CPUTestsBase {+public:+ static std::string getTestCaseName(const testing::TestParamInfo<PagedAttnQQBiasParams>& obj) {+ const auto& [inType, past_len, num_draft, head_size, pattern] = obj.param;+ std::ostringstream result;+ result << "Prc=" << inType << "_";+ result << "PastLen=" << past_len << "_";+ result << "NumDraft=" << num_draft << "_";+ result << "HS=" << head_size << "_";+ result << "Pattern=" << pattern.name;+ return result.str();+ }++ static std::shared_ptr<ov::op::v0::Parameter> make_param(const PartialShape& pshape,+ element::Type element_type,+ const std::string& name) {+ auto param = std::make_shared<v0::Parameter>(element_type, pshape);+ param->set_friendly_name(name);+ param->get_output_tensor(0).set_names({name});+ return param;+ }++ std::shared_ptr<ov::Model> get_pa_model(ov::element::Type data_type,+ ov::Dimension::value_type head_size,+ ov::Dimension::value_type head_num,+ bool enable_qq_bias) {+ auto q = make_param(PartialShape{ov::Dimension::dynamic(), ov::Dimension::dynamic()}, data_type, "q");+ auto k = make_param(PartialShape{ov::Dimension::dynamic(), head_num * head_size}, data_type, "k");+ auto v = make_param(PartialShape{ov::Dimension::dynamic(), head_num * head_size}, data_type, "v");+ auto key_cache = make_param(PartialShape{ov::Dimension::dynamic(), 32, ov::Dimension::dynamic()},+ ov::element::dynamic,+ "key_cache.0");+ auto value_cache = make_param(PartialShape{ov::Dimension::dynamic(), 32, ov::Dimension::dynamic()},+ ov::element::dynamic,+ "value_cache.0");+ auto past_lens = make_param(PartialShape{ov::Dimension::dynamic()}, ov::element::i32, "past_lens");+ auto subsequence_begins =+ make_param(PartialShape{ov::Dimension::dynamic()}, ov::element::i32, "subsequence_begins");+ auto block_indices = make_param(PartialShape{ov::Dimension::dynamic()}, ov::element::i32, "block_indices");+ auto block_indices_begins =+ make_param(PartialShape{ov::Dimension::dynamic()}, ov::element::i32, "block_indices_begins");++ float scale_value = 1.0f / std::sqrt(static_cast<float>(head_size));+ auto scale = std::make_shared<v0::Constant>(ov::element::f32, ov::Shape{}, std::vector<float>{scale_value});+ auto sliding_window = std::make_shared<v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{0});+ auto alibi_slopes = std::make_shared<v0::Constant>(ov::element::f32, Shape{0}, std::vector<float>{});+ auto max_context_len = std::make_shared<v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{1024});+ auto score_aggregation_window =+ std::make_shared<v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{0});+ auto rotated_block_indices =+ std::make_shared<v0::Constant>(ov::element::i32, Shape{0}, std::vector<int32_t>{0});+ auto rotation_deltas = std::make_shared<v0::Constant>(ov::element::i32, Shape{0}, std::vector<int32_t>{0});+ auto rotation_trig_lut = std::make_shared<v0::Constant>(ov::element::f32, Shape{0}, std::vector<float>{0});+ auto xattention_threshold = std::make_shared<v0::Constant>(ov::element::f32, Shape{0}, std::vector<float>{0});+ auto xattention_block_size =+ std::make_shared<v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{64});+ auto xattention_stride = std::make_shared<v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{8});+ auto sinks = std::static_pointer_cast<v0::Constant>(ov::test::utils::make_constant(data_type, Shape{0}));+ auto adaptive_rkv_start_size =+ std::make_shared<v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{0});+ auto adaptive_rkv_evictable_sizes =+ std::make_shared<v0::Constant>(ov::element::i32, Shape{0}, std::vector<int32_t>{0});+ auto adaptive_rkv_diversity_block_set_indices =+ std::make_shared<v0::Constant>(ov::element::i32, Shape{0}, std::vector<int32_t>{0});+ auto adaptive_rkv_diversity_block_set_indices_begins =+ std::make_shared<v0::Constant>(ov::element::i32, Shape{0}, std::vector<int32_t>{0});+ auto token_type_ids = std::make_shared<v0::Constant>(ov::element::i32, Shape{0}, std::vector<int32_t>{0});++ ParameterVector params =+ {q, k, v, key_cache, value_cache, past_lens, subsequence_begins, block_indices, block_indices_begins};++ OutputVector pa_inputs = {q,+ k,+ v,+ key_cache,+ value_cache,+ past_lens,+ subsequence_begins,+ block_indices,+ block_indices_begins,+ scale,+ sliding_window,+ alibi_slopes,+ max_context_len,+ score_aggregation_window,+ rotated_block_indices,+ rotation_deltas,+ rotation_trig_lut,+ xattention_threshold,+ xattention_block_size,+ xattention_stride,+ sinks,+ adaptive_rkv_start_size,+ adaptive_rkv_evictable_sizes,+ adaptive_rkv_diversity_block_set_indices,+ adaptive_rkv_diversity_block_set_indices_begins,+ token_type_ids};++ // Create qq_bias and qq_bias_begins as Parameters when enabled+ if (enable_qq_bias) {+ auto qq_bias_param = make_param(PartialShape{ov::Dimension::dynamic()}, ov::element::u8, "qq_bias");+ auto qq_bias_begins_param =+ make_param(PartialShape{ov::Dimension::dynamic()}, ov::element::i32, "qq_bias_begins");+ params.push_back(qq_bias_param);+ params.push_back(qq_bias_begins_param);+ pa_inputs.push_back(qq_bias_param);+ pa_inputs.push_back(qq_bias_begins_param);+ } else {+ // Use empty Constants when disabled+ auto qq_bias = std::make_shared<v0::Constant>(ov::element::u8, Shape{0}, std::vector<uint8_t>{});+ auto qq_bias_begins = std::make_shared<v0::Constant>(ov::element::i32, Shape{0}, std::vector<int32_t>{});+ pa_inputs.push_back(qq_bias);+ pa_inputs.push_back(qq_bias_begins);+ }++ OPENVINO_ASSERT(pa_inputs.size() == 28);++ auto paged_attn = std::make_shared<op::PagedAttentionExtension>(pa_inputs);+ paged_attn->get_rt_info()["num_k_heads"] = head_num;+ paged_attn->get_rt_info()["k_head_size"] = head_size;+ paged_attn->get_rt_info()["num_v_heads"] = head_num;+ paged_attn->get_rt_info()["v_head_size"] = head_size;++ return std::make_shared<ov::Model>(OutputVector{paged_attn}, params);+ }++ struct RunResult {+ ov::Tensor prefill_output;+ ov::Tensor decode_output;+ ov::Tensor key_cache;+ ov::Tensor value_cache;+ };++ // Run two iterations: prefill + decode+ // If enable_qq_bias is true, decode phase uses provided qq_bias; otherwise standard causal+ RunResult run_pa(std::shared_ptr<ov::Model> model,+ ov::element::Type data_type,+ size_t prefill_len,+ size_t num_draft,+ size_t head_size,+ size_t head_num,+ bool enable_qq_bias,+ const std::vector<uint8_t>& qq_bias_data = {},+ const std::vector<int32_t>& qq_bias_begins_data = {}) {+ // Use f32 inference precision for stable cross-type comparison, except for bf16 where we+ // explicitly want to exercise the bf16 paged-attention executor path.+ configuration[ov::hint::inference_precision.name()] =+ (data_type == ov::element::bf16) ? ov::element::bf16 : ov::element::f32;+ function = model;+ compile_model();+ auto infer_request = compiledModel.create_infer_request();++ auto params = model->get_parameters();+ size_t hidden_dim = head_num * head_size;+ size_t batch_size = 1;++ // Helper to fill tensors with test data+ auto fill_tensor = [](ov::Tensor& t, float base, float stride) {+ if (t.get_element_type() == ov::element::f32) {+ auto* p = t.data<float>();+ for (size_t i = 0; i < t.get_size(); i++) {+ p[i] = base + stride * static_cast<float>(i % 17);+ }+ } else if (t.get_element_type() == ov::element::f16) {+ auto* p = t.data<ov::float16>();+ for (size_t i = 0; i < t.get_size(); i++) {+ p[i] = ov::float16(base + stride * static_cast<float>(i % 17));+ }+ } else if (t.get_element_type() == ov::element::bf16) {+ auto* p = t.data<ov::bfloat16>();+ for (size_t i = 0; i < t.get_size(); i++) {+ p[i] = ov::bfloat16(base + stride * static_cast<float>(i % 17));+ }+ }+ };++ // Determine cache precision and create KV cache tensors+ ov::Tensor key_cache_tensor, value_cache_tensor;+ for (const auto& input : compiledModel.inputs()) {+ for (auto& name : input.get_names()) {+ if (name.find("key_cache.") == 0) {+ auto cache_precision = input.get_element_type();+ auto pshape = input.get_partial_shape();+ size_t total_tokens = prefill_len + num_draft;+ size_t block_nums = (total_tokens + 31) / 32;+ pshape[0] = block_nums;+ key_cache_tensor = ov::Tensor(cache_precision, pshape.get_shape());+ } else if (name.find("value_cache.") == 0) {+ auto cache_precision = input.get_element_type();+ auto pshape = input.get_partial_shape();+ size_t total_tokens = prefill_len + num_draft;+ size_t block_nums = (total_tokens + 31) / 32;+ pshape[0] = block_nums;+ value_cache_tensor = ov::Tensor(cache_precision, pshape.get_shape());+ }+ }+ }++ // ========== Iteration 1: Prefill phase ==========+ {+ ov::Tensor q_prefill(data_type, {prefill_len, hidden_dim});+ ov::Tensor k_prefill(data_type, {prefill_len, hidden_dim});+ ov::Tensor v_prefill(data_type, {prefill_len, hidden_dim});++ fill_tensor(q_prefill, 0.1f, 0.01f);+ fill_tensor(k_prefill, 0.2f, 0.01f);+ fill_tensor(v_prefill, 0.3f, 0.01f);++ size_t prefill_blocks = (prefill_len + 31) / 32;+ ov::Tensor past_lens(ov::element::i32, {batch_size});+ ov::Tensor subsequence_begins(ov::element::i32, {batch_size + 1});+ ov::Tensor block_indices(ov::element::i32, {prefill_blocks});+ ov::Tensor block_indices_begins(ov::element::i32, {batch_size + 1});++ past_lens.data<int32_t>()[0] = 0;+ subsequence_begins.data<int32_t>()[0] = 0;+ subsequence_begins.data<int32_t>()[1] = static_cast<int32_t>(prefill_len);+ block_indices_begins.data<int32_t>()[0] = 0;+ block_indices_begins.data<int32_t>()[1] = static_cast<int32_t>(prefill_blocks);+ for (size_t i = 0; i < prefill_blocks; i++) {+ block_indices.data<int32_t>()[i] = static_cast<int32_t>(i);+ }++ // Empty qq_bias for prefill+ ov::Tensor qq_bias_empty(ov::element::u8, {0});+ ov::Tensor qq_bias_begins_empty(ov::element::i32, {batch_size + 1});+ for (size_t i = 0; i <= batch_size; i++) {+ qq_bias_begins_empty.data<int32_t>()[i] = 0;+ }++ for (auto& param : params) {+ auto name = param->get_friendly_name();+ if (name == "q")+ infer_request.set_tensor(param, q_prefill);+ else if (name == "k")+ infer_request.set_tensor(param, k_prefill);+ else if (name == "v")+ infer_request.set_tensor(param, v_prefill);+ else if (name == "key_cache.0")+ infer_request.set_tensor(param, key_cache_tensor);+ else if (name == "value_cache.0")+ infer_request.set_tensor(param, value_cache_tensor);+ else if (name == "past_lens")+ infer_request.set_tensor(param, past_lens);+ else if (name == "subsequence_begins")+ infer_request.set_tensor(param, subsequence_begins);+ else if (name == "block_indices")+ infer_request.set_tensor(param, block_indices);+ else if (name == "block_indices_begins")+ infer_request.set_tensor(param, block_indices_begins);+ else if (name == "qq_bias")+ infer_request.set_tensor(param, qq_bias_empty);+ else if (name == "qq_bias_begins")+ infer_request.set_tensor(param, qq_bias_begins_empty);+ }++ infer_request.infer();+ }++ // ========== Iteration 2: Decode phase ==========+ ov::Tensor decode_output;+ {+ ov::Tensor q_decode(data_type, {num_draft, hidden_dim});+ ov::Tensor k_decode(data_type, {num_draft, hidden_dim});+ ov::Tensor v_decode(data_type, {num_draft, hidden_dim});++ fill_tensor(q_decode, 0.4f, 0.02f);+ fill_tensor(k_decode, 0.5f, 0.02f);+ fill_tensor(v_decode, 0.6f, 0.02f);++ size_t total_tokens = prefill_len + num_draft;+ size_t total_blocks = (total_tokens + 31) / 32;+ ov::Tensor past_lens(ov::element::i32, {batch_size});+ ov::Tensor subsequence_begins(ov::element::i32, {batch_size + 1});+ ov::Tensor block_indices(ov::element::i32, {total_blocks});+ ov::Tensor block_indices_begins(ov::element::i32, {batch_size + 1});++ past_lens.data<int32_t>()[0] = static_cast<int32_t>(prefill_len);+ subsequence_begins.data<int32_t>()[0] = 0;+ subsequence_begins.data<int32_t>()[1] = static_cast<int32_t>(num_draft);+ block_indices_begins.data<int32_t>()[0] = 0;+ block_indices_begins.data<int32_t>()[1] = static_cast<int32_t>(total_blocks);+ for (size_t i = 0; i < total_blocks; i++) {+ block_indices.data<int32_t>()[i] = static_cast<int32_t>(i);+ }++ // Prepare qq_bias tensors based on enable_qq_bias flag+ ov::Tensor qq_bias_decode, qq_bias_begins_decode;+ if (enable_qq_bias && !qq_bias_data.empty()) {+ // Use provided qq_bias data+ qq_bias_decode = ov::Tensor(ov::element::u8, {qq_bias_data.size()});+ std::memcpy(qq_bias_decode.data<uint8_t>(), qq_bias_data.data(), qq_bias_data.size());++ qq_bias_begins_decode = ov::Tensor(ov::element::i32, {qq_bias_begins_data.size()});+ std::memcpy(qq_bias_begins_decode.data<int32_t>(),+ qq_bias_begins_data.data(),+ qq_bias_begins_data.size() * sizeof(int32_t));+ } else {+ // No qq_bias (standard causal attention) - model without qq_bias params won't need these+ // These won't be set if model was created with enable_qq_bias=false+ }++ for (auto& param : params) {+ auto name = param->get_friendly_name();+ if (name == "q")+ infer_request.set_tensor(param, q_decode);+ else if (name == "k")+ infer_request.set_tensor(param, k_decode);+ else if (name == "v")+ infer_request.set_tensor(param, v_decode);+ else if (name == "key_cache.0")+ infer_request.set_tensor(param, key_cache_tensor);+ else if (name == "value_cache.0")+ infer_request.set_tensor(param, value_cache_tensor);+ else if (name == "past_lens")+ infer_request.set_tensor(param, past_lens);+ else if (name == "subsequence_begins")+ infer_request.set_tensor(param, subsequence_begins);+ else if (name == "block_indices")+ infer_request.set_tensor(param, block_indices);+ else if (name == "block_indices_begins")+ infer_request.set_tensor(param, block_indices_begins);+ else if (name == "qq_bias" && enable_qq_bias)+ infer_request.set_tensor(param, qq_bias_decode);+ else if (name == "qq_bias_begins" && enable_qq_bias)+ infer_request.set_tensor(param, qq_bias_begins_decode);+ }++ infer_request.infer();++ auto output = infer_request.get_output_tensor(0);+ decode_output = ov::Tensor{output.get_element_type(), output.get_shape()};+ output.copy_to(decode_output);+ }++ return {ov::Tensor{}, decode_output, key_cache_tensor, value_cache_tensor};+ }+};++// Test that qq_bias tree mask produces different output than full causal mask+TEST_P(PagedAttnQQBiasTest, SpeculativeDecodingTreeMask) {+ SKIP_IF_CURRENT_TEST_IS_DISABLED();+ const auto& [inType, prefill_len, num_draft, head_size, pattern] = this->GetParam();++ if (inType == ElementType::bf16 && !ov::with_cpu_x86_bfloat16())+ GTEST_SKIP();++ targetDevice = ov::test::utils::DEVICE_CPU;++ size_t head_num = 8;++ // Run with tree mask (qq_bias enabled with pattern)+ std::vector<int32_t> qq_bias_begins_tree = {0, static_cast<int32_t>(pattern.matrix.size())};+ auto model_tree = get_pa_model(inType, head_size, head_num, true);+ auto result_tree = run_pa(model_tree,+ inType,+ prefill_len,+ num_draft,+ head_size,+ head_num,+ true,+ pattern.matrix,+ qq_bias_begins_tree);++ // Run reference without qq_bias (standard causal attention)+ auto model_ref = get_pa_model(inType, head_size, head_num, false);+ auto result_ref = run_pa(model_ref, inType, prefill_len, num_draft, head_size, head_num, false);++ // Validate outputs+ ASSERT_GT(result_tree.decode_output.get_size(), 0);+ ASSERT_GT(result_ref.decode_output.get_size(), 0);+ ASSERT_EQ(result_tree.decode_output.get_size(), result_ref.decode_output.get_size());++ // Check for NaN+ auto check_no_nan = [](const ov::Tensor& t, const std::string& name) {+ if (t.get_element_type() == ov::element::f32) {+ auto* data = t.data<float>();+ for (size_t i = 0; i < t.get_size(); i++) {+ EXPECT_FALSE(std::isnan(data[i])) << name << " contains NaN at index " << i;+ }+ } else if (t.get_element_type() == ov::element::f16) {+ auto* data = t.data<ov::float16>();+ for (size_t i = 0; i < t.get_size(); i++) {+ float val = static_cast<float>(data[i]);+ EXPECT_FALSE(std::isnan(val)) << name << " contains NaN at index " << i;+ }+ } else if (t.get_element_type() == ov::element::bf16) {+ auto* data = t.data<ov::bfloat16>();+ for (size_t i = 0; i < t.get_size(); i++) {+ float val = static_cast<float>(data[i]);+ EXPECT_FALSE(std::isnan(val)) << name << " contains NaN at index " << i;+ }+ }+ };++ check_no_nan(result_tree.decode_output, "Tree mask output");+ check_no_nan(result_ref.decode_output, "Reference output");++ // For tree patterns that differ from standard causal, outputs should differ+ // Standard causal mask for N tokens: q_i can attend to k_0..k_i+ std::vector<uint8_t> standard_causal_mask;+ int N = pattern.num_draft_tokens;+ for (int i = 0; i < N; i++) {+ for (int j = 0; j < N; j++) {+ standard_causal_mask.push_back((j <= i) ? 1 : 0);+ }+ }++ bool pattern_differs_from_causal = false;+ for (size_t i = 0; i < pattern.matrix.size(); i++) {+ if (pattern.matrix[i] != standard_causal_mask[i]) {+ pattern_differs_from_causal = true;+ break;+ }+ }++ // Compare outputs - they should differ when patterns differ+ float max_diff = 0.0f;+ size_t diff_count = 0;++ if (inType == ov::element::f32) {+ auto* data_tree = result_tree.decode_output.data<float>();+ auto* data_ref = result_ref.decode_output.data<float>();+ for (size_t i = 0; i < result_tree.decode_output.get_size(); i++) {+ float diff = std::abs(data_tree[i] - data_ref[i]);+ if (diff > max_diff)+ max_diff = diff;+ if (diff > 1e-5f)+ diff_count++;+ }+ } else if (inType == ov::element::f16) {+ auto* data_tree = result_tree.decode_output.data<ov::float16>();+ auto* data_ref = result_ref.decode_output.data<ov::float16>();+ for (size_t i = 0; i < result_tree.decode_output.get_size(); i++) {+ float diff = std::abs(static_cast<float>(data_tree[i]) - static_cast<float>(data_ref[i]));+ if (diff > max_diff)+ max_diff = diff;+ if (diff > 1e-3f)+ diff_count++;+ }+ } else if (inType == ov::element::bf16) {+ auto* data_tree = result_tree.decode_output.data<ov::bfloat16>();+ auto* data_ref = result_ref.decode_output.data<ov::bfloat16>();+ for (size_t i = 0; i < result_tree.decode_output.get_size(); i++) {+ float diff = std::abs(static_cast<float>(data_tree[i]) - static_cast<float>(data_ref[i]));+ if (diff > max_diff)+ max_diff = diff;+ if (diff > 5e-3f)+ diff_count++;+ }+ }++ // Outputs should differ when tree pattern != full causal+ // Note: Due to test data characteristics, differences may be subtle+ // We primarily verify that the mechanism executes correctly without errors+ if (pattern_differs_from_causal)+ EXPECT_TRUE(diff_count > 0) << "expect mask effective for tree attention ";+ else+ EXPECT_TRUE(diff_count == 0) << "expect same result for full attention";+}++// Define test patterns for speculative decoding+const std::vector<QQBiasPattern> qq_bias_patterns = {{"tree_4tokens",+ // 4×4 matrix for 4 draft tokens with tree structure:+ // q0: [1 0 0 0] - only sees k0+ // q1: [1 1 0 0] - sees k0, k1+ // q2: [1 0 1 0] - sees k0, k2 (skips k1)+ // q3: [1 0 1 1] - sees k0, k2, k3 (skips k1)+ {1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1},+ 4},+ {"diagonal_4tokens",+ // 4×4 diagonal (standard causal)+ {1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1},+ 4}};++INSTANTIATE_TEST_SUITE_P(smoke_PagedAttnQQBias,+ PagedAttnQQBiasTest,+ ::testing::Combine(::testing::Values(ElementType::f32, ElementType::f16, ElementType::bf16),+ ::testing::Values(4, 8), // past_len+ ::testing::Values(4), // num_draft tokens+ ::testing::Values(64, 72), // head_size+ ::testing::ValuesIn(qq_bias_patterns)),+ PagedAttnQQBiasTest::getTestCaseName);++} // namespace test+} // namespace ovdiff --git a/src/plugins/intel_cpu/tests/unit/pa_kv_reorder_test.cpp b/src/plugins/intel_cpu/tests/unit/pa_kv_reorder_test.cppnew file mode 100644index 00000000000..30c8ae8e080--- /dev/null+++ b/src/plugins/intel_cpu/tests/unit/pa_kv_reorder_test.cpp@@ -0,0 +1,527 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <gtest/gtest.h>++#include <algorithm>+#include <cstring>+#include <vector>++#include "cpu_parallel.hpp"+#include "nodes/kernels/scaled_attn/cache_reorder.hpp"+#include "openvino/core/except.hpp"+#include "openvino/core/type/float16.hpp"+#include "utils/plain_tensor.hpp"++using namespace ov::intel_cpu;+using namespace ov::Extensions::Cpu::XARCH;++namespace {++// Common helpers shared by all PaKVReorder kernel tests.+class PaKVReorderTestBase : public ::testing::Test {+protected:+ static constexpr size_t kBlockSize = 32;+ static constexpr size_t kHeadSize = 64;+ static constexpr size_t kNumHeads = 2;+ // Typical uint8 quantization: data range [0, 255] mapped via (q - 128) * 0.1f.+ static constexpr float kDefaultScale = 0.1f;+ static constexpr float kDefaultZp = 128.0f;++ CpuParallelPtr make_cpu_parallel() {+ return std::make_shared<CpuParallel>(ov::intel_cpu::TbbPartitioner::STATIC);+ }++ // Build a 1D PlainTensor over `storage` (caller owns the memory).+ template <typename T>+ static PlainTensor make_index_tensor(std::vector<T>& storage) {+ PlainTensor t;+ t.template resize<T>({storage.size()}, storage.data());+ return t;+ }+};++// Fixture for f32 / non-quantized KV cache tests.+class PaKVReorderFloatCacheTest : public PaKVReorderTestBase {+protected:+ // Fill cache buffers so each (block, token) is uniquely identifiable. `value_offset` lets the+ // value tensor differ from the key tensor without changing the per-token signature.+ void init_float_cache(size_t num_blocks,+ std::vector<float>& key_data,+ std::vector<float>& value_data,+ float value_offset = 50000.0f) {+ const size_t total = num_blocks * kNumHeads * kBlockSize * kHeadSize;+ key_data.resize(total);+ value_data.resize(total);++ for (size_t b = 0; b < num_blocks; b++) {+ for (size_t h = 0; h < kNumHeads; h++) {+ for (size_t t = 0; t < kBlockSize; t++) {+ for (size_t d = 0; d < kHeadSize; d++) {+ const size_t idx =+ b * kNumHeads * kBlockSize * kHeadSize + h * kBlockSize * kHeadSize + t * kHeadSize + d;+ const float token_id = static_cast<float>(b * 1000 + t);+ key_data[idx] = token_id;+ value_data[idx] = token_id + value_offset;+ }+ }+ }+ }+ }++ static size_t cache_offset(size_t block, size_t head, size_t token) {+ return block * kNumHeads * kBlockSize * kHeadSize + head * kBlockSize * kHeadSize + token * kHeadSize;+ }++ static void expect_token_payload_equals(const std::vector<float>& dst_data,+ const std::vector<float>& src_data_orig,+ size_t dst_block,+ size_t dst_token,+ size_t src_block,+ size_t src_token) {+ for (size_t h = 0; h < kNumHeads; h++) {+ const size_t src_off = cache_offset(src_block, h, src_token);+ const size_t dst_off = cache_offset(dst_block, h, dst_token);+ for (size_t d = 0; d < kHeadSize; d++) {+ EXPECT_FLOAT_EQ(dst_data[dst_off + d], src_data_orig[src_off + d])+ << "mismatch at head=" << h << ", dim=" << d;+ }+ }+ }+};++// Fixture for u8 quantized KV cache tests.+class PaKVReorderQuantizedCacheTest : public PaKVReorderTestBase {+protected:+ static constexpr size_t kByChannelParamsBytes = 2 * sizeof(float) * kHeadSize; // scale[H] + zp[H]+ static constexpr size_t kByChannelDataBytes = kBlockSize * kHeadSize;+ static constexpr size_t kByChannelBlockHeadBytes = kByChannelParamsBytes + kByChannelDataBytes;++ static constexpr size_t kByTokenParamsBytes = 2 * sizeof(float); // scale + zp per token+ static constexpr size_t kByTokenStrideBytes = kByTokenParamsBytes + kHeadSize;+ static constexpr size_t kByTokenBlockHeadBytes = kBlockSize * kByTokenStrideBytes;++ // Fill one (block, head) of a by-channel quantized cache with kDefaultScale / kDefaultZp and a+ // recognizable quant payload.+ static void init_by_channel_block_head(uint8_t* base, size_t block_id, size_t pattern_offset) {+ auto* scales = reinterpret_cast<float*>(base);+ auto* zps = reinterpret_cast<float*>(base + sizeof(float) * kHeadSize);+ for (size_t d = 0; d < kHeadSize; d++) {+ scales[d] = kDefaultScale;+ zps[d] = kDefaultZp;+ }+ uint8_t* quant = base + kByChannelParamsBytes;+ for (size_t t = 0; t < kBlockSize; t++) {+ for (size_t d = 0; d < kHeadSize; d++) {+ quant[t * kHeadSize + d] = static_cast<uint8_t>((block_id * 10 + t + pattern_offset) % 256);+ }+ }+ }++ // Fill one (block, head) of a by-token (interleaved) quantized cache. Each token row contains+ // [scale, zp, data[head_size]].+ static void init_by_token_block_head(uint8_t* base, size_t block_id, size_t pattern_offset) {+ for (size_t t = 0; t < kBlockSize; t++) {+ uint8_t* token_ptr = base + t * kByTokenStrideBytes;+ auto* scale_ptr = reinterpret_cast<float*>(token_ptr);+ auto* zp_ptr = reinterpret_cast<float*>(token_ptr + sizeof(float));+ *scale_ptr = kDefaultScale;+ *zp_ptr = kDefaultZp;++ uint8_t* data_ptr = token_ptr + kByTokenParamsBytes;+ for (size_t d = 0; d < kHeadSize; d++) {+ data_ptr[d] = static_cast<uint8_t>((block_id * 10 + t + pattern_offset) % 256);+ }+ }+ }++ // PlainTensor describing a by-channel cache buffer. dim2 = block_size + 2*sizeof(float) packs+ // params and data along the same axis; explicit strides preserve the actual byte layout.+ static PlainTensor wrap_by_channel(uint8_t* buf, size_t num_blocks) {+ const size_t dim2_with_params = kBlockSize + 2 * sizeof(float); // 32 + 8 = 40+ const size_t strides[4] = {+ kNumHeads * kByChannelBlockHeadBytes, // bytes per block+ kByChannelBlockHeadBytes, // bytes per head+ kHeadSize, // bytes per token-or-params row+ 1 // bytes per element+ };+ PlainTensor t;+ t.resize<uint8_t>({num_blocks, kNumHeads, dim2_with_params, kHeadSize}, buf, strides);+ return t;+ }++ // PlainTensor describing a by-token (interleaved) cache buffer. The hidden axis carries+ // head_size + scale + zp; stride[2] is the byte distance between successive tokens.+ static PlainTensor wrap_by_token(uint8_t* buf, size_t num_blocks) {+ const size_t dim3_with_params = kHeadSize + 2 * sizeof(float); // 64 + 8 = 72+ const size_t strides[4] = {+ kNumHeads * kByTokenBlockHeadBytes, // bytes per block+ kByTokenBlockHeadBytes, // bytes per head+ kByTokenStrideBytes, // bytes per token (interleaved)+ 1 // bytes per element+ };+ PlainTensor t;+ t.resize<uint8_t>({num_blocks, kNumHeads, kBlockSize, dim3_with_params}, buf, strides);+ return t;+ }++ static float dequantize(uint8_t q, float zp, float scale) {+ return (static_cast<float>(q) - zp) * scale;+ }++ // Compare dequantized rows token-by-token. After requantization the raw u8 values can shift,+ // so verify in float space using each side's own scale/zp.+ static void expect_by_channel_token_dequant_close(const std::vector<uint8_t>& cache_after,+ const std::vector<uint8_t>& cache_before,+ size_t block,+ size_t dst_token,+ size_t src_token,+ float tolerance) {+ for (size_t h = 0; h < kNumHeads; h++) {+ const size_t base_offset = (block * kNumHeads + h) * kByChannelBlockHeadBytes;++ const auto* scales_after = reinterpret_cast<const float*>(cache_after.data() + base_offset);+ const auto* zps_after =+ reinterpret_cast<const float*>(cache_after.data() + base_offset + sizeof(float) * kHeadSize);+ const auto* scales_before = reinterpret_cast<const float*>(cache_before.data() + base_offset);+ const auto* zps_before =+ reinterpret_cast<const float*>(cache_before.data() + base_offset + sizeof(float) * kHeadSize);++ const uint8_t* data_after = cache_after.data() + base_offset + kByChannelParamsBytes;+ const uint8_t* data_before = cache_before.data() + base_offset + kByChannelParamsBytes;++ for (size_t d = 0; d < kHeadSize; d++) {+ const float dst_dequant =+ dequantize(data_after[dst_token * kHeadSize + d], zps_after[d], scales_after[d]);+ const float src_dequant =+ dequantize(data_before[src_token * kHeadSize + d], zps_before[d], scales_before[d]);+ EXPECT_NEAR(dst_dequant, src_dequant, tolerance) << "head=" << h << " dim=" << d;+ }+ }+ }++ // Verify a by-token (interleaved) update: scale, zp, and quantized payload should be byte-equal+ // because by-token reorder is a direct memcpy of the whole token record.+ static void expect_by_token_record_equal(const std::vector<uint8_t>& cache_after,+ const std::vector<uint8_t>& cache_before,+ size_t block,+ size_t dst_token,+ size_t src_token) {+ for (size_t h = 0; h < kNumHeads; h++) {+ const size_t base_offset = (block * kNumHeads + h) * kByTokenBlockHeadBytes;+ const uint8_t* dst_token_ptr = cache_after.data() + base_offset + dst_token * kByTokenStrideBytes;+ const uint8_t* src_token_ptr = cache_before.data() + base_offset + src_token * kByTokenStrideBytes;++ const auto* dst_scale = reinterpret_cast<const float*>(dst_token_ptr);+ const auto* dst_zp = reinterpret_cast<const float*>(dst_token_ptr + sizeof(float));+ const auto* src_scale = reinterpret_cast<const float*>(src_token_ptr);+ const auto* src_zp = reinterpret_cast<const float*>(src_token_ptr + sizeof(float));+ EXPECT_FLOAT_EQ(*dst_scale, *src_scale) << "head=" << h;+ EXPECT_FLOAT_EQ(*dst_zp, *src_zp) << "head=" << h;++ const uint8_t* dst_data = dst_token_ptr + kByTokenParamsBytes;+ const uint8_t* src_data = src_token_ptr + kByTokenParamsBytes;+ for (size_t d = 0; d < kHeadSize; d++) {+ EXPECT_EQ(dst_data[d], src_data[d]) << "head=" << h << " dim=" << d;+ }+ }+ }+};++// ----------------------------------------------------------------------------+// Float / non-quantized cache tests+// ----------------------------------------------------------------------------++TEST_F(PaKVReorderFloatCacheTest, SameBlock) {+ constexpr size_t num_blocks = 2;++ std::vector<float> key_data;+ std::vector<float> value_data;+ init_float_cache(num_blocks, key_data, value_data, 100000.0f);+ const auto key_data_copy = key_data;+ const auto value_data_copy = value_data;++ PlainTensor key_cache;+ key_cache.resize<float>({num_blocks, kNumHeads, kBlockSize, kHeadSize}, key_data.data());+ PlainTensor value_cache;+ value_cache.resize<float>({num_blocks, kNumHeads, kBlockSize, kHeadSize}, value_data.data());++ std::vector<int32_t> block_indices_data = {0, 1};+ std::vector<int32_t> block_indices_begins_data = {0, 2};+ std::vector<int32_t> block_update_indices_data = {10, 5}; // src=10, dst=5 (backward)+ std::vector<int32_t> block_update_indices_begins_data = {0, 1};++ auto block_indices = make_index_tensor(block_indices_data);+ auto block_indices_begins = make_index_tensor(block_indices_begins_data);+ auto block_update_indices = make_index_tensor(block_update_indices_data);+ auto block_update_indices_begins = make_index_tensor(block_update_indices_begins_data);++ reorder_kv_cache(key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins,+ /*key_by_channel=*/false,+ /*value_by_channel=*/false,+ make_cpu_parallel());++ // Token 5 should now hold token 10's original payload (within block 0).+ expect_token_payload_equals(key_data, key_data_copy, 0, 5, 0, 10);+ expect_token_payload_equals(value_data, value_data_copy, 0, 5, 0, 10);+}++TEST_F(PaKVReorderFloatCacheTest, CrossBlock) {+ constexpr size_t num_blocks = 4;++ std::vector<float> key_data;+ std::vector<float> value_data;+ init_float_cache(num_blocks, key_data, value_data);+ const auto key_data_copy = key_data;+ const auto value_data_copy = value_data;++ PlainTensor key_cache;+ key_cache.resize<float>({num_blocks, kNumHeads, kBlockSize, kHeadSize}, key_data.data());+ PlainTensor value_cache;+ value_cache.resize<float>({num_blocks, kNumHeads, kBlockSize, kHeadSize}, value_data.data());++ // Sequence uses physical blocks {0, 1, 2}; copy logical token 5 (in block 0) to+ // logical token 42 = 32 + 10 (in block 1).+ std::vector<int32_t> block_indices_data = {0, 1, 2};+ std::vector<int32_t> block_indices_begins_data = {0, 3};+ std::vector<int32_t> block_update_indices_data = {5, 42};+ std::vector<int32_t> block_update_indices_begins_data = {0, 1};++ auto block_indices = make_index_tensor(block_indices_data);+ auto block_indices_begins = make_index_tensor(block_indices_begins_data);+ auto block_update_indices = make_index_tensor(block_update_indices_data);+ auto block_update_indices_begins = make_index_tensor(block_update_indices_begins_data);++ reorder_kv_cache(key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins,+ /*key_by_channel=*/false,+ /*value_by_channel=*/false,+ make_cpu_parallel());++ expect_token_payload_equals(key_data, key_data_copy, 1, 10, 0, 5);+ expect_token_payload_equals(value_data, value_data_copy, 1, 10, 0, 5);+}++// ----------------------------------------------------------------------------+// Quantized cache tests+// ----------------------------------------------------------------------------++TEST_F(PaKVReorderQuantizedCacheTest, BothByChannel) {+ constexpr size_t num_blocks = 4;++ std::vector<uint8_t> key_cache_data(num_blocks * kNumHeads * kByChannelBlockHeadBytes);+ std::vector<uint8_t> value_cache_data(num_blocks * kNumHeads * kByChannelBlockHeadBytes);++ for (size_t b = 0; b < num_blocks; b++) {+ for (size_t h = 0; h < kNumHeads; h++) {+ const size_t off = (b * kNumHeads + h) * kByChannelBlockHeadBytes;+ init_by_channel_block_head(key_cache_data.data() + off, b, /*pattern_offset=*/0);+ init_by_channel_block_head(value_cache_data.data() + off, b, /*pattern_offset=*/50);+ }+ }++ const auto key_cache_copy = key_cache_data;+ const auto value_cache_copy = value_cache_data;++ PlainTensor key_cache = wrap_by_channel(key_cache_data.data(), num_blocks);+ PlainTensor value_cache = wrap_by_channel(value_cache_data.data(), num_blocks);++ // Same-block backward copy: token 10 → token 5 in block 0.+ std::vector<int32_t> block_indices_data = {0, 1, 2};+ std::vector<int32_t> block_indices_begins_data = {0, 3};+ std::vector<int32_t> block_update_indices_data = {10, 5};+ std::vector<int32_t> block_update_indices_begins_data = {0, 1};++ auto block_indices = make_index_tensor(block_indices_data);+ auto block_indices_begins = make_index_tensor(block_indices_begins_data);+ auto block_update_indices = make_index_tensor(block_update_indices_data);+ auto block_update_indices_begins = make_index_tensor(block_update_indices_begins_data);++ reorder_kv_cache(key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins,+ /*key_by_channel=*/true,+ /*value_by_channel=*/true,+ make_cpu_parallel());++ // For by-channel the requantize step may reshape scale/zp, so compare in dequantized space.+ expect_by_channel_token_dequant_close(key_cache_data, key_cache_copy, 0, 5, 10, 0.2f);+ expect_by_channel_token_dequant_close(value_cache_data, value_cache_copy, 0, 5, 10, 0.2f);+}++TEST_F(PaKVReorderQuantizedCacheTest, KeyByChannelValueByToken) {+ constexpr size_t num_blocks = 4;++ std::vector<uint8_t> key_cache_data(num_blocks * kNumHeads * kByChannelBlockHeadBytes);+ std::vector<uint8_t> value_cache_data(num_blocks * kNumHeads * kByTokenBlockHeadBytes);++ for (size_t b = 0; b < num_blocks; b++) {+ for (size_t h = 0; h < kNumHeads; h++) {+ const size_t key_off = (b * kNumHeads + h) * kByChannelBlockHeadBytes;+ init_by_channel_block_head(key_cache_data.data() + key_off, b, /*pattern_offset=*/0);++ const size_t val_off = (b * kNumHeads + h) * kByTokenBlockHeadBytes;+ init_by_token_block_head(value_cache_data.data() + val_off, b, /*pattern_offset=*/50);+ }+ }++ const auto key_cache_copy = key_cache_data;+ const auto value_cache_copy = value_cache_data;++ PlainTensor key_cache = wrap_by_channel(key_cache_data.data(), num_blocks);+ PlainTensor value_cache = wrap_by_token(value_cache_data.data(), num_blocks);++ std::vector<int32_t> block_indices_data = {0, 1, 2};+ std::vector<int32_t> block_indices_begins_data = {0, 3};+ std::vector<int32_t> block_update_indices_data = {10, 5};+ std::vector<int32_t> block_update_indices_begins_data = {0, 1};++ auto block_indices = make_index_tensor(block_indices_data);+ auto block_indices_begins = make_index_tensor(block_indices_begins_data);+ auto block_update_indices = make_index_tensor(block_update_indices_data);+ auto block_update_indices_begins = make_index_tensor(block_update_indices_begins_data);++ reorder_kv_cache(key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins,+ /*key_by_channel=*/true,+ /*value_by_channel=*/false,+ make_cpu_parallel());++ // Key path: by-channel, so compare dequantized values.+ expect_by_channel_token_dequant_close(key_cache_data, key_cache_copy, 0, 5, 10, 0.2f);+ // Value path: by-token, so the whole token record (scale, zp, quant) is byte-copied.+ expect_by_token_record_equal(value_cache_data, value_cache_copy, 0, 5, 10);+}++// ----------------------------------------------------------------------------+// Error-path tests (no need for cache fixtures — only validation is exercised).+// ----------------------------------------------------------------------------++TEST_F(PaKVReorderTestBase, Int8CacheIsRejected) {+ constexpr size_t num_blocks = 1;+ constexpr size_t num_heads = 1;+ constexpr size_t block_size = 4;+ constexpr size_t head_size = 8;++ std::vector<int8_t> key_data(num_blocks * num_heads * block_size * head_size, 1);+ std::vector<int8_t> value_data(num_blocks * num_heads * block_size * head_size, 2);++ PlainTensor key_cache;+ key_cache.resize<int8_t>({num_blocks, num_heads, block_size, head_size}, key_data.data());+ PlainTensor value_cache;+ value_cache.resize<int8_t>({num_blocks, num_heads, block_size, head_size}, value_data.data());++ std::vector<int32_t> block_indices_data = {0};+ std::vector<int32_t> block_indices_begins_data = {0, 1};+ std::vector<int32_t> block_update_indices_data = {0, 1};+ std::vector<int32_t> block_update_indices_begins_data = {0, 1};++ auto block_indices = make_index_tensor(block_indices_data);+ auto block_indices_begins = make_index_tensor(block_indices_begins_data);+ auto block_update_indices = make_index_tensor(block_update_indices_data);+ auto block_update_indices_begins = make_index_tensor(block_update_indices_begins_data);++ EXPECT_THROW(reorder_kv_cache(key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins,+ false,+ false,+ make_cpu_parallel()),+ ov::Exception);+}++TEST_F(PaKVReorderTestBase, InvalidBlockUpdateBeginsAreRejected) {+ constexpr size_t num_blocks = 1;+ constexpr size_t num_heads = 1;+ constexpr size_t block_size = 4;+ constexpr size_t head_size = 8;++ std::vector<float> key_data(num_blocks * num_heads * block_size * head_size, 1.f);+ std::vector<float> value_data(num_blocks * num_heads * block_size * head_size, 2.f);++ PlainTensor key_cache;+ key_cache.resize<float>({num_blocks, num_heads, block_size, head_size}, key_data.data());+ PlainTensor value_cache;+ value_cache.resize<float>({num_blocks, num_heads, block_size, head_size}, value_data.data());++ std::vector<int32_t> block_indices_data = {0};+ std::vector<int32_t> block_indices_begins_data = {0, 1};+ std::vector<int32_t> block_update_indices_data = {0, 1};+ // Non-monotonic offsets must be rejected.+ std::vector<int32_t> block_update_indices_begins_data = {1, 0};++ auto block_indices = make_index_tensor(block_indices_data);+ auto block_indices_begins = make_index_tensor(block_indices_begins_data);+ auto block_update_indices = make_index_tensor(block_update_indices_data);+ auto block_update_indices_begins = make_index_tensor(block_update_indices_begins_data);++ EXPECT_THROW(reorder_kv_cache(key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins,+ false,+ false,+ make_cpu_parallel()),+ ov::Exception);+}++TEST_F(PaKVReorderTestBase, InvalidBlockIndicesBeginsAreRejected) {+ constexpr size_t num_blocks = 1;+ constexpr size_t num_heads = 1;+ constexpr size_t block_size = 4;+ constexpr size_t head_size = 8;++ std::vector<float> key_data(num_blocks * num_heads * block_size * head_size, 1.f);+ std::vector<float> value_data(num_blocks * num_heads * block_size * head_size, 2.f);++ PlainTensor key_cache;+ key_cache.resize<float>({num_blocks, num_heads, block_size, head_size}, key_data.data());+ PlainTensor value_cache;+ value_cache.resize<float>({num_blocks, num_heads, block_size, head_size}, value_data.data());++ std::vector<int32_t> block_indices_data = {0};+ // begins[1] = 2 > block_indices.size() = 1 → out of range.+ std::vector<int32_t> block_indices_begins_data = {0, 2};+ std::vector<int32_t> block_update_indices_data = {0, 1};+ std::vector<int32_t> block_update_indices_begins_data = {0, 1};++ auto block_indices = make_index_tensor(block_indices_data);+ auto block_indices_begins = make_index_tensor(block_indices_begins_data);+ auto block_update_indices = make_index_tensor(block_update_indices_data);+ auto block_update_indices_begins = make_index_tensor(block_update_indices_begins_data);++ EXPECT_THROW(reorder_kv_cache(key_cache,+ value_cache,+ block_indices,+ block_indices_begins,+ block_update_indices,+ block_update_indices_begins,+ false,+ false,+ make_cpu_parallel()),+ ov::Exception);+}++} // namespacediff --git a/src/plugins/intel_gpu/include/intel_gpu/op/pa_kv_reorder.hpp b/src/plugins/intel_gpu/include/intel_gpu/op/pa_kv_reorder.hppdeleted file mode 100644index 0976a93040a..00000000000--- a/src/plugins/intel_gpu/include/intel_gpu/op/pa_kv_reorder.hpp+++ /dev/null@@ -1,31 +0,0 @@-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#pragma once--#include "openvino/op/op.hpp"--namespace ov::intel_gpu::op {--class PA_KV_Reorder : public ov::op::Op {-public:- OPENVINO_OP("PaKVReorder", "gpu_opset");-- PA_KV_Reorder() = default;-- PA_KV_Reorder(const Output<Node>& key_cache,- const Output<Node>& value_cache,- const Output<Node>& block_indices,- const Output<Node>& block_indices_begins,- const Output<Node>& block_update_indices,- const Output<Node>& block_update_indices_begins);-- bool visit_attributes(ov::AttributeVisitor& visitor) override;-- void validate_and_infer_types() override;-- std::shared_ptr<Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;-};--} // namespace ov::intel_gpu::opdiff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/pa_kv_reorder.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/pa_kv_reorder.hppindex 52ae3df8bc7..2d67caa1c96 100644--- a/src/plugins/intel_gpu/include/intel_gpu/primitives/pa_kv_reorder.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/pa_kv_reorder.hpp@@ -4,8 +4,6 @@#pragma once-#include <array>-#include "primitive.hpp"namespace cldnn {@@ -38,12 +36,6 @@ struct pa_kv_reorder : public primitive_base<pa_kv_reorder> {seed = hash_combine(seed, adjusted_v_head_size);seed = hash_combine(seed, static_cast<size_t>(cache_dt));seed = hash_combine(seed, is_kv_compressed);- for (const auto value : key_cache_dim_order) {- seed = hash_combine(seed, value);- }- for (const auto value : value_cache_dim_order) {- seed = hash_combine(seed, value);- }return seed;}@@ -55,8 +47,7 @@ struct pa_kv_reorder : public primitive_base<pa_kv_reorder> {return is_key_by_channel == rhs_casted.is_key_by_channel && scales_zp_size == rhs_casted.scales_zp_size && kv_heads_num == rhs_casted.kv_heads_num &&adjusted_k_head_size == rhs_casted.adjusted_k_head_size &&adjusted_paged_attention_block_size == rhs_casted.adjusted_paged_attention_block_size &&- adjusted_v_head_size == rhs_casted.adjusted_v_head_size && cache_dt == rhs_casted.cache_dt && is_kv_compressed == rhs_casted.is_kv_compressed &&- key_cache_dim_order == rhs_casted.key_cache_dim_order && value_cache_dim_order == rhs_casted.value_cache_dim_order;+ adjusted_v_head_size == rhs_casted.adjusted_v_head_size && cache_dt == rhs_casted.cache_dt && is_kv_compressed == rhs_casted.is_kv_compressed;}void save(BinaryOutputBuffer& ob) const override {@@ -69,12 +60,6 @@ struct pa_kv_reorder : public primitive_base<pa_kv_reorder> {ob << adjusted_v_head_size;ob << static_cast<int64_t>(cache_dt);ob << is_kv_compressed;- for (const auto value : key_cache_dim_order) {- ob << value;- }- for (const auto value : value_cache_dim_order) {- ob << value;- }}void load(BinaryInputBuffer& ib) override {@@ -89,12 +74,6 @@ struct pa_kv_reorder : public primitive_base<pa_kv_reorder> {ib >> cache_dt_val;cache_dt = static_cast<data_types>(cache_dt_val);ib >> is_kv_compressed;- for (auto& value : key_cache_dim_order) {- ib >> value;- }- for (auto& value : value_cache_dim_order) {- ib >> value;- }}bool is_key_by_channel = false;@@ -105,8 +84,6 @@ struct pa_kv_reorder : public primitive_base<pa_kv_reorder> {size_t adjusted_v_head_size = 0;data_types cache_dt = data_types::f16;bool is_kv_compressed = false;- std::array<size_t, 4> key_cache_dim_order = {0, 1, 3, 2};- std::array<size_t, 4> value_cache_dim_order = {0, 1, 2, 3};};} // namespace cldnndiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_kv_cache_reorder_ref.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_kv_cache_reorder_ref.clindex 331b998e086..8a5c86e7646 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_kv_cache_reorder_ref.cl+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_kv_cache_reorder_ref.cl@@ -67,55 +67,34 @@ inline void FUNC(requantize_and_store_by_channel_block)(__global OUTPUT_TYPE* ke#if defined(IS_KV_COMPRESSED) && defined(IS_KEY_BY_CHANNEL) && IS_INT4_COMPRESSEDinline void FUNC(requantize_and_store_by_channel_block_int4)(__global OUTPUT_TYPE* key_cache,const uint dst_base,- UNCOMPRESSED_TYPE* dequant_vals0,- UNCOMPRESSED_TYPE* dequant_vals1) {- UNCOMPRESSED_TYPE min_value0 = UNCOMPRESSED_VAL_MAX;- UNCOMPRESSED_TYPE max_value0 = UNCOMPRESSED_VAL_MIN;- UNCOMPRESSED_TYPE min_value1 = UNCOMPRESSED_VAL_MAX;- UNCOMPRESSED_TYPE max_value1 = UNCOMPRESSED_VAL_MIN;-- for (uint token = 0; token < PAGED_ATTENTION_BLOCK_SIZE; ++token) {- UNCOMPRESSED_TYPE val0 = dequant_vals0[token];- UNCOMPRESSED_TYPE val1 = dequant_vals1[token];- min_value0 = fmin(min_value0, val0);- max_value0 = fmax(max_value0, val0);- min_value1 = fmin(min_value1, val1);- max_value1 = fmax(max_value1, val1);+ UNCOMPRESSED_TYPE* dequant_vals) {+ UNCOMPRESSED_TYPE min_value = UNCOMPRESSED_VAL_MAX;+ UNCOMPRESSED_TYPE max_value = UNCOMPRESSED_VAL_MIN;+ for (uint t = 0; t < PAGED_ATTENTION_BLOCK_SIZE; ++t) {+ min_value = fmin(min_value, dequant_vals[t]);+ max_value = fmax(max_value, dequant_vals[t]);}#define ACCUMULATOR_TYPE float- ACCUMULATOR_TYPE range0 = max_value0 - min_value0;- ACCUMULATOR_TYPE range1 = max_value1 - min_value1;- const ACCUMULATOR_TYPE min_range0 = fabs(max_value0 * 0.1f);- const ACCUMULATOR_TYPE min_range1 = fabs(max_value1 * 0.1f);- if (range0 <= min_range0) {- range0 += fmax(1.0f, min_range0);- }- if (range1 <= min_range1) {- range1 += fmax(1.0f, min_range1);+ ACCUMULATOR_TYPE range = (max_value == min_value) ? 0.001f : (ACCUMULATOR_TYPE)(max_value - min_value);+ const ACCUMULATOR_TYPE min_range = fabs(max_value * 0.1f);+ if (range <= min_range) {+ range += fmax(1.0f, min_range);}- ACCUMULATOR_TYPE scale_tmp0 = (ACCUMULATOR_TYPE)((UINT4_RANGE) / range0);- ACCUMULATOR_TYPE zp_tmp0 = (ACCUMULATOR_TYPE)(-min_value0 * scale_tmp0);- ACCUMULATOR_TYPE scale_tmp1 = (ACCUMULATOR_TYPE)((UINT4_RANGE) / range1);- ACCUMULATOR_TYPE zp_tmp1 = (ACCUMULATOR_TYPE)(-min_value1 * scale_tmp1);- UNCOMPRESSED_TYPE scale0 = (UNCOMPRESSED_TYPE)(scale_tmp0);- UNCOMPRESSED_TYPE zp0 = (UNCOMPRESSED_TYPE)(zp_tmp0);- UNCOMPRESSED_TYPE scale1 = (UNCOMPRESSED_TYPE)(scale_tmp1);- UNCOMPRESSED_TYPE zp1 = (UNCOMPRESSED_TYPE)(zp_tmp1);+ ACCUMULATOR_TYPE scale_tmp = (ACCUMULATOR_TYPE)((UINT4_RANGE) / range);+ ACCUMULATOR_TYPE zp_tmp = (ACCUMULATOR_TYPE)(-min_value * scale_tmp);#undef ACCUMULATOR_TYPE- for (uint token = 0; token < PAGED_ATTENTION_BLOCK_SIZE; ++token) {- char2 quantized = 0;- quantized.s0 = convert_char_rte(dequant_vals0[token] * scale0 + zp0);- quantized.s1 = convert_char_rte(dequant_vals1[token] * scale1 + zp1);- key_cache[dst_base + token] = cvt_int8x2_to_uint4x2(quantized);+ for (uint t = 0; t < PAGED_ATTENTION_BLOCK_SIZE; t += U4_ELEMS_PER_BYTE) {+ char q0 = (char)clamp(convert_int_rte((float)(dequant_vals[t] * scale_tmp + zp_tmp)), 0, UINT4_RANGE);+ char q1 = (char)clamp(convert_int_rte((float)(dequant_vals[t + 1] * scale_tmp + zp_tmp)), 0, UINT4_RANGE);+ char2 res = {q0, q1};+ key_cache[dst_base + t / U4_ELEMS_PER_BYTE] = cvt_int8x2_to_uint4x2(res);}- UNCOMPRESSED_TYPE* comp_ptr = (UNCOMPRESSED_TYPE*)(key_cache + (dst_base + PAGED_ATTENTION_BLOCK_SIZE));- comp_ptr[0] = 1.0f / scale0;- comp_ptr[1] = zp0;- comp_ptr[2] = 1.0f / scale1;- comp_ptr[3] = zp1;+ UNCOMPRESSED_TYPE* comp_ptr = (UNCOMPRESSED_TYPE*)(key_cache + dst_base + PACKED_PAGED_ATTENTION_BLOCK_SIZE);+ comp_ptr[0] = (UNCOMPRESSED_TYPE)(1.0f / scale_tmp);+ comp_ptr[1] = (UNCOMPRESSED_TYPE)zp_tmp;}#endif@@ -176,10 +155,15 @@ KERNEL(pa_kv_cache_reorder)(#endif#ifdef IS_KEY_BY_CHANNEL- const uint key_src_base = OUTPUT_OFFSET + src_block * KV_HEADS_NUM * phys_adjusted_k_head_size * ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE +- head_idx * phys_adjusted_k_head_size * ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE;- const uint key_dst_base = OUTPUT_OFFSET + dst_block * KV_HEADS_NUM * phys_adjusted_k_head_size * ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE +- head_idx * phys_adjusted_k_head_size * ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE;+ #if IS_KV_COMPRESSED && IS_INT4_COMPRESSED+ const uint phys_adjusted_block_size = PACKED_ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE;+ #else+ const uint phys_adjusted_block_size = ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE;+ #endif+ const uint key_src_base = OUTPUT_OFFSET + src_block * KV_HEADS_NUM * phys_adjusted_k_head_size * phys_adjusted_block_size ++ head_idx * phys_adjusted_k_head_size * phys_adjusted_block_size;+ const uint key_dst_base = OUTPUT_OFFSET + dst_block * KV_HEADS_NUM * phys_adjusted_k_head_size * phys_adjusted_block_size ++ head_idx * phys_adjusted_k_head_size * phys_adjusted_block_size;#elseconst uint key_src_base = OUTPUT_OFFSET + src_block * KV_HEADS_NUM * phys_adjusted_k_head_size * PAGED_ATTENTION_BLOCK_SIZE +head_idx * phys_adjusted_k_head_size * PAGED_ATTENTION_BLOCK_SIZE;@@ -218,48 +202,55 @@ KERNEL(pa_kv_cache_reorder)(// 2. copy the src slot to dst slot// 3. if dst is in a different block, re-quantize dst block with updated scale/zp#if IS_INT4_COMPRESSED- for (uint k = sglid; k < phys_k_head_size; k += (uint)SUBGROUP_SIZE) {- const uint src_off = key_src_base + k * ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE + src_slot;- const uint dst_base = key_dst_base + k * ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE;-- const uint src_comp_off = key_src_base + k * ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE + PAGED_ATTENTION_BLOCK_SIZE;- const uint dst_comp_off = key_dst_base + k * ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE + PAGED_ATTENTION_BLOCK_SIZE;- UNCOMPRESSED_TYPE* src_comp_ptr = key_cache + src_comp_off;- UNCOMPRESSED_TYPE* dst_comp_ptr = key_cache + dst_comp_off;-- const UNCOMPRESSED_TYPE src_scale_inv0 = src_comp_ptr[0];- const UNCOMPRESSED_TYPE src_zp0 = src_comp_ptr[1];- const UNCOMPRESSED_TYPE src_scale_inv1 = src_comp_ptr[2];- const UNCOMPRESSED_TYPE src_zp1 = src_comp_ptr[3];- const UNCOMPRESSED_TYPE dst_scale_inv0 = dst_comp_ptr[0];- const UNCOMPRESSED_TYPE dst_zp0 = dst_comp_ptr[1];- const UNCOMPRESSED_TYPE dst_scale_inv1 = dst_comp_ptr[2];- const UNCOMPRESSED_TYPE dst_zp1 = dst_comp_ptr[3];-- OUTPUT_TYPE src_packed = key_cache[src_off];- char2 src_unpacked = unpack_to_char(*(uint4x2_t *)&src_packed);-- const UNCOMPRESSED_TYPE src_val0 = ((UNCOMPRESSED_TYPE)(src_unpacked.s0) - src_zp0) * src_scale_inv0;- const UNCOMPRESSED_TYPE src_val1 = ((UNCOMPRESSED_TYPE)(src_unpacked.s1) - src_zp1) * src_scale_inv1;-- UNCOMPRESSED_TYPE dequant_vals0[PAGED_ATTENTION_BLOCK_SIZE];- UNCOMPRESSED_TYPE dequant_vals1[PAGED_ATTENTION_BLOCK_SIZE];-- for (uint token = 0; token < PAGED_ATTENTION_BLOCK_SIZE; ++token) {- OUTPUT_TYPE dst_packed = key_cache[dst_base + token];- char2 dst_unpacked = unpack_to_char(*(uint4x2_t *)&dst_packed);-- UNCOMPRESSED_TYPE val0 = ((UNCOMPRESSED_TYPE)(dst_unpacked.s0) - dst_zp0) * dst_scale_inv0;- UNCOMPRESSED_TYPE val1 = ((UNCOMPRESSED_TYPE)(dst_unpacked.s1) - dst_zp1) * dst_scale_inv1;- if (token == dst_slot) {- val0 = src_val0;- val1 = src_val1;+ if (src_block == dst_block) {+ // Fast path: nibble shuffle within the same column. scale/zp unchanged,+ // no dequant/requant — avoids accumulating rounding error across reorders.+ for (uint k = sglid; k < phys_k_head_size; k += (uint)SUBGROUP_SIZE) {+ const uint col_base = key_dst_base + k * PACKED_ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE;++ OUTPUT_TYPE src_byte = key_cache[col_base + src_slot / U4_ELEMS_PER_BYTE];+ char2 src_pair = unpack_to_char(*(uint4x2_t*)&src_byte);+ const char src_nibble = (src_slot % U4_ELEMS_PER_BYTE == 0) ? src_pair.s0 : src_pair.s1;++ const uint dst_byte_off = col_base + dst_slot / U4_ELEMS_PER_BYTE;+ OUTPUT_TYPE dst_byte = key_cache[dst_byte_off];+ char2 dst_pair = unpack_to_char(*(uint4x2_t*)&dst_byte);+ if (dst_slot % U4_ELEMS_PER_BYTE == 0) {+ dst_pair.s0 = src_nibble;+ } else {+ dst_pair.s1 = src_nibble;}- dequant_vals0[token] = val0;- dequant_vals1[token] = val1;+ key_cache[dst_byte_off] = cvt_int8x2_to_uint4x2(dst_pair);}+ } else {+ for (uint k = sglid; k < phys_k_head_size; k += (uint)SUBGROUP_SIZE) {+ const uint src_col_base = key_src_base + k * PACKED_ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE;+ const uint dst_col_base = key_dst_base + k * PACKED_ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE;++ UNCOMPRESSED_TYPE* src_comp_ptr = (UNCOMPRESSED_TYPE*)(key_cache + src_col_base + PACKED_PAGED_ATTENTION_BLOCK_SIZE);+ UNCOMPRESSED_TYPE* dst_comp_ptr = (UNCOMPRESSED_TYPE*)(key_cache + dst_col_base + PACKED_PAGED_ATTENTION_BLOCK_SIZE);+ const UNCOMPRESSED_TYPE src_scale_inv = src_comp_ptr[0];+ const UNCOMPRESSED_TYPE src_zp = src_comp_ptr[1];+ const UNCOMPRESSED_TYPE dst_scale_inv = dst_comp_ptr[0];+ const UNCOMPRESSED_TYPE dst_zp = dst_comp_ptr[1];++ OUTPUT_TYPE src_byte = key_cache[src_col_base + src_slot / U4_ELEMS_PER_BYTE];+ char2 src_pair = unpack_to_char(*(uint4x2_t*)&src_byte);+ const char src_nibble = (src_slot % U4_ELEMS_PER_BYTE == 0) ? src_pair.s0 : src_pair.s1;+ const UNCOMPRESSED_TYPE src_val = ((UNCOMPRESSED_TYPE)src_nibble - src_zp) * src_scale_inv;++ UNCOMPRESSED_TYPE dequant_vals[PAGED_ATTENTION_BLOCK_SIZE];+ for (uint t = 0; t < PAGED_ATTENTION_BLOCK_SIZE; ++t) {+ OUTPUT_TYPE dst_byte = key_cache[dst_col_base + t / U4_ELEMS_PER_BYTE];+ char2 dst_pair = unpack_to_char(*(uint4x2_t*)&dst_byte);+ const char dst_nibble = (t % U4_ELEMS_PER_BYTE == 0) ? dst_pair.s0 : dst_pair.s1;+ UNCOMPRESSED_TYPE v = ((UNCOMPRESSED_TYPE)dst_nibble - dst_zp) * dst_scale_inv;+ if (t == dst_slot) v = src_val;+ dequant_vals[t] = v;+ }- FUNC_CALL(requantize_and_store_by_channel_block_int4)(key_cache, dst_base, dequant_vals0, dequant_vals1);+ FUNC_CALL(requantize_and_store_by_channel_block_int4)(key_cache, dst_col_base, dequant_vals);+ }}#elseif (src_block == dst_block) {@@ -339,9 +330,11 @@ KERNEL(pa_kv_cache_reorder)(// value cache: per-token quantization#if IS_INT4_COMPRESSED- for (uint v = sglid; v < phys_v_head_size; v += (uint)SUBGROUP_SIZE) {- const uint src_off = val_src_base + src_slot * phys_v_head_size + v;- const uint dst_off = val_dst_base + dst_slot * phys_v_head_size + v;+ // u4 per-token layout: each token row = [packed_v_head_size data bytes][scale][zp]+ // Copy the whole row in one pass, scale/zp included.+ for (uint v = sglid; v < phys_adjusted_v_head_size; v += (uint)SUBGROUP_SIZE) {+ const uint src_off = val_src_base + src_slot * phys_adjusted_v_head_size + v;+ const uint dst_off = val_dst_base + dst_slot * phys_adjusted_v_head_size + v;value_cache[dst_off] = value_cache[src_off];}#else@@ -362,6 +355,9 @@ KERNEL(pa_kv_cache_reorder)(}#endif+ #if !IS_INT4_COMPRESSED+ // INT8 per-token: scale/zp arrays live at end of block, indexed by token slot.+ // INT4 per-token already copied scale/zp inline with the token row.if (sglid == 0) {const uint comp_src_base = val_src_base + phys_v_head_size * PAGED_ATTENTION_BLOCK_SIZE;const uint comp_dst_base = val_dst_base + phys_v_head_size * PAGED_ATTENTION_BLOCK_SIZE;@@ -370,6 +366,7 @@ KERNEL(pa_kv_cache_reorder)(dst_comp_ptr[dst_slot] = src_comp_ptr[src_slot];dst_comp_ptr[PAGED_ATTENTION_BLOCK_SIZE + dst_slot] = src_comp_ptr[PAGED_ATTENTION_BLOCK_SIZE + src_slot];}+ #endif#endif}}\ No newline at end of filediff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_kv_reorder.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_kv_reorder.cppindex f285d0ee47a..bc7a0587e7a 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_kv_reorder.cpp+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_kv_reorder.cpp@@ -88,14 +88,29 @@ protected:jit.make("ADJUSTED_V_HEAD_SIZE", adjusted_v_head_size);if (is_int4_compressed) {- const size_t packed_k_head_size = align_to(k_head_size / u4_elems_per_byte, subgroup_size);+ size_t packed_k_head_size;+ size_t packed_adjusted_k_head_size;+ size_t packed_paged_attention_block_size;+ size_t packed_adjusted_paged_attention_block_size;+ if (is_key_by_channel) {+ packed_k_head_size = k_head_size;+ packed_adjusted_k_head_size = k_head_size;+ packed_paged_attention_block_size = cldnn::paged_attention::block_size / u4_elems_per_byte;+ packed_adjusted_paged_attention_block_size = packed_paged_attention_block_size + scales_zp_size;+ } else {+ packed_k_head_size = align_to(k_head_size / u4_elems_per_byte, subgroup_size);+ packed_adjusted_k_head_size = packed_k_head_size + scales_zp_size;+ packed_paged_attention_block_size = cldnn::paged_attention::block_size;+ packed_adjusted_paged_attention_block_size = cldnn::paged_attention::block_size;+ }const size_t packed_v_head_size = align_to(v_head_size / u4_elems_per_byte, subgroup_size);- const size_t packed_adjusted_k_head_size = is_key_by_channel ? packed_k_head_size : packed_k_head_size + scales_zp_size;const size_t packed_adjusted_v_head_size = packed_v_head_size + scales_zp_size;jit.make("PACKED_K_HEAD_SIZE", packed_k_head_size);jit.make("PACKED_V_HEAD_SIZE", packed_v_head_size);jit.make("PACKED_ADJUSTED_K_HEAD_SIZE", packed_adjusted_k_head_size);jit.make("PACKED_ADJUSTED_V_HEAD_SIZE", packed_adjusted_v_head_size);+ jit.make("PACKED_PAGED_ATTENTION_BLOCK_SIZE", packed_paged_attention_block_size);+ jit.make("PACKED_ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE", packed_adjusted_paged_attention_block_size);}} else {jit.make("ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE", cldnn::paged_attention::block_size);diff --git a/src/plugins/intel_gpu/src/plugin/ops/pa_kv_reorder.cpp b/src/plugins/intel_gpu/src/plugin/ops/pa_kv_reorder.cppindex d4fcf4401ee..65c3a81271d 100644--- a/src/plugins/intel_gpu/src/plugin/ops/pa_kv_reorder.cpp+++ b/src/plugins/intel_gpu/src/plugin/ops/pa_kv_reorder.cpp@@ -2,7 +2,7 @@// SPDX-License-Identifier: Apache-2.0//-#include "intel_gpu/op/pa_kv_reorder.hpp"+#include "openvino/op/pa_kv_reorder.hpp"#include <algorithm>@@ -10,64 +10,95 @@#include "intel_gpu/plugin/program_builder.hpp"#include "intel_gpu/primitives/pa_kv_reorder.hpp"#include "intel_gpu/primitives/paged_attention.hpp"+#include "openvino/runtime/internal_properties.hpp"namespace ov {namespace op {namespace internal {-using PA_KV_Reorder = ov::intel_gpu::op::PA_KV_Reorder;+using PA_KV_Reorder = ov::op::internal::PaKVReorder;} // namespace internal} // namespace op} // namespace ovnamespace ov::intel_gpu {+namespace {++bool is_compressed_cache_type(const ov::element::Type& type) {+ return type == ov::element::i8 || type == ov::element::u8 || type == ov::element::i4 || type == ov::element::u4;+}++size_t infer_scales_zp_size(const ov::element::Type& cache_type, const ov::element::Type& infer_precision) {+ if (!is_compressed_cache_type(cache_type)) {+ return 0;+ }+ // One scale + one zp (each `infer_precision`-typed) per quantization group, matching+ // pa_kv_cache_update kernel which writes comp_ptr[token]=1/scale, comp_ptr[BLOCK+token]=zp.+ if (cache_type == ov::element::i4 || cache_type == ov::element::u4) {+ return 2 * infer_precision.size();+ }+ return (2 * infer_precision.size()) / cache_type.size();+}++} // namespace+static void CreatePA_KV_ReorderOp(ProgramBuilder& p, const std::shared_ptr<ov::op::internal::PA_KV_Reorder>& op) {validate_inputs_count(op, {6});auto inputs = p.GetInputInfo(op);auto prim = cldnn::pa_kv_reorder(cldnn::primitive_id(layer_type_name_ID(op)), std::vector<cldnn::input_info>(inputs.begin(), inputs.end()));++ const auto& config = p.get_config();+ // Use configured kv_cache_precision (e.g. u4) — NOT the parameter's element type, which+ // ConvertPagedAttnInputs rewrites to i8/u8 for RemoteTensor compatibility even when the+ // underlying cache layout is packed u4.+ const auto cache_type = config.get_kv_cache_precision();+ const auto infer_precision = config.get_inference_precision();+ const auto key_cache_quant_mode = config.get_key_cache_quant_mode();++ prim.cache_dt = cldnn::element_type_to_data_type(cache_type);+ prim.scales_zp_size = infer_scales_zp_size(cache_type, infer_precision);+ prim.is_kv_compressed = prim.scales_zp_size > 0;+ prim.is_key_by_channel = (key_cache_quant_mode == ov::internal::CacheQuantMode::BY_CHANNEL);++ const auto key_cache_ps = op->get_input_partial_shape(cldnn::pa_kv_reorder::PaKVReorderInputIdx::KEY_CACHE);+ const auto value_cache_ps = op->get_input_partial_shape(cldnn::pa_kv_reorder::PaKVReorderInputIdx::VALUE_CACHE);++ OPENVINO_ASSERT(key_cache_ps.rank().is_static() && key_cache_ps.rank().get_length() == 4,+ "[GPU] pa_kv_reorder expects 4D key cache, got rank ", key_cache_ps.rank());+ OPENVINO_ASSERT(value_cache_ps.rank().is_static() && value_cache_ps.rank().get_length() == 4,+ "[GPU] pa_kv_reorder expects 4D value cache, got rank ", value_cache_ps.rank());+const auto& rt_info = op->get_rt_info();const auto k_head_size_id = "k_head_size";const auto v_head_size_id = "v_head_size";const auto num_k_heads_id = "num_k_heads";- const auto has_rt_head_info =- rt_info.find(k_head_size_id) != rt_info.end() && rt_info.find(v_head_size_id) != rt_info.end() && rt_info.find(num_k_heads_id) != rt_info.end();- if (!has_rt_head_info)- OPENVINO_THROW("[GPU] pa_kv_reorder op missing runtime head size information in rt_info");-- constexpr const char* rt_is_key_by_channel = "pa_kv_reorder.is_key_by_channel";- constexpr const char* rt_scales_zp_size = "pa_kv_reorder.scales_zp_size";- constexpr const char* rt_key_dim_order = "pa_kv_reorder.key_cache_dim_order";- constexpr const char* rt_value_dim_order = "pa_kv_reorder.value_cache_dim_order";- const auto has_rt_compress_info = rt_info.find(rt_is_key_by_channel) != rt_info.end() && rt_info.find(rt_scales_zp_size) != rt_info.end() &&- rt_info.find(rt_key_dim_order) != rt_info.end() && rt_info.find(rt_value_dim_order) != rt_info.end();-- if (!has_rt_compress_info) {- OPENVINO_THROW("[GPU] pa_kv_reorder op missing runtime compression information in rt_info");- }- prim.kv_heads_num = static_cast<size_t>(rt_info.at(num_k_heads_id).as<int64_t>());- prim.adjusted_paged_attention_block_size = cldnn::paged_attention::block_size;- prim.adjusted_k_head_size = static_cast<size_t>(rt_info.at(k_head_size_id).as<int64_t>());- prim.adjusted_v_head_size = static_cast<size_t>(rt_info.at(v_head_size_id).as<int64_t>());- prim.cache_dt = cldnn::element_type_to_data_type(op->get_input_element_type(cldnn::pa_kv_reorder::PaKVReorderInputIdx::KEY_CACHE));- prim.scales_zp_size = static_cast<size_t>(rt_info.at(rt_scales_zp_size).as<int64_t>());- prim.is_kv_compressed = prim.scales_zp_size > 0;+ OPENVINO_ASSERT(rt_info.find(k_head_size_id) != rt_info.end() &&+ rt_info.find(v_head_size_id) != rt_info.end() &&+ rt_info.find(num_k_heads_id) != rt_info.end(),+ "[GPU] pa_kv_reorder: input shapes are dynamic but rt_info is missing "+ "k_head_size/v_head_size/num_k_heads");+ const size_t k_head_size = rt_info.at(k_head_size_id).as<int64_t>();+ const size_t v_head_size = rt_info.at(v_head_size_id).as<int64_t>();+ const size_t kv_heads_num = rt_info.at(num_k_heads_id).as<int64_t>();+ const size_t block_size = cldnn::paged_attention::block_size;++ prim.kv_heads_num = kv_heads_num;if (prim.is_kv_compressed) {- if (rt_info.at(rt_is_key_by_channel).as<bool>()) {- prim.is_key_by_channel = true;- prim.adjusted_paged_attention_block_size = prim.adjusted_paged_attention_block_size + prim.scales_zp_size;+ if (prim.is_key_by_channel) {+ prim.adjusted_k_head_size = k_head_size;+ prim.adjusted_paged_attention_block_size = block_size + prim.scales_zp_size;} else {- prim.adjusted_k_head_size = prim.adjusted_k_head_size + prim.scales_zp_size;+ prim.adjusted_k_head_size = k_head_size + prim.scales_zp_size;+ prim.adjusted_paged_attention_block_size = block_size;}- prim.adjusted_v_head_size = prim.adjusted_v_head_size + prim.scales_zp_size;- const auto key_dim_order = rt_info.at(rt_key_dim_order).as<std::vector<size_t>>();- const auto value_dim_order = rt_info.at(rt_value_dim_order).as<std::vector<size_t>>();- OPENVINO_ASSERT(key_dim_order.size() == 4 && value_dim_order.size() == 4, "[GPU] Invalid pa_kv_reorder dim order metadata size");-- std::copy(key_dim_order.begin(), key_dim_order.end(), prim.key_cache_dim_order.begin());- std::copy(value_dim_order.begin(), value_dim_order.end(), prim.value_cache_dim_order.begin());+ prim.adjusted_v_head_size = v_head_size + prim.scales_zp_size;+ } else {+ prim.adjusted_k_head_size = k_head_size;+ prim.adjusted_paged_attention_block_size = block_size;+ prim.adjusted_v_head_size = v_head_size;}prim.num_outputs = op->get_output_size();diff --git a/src/plugins/intel_gpu/src/plugin/transformations/op/pa_kv_reorder.cpp b/src/plugins/intel_gpu/src/plugin/transformations/op/pa_kv_reorder.cppdeleted file mode 100644index 48cedc2f5bd..00000000000--- a/src/plugins/intel_gpu/src/plugin/transformations/op/pa_kv_reorder.cpp+++ /dev/null@@ -1,36 +0,0 @@-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#include "intel_gpu/op/pa_kv_reorder.hpp"--namespace ov::intel_gpu::op {--PA_KV_Reorder::PA_KV_Reorder(const Output<Node>& key_cache,- const Output<Node>& value_cache,- const Output<Node>& block_indices,- const Output<Node>& block_indices_begins,- const Output<Node>& block_update_indices,- const Output<Node>& block_update_indices_begins)- : Op({key_cache, value_cache, block_indices, block_indices_begins, block_update_indices, block_update_indices_begins}) {- set_output_size(1);- validate_and_infer_types();-}--bool PA_KV_Reorder::visit_attributes(ov::AttributeVisitor& visitor) {- (void)visitor;- return true;-}--void PA_KV_Reorder::validate_and_infer_types() {- NODE_VALIDATION_CHECK(this, get_input_size() == 6, "PaKVReorder expects 6 inputs, but got ", get_input_size());-- set_output_type(0, ov::element::u8, ov::PartialShape{1});-}--std::shared_ptr<Node> PA_KV_Reorder::clone_with_new_inputs(const ov::OutputVector& new_args) const {- check_new_args_count(this, new_args);- return std::make_shared<PA_KV_Reorder>(new_args.at(0), new_args.at(1), new_args.at(2), new_args.at(3), new_args.at(4), new_args.at(5));-}--} // namespace ov::intel_gpu::opdiff --git a/src/plugins/intel_gpu/src/plugin/transformations/pa_kv_reorder_fusion.hpp b/src/plugins/intel_gpu/src/plugin/transformations/pa_kv_reorder_fusion.hppdeleted file mode 100644index d7f3a562aeb..00000000000--- a/src/plugins/intel_gpu/src/plugin/transformations/pa_kv_reorder_fusion.hpp+++ /dev/null@@ -1,82 +0,0 @@-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#pragma once--#include <vector>--#include "openvino/core/type/element_type.hpp"-#include "openvino/pass/pass.hpp"--namespace ov::intel_gpu {--/// Fuses paired key/value cache reorder paths into a single PA_KV_Reorder op.-///-/// ┌───────────────┐ ┌───────────────┐-/// │ Parameter │ │ Parameter │-/// │ key_cache │ │ value_cache │-/// └───────┬───────┘ └───────┬───────┘-/// │ │-/// ┌─────┴─────┐ ┌─────┴─────┐-/// │ Gather │<────────── block_update_indices ────────│ Gather │-/// └─────┬─────┘ └─────┬─────┘-/// │ │-/// ┌───────┴────────┐ ┌───────┴────────┐-/// │ ScatterUpdate │<──────────── block_indices ────────│ ScatterUpdate │-/// └───────┬────────┘ └───────┬────────┘-/// │ │-/// └───────────────────┐ ┌───────────────────────┘-/// │ │-/// ┌──┴─────────┴───┐-/// │ Concat │-/// └──────┬─────────┘-/// │-/// Result-///-/// =>-///-/// ┌───────────────┐ ┌───────────────┐-/// │ Parameter │ │ Parameter │-/// │ key_cache │ │ value_cache │-/// └───────┬───────┘ └───────┬───────┘-/// │ │-/// └───────────────►┌────────────────────────┐◄────┘-/// ┌───────────────┐ │ PA_KV_Reorder │ ┌─────────────────────┐-/// │ Parameter │────────►│ │◄───────│ Parameter │-/// │ block_indices │ │ │ │ block_update_indices│-/// └───────────────┘ │ │ └─────────────────────┘-/// ┌────────────────────┐ │ │ ┌────────────────────────────┐-/// │ Parameter │──────►│ │◄──────│ Parameter │-/// │ block_indices_begins│ └────────────┬───────────┘ │ block_update_indices_begins│-/// └────────────────────┘ │ └────────────────────────────┘-/// │-/// Result--class PaKVReorderFusion : public ov::pass::ModelPass {-public:- OPENVINO_MODEL_PASS_RTTI("PaKVReorderFusion");- explicit PaKVReorderFusion(bool key_cache_quant_by_channel = false,- std::vector<size_t> key_cache_dim_order = {0, 1, 3, 2},- std::vector<size_t> value_cache_dim_order = {0, 1, 2, 3},- ov::element::Type key_cache_precision = ov::element::dynamic,- ov::element::Type value_cache_precision = ov::element::dynamic,- ov::element::Type inference_precision = ov::element::f16)- : m_key_cache_quant_by_channel(key_cache_quant_by_channel),- m_key_cache_dim_order(std::move(key_cache_dim_order)),- m_value_cache_dim_order(std::move(value_cache_dim_order)),- m_key_cache_precision(key_cache_precision),- m_value_cache_precision(value_cache_precision),- m_inference_precision(inference_precision) {}- bool run_on_model(const std::shared_ptr<ov::Model>& m) override;--private:- bool m_key_cache_quant_by_channel = false;- std::vector<size_t> m_key_cache_dim_order = {0, 1, 3, 2};- std::vector<size_t> m_value_cache_dim_order = {0, 1, 2, 3};- ov::element::Type m_key_cache_precision = ov::element::dynamic;- ov::element::Type m_value_cache_precision = ov::element::dynamic;- ov::element::Type m_inference_precision = ov::element::f16;-};--} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cppindex 3a87658dfed..b6e281a2836 100644--- a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp+++ b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp@@ -104,7 +104,6 @@#include "plugin/transformations/lora_subgraph_horizontal_fusion.hpp"#include "plugin/transformations/move_fc_reshape_to_weights.hpp"#include "plugin/transformations/optimize_subsequent_reshapes.hpp"-#include "plugin/transformations/pa_kv_reorder_fusion.hpp"#include "plugin/transformations/print_model_statistics.hpp"#include "plugin/transformations/sink_reshape.hpp"#include "plugin/transformations/transpose_fusion.hpp"@@ -819,12 +818,6 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {precision = (config.get_kv_cache_precision() == ov::element::i4) ? ov::element::i8 : ov::element::u8;}});- manager.register_pass<ov::intel_gpu::PaKVReorderFusion>(kv_cache_config.keyCacheQuantBychannel,- kv_cache_config.keyCacheDimOrder,- kv_cache_config.valueCacheDimOrder,- kv_cache_config.keyCachePrecision,- kv_cache_config.valueCachePrecision,- kv_cache_config.inferencePrecision);}pass_config->set_callback<ov::pass::ScaledDotProductAttentionDecomposition>([&](const std::shared_ptr<const ov::Node> node){diff --git a/src/plugins/intel_gpu/src/runtime/execution_config.cpp b/src/plugins/intel_gpu/src/runtime/execution_config.cppindex 3fa599116dc..dc8ee6ae3e0 100644--- a/src/plugins/intel_gpu/src/runtime/execution_config.cpp+++ b/src/plugins/intel_gpu/src/runtime/execution_config.cpp@@ -274,19 +274,24 @@ void ExecutionConfig::apply_model_specific_options(const IRemoteContext* context}}- auto is_auxiliary_kv_update_model = [](const ov::Model& model) {- if (model.get_rt_info().count("auxiliary_kv_update_model")) {- return model.get_rt_info<ov::Any>("auxiliary_kv_update_model").template as<bool>();- }- return false;+ // Auxiliary KV-update model (e.g. EAGLE3 reorder graph) has no PA op and no 4-bit MatMul,+ // so the auto-detection branches below can't see the main model's effective precision.+ // genai stamps it into rt_info["real_kv_cache_precision"] — honor it here so the auxiliary+ // graph compiles against the same cache layout as the main PA model.+ auto get_auxiliary_kv_cache_precision = [](const ov::Model& model) -> ov::element::Type {+ const auto& rt = model.get_rt_info();+ auto prec_it = rt.find("auxiliary_kv_cache_precision");+ return prec_it == rt.end() ? ov::element::dynamic : prec_it->second.as<ov::element::Type>();};if (!is_set_by_user(ov::hint::kv_cache_precision) || get_kv_cache_precision() == ov::element::dynamic) {- if (is_paged_attention_model && has_4bit_weights &&- m_key_cache_quant_mode != ov::internal::CacheQuantMode::BY_TOKEN) {+ const auto auxiliary_kv_prec = get_auxiliary_kv_cache_precision(model);+ if (auxiliary_kv_prec != ov::element::dynamic) {+ m_kv_cache_precision = auxiliary_kv_prec;+ } else if (is_paged_attention_model && has_4bit_weights && m_key_cache_quant_mode != ov::internal::CacheQuantMode::BY_TOKEN) {// Enable 4-bit KV-cache compression for PA models with 4-bit compressed weightsm_kv_cache_precision = ov::element::u4;GPU_DEBUG_INFO << "[Info] 4-bit weights detected. Setting KV-cache precision to u4." << std::endl;- } else if (is_paged_attention_model || !info.supports_immad || is_auxiliary_kv_update_model(model) ) {+ } else if (is_paged_attention_model || !info.supports_immad) {// Enable KV-cache compression by default for:// 1) Non-systolic platforms in case of SDPA-based models// 2) For any platforms in case of PagedAttention-based modeldiff --git a/src/plugins/intel_gpu/tests/unit/test_cases/pa_kv_reorder_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/pa_kv_reorder_gpu_test.cppindex c487d146b2e..18d92e55f57 100644--- a/src/plugins/intel_gpu/tests/unit/test_cases/pa_kv_reorder_gpu_test.cpp+++ b/src/plugins/intel_gpu/tests/unit/test_cases/pa_kv_reorder_gpu_test.cpp@@ -2,35 +2,28 @@// SPDX-License-Identifier: Apache-2.0//-#include "test_utils.h"-+#include <cstring>#include <intel_gpu/primitives/input_layout.hpp>#include <intel_gpu/primitives/mutable_data.hpp>#include <intel_gpu/primitives/pa_kv_reorder.hpp>#include <intel_gpu/primitives/paged_attention.hpp>--#include <cstring>-#include <type_traits>#include <tuple>+#include <type_traits>#include <vector>+#include "test_utils.h"+using namespace cldnn;using namespace ::tests;namespace {size_t key_offset(size_t block, size_t head, size_t k, size_t token, size_t kv_heads, size_t k_head_size, size_t block_size) {- return block * kv_heads * k_head_size * block_size +- head * k_head_size * block_size +- k * block_size +- token;+ return block * kv_heads * k_head_size * block_size + head * k_head_size * block_size + k * block_size + token;}size_t value_offset(size_t block, size_t head, size_t token, size_t v, size_t kv_heads, size_t v_head_size, size_t block_size) {- return block * kv_heads * block_size * v_head_size +- head * block_size * v_head_size +- token * v_head_size +- v;+ return block * kv_heads * block_size * v_head_size + head * block_size * v_head_size + token * v_head_size + v;}size_t key_comp_byte_offset(size_t block,@@ -42,8 +35,7 @@ size_t key_comp_byte_offset(size_t block,size_t k_head_size,size_t adjusted_k_head_size,size_t block_size) {- const size_t block_base = block * kv_heads * adjusted_k_head_size * block_size +- head * adjusted_k_head_size * block_size;+ const size_t block_base = block * kv_heads * adjusted_k_head_size * block_size + head * adjusted_k_head_size * block_size;const size_t comp_base = block_base + k_head_size * block_size;const size_t token_base = (is_zp ? (block_size + token) : token) * sizeof(ov::float16);return comp_base + token_base + byte_in_fp16;@@ -58,8 +50,7 @@ size_t value_comp_byte_offset(size_t block,size_t v_head_size,size_t adjusted_v_head_size,size_t block_size) {- const size_t block_base = block * kv_heads * block_size * adjusted_v_head_size +- head * block_size * adjusted_v_head_size;+ const size_t block_base = block * kv_heads * block_size * adjusted_v_head_size + head * block_size * adjusted_v_head_size;const size_t comp_base = block_base + v_head_size * block_size;const size_t token_base = (is_zp ? (block_size + token) : token) * sizeof(ov::float16);return comp_base + token_base + byte_in_fp16;@@ -73,11 +64,32 @@ size_t value_data_offset_compressed(size_t block,size_t v_head_size,size_t adjusted_v_head_size,size_t block_size) {- const size_t block_base = block * kv_heads * block_size * adjusted_v_head_size +- head * block_size * adjusted_v_head_size;+ const size_t block_base = block * kv_heads * block_size * adjusted_v_head_size + head * block_size * adjusted_v_head_size;return block_base + token * v_head_size + v;}+// u4 V BY_TOKEN layout: each token row is `packed_v_head_size` data bytes followed inline+// by `[fp16 scale][fp16 zp]` (mirrors quantize_and_save_per_token in pa_kv_cache_update_ref.cl+// when out_data_pitch == 1).+size_t value_data_offset_int4_per_token(size_t block, size_t head, size_t token, size_t v, size_t kv_heads, size_t adjusted_v_head_size, size_t block_size) {+ const size_t block_base = block * kv_heads * block_size * adjusted_v_head_size + head * block_size * adjusted_v_head_size;+ return block_base + token * adjusted_v_head_size + v;+}++size_t value_comp_byte_offset_int4_per_token(size_t block,+ size_t head,+ size_t token,+ size_t byte_in_fp16,+ bool is_zp,+ size_t kv_heads,+ size_t packed_v_head_size,+ size_t adjusted_v_head_size,+ size_t block_size) {+ const size_t block_base = block * kv_heads * block_size * adjusted_v_head_size + head * block_size * adjusted_v_head_size;+ const size_t row_base = block_base + token * adjusted_v_head_size + packed_v_head_size;+ return row_base + (is_zp ? sizeof(ov::float16) : 0) + byte_in_fp16;+}+void run_copy_between_blocks_single_sequence_compressed_int4_test(data_types cache_dt) {auto& engine = get_test_engine();@@ -119,10 +131,13 @@ void run_copy_between_blocks_single_sequence_compressed_int4_test(data_types cacset_values<int32_t>(block_indices_mem, {0, 1});set_values<int32_t>(block_indices_begins_mem, {0, 2});- set_values<int32_t>(block_update_indices_mem, {- 0, 17,- 15, 16,- });+ set_values<int32_t>(block_update_indices_mem,+ {+ 0,+ 17,+ 15,+ 16,+ });set_values<int32_t>(block_update_indices_begins_mem, {0, 2});topology topo;@@ -174,12 +189,12 @@ void run_copy_between_blocks_single_sequence_compressed_int4_test(data_types cac}for (size_t v = 0; v < packed_v_head_size; v++) {- const auto src0 = value_cache_ref[value_data_offset_compressed(0, 0, 0, v, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)];- const auto dst17 = value_ptr[value_data_offset_compressed(1, 0, 1, v, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)];+ const auto src0 = value_cache_ref[value_data_offset_int4_per_token(0, 0, 0, v, kv_heads, adjusted_v_head_size, block_size)];+ const auto dst17 = value_ptr[value_data_offset_int4_per_token(1, 0, 1, v, kv_heads, adjusted_v_head_size, block_size)];ASSERT_EQ(dst17, src0);- const auto src15 = value_cache_ref[value_data_offset_compressed(0, 0, 15, v, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)];- const auto dst16 = value_ptr[value_data_offset_compressed(1, 0, 0, v, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)];+ const auto src15 = value_cache_ref[value_data_offset_int4_per_token(0, 0, 15, v, kv_heads, adjusted_v_head_size, block_size)];+ const auto dst16 = value_ptr[value_data_offset_int4_per_token(1, 0, 0, v, kv_heads, adjusted_v_head_size, block_size)];ASSERT_EQ(dst16, src15);}@@ -189,10 +204,10 @@ void run_copy_between_blocks_single_sequence_compressed_int4_test(data_types cacASSERT_EQ(key_ptr[key_comp_byte_offset(1, 0, 1, byte, true, kv_heads, packed_k_head_size, adjusted_k_head_size, block_size)],key_cache_ref[key_comp_byte_offset(0, 0, 0, byte, true, kv_heads, packed_k_head_size, adjusted_k_head_size, block_size)]);- ASSERT_EQ(value_ptr[value_comp_byte_offset(1, 0, 1, byte, false, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)],- value_cache_ref[value_comp_byte_offset(0, 0, 0, byte, false, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)]);- ASSERT_EQ(value_ptr[value_comp_byte_offset(1, 0, 1, byte, true, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)],- value_cache_ref[value_comp_byte_offset(0, 0, 0, byte, true, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)]);+ ASSERT_EQ(value_ptr[value_comp_byte_offset_int4_per_token(1, 0, 1, byte, false, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)],+ value_cache_ref[value_comp_byte_offset_int4_per_token(0, 0, 0, byte, false, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)]);+ ASSERT_EQ(value_ptr[value_comp_byte_offset_int4_per_token(1, 0, 1, byte, true, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)],+ value_cache_ref[value_comp_byte_offset_int4_per_token(0, 0, 0, byte, true, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)]);}}@@ -212,12 +227,7 @@ ov::float16 read_fp16_from_u8_vector(const std::vector<uint8_t>& buffer, size_treturn ov::float16::from_bits(bits);}-void fill_key_cache(memory::ptr key_cache_mem,- size_t blocks_num,- size_t kv_heads,- size_t k_head_size,- size_t block_size,- std::vector<ov::float16>& values) {+void fill_key_cache(memory::ptr key_cache_mem, size_t blocks_num, size_t kv_heads, size_t k_head_size, size_t block_size, std::vector<ov::float16>& values) {values.resize(key_cache_mem->count());for (size_t b = 0; b < blocks_num; b++) {for (size_t h = 0; h < kv_heads; h++) {@@ -284,10 +294,13 @@ TEST(pa_kv_reorder_gpu, copy_between_blocks_single_sequence) {set_values<int32_t>(block_indices_mem, {0, 1});set_values<int32_t>(block_indices_begins_mem, {0, 2});- set_values<int32_t>(block_update_indices_mem, {- 0, 17,- 15, 16,- });+ set_values<int32_t>(block_update_indices_mem,+ {+ 0,+ 17,+ 15,+ 16,+ });set_values<int32_t>(block_update_indices_begins_mem, {0, 2});topology topo;@@ -347,8 +360,7 @@ TEST(pa_kv_reorder_gpu, copy_between_blocks_single_sequence) {ASSERT_EQ(dst16, src15);}- ASSERT_EQ(key_ptr[key_offset(0, 0, 0, 0, kv_heads, k_head_size, block_size)],- key_cache_ref[key_offset(0, 0, 0, 0, kv_heads, k_head_size, block_size)]);+ ASSERT_EQ(key_ptr[key_offset(0, 0, 0, 0, kv_heads, k_head_size, block_size)], key_cache_ref[key_offset(0, 0, 0, 0, kv_heads, k_head_size, block_size)]);ASSERT_EQ(value_ptr[value_offset(0, 0, 0, 0, kv_heads, v_head_size, block_size)],value_cache_ref[value_offset(0, 0, 0, 0, kv_heads, v_head_size, block_size)]);}@@ -384,10 +396,13 @@ TEST(pa_kv_reorder_gpu, updates_are_scoped_per_sequence) {// Sequence 0 uses physical block 0, sequence 1 uses physical block 2.set_values<int32_t>(block_indices_mem, {0, 2});set_values<int32_t>(block_indices_begins_mem, {0, 1, 2});- set_values<int32_t>(block_update_indices_mem, {- 1, 3, // seq0: slot1 -> slot3 in block0- 2, 4, // seq1: slot2 -> slot4 in block2- });+ set_values<int32_t>(block_update_indices_mem,+ {+ 1,+ 3, // seq0: slot1 -> slot3 in block0+ 2,+ 4, // seq1: slot2 -> slot4 in block2+ });set_values<int32_t>(block_update_indices_begins_mem, {0, 1, 2});topology topo;@@ -428,14 +443,11 @@ TEST(pa_kv_reorder_gpu, updates_are_scoped_per_sequence) {cldnn::mem_lock<ov::float16, mem_lock_type::read> value_ptr(value_cache_mem, network->get_stream());for (size_t k = 0; k < k_head_size; k++) {- ASSERT_EQ(key_ptr[key_offset(0, 0, k, 3, kv_heads, k_head_size, block_size)],- key_cache_ref[key_offset(0, 0, k, 1, kv_heads, k_head_size, block_size)]);- ASSERT_EQ(key_ptr[key_offset(2, 0, k, 4, kv_heads, k_head_size, block_size)],- key_cache_ref[key_offset(2, 0, k, 2, kv_heads, k_head_size, block_size)]);+ ASSERT_EQ(key_ptr[key_offset(0, 0, k, 3, kv_heads, k_head_size, block_size)], key_cache_ref[key_offset(0, 0, k, 1, kv_heads, k_head_size, block_size)]);+ ASSERT_EQ(key_ptr[key_offset(2, 0, k, 4, kv_heads, k_head_size, block_size)], key_cache_ref[key_offset(2, 0, k, 2, kv_heads, k_head_size, block_size)]);// Unused middle block must stay untouched.- ASSERT_EQ(key_ptr[key_offset(1, 0, k, 4, kv_heads, k_head_size, block_size)],- key_cache_ref[key_offset(1, 0, k, 4, kv_heads, k_head_size, block_size)]);+ ASSERT_EQ(key_ptr[key_offset(1, 0, k, 4, kv_heads, k_head_size, block_size)], key_cache_ref[key_offset(1, 0, k, 4, kv_heads, k_head_size, block_size)]);}for (size_t v = 0; v < v_head_size; v++) {@@ -488,10 +500,13 @@ TEST(pa_kv_reorder_gpu, copy_between_blocks_single_sequence_compressed) {set_values<int32_t>(block_indices_mem, {0, 1});set_values<int32_t>(block_indices_begins_mem, {0, 2});- set_values<int32_t>(block_update_indices_mem, {- 0, 17,- 15, 16,- });+ set_values<int32_t>(block_update_indices_mem,+ {+ 0,+ 17,+ 15,+ 16,+ });set_values<int32_t>(block_update_indices_begins_mem, {0, 2});topology topo;@@ -612,10 +627,13 @@ TEST(pa_kv_reorder_gpu, updates_are_scoped_per_sequence_compressed) {set_values<int32_t>(block_indices_mem, {0, 2});set_values<int32_t>(block_indices_begins_mem, {0, 1, 2});- set_values<int32_t>(block_update_indices_mem, {- 1, 3, // seq0: slot1 -> slot3 in block0- 2, 4, // seq1: slot2 -> slot4 in block2- });+ set_values<int32_t>(block_update_indices_mem,+ {+ 1,+ 3, // seq0: slot1 -> slot3 in block0+ 2,+ 4, // seq1: slot2 -> slot4 in block2+ });set_values<int32_t>(block_update_indices_begins_mem, {0, 1, 2});topology topo;@@ -762,24 +780,8 @@ TEST(pa_kv_reorder_gpu, copy_between_blocks_single_sequence_compressed_key_by_chconst ov::float16 scale = ov::float16(0.25f * static_cast<float>(1 + ((b + t) % 3)));const ov::float16 zp = ov::float16(static_cast<float>((static_cast<int>(t) % 5) - 2));for (size_t byte = 0; byte < sizeof(ov::float16); byte++) {- const auto scale_off = value_comp_byte_offset(b,- h,- t,- byte,- false,- kv_heads,- v_head_size,- adjusted_v_head_size,- block_size);- const auto zp_off = value_comp_byte_offset(b,- h,- t,- byte,- true,- kv_heads,- v_head_size,- adjusted_v_head_size,- block_size);+ const auto scale_off = value_comp_byte_offset(b, h, t, byte, false, kv_heads, v_head_size, adjusted_v_head_size, block_size);+ const auto zp_off = value_comp_byte_offset(b, h, t, byte, true, kv_heads, v_head_size, adjusted_v_head_size, block_size);value_cache_ref[scale_off] = reinterpret_cast<const int8_t*>(&scale)[byte];value_cache_ref[zp_off] = reinterpret_cast<const int8_t*>(&zp)[byte];}@@ -792,10 +794,13 @@ TEST(pa_kv_reorder_gpu, copy_between_blocks_single_sequence_compressed_key_by_chset_values<int32_t>(block_indices_mem, {0, 1});set_values<int32_t>(block_indices_begins_mem, {0, 2});- set_values<int32_t>(block_update_indices_mem, {- 0, 17,- 15, 16,- });+ set_values<int32_t>(block_update_indices_mem,+ {+ 0,+ 17,+ 15,+ 16,+ });set_values<int32_t>(block_update_indices_begins_mem, {0, 2});topology topo;@@ -848,8 +853,10 @@ TEST(pa_kv_reorder_gpu, copy_between_blocks_single_sequence_compressed_key_by_chconst float dst_scale_inv = static_cast<float>(read_fp16_from_byte_buffer(key_ptr, comp_scale_byte_offset));const float dst_zp = static_cast<float>(read_fp16_from_byte_buffer(key_ptr, comp_zp_byte_offset));- const float dst17_dequant = (static_cast<float>(key_ptr[key_offset(1, 0, k, 1, kv_heads, k_head_size, adjusted_paged_attention_block_size)]) - dst_zp) * dst_scale_inv;- const float dst16_dequant = (static_cast<float>(key_ptr[key_offset(1, 0, k, 0, kv_heads, k_head_size, adjusted_paged_attention_block_size)]) - dst_zp) * dst_scale_inv;+ const float dst17_dequant =+ (static_cast<float>(key_ptr[key_offset(1, 0, k, 1, kv_heads, k_head_size, adjusted_paged_attention_block_size)]) - dst_zp) * dst_scale_inv;+ const float dst16_dequant =+ (static_cast<float>(key_ptr[key_offset(1, 0, k, 0, kv_heads, k_head_size, adjusted_paged_attention_block_size)]) - dst_zp) * dst_scale_inv;ASSERT_NEAR(dst17_dequant, static_cast<float>(src0_q), 1.0f);ASSERT_NEAR(dst16_dequant, static_cast<float>(src15_q), 1.0f);@@ -880,16 +887,20 @@ TEST(pa_kv_reorder_gpu, copy_between_blocks_single_sequence_compressed_u4_key_byconstexpr size_t blocks_num = 2;constexpr size_t kv_heads = 1;constexpr size_t k_head_size = 32;- constexpr size_t packed_k_head_size = k_head_size / 2;constexpr size_t v_head_size = 16;constexpr size_t subgroup_size = 16;+ constexpr size_t block_size = cldnn::paged_attention::block_size;+ // u4 BY_CHANNEL key layout: each column = one head dim with 16 tokens packed as 8 bytes+ // (lo nibble = token 2t, hi nibble = token 2t+1) followed by [scale_inv (f16)][zp (f16)] = 12 bytes/col.+ // Number of columns = k_head_size (NOT halved, since BY_CHANNEL packs along the token axis).+ constexpr size_t packed_block_size = block_size / 2;+ constexpr size_t scales_zp_size = sizeof(ov::float16) * 2;+ constexpr size_t adjusted_paged_attention_block_size = packed_block_size + scales_zp_size;+ // u4 V is per-token inline: each token row = packed_v_head_size bytes + [scale][zp] (f16 each).constexpr size_t packed_v_head_size = ((v_head_size / 2 + subgroup_size - 1) / subgroup_size) * subgroup_size;- constexpr size_t scales_zp_size = sizeof(ov::float16) * 4;- constexpr size_t adjusted_paged_attention_block_size = cldnn::paged_attention::block_size + scales_zp_size;constexpr size_t adjusted_v_head_size = packed_v_head_size + scales_zp_size;- constexpr size_t block_size = cldnn::paged_attention::block_size;- auto key_cache_layout = layout{ov::PartialShape{blocks_num, kv_heads, packed_k_head_size, adjusted_paged_attention_block_size}, data_types::u8, format::bfyx};+ auto key_cache_layout = layout{ov::PartialShape{blocks_num, kv_heads, k_head_size, adjusted_paged_attention_block_size}, data_types::u8, format::bfyx};auto value_cache_layout = layout{ov::PartialShape{blocks_num, kv_heads, block_size, adjusted_v_head_size}, data_types::u8, format::bfyx};auto block_indices_layout = layout{ov::PartialShape{2}, data_types::i32, format::bfyx};auto block_indices_begins_layout = layout{ov::PartialShape{2}, data_types::i32, format::bfyx};@@ -912,58 +923,43 @@ TEST(pa_kv_reorder_gpu, copy_between_blocks_single_sequence_compressed_u4_key_bybuffer[byte_offset + 1] = static_cast<uint8_t>((bits >> 8) & 0xFF);};- // Fill key cache data and per-packed-dim comp params.+ // Fill key cache: each head dim h gets a column with 8 packed token bytes (16 tokens / 2)+ // followed by [scale_inv (f16)][zp (f16)]. Within a packed byte, lo nibble = token 2t, hi = token 2t+1.for (size_t b = 0; b < blocks_num; b++) {- for (size_t p = 0; p < packed_k_head_size; p++) {- const float s0 = 0.10f + 0.01f * static_cast<float>(p);- const float z0 = static_cast<float>((static_cast<int>(p) % 4) + 1);- const float s1 = 0.08f + 0.01f * static_cast<float>(p);- const float z1 = static_cast<float>((static_cast<int>(p) % 5) + 2);-- const size_t comp_base = key_offset(b, 0, p, block_size, kv_heads, packed_k_head_size, adjusted_paged_attention_block_size);- write_fp16_bytes(key_cache_ref, comp_base + 0 * sizeof(ov::float16), ov::float16(s0));- write_fp16_bytes(key_cache_ref, comp_base + 1 * sizeof(ov::float16), ov::float16(z0));- write_fp16_bytes(key_cache_ref, comp_base + 2 * sizeof(ov::float16), ov::float16(s1));- write_fp16_bytes(key_cache_ref, comp_base + 3 * sizeof(ov::float16), ov::float16(z1));-- for (size_t t = 0; t < block_size; t++) {- const uint8_t q0 = static_cast<uint8_t>((3 * t + p + b) & 0xF);- const uint8_t q1 = static_cast<uint8_t>((2 * t + 2 * p + 1 + b) & 0xF);- key_cache_ref[key_offset(b, 0, p, t, kv_heads, packed_k_head_size, adjusted_paged_attention_block_size)] =- static_cast<uint8_t>((q0 & 0xF) | ((q1 & 0xF) << 4));+ for (size_t h = 0; h < k_head_size; h++) {+ const float scale_inv = 0.10f + 0.01f * static_cast<float>(h);+ const float zp = static_cast<float>((static_cast<int>(h) % 5) + 1);++ const size_t comp_base = key_offset(b, 0, h, packed_block_size, kv_heads, k_head_size, adjusted_paged_attention_block_size);+ write_fp16_bytes(key_cache_ref, comp_base + 0 * sizeof(ov::float16), ov::float16(scale_inv));+ write_fp16_bytes(key_cache_ref, comp_base + 1 * sizeof(ov::float16), ov::float16(zp));++ for (size_t byte_in_col = 0; byte_in_col < packed_block_size; byte_in_col++) {+ const size_t t_lo = byte_in_col * 2;+ const size_t t_hi = byte_in_col * 2 + 1;+ const uint8_t q_lo = static_cast<uint8_t>((3 * t_lo + h + b) & 0xF);+ const uint8_t q_hi = static_cast<uint8_t>((3 * t_hi + h + b) & 0xF);+ key_cache_ref[key_offset(b, 0, h, byte_in_col, kv_heads, k_head_size, adjusted_paged_attention_block_size)] =+ static_cast<uint8_t>((q_lo & 0xF) | ((q_hi & 0xF) << 4));}}}- // Fill value cache with packed BY_TOKEN style bytes and comp bytes.+ // Fill value cache with u4 per-token-inline layout: each token row holds packed data+ // followed by inline [scale][zp] (matches quantize_and_save_per_token, pitch == 1).for (size_t b = 0; b < blocks_num; b++) {for (size_t t = 0; t < block_size; t++) {for (size_t p = 0; p < packed_v_head_size; p++) {- value_cache_ref[value_data_offset_compressed(b, 0, t, p, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)] =+ value_cache_ref[value_data_offset_int4_per_token(b, 0, t, p, kv_heads, adjusted_v_head_size, block_size)] =static_cast<uint8_t>((7 * t + 5 * p + b) % 251);}const ov::float16 scale = ov::float16(0.125f * static_cast<float>(1 + ((b + t) % 3)));const ov::float16 zp = ov::float16(static_cast<float>((static_cast<int>(t) % 7) - 3));for (size_t byte = 0; byte < sizeof(ov::float16); byte++) {- const auto scale_off = value_comp_byte_offset(b,- 0,- t,- byte,- false,- kv_heads,- packed_v_head_size,- adjusted_v_head_size,- block_size);- const auto zp_off = value_comp_byte_offset(b,- 0,- t,- byte,- true,- kv_heads,- packed_v_head_size,- adjusted_v_head_size,- block_size);+ const auto scale_off =+ value_comp_byte_offset_int4_per_token(b, 0, t, byte, false, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size);+ const auto zp_off = value_comp_byte_offset_int4_per_token(b, 0, t, byte, true, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size);value_cache_ref[scale_off] = reinterpret_cast<const uint8_t*>(&scale)[byte];value_cache_ref[zp_off] = reinterpret_cast<const uint8_t*>(&zp)[byte];}@@ -975,10 +971,13 @@ TEST(pa_kv_reorder_gpu, copy_between_blocks_single_sequence_compressed_u4_key_byset_values<int32_t>(block_indices_mem, {0, 1});set_values<int32_t>(block_indices_begins_mem, {0, 2});- set_values<int32_t>(block_update_indices_mem, {- 0, 17,- 15, 16,- });+ set_values<int32_t>(block_update_indices_mem,+ {+ 0,+ 17,+ 15,+ 16,+ });set_values<int32_t>(block_update_indices_begins_mem, {0, 2});topology topo;@@ -1020,72 +1019,60 @@ TEST(pa_kv_reorder_gpu, copy_between_blocks_single_sequence_compressed_u4_key_bycldnn::mem_lock<uint8_t, mem_lock_type::read> key_ptr(key_cache_mem, network->get_stream());cldnn::mem_lock<uint8_t, mem_lock_type::read> value_ptr(value_cache_mem, network->get_stream());- auto unpack_q_pair = [](uint8_t packed) {- return std::make_pair(static_cast<uint8_t>(packed & 0xF), static_cast<uint8_t>((packed >> 4) & 0xF));+ auto read_nibble_at_token = [&](const auto& buffer, size_t block, size_t h, size_t token) {+ const size_t byte_off = key_offset(block, 0, h, token / 2, kv_heads, k_head_size, adjusted_paged_attention_block_size);+ const uint8_t packed = buffer[byte_off];+ return (token % 2 == 0) ? static_cast<uint8_t>(packed & 0xF) : static_cast<uint8_t>((packed >> 4) & 0xF);};- auto read_comp_output = [&](const cldnn::mem_lock<uint8_t, mem_lock_type::read>& ptr, size_t block, size_t packed_k) {- const size_t comp_base = key_offset(block, 0, packed_k, block_size, kv_heads, packed_k_head_size, adjusted_paged_attention_block_size);- const float s0 = static_cast<float>(read_fp16_from_byte_buffer(ptr, comp_base + 0 * sizeof(ov::float16)));- const float z0 = static_cast<float>(read_fp16_from_byte_buffer(ptr, comp_base + 1 * sizeof(ov::float16)));- const float s1 = static_cast<float>(read_fp16_from_byte_buffer(ptr, comp_base + 2 * sizeof(ov::float16)));- const float z1 = static_cast<float>(read_fp16_from_byte_buffer(ptr, comp_base + 3 * sizeof(ov::float16)));- return std::make_tuple(s0, z0, s1, z1);+ auto read_col_comp = [&](const auto& buffer, size_t block, size_t h) {+ const size_t comp_base = key_offset(block, 0, h, packed_block_size, kv_heads, k_head_size, adjusted_paged_attention_block_size);+ const float scale_inv = static_cast<float>(read_fp16_from_byte_buffer(buffer, comp_base + 0 * sizeof(ov::float16)));+ const float zp = static_cast<float>(read_fp16_from_byte_buffer(buffer, comp_base + 1 * sizeof(ov::float16)));+ return std::make_pair(scale_inv, zp);};- auto read_comp_ref = [&](const std::vector<uint8_t>& buffer, size_t block, size_t packed_k) {- const size_t comp_base = key_offset(block, 0, packed_k, block_size, kv_heads, packed_k_head_size, adjusted_paged_attention_block_size);- const float s0 = static_cast<float>(read_fp16_from_u8_vector(buffer, comp_base + 0 * sizeof(ov::float16)));- const float z0 = static_cast<float>(read_fp16_from_u8_vector(buffer, comp_base + 1 * sizeof(ov::float16)));- const float s1 = static_cast<float>(read_fp16_from_u8_vector(buffer, comp_base + 2 * sizeof(ov::float16)));- const float z1 = static_cast<float>(read_fp16_from_u8_vector(buffer, comp_base + 3 * sizeof(ov::float16)));- return std::make_tuple(s0, z0, s1, z1);+ auto read_col_comp_ref = [&](const std::vector<uint8_t>& buffer, size_t block, size_t h) {+ const size_t comp_base = key_offset(block, 0, h, packed_block_size, kv_heads, k_head_size, adjusted_paged_attention_block_size);+ const float scale_inv = static_cast<float>(read_fp16_from_u8_vector(buffer, comp_base + 0 * sizeof(ov::float16)));+ const float zp = static_cast<float>(read_fp16_from_u8_vector(buffer, comp_base + 1 * sizeof(ov::float16)));+ return std::make_pair(scale_inv, zp);};- for (size_t p = 0; p < packed_k_head_size; p++) {- const uint8_t src_packed_0 = key_cache_ref[key_offset(0, 0, p, 0, kv_heads, packed_k_head_size, adjusted_paged_attention_block_size)];- const uint8_t src_packed_15 = key_cache_ref[key_offset(0, 0, p, 15, kv_heads, packed_k_head_size, adjusted_paged_attention_block_size)];- const auto [src_q0_0, src_q1_0] = unpack_q_pair(src_packed_0);- const auto [src_q0_15, src_q1_15] = unpack_q_pair(src_packed_15);-- const auto [src_s0, src_z0, src_s1, src_z1] = read_comp_ref(key_cache_ref, 0, p);- const auto [dst_s0, dst_z0, dst_s1, dst_z1] = read_comp_output(key_ptr, 1, p);-- const float src_val0_0 = (static_cast<float>(src_q0_0) - src_z0) * src_s0;- const float src_val1_0 = (static_cast<float>(src_q1_0) - src_z1) * src_s1;- const float src_val0_15 = (static_cast<float>(src_q0_15) - src_z0) * src_s0;- const float src_val1_15 = (static_cast<float>(src_q1_15) - src_z1) * src_s1;-- const uint8_t dst_packed_17 = key_ptr[key_offset(1, 0, p, 1, kv_heads, packed_k_head_size, adjusted_paged_attention_block_size)];- const uint8_t dst_packed_16 = key_ptr[key_offset(1, 0, p, 0, kv_heads, packed_k_head_size, adjusted_paged_attention_block_size)];- const auto [dst_q0_17, dst_q1_17] = unpack_q_pair(dst_packed_17);- const auto [dst_q0_16, dst_q1_16] = unpack_q_pair(dst_packed_16);-- const float dst_val0_17 = (static_cast<float>(dst_q0_17) - dst_z0) * dst_s0;- const float dst_val1_17 = (static_cast<float>(dst_q1_17) - dst_z1) * dst_s1;- const float dst_val0_16 = (static_cast<float>(dst_q0_16) - dst_z0) * dst_s0;- const float dst_val1_16 = (static_cast<float>(dst_q1_16) - dst_z1) * dst_s1;-- ASSERT_NEAR(dst_val0_17, src_val0_0, 1.0f);- ASSERT_NEAR(dst_val1_17, src_val1_0, 1.0f);- ASSERT_NEAR(dst_val0_16, src_val0_15, 1.0f);- ASSERT_NEAR(dst_val1_16, src_val1_15, 1.0f);+ // Reorder maps src token 0 -> dst token 17 (block 1, slot 1) and src token 15 -> dst token 16 (block 1, slot 0).+ // Compare in dequantized space because the dst column is requantized end-to-end on cross-block copies.+ for (size_t h = 0; h < k_head_size; h++) {+ const auto [src_scale_inv, src_zp] = read_col_comp_ref(key_cache_ref, 0, h);+ const auto [dst_scale_inv, dst_zp] = read_col_comp(key_ptr, 1, h);++ const uint8_t src_q0 = read_nibble_at_token(key_cache_ref, 0, h, 0);+ const uint8_t src_q15 = read_nibble_at_token(key_cache_ref, 0, h, 15);+ const float src_val0 = (static_cast<float>(src_q0) - src_zp) * src_scale_inv;+ const float src_val15 = (static_cast<float>(src_q15) - src_zp) * src_scale_inv;++ const uint8_t dst_q1 = read_nibble_at_token(key_ptr, 1, h, 1);+ const uint8_t dst_q0 = read_nibble_at_token(key_ptr, 1, h, 0);+ const float dst_val1 = (static_cast<float>(dst_q1) - dst_zp) * dst_scale_inv;+ const float dst_val0 = (static_cast<float>(dst_q0) - dst_zp) * dst_scale_inv;++ ASSERT_NEAR(dst_val1, src_val0, 1.0f);+ ASSERT_NEAR(dst_val0, src_val15, 1.0f);}for (size_t p = 0; p < packed_v_head_size; p++) {- const auto src0 = value_cache_ref[value_data_offset_compressed(0, 0, 0, p, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)];- const auto dst17 = value_ptr[value_data_offset_compressed(1, 0, 1, p, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)];+ const auto src0 = value_cache_ref[value_data_offset_int4_per_token(0, 0, 0, p, kv_heads, adjusted_v_head_size, block_size)];+ const auto dst17 = value_ptr[value_data_offset_int4_per_token(1, 0, 1, p, kv_heads, adjusted_v_head_size, block_size)];ASSERT_EQ(dst17, src0);- const auto src15 = value_cache_ref[value_data_offset_compressed(0, 0, 15, p, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)];- const auto dst16 = value_ptr[value_data_offset_compressed(1, 0, 0, p, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)];+ const auto src15 = value_cache_ref[value_data_offset_int4_per_token(0, 0, 15, p, kv_heads, adjusted_v_head_size, block_size)];+ const auto dst16 = value_ptr[value_data_offset_int4_per_token(1, 0, 0, p, kv_heads, adjusted_v_head_size, block_size)];ASSERT_EQ(dst16, src15);}for (size_t byte = 0; byte < sizeof(ov::float16); byte++) {- ASSERT_EQ(value_ptr[value_comp_byte_offset(1, 0, 1, byte, false, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)],- value_cache_ref[value_comp_byte_offset(0, 0, 0, byte, false, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)]);- ASSERT_EQ(value_ptr[value_comp_byte_offset(1, 0, 1, byte, true, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)],- value_cache_ref[value_comp_byte_offset(0, 0, 0, byte, true, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)]);+ ASSERT_EQ(value_ptr[value_comp_byte_offset_int4_per_token(1, 0, 1, byte, false, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)],+ value_cache_ref[value_comp_byte_offset_int4_per_token(0, 0, 0, byte, false, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)]);+ ASSERT_EQ(value_ptr[value_comp_byte_offset_int4_per_token(1, 0, 1, byte, true, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)],+ value_cache_ref[value_comp_byte_offset_int4_per_token(0, 0, 0, byte, true, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)]);}}diff --git a/src/plugins/intel_gpu/tests/unit/transformations/pa_kv_reorder_fusion_test.cpp b/src/plugins/intel_gpu/tests/unit/transformations/pa_kv_reorder_fusion_test.cppdeleted file mode 100644index d2990ec9fdb..00000000000--- a/src/plugins/intel_gpu/tests/unit/transformations/pa_kv_reorder_fusion_test.cpp+++ /dev/null@@ -1,162 +0,0 @@-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#include "common_test_utils/ov_test_utils.hpp"--#include "openvino/core/model.hpp"-#include "openvino/op/concat.hpp"-#include "openvino/op/constant.hpp"-#include "openvino/op/gather.hpp"-#include "openvino/op/parameter.hpp"-#include "openvino/op/result.hpp"-#include "openvino/op/scatter_update.hpp"--#include "intel_gpu/op/pa_kv_reorder.hpp"-#include "plugin/transformations/pa_kv_reorder_fusion.hpp"--#include <memory>--using namespace testing;-using namespace ov::intel_gpu;--namespace ov {-namespace test {-namespace intel_gpu {--TEST_F(TransformationTestsF, PaKVReorderFusion_basic) {- disable_result_friendly_names_check();- {- auto key_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{4, 2});- key_cache->set_friendly_name("key_cache.0_clone_for_k_update");- auto value_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{4, 2});- value_cache->set_friendly_name("value_cache.0_clone_for_v_update");-- auto block_indices = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{2});- block_indices->set_friendly_name("block_indices");- auto block_indices_begins = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{2});- block_indices_begins->set_friendly_name("block_indices_begins");-- auto block_update_indices = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{2});- block_update_indices->set_friendly_name("block_update_indices");- auto block_update_indices_begins = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{2});- block_update_indices_begins->set_friendly_name("block_update_indices_begins");-- auto gather_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});- auto scatter_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});-- auto key_gather = std::make_shared<ov::op::v8::Gather>(key_cache, block_update_indices, gather_axis);- auto value_gather = std::make_shared<ov::op::v8::Gather>(value_cache, block_update_indices, gather_axis);-- auto key_scatter = std::make_shared<ov::op::v3::ScatterUpdate>(key_cache, block_indices, key_gather, scatter_axis);- auto value_scatter = std::make_shared<ov::op::v3::ScatterUpdate>(value_cache, block_indices, value_gather, scatter_axis);-- auto concat = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{key_scatter, value_scatter}, 0);- auto result = std::make_shared<ov::op::v0::Result>(concat);-- model = std::make_shared<ov::Model>(ov::ResultVector{result},- ov::ParameterVector{key_cache,- value_cache,- block_indices,- block_indices_begins,- block_update_indices,- block_update_indices_begins});-- manager.register_pass<PaKVReorderFusion>(false,- std::vector<size_t>{0, 1, 3, 2},- std::vector<size_t>{0, 1, 2, 3},- ov::element::f16,- ov::element::f16,- ov::element::f16);- }-- {- auto key_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{4, 2});- key_cache->set_friendly_name("key_cache.0_clone_for_k_update");- auto value_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{4, 2});- value_cache->set_friendly_name("value_cache.0_clone_for_v_update");-- auto block_indices = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{2});- block_indices->set_friendly_name("block_indices");- auto block_indices_begins = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{2});- block_indices_begins->set_friendly_name("block_indices_begins");-- auto block_update_indices = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{2});- block_update_indices->set_friendly_name("block_update_indices");- auto block_update_indices_begins = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{2});- block_update_indices_begins->set_friendly_name("block_update_indices_begins");-- auto pa_kv_reorder = std::make_shared<ov::intel_gpu::op::PA_KV_Reorder>(key_cache,- value_cache,- block_indices,- block_indices_begins,- block_update_indices,- block_update_indices_begins);- pa_kv_reorder->set_friendly_name("pa_kv_reorder_0");- auto result = std::make_shared<ov::op::v0::Result>(pa_kv_reorder);-- model_ref = std::make_shared<ov::Model>(ov::ResultVector{result},- ov::ParameterVector{key_cache,- value_cache,- block_indices,- block_indices_begins,- block_update_indices,- block_update_indices_begins});- comparator.enable(FunctionsComparator::ATTRIBUTES);- }-}--TEST_F(TransformationTestsF, PaKVReorderFusion_skip_on_mismatched_block_indices) {- disable_result_friendly_names_check();- auto key_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{4, 2});- key_cache->set_friendly_name("key_cache.0_clone_for_k_update");- auto value_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{4, 2});- value_cache->set_friendly_name("value_cache.0_clone_for_v_update");-- auto block_indices_k = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{2});- block_indices_k->set_friendly_name("block_indices_k");- auto block_indices_v = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{2});- block_indices_v->set_friendly_name("block_indices_v");-- auto block_indices_begins = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{2});- block_indices_begins->set_friendly_name("block_indices_begins");- auto block_update_indices = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{2});- block_update_indices->set_friendly_name("block_update_indices");- auto block_update_indices_begins = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{2});- block_update_indices_begins->set_friendly_name("block_update_indices_begins");-- auto gather_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});- auto scatter_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});-- auto key_gather = std::make_shared<ov::op::v8::Gather>(key_cache, block_update_indices, gather_axis);- auto value_gather = std::make_shared<ov::op::v8::Gather>(value_cache, block_update_indices, gather_axis);-- auto key_scatter = std::make_shared<ov::op::v3::ScatterUpdate>(key_cache, block_indices_k, key_gather, scatter_axis);- auto value_scatter = std::make_shared<ov::op::v3::ScatterUpdate>(value_cache, block_indices_v, value_gather, scatter_axis);-- auto concat = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{key_scatter, value_scatter}, 0);- auto result = std::make_shared<ov::op::v0::Result>(concat);-- model = std::make_shared<ov::Model>(ov::ResultVector{result},- ov::ParameterVector{key_cache,- value_cache,- block_indices_k,- block_indices_v,- block_indices_begins,- block_update_indices,- block_update_indices_begins});-- manager.register_pass<PaKVReorderFusion>(false,- std::vector<size_t>{0, 1, 3, 2},- std::vector<size_t>{0, 1, 2, 3},- ov::element::f16,- ov::element::f16,- ov::element::f16);-- model_ref = model->clone();- comparator.enable(FunctionsComparator::ATTRIBUTES);-}--} // namespace intel_gpu-} // namespace test-} // namespace ov