Skip to content

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

[CPU]Implement QSAIndexer, SpraseSDPA,SparsePA, PagedQSAIndexer (#39201)

Zhang Yid200513bc810
diff --git a/src/common/transformations/src/transformations/paged_attention/convert_pagedattn_inputs.cpp b/src/common/transformations/src/transformations/paged_attention/convert_pagedattn_inputs.cpp
index 9aa512079bc..d93e2863af3 100644
--- a/src/common/transformations/src/transformations/paged_attention/convert_pagedattn_inputs.cpp
+++ b/src/common/transformations/src/transformations/paged_attention/convert_pagedattn_inputs.cpp
@@ -15,6 +15,7 @@
#include "openvino/op/paged_causal_conv1d.hpp"
#include "openvino/op/paged_gated_delta_net.hpp"
#include "openvino/op/paged_selective_ssm.hpp"
+#include "openvino/op/paged_sparse_attention.hpp"
#include "openvino/pass/pattern/op/wrap_type.hpp"
#include "openvino/util/log.hpp"
#include "transformations/rt_info/keep_const_precision.hpp"
@@ -35,6 +36,7 @@ ConvertPagedAttnInputs::ConvertPagedAttnInputs(const KVCacheConfig& config,
MATCHER_SCOPE(ConvertPagedAttnInputs);
auto paged_op = pattern::wrap_type<ov::op::PagedAttentionExtension,
+ ov::op::internal::PagedSparseAttention,
ov::op::internal::PagedCausalConv1D,
ov::op::internal::PagedGatedDeltaNet,
ov::op::internal::PagedSelectiveSSM>();
@@ -42,7 +44,12 @@ ConvertPagedAttnInputs::ConvertPagedAttnInputs(const KVCacheConfig& config,
const auto root = m.get_match_root();
bool status = false;
- if (const auto pa_op = ov::as_type_ptr<ov::op::PagedAttentionExtension>(root)) {
+ // PagedAttentionExtension and PagedSparseAttention share the key/value cache inputs (3, 4) and the
+ // `num_k_heads`/`k_head_size`/`num_v_heads`/`v_head_size` runtime info that defines the cache shape.
+ const auto pa_op =
+ ov::is_type_any_of<ov::op::PagedAttentionExtension, ov::op::internal::PagedSparseAttention>(root) ? root
+ : nullptr;
+ if (pa_op) {
auto key_cache = ov::as_type_ptr<v0::Parameter>(pa_op->get_input_node_shared_ptr(3));
auto value_cache = ov::as_type_ptr<v0::Parameter>(pa_op->get_input_node_shared_ptr(4));
if (!key_cache || !value_cache) {
diff --git a/src/common/transformations/tests/common_optimizations/convert_pagedattn_inputs.cpp b/src/common/transformations/tests/common_optimizations/convert_pagedattn_inputs.cpp
index 625b95846b5..5da53c5084b 100644
--- a/src/common/transformations/tests/common_optimizations/convert_pagedattn_inputs.cpp
+++ b/src/common/transformations/tests/common_optimizations/convert_pagedattn_inputs.cpp
@@ -12,6 +12,7 @@
#include "openvino/op/paged_causal_conv1d.hpp"
#include "openvino/op/paged_gated_delta_net.hpp"
#include "openvino/op/paged_selective_ssm.hpp"
+#include "openvino/op/paged_sparse_attention.hpp"
#include "openvino/pass/constant_folding.hpp"
#include "openvino/pass/manager.hpp"
#include "openvino/runtime/properties.hpp"
@@ -674,4 +675,87 @@ TEST_F(ConvertPagedAttnInputsStateTableTest, ConvertPagedSelectiveSSMIndependent
EXPECT_EQ(paged_ssm->get_output_element_type(0), element::f32);
}
+// PagedSparseAttention caches get the same precision and padded shapes as PagedAttentionExtension, and the op
+// stays valid with the padded shapes.
+TEST(ConvertPagedAttnInputsSparseTest, PagedSparseAttentionQuantizedCaches) {
+ constexpr size_t num_heads = 4;
+ constexpr size_t num_kv_heads = 2;
+ constexpr size_t key_head_size = 32;
+ constexpr size_t value_head_size = 16;
+ constexpr size_t key_block_size = 32;
+ constexpr size_t value_block_size = 32;
+
+ auto query = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, num_heads * key_head_size});
+ auto key = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, num_kv_heads * key_head_size});
+ auto value = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, num_kv_heads * value_head_size});
+ auto key_cache = std::make_shared<v0::Parameter>(element::dynamic, PartialShape::dynamic(4));
+ auto value_cache = std::make_shared<v0::Parameter>(element::dynamic, PartialShape::dynamic(4));
+ auto past_lens = std::make_shared<v0::Parameter>(element::i32, PartialShape{-1});
+ auto subsequence_begins = std::make_shared<v0::Parameter>(element::i32, PartialShape{-1});
+ auto block_indices = std::make_shared<v0::Parameter>(element::i32, PartialShape{-1});
+ auto block_indices_begins = std::make_shared<v0::Parameter>(element::i32, PartialShape{-1});
+ auto selected_block_indices = std::make_shared<v0::Parameter>(element::i32, PartialShape{-1, 1, 8});
+ auto selected_block_count = std::make_shared<v0::Parameter>(element::i32, PartialShape{-1, 1});
+ auto scale = std::make_shared<v0::Constant>(element::f32, Shape{}, 0.5f);
+ auto sinks = std::make_shared<v0::Constant>(element::f32, Shape{0});
+ auto psa = std::make_shared<op::internal::PagedSparseAttention>(OutputVector{query,
+ key,
+ value,
+ key_cache,
+ value_cache,
+ past_lens,
+ subsequence_begins,
+ block_indices,
+ block_indices_begins,
+ selected_block_indices,
+ selected_block_count,
+ scale,
+ sinks},
+ 4);
+ psa->get_rt_info()["num_k_heads"] = num_kv_heads;
+ psa->get_rt_info()["k_head_size"] = key_head_size;
+ psa->get_rt_info()["num_v_heads"] = num_kv_heads;
+ psa->get_rt_info()["v_head_size"] = value_head_size;
+ auto model = std::make_shared<ov::Model>(OutputVector{psa},
+ ParameterVector{query,
+ key,
+ value,
+ key_cache,
+ value_cache,
+ past_lens,
+ subsequence_begins,
+ block_indices,
+ block_indices_begins,
+ selected_block_indices,
+ selected_block_count});
+
+ ov::pass::ConvertPagedAttnInputs::KVCacheConfig cacheConfig;
+ cacheConfig.inferencePrecision = element::f32;
+ cacheConfig.keyCachePrecision = element::u8;
+ cacheConfig.valueCachePrecision = element::u8;
+ cacheConfig.keyCacheBlockSize = key_block_size;
+ cacheConfig.valueCacheBlockSize = value_block_size;
+ // u8 by-token: scale and zero point are appended to the head size.
+ auto update_shape = [](const ov::element::Type& precision, const bool, const size_t, int64_t& head_size, int64_t&) {
+ if (precision == ov::element::u8) {
+ head_size += 2 * sizeof(float);
+ }
+ };
+
+ ov::pass::Manager manager;
+ manager.register_pass<ov::pass::ConvertPagedAttnInputs>(cacheConfig, update_shape);
+ manager.run_passes(model);
+
+ EXPECT_EQ(key_cache->get_element_type(), element::u8);
+ EXPECT_EQ(value_cache->get_element_type(), element::u8);
+ EXPECT_EQ(key_cache->get_partial_shape(),
+ (PartialShape{-1, num_kv_heads, key_block_size, key_head_size + 2 * sizeof(float)}));
+ EXPECT_EQ(value_cache->get_partial_shape(),
+ (PartialShape{-1, num_kv_heads, value_block_size, value_head_size + 2 * sizeof(float)}));
+
+ // The padded caches must still validate against the unpadded key/value widths.
+ EXPECT_NO_THROW(model->validate_nodes_and_infer_types());
+ EXPECT_EQ(psa->get_output_partial_shape(0), (PartialShape{-1, num_heads * value_head_size}));
+}
+
} // namespace
diff --git a/src/plugins/intel_cpu/CMakeLists.txt b/src/plugins/intel_cpu/CMakeLists.txt
index 9df23e758fe..84e0bce5d71 100644
--- a/src/plugins/intel_cpu/CMakeLists.txt
+++ b/src/plugins/intel_cpu/CMakeLists.txt
@@ -281,6 +281,34 @@ cross_compiled_file(${TARGET_NAME}
NAME turboq_quantize_head turboq_quantize
NAMESPACE ov::Extensions::Cpu::XARCH
)
+cross_compiled_file(${TARGET_NAME}
+ ARCH AVX512F AVX2 ANY
+ src/nodes/kernels/sparse_attn/sparse_sdpa_kernel.cpp
+ API src/nodes/kernels/sparse_attn/sparse_sdpa_kernel.hpp
+ NAME sparse_sdpa_compute sparse_kv_dequantize_rows
+ NAMESPACE ov::Extensions::Cpu::XARCH
+)
+cross_compiled_file(${TARGET_NAME}
+ ARCH AVX512F AVX2 ANY
+ src/nodes/kernels/sparse_attn/sparse_pa_kernel.cpp
+ API src/nodes/kernels/sparse_attn/sparse_pa_kernel.hpp
+ NAME sparse_pa_compute
+ NAMESPACE ov::Extensions::Cpu::XARCH
+)
+cross_compiled_file(${TARGET_NAME}
+ ARCH AVX512F AVX2 ANY
+ src/nodes/kernels/sparse_attn/qsa_indexer_kernel.cpp
+ API src/nodes/kernels/sparse_attn/qsa_indexer_kernel.hpp
+ NAME qsa_indexer_compute
+ NAMESPACE ov::Extensions::Cpu::XARCH
+)
+cross_compiled_file(${TARGET_NAME}
+ ARCH AVX512F AVX2 ANY
+ src/nodes/kernels/sparse_attn/paged_qsa_indexer_kernel.cpp
+ API src/nodes/kernels/sparse_attn/paged_qsa_indexer_kernel.hpp
+ NAME paged_qsa_indexer_compute
+ NAMESPACE ov::Extensions::Cpu::XARCH
+)
## turboq_rotation.cpp holds scalar setup only (sign cache, env parsing);
## SIMD WHT butterfly is inline in turboq_rotation.hpp and gets ISA-specialized
## when included by cross-compiled translation units.
diff --git a/src/plugins/intel_cpu/sources.cmake b/src/plugins/intel_cpu/sources.cmake
index 1258eb83ea7..a68e247229b 100644
--- a/src/plugins/intel_cpu/sources.cmake
+++ b/src/plugins/intel_cpu/sources.cmake
@@ -356,6 +356,12 @@ set(CPU_PLUGIN_SRCS
${CPU_SRC_DIR}/nodes/kernels/scaled_attn/softmax.cpp
${CPU_SRC_DIR}/nodes/kernels/scaled_attn/softmax.hpp
${CPU_SRC_DIR}/nodes/kernels/scaled_attn/softmax_kernel.hpp
+ ${CPU_SRC_DIR}/nodes/kernels/sparse_attn/sparse_brgemm.hpp
+ ${CPU_SRC_DIR}/nodes/kernels/sparse_attn/sparse_brgemm_kernel.hpp
+ ${CPU_SRC_DIR}/nodes/kernels/sparse_attn/sparse_pa_kernel.cpp
+ ${CPU_SRC_DIR}/nodes/kernels/sparse_attn/sparse_pa_kernel.hpp
+ ${CPU_SRC_DIR}/nodes/kernels/sparse_attn/sparse_sdpa_kernel.cpp
+ ${CPU_SRC_DIR}/nodes/kernels/sparse_attn/sparse_sdpa_kernel.hpp
${CPU_SRC_DIR}/nodes/kernels/scaled_attn/transpose.hpp
${CPU_SRC_DIR}/nodes/kernels/scaled_attn/transpose_kernel.hpp
${CPU_SRC_DIR}/nodes/kernels/scaled_attn/xattention.hpp
@@ -412,6 +418,8 @@ set(CPU_PLUGIN_SRCS
${CPU_SRC_DIR}/nodes/paged_causal_conv1d.h
${CPU_SRC_DIR}/nodes/paged_gated_delta_net.cpp
${CPU_SRC_DIR}/nodes/paged_gated_delta_net.h
+ ${CPU_SRC_DIR}/nodes/paged_qsa_indexer.cpp
+ ${CPU_SRC_DIR}/nodes/paged_qsa_indexer.h
${CPU_SRC_DIR}/nodes/paged_selective_ssm.cpp
${CPU_SRC_DIR}/nodes/paged_selective_ssm.h
${CPU_SRC_DIR}/nodes/pooling.cpp
@@ -428,6 +436,16 @@ set(CPU_PLUGIN_SRCS
${CPU_SRC_DIR}/nodes/psroi_pooling.h
${CPU_SRC_DIR}/nodes/qkv_proj.cpp
${CPU_SRC_DIR}/nodes/qkv_proj.h
+ ${CPU_SRC_DIR}/nodes/qsa_indexer.cpp
+ ${CPU_SRC_DIR}/nodes/qsa_indexer.h
+ ${CPU_SRC_DIR}/nodes/kernels/sparse_attn/qsa_indexer_common.hpp
+ ${CPU_SRC_DIR}/nodes/kernels/sparse_attn/paged_qsa_indexer_kernel.cpp
+ ${CPU_SRC_DIR}/nodes/kernels/sparse_attn/paged_qsa_indexer_kernel.hpp
+ ${CPU_SRC_DIR}/nodes/kernels/sparse_attn/qsa_indexer_kernel.cpp
+ ${CPU_SRC_DIR}/nodes/kernels/sparse_attn/qsa_indexer_kernel.hpp
+ ${CPU_SRC_DIR}/nodes/kernels/sparse_attn/qsa_brgemm.hpp
+ ${CPU_SRC_DIR}/nodes/kernels/sparse_attn/qsa_indexer_brgemm_kernel.hpp
+ ${CPU_SRC_DIR}/nodes/kernels/sparse_attn/qsa_kernel_utils.hpp
${CPU_SRC_DIR}/nodes/random_uniform.cpp
${CPU_SRC_DIR}/nodes/random_uniform.hpp
${CPU_SRC_DIR}/nodes/range.cpp
@@ -484,6 +502,10 @@ set(CPU_PLUGIN_SRCS
${CPU_SRC_DIR}/nodes/space_to_depth.h
${CPU_SRC_DIR}/nodes/sparse_fill_empty_rows.cpp
${CPU_SRC_DIR}/nodes/sparse_fill_empty_rows.h
+ ${CPU_SRC_DIR}/nodes/sparse_sdpa.cpp
+ ${CPU_SRC_DIR}/nodes/sparse_sdpa.h
+ ${CPU_SRC_DIR}/nodes/sparse_pa.cpp
+ ${CPU_SRC_DIR}/nodes/sparse_pa.h
${CPU_SRC_DIR}/nodes/split.cpp
${CPU_SRC_DIR}/nodes/split.h
${CPU_SRC_DIR}/nodes/stft.cpp
@@ -584,8 +606,12 @@ set(CPU_PLUGIN_SRCS
${CPU_SRC_DIR}/transformations/cpu_opset/common/op/power_static.hpp
${CPU_SRC_DIR}/transformations/cpu_opset/common/op/read_value_with_subgraph.cpp
${CPU_SRC_DIR}/transformations/cpu_opset/common/op/read_value_with_subgraph.hpp
+ ${CPU_SRC_DIR}/transformations/cpu_opset/common/op/qsa_indexer.cpp
+ ${CPU_SRC_DIR}/transformations/cpu_opset/common/op/qsa_indexer.hpp
${CPU_SRC_DIR}/transformations/cpu_opset/common/op/sdpa.cpp
${CPU_SRC_DIR}/transformations/cpu_opset/common/op/sdpa.hpp
+ ${CPU_SRC_DIR}/transformations/cpu_opset/common/op/sparse_attention_with_kv_cache.cpp
+ ${CPU_SRC_DIR}/transformations/cpu_opset/common/op/sparse_attention_with_kv_cache.hpp
${CPU_SRC_DIR}/transformations/cpu_opset/common/op/submodel.cpp
${CPU_SRC_DIR}/transformations/cpu_opset/common/op/submodel.hpp
${CPU_SRC_DIR}/transformations/cpu_opset/common/op/swish_cpu.cpp
@@ -861,6 +887,8 @@ set(CPU_PLUGIN_X64_SRCS
${CPU_SRC_DIR}/transformations/cpu_opset/x64/pass/mlp_fusion.hpp
${CPU_SRC_DIR}/transformations/cpu_opset/x64/pass/qkv_proj_fusion.cpp
${CPU_SRC_DIR}/transformations/cpu_opset/x64/pass/qkv_proj_fusion.hpp
+ ${CPU_SRC_DIR}/transformations/cpu_opset/x64/pass/sparse_attention_kv_cache_fusion.cpp
+ ${CPU_SRC_DIR}/transformations/cpu_opset/x64/pass/sparse_attention_kv_cache_fusion.hpp
${CPU_SRC_DIR}/transformations/cpu_opset/x64/pass/sdpa_fuse_transpose_reshape.cpp
${CPU_SRC_DIR}/transformations/cpu_opset/x64/pass/sdpa_fuse_transpose_reshape.hpp
${CPU_SRC_DIR}/transformations/cpu_opset/x64/pass/simplify_fakequantize.hpp
diff --git a/src/plugins/intel_cpu/src/cpu_types.cpp b/src/plugins/intel_cpu/src/cpu_types.cpp
index c57e489e7e6..9dc1cd21ce2 100644
--- a/src/plugins/intel_cpu/src/cpu_types.cpp
+++ b/src/plugins/intel_cpu/src/cpu_types.cpp
@@ -270,7 +270,12 @@ static const TypeToNameMap& get_type_to_name_tbl() {
{"PagedGatedDeltaNet", Type::PagedGatedDeltaNet},
{"SelectiveSSM", Type::SelectiveSSM},
{"PagedSelectiveSSM", Type::PagedSelectiveSSM},
- {"PagedCausalConv1D", Type::PagedCausalConv1D}};
+ {"PagedCausalConv1D", Type::PagedCausalConv1D},
+ {"QSAIndexer", Type::QSAIndexer},
+ {"SparseAttention", Type::SparseSDPA},
+ {"SparseAttentionWithKVCache", Type::SparseSDPA},
+ {"PagedQSAIndexer", Type::PagedQSAIndexer},
+ {"PagedSparseAttention", Type::SparsePA}};
return type_to_name_tbl;
}
@@ -413,6 +418,10 @@ std::string NameFromType(const Type type) {
CASE(SelectiveSSM);
CASE(PagedSelectiveSSM);
CASE(PagedCausalConv1D);
+ CASE(QSAIndexer);
+ CASE(SparseSDPA);
+ CASE(PagedQSAIndexer);
+ CASE(SparsePA);
CASE(Unknown);
}
#undef CASE
diff --git a/src/plugins/intel_cpu/src/cpu_types.h b/src/plugins/intel_cpu/src/cpu_types.h
index 7eead701b6c..e25c559526c 100644
--- a/src/plugins/intel_cpu/src/cpu_types.h
+++ b/src/plugins/intel_cpu/src/cpu_types.h
@@ -145,7 +145,11 @@ enum class Type : uint8_t {
PagedGatedDeltaNet,
SelectiveSSM,
PagedSelectiveSSM,
- PagedCausalConv1D
+ PagedCausalConv1D,
+ QSAIndexer,
+ SparseSDPA,
+ PagedQSAIndexer,
+ SparsePA,
};
enum class Algorithm : uint8_t {
diff --git a/src/plugins/intel_cpu/src/extension.cpp b/src/plugins/intel_cpu/src/extension.cpp
index ebdf8fdf280..a221dc1da97 100644
--- a/src/plugins/intel_cpu/src/extension.cpp
+++ b/src/plugins/intel_cpu/src/extension.cpp
@@ -46,7 +46,9 @@
#include "openvino/op/paged_attention.hpp"
#include "openvino/op/paged_causal_conv1d.hpp"
#include "openvino/op/paged_gated_delta_net.hpp"
+#include "openvino/op/paged_qsa_indexer.hpp"
#include "openvino/op/paged_selective_ssm.hpp"
+#include "openvino/op/paged_sparse_attention.hpp"
#include "openvino/op/prelu.hpp"
#include "openvino/op/prior_box.hpp"
#include "openvino/op/prior_box_clustered.hpp"
@@ -62,6 +64,7 @@
#include "openvino/op/selective_ssm.hpp"
#include "openvino/op/shape_of.hpp"
#include "openvino/op/shuffle_channels.hpp"
+#include "openvino/op/sparse_attention.hpp"
#include "openvino/op/squeeze.hpp"
#include "openvino/op/subtract.hpp"
#include "openvino/op/unsqueeze.hpp"
@@ -114,6 +117,8 @@
# include "transformations/snippets/common/op/store_convert.hpp"
#endif
#if defined(OPENVINO_ARCH_X86_64)
+# include "transformations/cpu_opset/common/op/qsa_indexer.hpp"
+# include "transformations/cpu_opset/common/op/sparse_attention_with_kv_cache.hpp"
# include "transformations/cpu_opset/x64/op/interaction.hpp"
# include "transformations/cpu_opset/x64/op/llm_mlp.hpp"
# include "transformations/cpu_opset/x64/op/qkv_proj.hpp"
@@ -217,17 +222,21 @@ OPENVINO_CREATE_EXTENSIONS(std::vector<ov::Extension::Ptr>({
std::make_shared<ov::OpExtension<ov::op::internal::SelectiveSSM>>(),
std::make_shared<ov::OpExtension<ov::op::internal::PagedSelectiveSSM>>(),
std::make_shared<ov::OpExtension<ov::op::internal::PagedCausalConv1D>>(),
+ std::make_shared<ov::OpExtension<ov::op::internal::PagedQSAIndexer>>(),
+ std::make_shared<ov::OpExtension<ov::op::internal::PagedSparseAttention>>(),
// clang-format off
OP_EXTENSION_X64(std::make_shared<ov::OpExtension<ov::intel_cpu::InteractionNode>>())
OP_EXTENSION_X64(std::make_shared<ov::OpExtension<ov::intel_cpu::LLMMLPNode>>())
OP_EXTENSION_X64(std::make_shared<ov::OpExtension<ov::intel_cpu::QKVProjectionNode>>())
OP_EXTENSION_X64(std::make_shared<ov::OpExtension<ov::intel_cpu::ScaledDotProductAttentionWithKVCache>>())
+ OP_EXTENSION_X64(std::make_shared<ov::OpExtension<ov::intel_cpu::SparseAttentionWithKVCache>>())
OP_EXTENSION_X64(std::make_shared<ov::OpExtension<ov::intel_cpu::LoadConvertSaturation>>())
OP_EXTENSION_X64(std::make_shared<ov::OpExtension<ov::intel_cpu::LoadConvertTruncation>>())
OP_EXTENSION_X64(std::make_shared<ov::OpExtension<ov::intel_cpu::StoreConvertSaturation>>())
OP_EXTENSION_X64(std::make_shared<ov::OpExtension<ov::intel_cpu::StoreConvertTruncation>>())
OP_EXTENSION_X64(std::make_shared<ov::OpExtension<ov::intel_cpu::BrgemmCPU>>())
OP_EXTENSION_X64(std::make_shared<ov::OpExtension<ov::intel_cpu::BrgemmCopyB>>())
+ OP_EXTENSION_X64(std::make_shared<ov::OpExtension<ov::intel_cpu::QSAIndexerNode>>())
OP_EXTENSION_ARM64(std::make_shared<ov::OpExtension<ov::intel_cpu::LoadConvertSaturation>>())
OP_EXTENSION_ARM64(std::make_shared<ov::OpExtension<ov::intel_cpu::LoadConvertTruncation>>())
OP_EXTENSION_ARM64(std::make_shared<ov::OpExtension<ov::intel_cpu::StoreConvertSaturation>>())
@@ -295,6 +304,7 @@ OPENVINO_CREATE_EXTENSIONS(std::vector<ov::Extension::Ptr>({
std::make_shared<TypeRelaxedExtension<ov::op::v5::NonMaxSuppression>>(),
std::make_shared<TypeRelaxedExtension<ov::op::v8::PriorBox>>(),
std::make_shared<TypeRelaxedExtension<ov::op::v9::NonMaxSuppression>>(),
+ std::make_shared<TypeRelaxedExtension<ov::op::v17::SparseAttention>>(),
std::make_shared<ov::OpExtension<ov::snippets::op::Brgemm>>(),
std::make_shared<ov::OpExtension<ov::snippets::op::BroadcastLoad>>(),
std::make_shared<ov::OpExtension<ov::snippets::op::BroadcastMove>>(),
diff --git a/src/plugins/intel_cpu/src/graph.cpp b/src/plugins/intel_cpu/src/graph.cpp
index c3a27483f3d..01a6087df74 100644
--- a/src/plugins/intel_cpu/src/graph.cpp
+++ b/src/plugins/intel_cpu/src/graph.cpp
@@ -2159,6 +2159,20 @@ void Graph::EnforceInferencePrecision() const {
if (node->getType() == Type::PagedAttention && any_of(inPort, 3U, 4U)) {
return true;
}
+ // The caches of SparsePA are written directly. The op needs the scale in the query type, but a constant
+ // input is never converted: enforce it explicitly.
+ if (node->getType() == Type::SparsePA) {
+ if (any_of(inPort, 3U, 4U)) {
+ return true;
+ }
+ if (inPort == 11U) {
+ return false;
+ }
+ }
+ // PagedQSAIndexer writes its caches directly and the op needs one element type on all float inputs.
+ if (node->getType() == Type::PagedQSAIndexer) {
+ return true;
+ }
// kv cache of PaKVReorder should be written directly
if (node->getType() == Type::PaKVReorder && any_of(inPort, 0U, 1U)) {
return true;
diff --git a/src/plugins/intel_cpu/src/graph_optimizer.cpp b/src/plugins/intel_cpu/src/graph_optimizer.cpp
index cc48904d34b..af14de6a1c4 100644
--- a/src/plugins/intel_cpu/src/graph_optimizer.cpp
+++ b/src/plugins/intel_cpu/src/graph_optimizer.cpp
@@ -50,6 +50,7 @@
#include "nodes/reshape.h"
#include "nodes/rnn.h"
#include "nodes/scaled_attn.h"
+#include "nodes/sparse_sdpa.h"
#include "nodes/transpose.h"
#include "onednn/iml_type_mapper.h"
#include "openvino/core/except.hpp"
@@ -233,6 +234,10 @@ void GraphOptimizer::ApplyCommonGraphOptimizations(Graph& graph) {
MatchSdpaKvCache(graph);
graph.RemoveDroppedNodes();
+ OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "MatchSparseSdpaKvCache");
+ MatchSparseSdpaKvCache(graph);
+ graph.RemoveDroppedNodes();
+
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "DropRedundantMemoryOutput");
DropRedundantMemoryOutput(graph);
graph.RemoveDroppedNodes();
@@ -3285,6 +3290,139 @@ void GraphOptimizer::MatchSdpaKvCache(Graph& graph) {
}
}
+// The counterpart of MatchSdpaKvCache for SparseSDPA (SparseAttentionWithKVCache): replaces the MemoryInput /
+// MemoryOutput pairs of its key/value states with MemoryInputSparseSDPA / MemoryOutputStub, so the node owns the
+// KV cache. It is a separate function on purpose: it never touches the ScaledDotProductAttention flow.
+void GraphOptimizer::MatchSparseSdpaKvCache(Graph& graph) {
+ const auto& graphNodes = graph.GetNodes();
+
+ auto isSuitableMemInput = [](const NodePtr& node) -> bool {
+ if (Type::MemoryInput != node->getType()) {
+ return false;
+ }
+ NodePtr childSparse = nullptr;
+ auto&& childEdges = node->getChildEdgesAtPort(0);
+ for (auto&& item : childEdges) {
+ auto childNode = item->getChild();
+ if (none_of(childNode->getType(), Type::SparseSDPA, Type::ShapeOf)) {
+ return false;
+ }
+
+ if (Type::SparseSDPA == childNode->getType()) {
+ auto sparse = std::dynamic_pointer_cast<node::SparseSDPA>(childNode);
+ if (!sparse || !sparse->isStateful()) {
+ return false;
+ }
+ if (childSparse && childSparse != childNode) {
+ // only one child SparseSDPA supported
+ return false;
+ }
+ childSparse = childNode;
+ }
+ }
+ if (!childSparse) {
+ return false;
+ }
+
+ CPU_GRAPH_OPTIMIZER_SCOPE(MatchSparseSdpaKvCache_isSuitableMemInput);
+
+ auto memInputNode = std::dynamic_pointer_cast<node::MemoryInputBase>(node);
+ OPENVINO_ASSERT(memInputNode, "MemoryInput node ", node->getName(), " has unexpected dynamic type");
+ auto& memOutputNode = memInputNode->getOutputNode();
+ auto memOutputParent = memOutputNode.getParentEdgeAt(0)->getParent();
+ return memOutputParent == childSparse;
+ };
+
+ for (size_t i = 0; i < graphNodes.size(); i++) {
+ auto node = graphNodes[i];
+ if (!isSuitableMemInput(node)) {
+ continue;
+ }
+
+ CPU_GRAPH_OPTIMIZER_SCOPE(MatchSparseSdpaKvCache_Node);
+
+ // Node is already modified
+ if (std::dynamic_pointer_cast<node::MemoryInputSparseSDPA>(node)) {
+ continue;
+ }
+
+ auto memInputNode = std::dynamic_pointer_cast<node::MemoryInputBase>(node);
+ OPENVINO_ASSERT(memInputNode, "MemoryInput node ", node->getName(), " has unexpected dynamic type");
+
+ std::optional<std::vector<Shape>> inputShapes;
+ std::optional<std::vector<ov::element::Type>> inputPrcs;
+ if (!node->getParentEdges().empty()) {
+ inputShapes = std::optional<std::vector<Shape>>(std::vector<Shape>{});
+ inputPrcs = std::optional<std::vector<ov::element::Type>>(std::vector<ov::element::Type>{});
+
+ auto& input_shape_vec = *inputShapes;
+ auto& input_prc_vec = *inputPrcs;
+
+ for (size_t j = 0; j < node->getParentEdges().size(); j++) {
+ input_shape_vec.push_back(node->getInputShapeAtPort(j));
+ input_prc_vec.push_back(node->getOriginalInputPrecisionAtPort(j));
+ }
+ }
+
+ // search for SparseSDPA
+ std::shared_ptr<node::SparseSDPA> sparse;
+ for (auto&& edge : node->getChildEdgesAtPort(0)) {
+ auto child = edge->getChild();
+ if (Type::SparseSDPA == child->getType()) {
+ sparse = std::dynamic_pointer_cast<node::SparseSDPA>(child);
+ if (sparse) {
+ break;
+ }
+ OPENVINO_THROW("Couldn't cast node", child->getName(), " to SparseSDPA type");
+ }
+ }
+
+ // capture reference to the original mem output before graph transformations
+ auto& memOutput = memInputNode->getOutputNode();
+
+ auto memInputSparse = std::make_shared<MemoryInputSparseSDPA>(memInputNode->getId(),
+ memInputNode->getName(),
+ memInputNode->getTypeStr(),
+ memInputNode->getOutputShapeAtPort(0),
+ memInputNode->getOriginalOutputPrecisionAtPort(0),
+ graph.getGraphContext(),
+ inputShapes,
+ inputPrcs,
+ sparse);
+
+ if (!memInputNode->getParentEdges().empty()) {
+ auto parentEdge = memInputNode->getParentEdgeAt(0);
+ auto parent = parentEdge->getParent();
+ const auto inputNum = parentEdge->getInputNum();
+ graph.RemoveEdge(parentEdge);
+ graph.CreateEdge(parent, memInputSparse, inputNum, 0);
+ }
+
+ for (auto&& edge : memInputNode->getChildEdgesAtPort(0)) {
+ auto child = edge->getChild();
+ const auto outputNum = edge->getOutputNum();
+ graph.RemoveEdge(edge);
+ graph.CreateEdge(memInputSparse, child, 0, outputNum);
+ }
+
+ // create a stub memory output
+ auto memOutputStub = std::make_shared<MemoryOutputStub>(memOutput.getId(),
+ memOutput.getName(),
+ memOutput.getTypeStr(),
+ memOutput.getInputShapeAtPort(0),
+ memOutput.getOriginalInputPrecisionAtPort(0),
+ graph.getGraphContext());
+
+ auto memOutputEdge = memOutput.getParentEdgeAt(0);
+ const auto inputNum = memOutputEdge->getInputNum();
+ graph.RemoveEdge(memOutputEdge);
+ graph.CreateEdge(sparse, memOutputStub, inputNum, 0);
+
+ graph.AddNode(memInputSparse);
+ graph.AddNode(memOutputStub);
+ }
+}
+
void GraphOptimizer::DropRedundantMemoryOutput(Graph& graph) {
// When we have a MemoryInput->MemoryOutput pair, that means that the state is immediately populated with the init
// subgraph values when the init subgraph exists. In all the other cases the state is simply a read only object.
diff --git a/src/plugins/intel_cpu/src/graph_optimizer.h b/src/plugins/intel_cpu/src/graph_optimizer.h
index 456578cb50d..32e6c8ab4c6 100644
--- a/src/plugins/intel_cpu/src/graph_optimizer.h
+++ b/src/plugins/intel_cpu/src/graph_optimizer.h
@@ -54,6 +54,7 @@ private:
static void RemoveMemoryInputConvert(Graph& graph);
static void RemoveConvertMemoryOutput(Graph& graph);
static void MatchSdpaKvCache(Graph& graph);
+ static void MatchSparseSdpaKvCache(Graph& graph);
static void DropRedundantMemoryOutput(Graph& graph);
static bool canBeInplaced(const NodePtr& parentNode, const NodePtr& childNode);
diff --git a/src/plugins/intel_cpu/src/memory_state.cpp b/src/plugins/intel_cpu/src/memory_state.cpp
index 62d1e7a4194..04d34a6bc76 100644
--- a/src/plugins/intel_cpu/src/memory_state.cpp
+++ b/src/plugins/intel_cpu/src/memory_state.cpp
@@ -16,6 +16,7 @@
#include <vector>
#include "cpu_memory.h"
+#include "cpu_parallel.hpp"
#include "cpu_tensor.h"
#include "cpu_types.h"
#include "dnnl_extension_utils.h"
@@ -25,9 +26,11 @@
#include "memory_desc/cpu_memory_desc_utils.h"
#include "nodes/kernels/scaled_attn/attn_quant.hpp"
#include "nodes/kernels/scaled_attn/cache_spec.hpp"
+#include "nodes/kernels/sparse_attn/sparse_sdpa_kernel.hpp"
#include "openvino/core/except.hpp"
#include "openvino/core/parallel.hpp"
#include "openvino/core/type/element_type.hpp"
+#include "openvino/runtime/intel_cpu/properties.hpp"
#include "openvino/runtime/internal_properties.hpp"
#include "openvino/runtime/itensor.hpp"
#include "openvino/runtime/so_ptr.hpp"
@@ -443,4 +446,105 @@ MemoryPtr VariableStateKVcache::hidden_state_mem() const {
void VariableStateKVcache::assign_hidden_state(const MemoryPtr& mem) {
m_hidden_state = mem;
}
+
+namespace {
+bool is_quantized_bhls(const ov::Extensions::Cpu::CacheSpec& spec) {
+ return spec.precision == ov::element::u8 || spec.precision == ov::element::u4;
+}
+} // namespace
+
+ov::SoPtr<ov::ITensor> VariableStateKVcacheBHLS::get_state() const {
+ auto mem = internal_state_mem();
+ if (!mem || is_reset_state()) {
+ auto new_desc = to_static(get_external_desc());
+ auto external_mem = std::make_shared<Memory>(get_engine(), new_desc);
+ return std::make_shared<Tensor>(external_mem);
+ }
+
+ auto&& dims = mem->getStaticDims();
+ OPENVINO_ASSERT(dims.size() == 4, "BHLS KV cache state is expected to be 4D");
+ auto actual_external_desc = get_external_desc()->cloneWithNewDims(dims);
+ auto external_mem = std::make_shared<Memory>(get_engine(), actual_external_desc);
+
+ PlainTensor src;
+ PlainTensor dst;
+ src.reset(mem);
+ dst.reset(external_mem);
+ const auto B = src.size(0);
+ const auto H = src.size(1);
+ const auto L = src.size(2);
+ const auto S = src.size(3);
+ // rows along L are contiguous in both the cache (capacity strides) and the dense external tensor
+ OPENVINO_ASSERT(all_of(1U, src.stride(3), dst.stride(3)) && dst.stride(2) == S);
+ if (is_quantized_bhls(get_spec())) {
+ // dequantize into f32 rows and convert them to the external precision
+ auto& scale_zp = const_cast<VariableStateKVcacheBHLS*>(this)->get_scale_zp();
+ const ov::Extensions::Cpu::SparseKVQuant quant{get_spec().precision,
+ get_spec().group_size,
+ get_spec().by_channel,
+ &scale_zp};
+ parallel_for2d(B, H, [&](size_t b, size_t h) {
+ std::vector<float> rows(L * S);
+ ov::Extensions::Cpu::XARCH::sparse_kv_dequantize_rows(src, quant, b, h, L, S, rows.data());
+ cpu_convert(rows.data(), dst.ptr_v(b, h, 0), ov::element::f32, dst.m_dt, L * S);
+ });
+ return std::make_shared<Tensor>(external_mem);
+ }
+ OPENVINO_ASSERT(src.stride(2) == S);
+ parallel_for2d(B, H, [&](size_t b, size_t h) {
+ cpu_convert(src.ptr_v(b, h, 0), dst.ptr_v(b, h, 0), src.m_dt, dst.m_dt, L * S);
+ });
+ return std::make_shared<Tensor>(external_mem);
+}
+
+void VariableStateKVcacheBHLS::set_state_impl(const ov::SoPtr<ov::ITensor>& state) {
+ m_state = state; // simply to extend the lifetime
+ auto state_desc = MemoryDescUtils::generateCpuBlockedMemoryDesc(m_state);
+
+ auto dense_internal_desc = internal_desc()->cloneWithNewDims(state_desc->getShape().getStaticDims());
+ auto internal_mem = std::make_shared<Memory>(get_engine(), dense_internal_desc);
+ Memory external_mem(get_engine(), state_desc, m_state->data());
+ if (is_quantized_bhls(get_spec())) {
+ static const auto cpu_parallel = std::make_shared<CpuParallel>(ov::intel_cpu::TbbPartitioner::STATIC);
+ auto&& dims = state_desc->getShape().getStaticDims();
+ OPENVINO_ASSERT(dims.size() == 4, "BHLS KV cache state is expected to be 4D");
+ PlainTensor external;
+ PlainTensor internal;
+ external.resize(dims, state_desc->getPrecision().size(), state_desc->getPrecision(), m_state->data());
+ internal.reset(internal_mem);
+ PlainTensor scale_zp;
+ const auto group_size = get_spec().group_size;
+ if (get_spec().by_channel) {
+ // [2 * groups of tokens, B, H, S]
+ scale_zp.resize<float>({2 * ((dims[2] + group_size - 1) / group_size), dims[0], dims[1], dims[3]});
+ if (dims[2] > 0) {
+ ov::Extensions::Cpu::XARCH::attn_quant_by_channel(external,
+ internal,
+ scale_zp,
+ 0,
+ group_size,
+ cpu_parallel);
+ }
+ } else {
+ // [L, B, H, 2 * groups of the row]
+ scale_zp.resize<float>({dims[2], dims[0], dims[1], 2 * dims[3] / group_size});
+ if (dims[2] > 0) {
+ ov::Extensions::Cpu::XARCH::attn_quant_by_token(external,
+ internal,
+ scale_zp,
+ 0,
+ group_size,
+ cpu_parallel);
+ }
+ }
+ set_scale_zp(scale_zp);
+ } else {
+ internal_mem->load(external_mem, true, false);
+ }
+
+ assign_internal_state(internal_mem);
+ assign_internal_state_max_size(dense_internal_desc->getCurrentMemSize() /
+ dense_internal_desc->getPrecision().size());
+}
+
} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/memory_state.h b/src/plugins/intel_cpu/src/memory_state.h
index d213196c4d3..2dd453c152a 100644
--- a/src/plugins/intel_cpu/src/memory_state.h
+++ b/src/plugins/intel_cpu/src/memory_state.h
@@ -185,6 +185,24 @@ private:
ov::Extensions::Cpu::CacheSpec m_spec;
};
+// KV cache state whose internal buffer is kept in the plain BHLS order (B, H, L, S), float precision only.
+// It is used by the sparse attention node, whose kernels require contiguous rows along L. The base class
+// get_state() / set_state_impl() assume the LBHS order and the beam table, so they are overridden here
+// instead of being generalized: VariableStateKVcache stays untouched.
+// The internal buffer may have a capacity larger than the logical length along L; the capacity is
+// carried by the strides of the internal memory descriptor.
+class VariableStateKVcacheBHLS : public VariableStateKVcache {
+public:
+ using VariableStateKVcache::VariableStateKVcache;
+
+ // ov::IVariableState
+ ov::SoPtr<ov::ITensor> get_state() const override;
+
+private:
+ // ov::intel_cpu::VariableStateBase
+ void set_state_impl(const ov::SoPtr<ov::ITensor>& state) override;
+};
+
using MemStatePtr = std::shared_ptr<IVariableState>;
using MemStateCPtr = std::shared_ptr<const IVariableState>;
} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/paged_qsa_indexer_kernel.cpp b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/paged_qsa_indexer_kernel.cpp
new file mode 100644
index 00000000000..2524b89c39a
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/paged_qsa_indexer_kernel.cpp
@@ -0,0 +1,425 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "paged_qsa_indexer_kernel.hpp"
+
+#include <algorithm>
+#include <cstddef>
+#include <cstdint>
+#include <utility>
+
+#include "cpu_parallel.hpp"
+#include "nodes/kernels/sparse_attn/qsa_kernel_utils.hpp"
+#include "openvino/core/except.hpp"
+#include "openvino/core/parallel.hpp"
+#include "openvino/core/type/bfloat16.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "openvino/core/type/float16.hpp"
+#include "openvino/op/paged_qsa_indexer.hpp"
+#include "utils/general_utils.h"
+#include "utils/plain_tensor.hpp"
+
+#ifdef OPENVINO_ARCH_X86_64
+# include "nodes/kernels/sparse_attn/qsa_brgemm.hpp"
+# include "nodes/kernels/sparse_attn/qsa_indexer_brgemm_kernel.hpp"
+#endif
+
+namespace ov::Extensions::Cpu::XARCH {
+
+namespace {
+
+using ov::intel_cpu::div_up;
+#ifdef OPENVINO_ARCH_X86_64
+using ov::intel_cpu::node::qsa::kScoreBlockRows;
+#endif
+using ov::intel_cpu::PlainTensor;
+using ov::intel_cpu::node::qsa::QsaBrgemm;
+using ov::intel_cpu::node::qsa::paged::block_address;
+using ov::intel_cpu::node::qsa::paged::Config;
+using ov::intel_cpu::node::qsa::paged::index_key_heads;
+using ov::intel_cpu::node::qsa::paged::index_query_heads;
+using ov::intel_cpu::node::qsa::paged::num_sequences;
+using ov::intel_cpu::node::qsa::paged::num_tokens;
+using ov::intel_cpu::node::qsa::paged::PagedPorts;
+using ov::intel_cpu::node::qsa::paged::PagedScratchLayout;
+using ov::intel_cpu::node::qsa::paged::seq_plan;
+using ov::intel_cpu::node::qsa::paged::SeqPlan;
+using ov::intel_cpu::node::qsa::paged::SeqStats;
+using ov::intel_cpu::node::qsa::paged::ThreadLayout;
+using ov::intel_cpu::node::qsa::paged::token_address;
+
+static_assert(ThreadLayout::kStageRows == qsa::kScoreRows);
+
+// A row of a port as f32: the row itself when the data is f32 (no copy), otherwise converted into `scratch`. All the
+// floating-point ports have the precision T (the op validates it), so no port needs a run-time lookup of its own.
+template <typename T, typename... Idx>
+const float* row_view(const PlainTensor& t, size_t len, float* scratch, Idx... idx) {
+ if constexpr (std::is_same_v<T, float>) {
+ return t.ptr<float>(idx...);
+ } else {
+ cvt_copy(scratch, t.ptr<T>(idx...), 1, len, 0, 0);
+ return scratch;
+ }
+}
+
+// The buffers of one worker thread's slice of the scratch; the phases run one after the other, so they share them.
+struct ThreadBuffers {
+ float* q_normed; // [H_iq, D_idx] normalized + rotated index queries
+ float* row_buf; // [D_idx] a converted row
+ float* summary_buf; // [D_idx] a pooled summary row
+ float* pooled; // [D_idx] the mean of the raw keys of a block
+ float* cos_sin; // [2 * rotary_dim] the interleaved cos / sin row of a block
+ float* cos_tmp; // [rotary_dim] a cos row
+ float* sin_tmp; // [rotary_dim] a sin row
+ float* stage; // [4, D_idx] summary rows converted to f32 (the scoring)
+ float* score_f32; // [blocks] the scores of the blocks of a token and selection head
+ qsa::BlockScore* scores; // [blocks] (score * scale, block), what the top-k selects from
+ int32_t* chosen; // [block_topk]
+};
+
+// The scratch of a call, bound to its memory.
+struct Scratch {
+ template <typename T>
+ Scratch(std::in_place_type_t<T>,
+ const PagedPorts& p,
+ const Config& c,
+ const PagedScratchLayout& layout,
+ uint8_t* memory)
+ : token_seq(reinterpret_cast<int32_t*>(memory)),
+ shared(memory + layout.scorer_shared_offset),
+ threads(memory + layout.threads_offset),
+ m_layout(layout) {
+ const size_t D_idx = c.indexer_head_dim;
+ auto* const q_norm = reinterpret_cast<float*>(memory + layout.norm_weights_offset);
+ auto* const k_norm = q_norm + D_idx;
+ // f32 weights are used in place; 16-bit ones are converted once per call into the scratch
+ q_norm_w = qsa::row_as_f32(p.q_norm_weight.ptr<T>(), D_idx, q_norm);
+ k_norm_w = qsa::row_as_f32(p.k_norm_weight.ptr<T>(), D_idx, k_norm);
+ const size_t tokens = num_tokens(p);
+ std::fill_n(token_seq, tokens, static_cast<int32_t>(-1));
+ for (size_t seq = 0; seq < num_sequences(p); seq++) {
+ const auto plan = seq_plan(p, c, seq);
+ for (int64_t t = plan.token_begin; t < plan.token_begin + plan.q_len; t++) {
+ if (static_cast<size_t>(t) < tokens) {
+ token_seq[t] = static_cast<int32_t>(seq);
+ }
+ }
+ }
+ }
+
+ // This worker thread's slice of the scratch.
+ [[nodiscard]] ThreadBuffers thread() const {
+ const auto& t = m_layout.thread;
+ auto* const slice = threads + static_cast<size_t>(parallel_get_thread_num()) * m_layout.thread_bytes;
+ auto* const floats = reinterpret_cast<float*>(slice);
+ return {floats + t.q_normed_off,
+ floats + t.row_buf_off,
+ floats + t.summary_buf_off,
+ floats + t.pooled_off,
+ floats + t.cos_sin_off,
+ floats + t.cos_tmp_off,
+ floats + t.sin_tmp_off,
+ floats + t.stage_off,
+ floats + t.score_f32_off,
+ reinterpret_cast<qsa::BlockScore*>(slice + t.scores_off),
+ reinterpret_cast<int32_t*>(slice + t.chosen_off)};
+ }
+
+ int32_t* token_seq; // per token: its sequence, -1 for a token that belongs to none
+ const float* q_norm_w = nullptr;
+ const float* k_norm_w = nullptr;
+ uint8_t* shared; // the brgemm scorer's scratch shared by the threads
+ uint8_t* threads; // the slices of the worker threads
+
+private:
+ const PagedScratchLayout& m_layout;
+};
+
+#ifdef OPENVINO_ARCH_X86_64
+// The paged layout of a call as the brgemm scoring sees it (see BrgemmRunner): rows are sequences, token v of a
+// sequence is flat token plan.token_begin + v, and summary blocks are addressed through the page table. `T` is the
+// summary cache precision.
+template <typename T>
+class PagedSource {
+public:
+ using Element = T;
+
+ PagedSource(const PagedPorts& ports, const Config& config, const float* q_norm_weight)
+ : m_p(ports),
+ m_c(config),
+ m_q_norm_w(q_norm_weight) {}
+
+ [[nodiscard]] int64_t tokens(size_t seq) const {
+ return plan(seq).q_len;
+ }
+ // the complete blocks up to the one the token completes
+ [[nodiscard]] int64_t blocks_visible(size_t seq, int64_t v) const {
+ return plan(seq).blocks_visible(v);
+ }
+ [[nodiscard]] int64_t blocks(size_t seq) const {
+ return plan(seq).total_blocks();
+ }
+ [[nodiscard]] const float* query_row(size_t seq, int64_t v, size_t h, float* buf) const {
+ return row_view<T>(m_p.q_idx, m_c.indexer_head_dim, buf, token(seq, v), h * m_c.indexer_head_dim);
+ }
+ [[nodiscard]] const float* rope_cos(size_t seq, int64_t v, float* buf) const {
+ return row_view<T>(m_p.rope_cos, m_c.indexer_rotary_dim, buf, token(seq, v));
+ }
+ [[nodiscard]] const float* rope_sin(size_t seq, int64_t v, float* buf) const {
+ return row_view<T>(m_p.rope_sin, m_c.indexer_rotary_dim, buf, token(seq, v));
+ }
+ [[nodiscard]] const float* q_norm_weight() const {
+ return m_q_norm_w;
+ }
+ // 32 blocks that lie in one page are used in place; blocks of several pages (a small page, or the end of the
+ // sequence) are gathered, run by run, into the zero-padded stage.
+ [[nodiscard]] const T* block_rows(size_t seq, size_t key_head, size_t first, size_t count, T* stage) const {
+ const auto seq_plan = plan(seq);
+ const auto slots = static_cast<size_t>(seq_plan.slots_per_page);
+ const auto [first_page, first_slot] = block_address(m_p, seq_plan, static_cast<int64_t>(first));
+ if (count == kScoreBlockRows && first_slot + count <= slots) {
+ return m_p.summary_cache.ptr<T>(first_page, key_head, first_slot);
+ }
+ const size_t dim = m_c.indexer_head_dim;
+ size_t done = 0;
+ while (done < count) {
+ const auto [page, slot] = block_address(m_p, seq_plan, static_cast<int64_t>(first + done));
+ const size_t run = std::min(count - done, slots - slot);
+ std::copy_n(m_p.summary_cache.ptr<T>(page, key_head, slot), run * dim, stage + done * dim);
+ done += run;
+ }
+ std::fill_n(stage + count * dim, (kScoreBlockRows - count) * dim, T{});
+ return stage;
+ }
+ [[nodiscard]] int32_t* selection_indices(size_t seq, int64_t v, size_t sel_head) const {
+ return m_p.sel_indices.ptr<int32_t>(token(seq, v), sel_head, 0);
+ }
+ [[nodiscard]] int32_t* selection_count(size_t seq, int64_t v, size_t sel_head) const {
+ return m_p.sel_count.ptr<int32_t>(token(seq, v), sel_head);
+ }
+
+private:
+ [[nodiscard]] SeqPlan plan(size_t seq) const {
+ return seq_plan(m_p, m_c, seq);
+ }
+ [[nodiscard]] size_t token(size_t seq, int64_t v) const {
+ return static_cast<size_t>(plan(seq).token_begin + v);
+ }
+
+ const PagedPorts& m_p;
+ const Config& m_c;
+ const float* m_q_norm_w;
+};
+
+// ---- Phase 3 on brgemm (the steps are described in qsa_indexer_brgemm_kernel.hpp) ----
+template <typename T>
+void run_brgemm_scorer(const QsaBrgemm& brgemm,
+ const PagedPorts& p,
+ const Config& c,
+ const SeqStats& stats,
+ const Scratch& scratch,
+ const ov::intel_cpu::CpuParallel& parallel) {
+ const auto plan = brgemm.plan(num_sequences(p), stats.max_q_len, stats.max_blocks);
+ const PagedSource<T> source(p, c, scratch.q_norm_w);
+ qsa::BrgemmRunner(brgemm).run(plan, source, scratch.shared, scratch.threads, parallel);
+}
+#endif
+
+// ---- Phase 1, per token: append the raw index keys to the paged cache. A token that starts a block also stores its
+// interleaved cos/sin row, for the block's summary to use once the block completes. A block that can never complete
+// is skipped. ----
+template <typename T>
+void store_token_rows(const PagedPorts& p, const Config& c, const Scratch& scratch, size_t token) {
+ const auto plan = seq_plan(p, c, static_cast<size_t>(scratch.token_seq[token]));
+ const int64_t logical_pos = plan.past_len + (static_cast<int64_t>(token) - plan.token_begin);
+ const auto buf = scratch.thread();
+ const size_t D_idx = c.indexer_head_dim;
+ const size_t rotary_dim = c.indexer_rotary_dim;
+
+ if (logical_pos % plan.key_block_size == 0) {
+ const int64_t block_idx = logical_pos / plan.key_block_size;
+ if (block_idx < plan.block_capacity) {
+ float* const cos_sin = buf.cos_sin;
+ const float* const cos_row = row_view<T>(p.rope_cos, rotary_dim, buf.cos_tmp, token);
+ const float* const sin_row = row_view<T>(p.rope_sin, rotary_dim, buf.sin_tmp, token);
+ for (size_t j = 0; j < rotary_dim; j++) {
+ cos_sin[2 * j] = cos_row[j];
+ cos_sin[2 * j + 1] = sin_row[j];
+ }
+ const auto [page, slot] = block_address(p, plan, block_idx);
+ cvt_copy(p.indexer_rope_cache.ptr<T>(page, slot), cos_sin, 1, 2 * rotary_dim, 0, 0);
+ }
+ }
+ const auto [cur_page, cur_slot] = token_address(p, plan, logical_pos);
+ for (size_t key_head = 0; key_head < index_key_heads(p, c); key_head++) {
+ const float* const row = row_view<T>(p.k_idx, D_idx, buf.row_buf, token, key_head * D_idx);
+ cvt_copy(p.raw_k_cache.ptr<T>(cur_page, key_head, cur_slot), row, 1, D_idx, 0, 0);
+ }
+}
+
+// ---- Phase 2, per (sequence, index-key head, block completed by the call): the summary of the block is the mean of
+// its raw keys, RMSNorm'ed and RoPE'd with the coefficients of its first token. The blocks are independent of each
+// other. ----
+template <typename T>
+void pool_block(const PagedPorts& p, const Config& c, const Scratch& scratch, size_t seq, size_t key_head, size_t j) {
+ const auto plan = seq_plan(p, c, seq);
+ const auto buf = scratch.thread();
+ float* const pooled = buf.pooled;
+ const size_t D_idx = c.indexer_head_dim;
+ const size_t rotary_dim = c.indexer_rotary_dim;
+
+ const int64_t block_idx = plan.past_blocks + static_cast<int64_t>(j);
+ const int64_t block_start = block_idx * plan.key_block_size;
+ const auto [block_page, block_slot] = block_address(p, plan, block_idx);
+ std::fill_n(pooled, D_idx, 0.0F);
+ for (int64_t pos = block_start; pos < block_start + plan.key_block_size; pos++) {
+ const auto [p_page, p_slot] = token_address(p, plan, pos);
+ qsa::add_inplace(pooled, row_view<T>(p.raw_k_cache, D_idx, buf.row_buf, p_page, key_head, p_slot), D_idx);
+ }
+ qsa::scale_inplace(pooled, 1.0F / static_cast<float>(plan.key_block_size), D_idx);
+ // the cos / sin of the first token of the block were stored interleaved; the RoPE takes them apart
+ const float* const cos_sin = row_view<T>(p.indexer_rope_cache, 2 * rotary_dim, buf.cos_sin, block_page, block_slot);
+ for (size_t k = 0; k < rotary_dim; k++) {
+ buf.cos_tmp[k] = cos_sin[2 * k];
+ buf.sin_tmp[k] = cos_sin[2 * k + 1];
+ }
+ qsa::rms_rope(pooled, buf.summary_buf, scratch.k_norm_w, D_idx, rotary_dim, c.epsilon, buf.cos_tmp, buf.sin_tmp);
+ cvt_copy(p.summary_cache.ptr<T>(block_page, key_head, block_slot), buf.summary_buf, 1, D_idx, 0, 0);
+}
+
+// ---- Phase 3, per token: RMSNorm + partial RoPE of every index-query head, then per selection head the score of
+// each complete block (sum over its heads of max(0, q . summary)) and the top-k blocks in ascending order. ----
+template <typename T>
+void select_blocks(const PagedPorts& p, const Config& c, const Scratch& scratch, size_t token) {
+ const auto plan = seq_plan(p, c, static_cast<size_t>(scratch.token_seq[token]));
+ const auto buf = scratch.thread();
+ const size_t D_idx = c.indexer_head_dim;
+ const size_t rotary_dim = c.indexer_rotary_dim;
+ const size_t index_keys = index_key_heads(p, c);
+ const size_t index_queries = index_query_heads(p, c);
+ const size_t heads_per_key = index_queries / index_keys;
+ const size_t selection_heads = c.num_selection_heads;
+ const float scale = ov::op::internal::PagedQSAIndexer::effective_scale(c);
+
+ const float* const cos_row = row_view<T>(p.rope_cos, rotary_dim, buf.cos_tmp, token);
+ const float* const sin_row = row_view<T>(p.rope_sin, rotary_dim, buf.sin_tmp, token);
+ for (size_t h = 0; h < index_queries; h++) {
+ const float* const q_row = row_view<T>(p.q_idx, D_idx, buf.row_buf, token, h * D_idx);
+ qsa::rms_rope(q_row,
+ buf.q_normed + h * D_idx,
+ scratch.q_norm_w,
+ D_idx,
+ rotary_dim,
+ c.epsilon,
+ cos_row,
+ sin_row);
+ }
+
+ // The complete blocks visible to this token, including the one this token completes.
+ const int64_t n_complete = plan.blocks_visible(static_cast<int64_t>(token) - plan.token_begin);
+ const auto slots = static_cast<size_t>(plan.slots_per_page);
+ for (size_t sel_head = 0; sel_head < selection_heads; sel_head++) {
+ // The index key heads of the selection head, and so their query heads: contiguous ranges.
+ const size_t key_head_begin = div_up(sel_head * index_keys, selection_heads);
+ const size_t key_head_end = div_up((sel_head + 1) * index_keys, selection_heads);
+ size_t k = 0;
+ if (n_complete > 0) {
+ // the scores of the complete blocks, summed over the index key heads of the selection head: the blocks
+ // of a head lie in runs of consecutive rows, one per page
+ std::fill_n(buf.score_f32, static_cast<size_t>(n_complete), 0.0F);
+ for (size_t key_head = key_head_begin; key_head < key_head_end; key_head++) {
+ for (size_t blk = 0; blk < static_cast<size_t>(n_complete);) {
+ const auto [page, slot] = block_address(p, plan, static_cast<int64_t>(blk));
+ const size_t run = std::min(static_cast<size_t>(n_complete) - blk, slots - slot);
+ qsa::score_run<T>(buf.q_normed + key_head * heads_per_key * D_idx,
+ p.summary_cache.ptr<T>(page, key_head, slot),
+ run,
+ heads_per_key,
+ D_idx,
+ buf.score_f32 + blk,
+ buf.stage);
+ blk += run;
+ }
+ }
+ for (int64_t blk = 0; blk < n_complete; blk++) {
+ buf.scores[blk] = {buf.score_f32[blk] * scale, static_cast<int32_t>(blk)};
+ }
+ k = qsa::select_topk(buf.scores, buf.chosen, static_cast<size_t>(n_complete), c.block_topk, false);
+ }
+
+ std::copy_n(buf.chosen, k, p.sel_indices.ptr<int32_t>(token, sel_head, 0));
+ *p.sel_count.ptr<int32_t>(token, sel_head) = static_cast<int32_t>(k);
+ }
+}
+
+// The computation of the node, T is the precision of the summary blocks.
+template <typename T>
+void run_indexer(const PagedPorts& ports,
+ const Config& config,
+ const PagedScratchLayout& layout,
+ uint8_t* memory,
+ [[maybe_unused]] const QsaBrgemm* brgemm,
+ const ov::intel_cpu::CpuParallel& parallel) {
+ const size_t tokens = num_tokens(ports);
+ const auto stats = ov::intel_cpu::node::qsa::paged::seq_stats(ports, config);
+ const Scratch scratch(std::in_place_type<T>, ports, config, layout, memory);
+
+ std::fill_n(ports.sel_indices.ptr<int32_t>(), tokens * config.num_selection_heads * config.block_topk, -1);
+ std::fill_n(ports.sel_count.ptr<int32_t>(), tokens * config.num_selection_heads, 0);
+
+ // Phase 1: the raw keys of the tokens (and the rope rows of the blocks they start) go to the caches; disjoint
+ // slots.
+ parallel.parallel_for(tokens, [&](size_t token) {
+ if (scratch.token_seq[token] >= 0) {
+ store_token_rows<T>(ports, config, scratch, token);
+ }
+ });
+ // Phase 2: the blocks this call completes are independent of each other (they read the raw rows of this and of
+ // earlier calls, written by phase 1 or before).
+ if (stats.max_new_blocks > 0) {
+ parallel.parallel_for3d(num_sequences(ports),
+ index_key_heads(ports, config),
+ static_cast<size_t>(stats.max_new_blocks),
+ [&](size_t seq, size_t key_head, size_t j) {
+ if (static_cast<int64_t>(j) < seq_plan(ports, config, seq).new_blocks) {
+ pool_block<T>(ports, config, scratch, seq, key_head, j);
+ }
+ });
+ }
+ // Phase 3: a token scores the complete blocks up to the one it completes, all written by now.
+#ifdef OPENVINO_ARCH_X86_64
+ if (brgemm != nullptr) {
+ run_brgemm_scorer<T>(*brgemm, ports, config, stats, scratch, parallel);
+ return;
+ }
+#endif
+ parallel.parallel_for(tokens, [&](size_t token) {
+ if (scratch.token_seq[token] >= 0) {
+ select_blocks<T>(ports, config, scratch, token);
+ }
+ });
+}
+
+} // namespace
+
+void paged_qsa_indexer_compute(const ov::intel_cpu::node::qsa::paged::PagedPorts& ports,
+ const ov::op::internal::PagedQSAIndexer::Config& config,
+ const ov::intel_cpu::node::qsa::paged::PagedScratchLayout& layout,
+ uint8_t* scratch,
+ const ov::intel_cpu::node::qsa::QsaBrgemm* brgemm,
+ const ov::intel_cpu::CpuParallelPtr& cpu_parallel) {
+ // The precision of the summary blocks: the one the block scoring works in.
+ const auto precision = ports.summary_cache.get_precision();
+ if (precision == ov::element::f32) {
+ run_indexer<float>(ports, config, layout, scratch, brgemm, *cpu_parallel);
+ } else if (precision == ov::element::f16) {
+ run_indexer<ov::float16>(ports, config, layout, scratch, brgemm, *cpu_parallel);
+ } else if (precision == ov::element::bf16) {
+ run_indexer<ov::bfloat16>(ports, config, layout, scratch, brgemm, *cpu_parallel);
+ } else {
+ OPENVINO_THROW("PagedQSAIndexer: unsupported summary precision ", precision);
+ }
+}
+
+} // namespace ov::Extensions::Cpu::XARCH
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/paged_qsa_indexer_kernel.hpp b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/paged_qsa_indexer_kernel.hpp
new file mode 100644
index 00000000000..caa26ef50cc
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/paged_qsa_indexer_kernel.hpp
@@ -0,0 +1,256 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+// PagedQSAIndexer computation: the per-token math of the QSAIndexer (see qsa_indexer_kernel.hpp) over caches addressed
+// through the PagedAttention page table. A call appends the new raw keys, pools the blocks they complete, and keeps
+// each token's block_topk best blocks. This header holds what the node and the kernel share.
+
+#pragma once
+
+#include <algorithm>
+#include <cstddef>
+#include <cstdint>
+#include <utility>
+#include <vector>
+
+#include "cpu_memory.h"
+#include "cpu_parallel.hpp"
+#include "nodes/kernels/sparse_attn/qsa_indexer_common.hpp"
+#include "openvino/core/except.hpp"
+#include "openvino/op/paged_qsa_indexer.hpp"
+#include "utils/general_utils.h"
+#include "utils/plain_tensor.hpp"
+
+namespace ov::intel_cpu::node::qsa {
+
+class QsaBrgemm; // x64 only, see qsa_brgemm.hpp
+
+} // namespace ov::intel_cpu::node::qsa
+
+namespace ov::intel_cpu::node::qsa::paged {
+
+using Config = ov::op::internal::PagedQSAIndexer::Config;
+
+/// @brief Fixed output order of ov::op::internal::PagedQSAIndexer (not part of the op's public API).
+struct OutputIdx {
+ static constexpr size_t SEL_INDICES = 0; ///< [tokens, h_sel, block_topk]
+ static constexpr size_t SEL_COUNT = 1; ///< [tokens, h_sel]
+
+ static constexpr size_t COUNT = 2;
+};
+
+// The ports of the node, each taken by its own name.
+struct PagedPorts {
+ using In = ov::op::internal::PagedQSAIndexer::InputIdx;
+
+ PagedPorts(const std::vector<MemoryPtr>& inputs, const std::vector<MemoryPtr>& outputs)
+ : q_idx(inputs.at(In::INDEX_QUERY)),
+ k_idx(inputs.at(In::RAW_INDEX_KEYS)),
+ rope_cos(inputs.at(In::ROPE_COS)),
+ rope_sin(inputs.at(In::ROPE_SIN)),
+ q_norm_weight(inputs.at(In::Q_NORM_WEIGHT)),
+ k_norm_weight(inputs.at(In::K_NORM_WEIGHT)),
+ past_lens(inputs.at(In::PAST_LENS)),
+ subsequence_begins(inputs.at(In::SUBSEQUENCE_BEGINS)),
+ block_indices(inputs.at(In::BLOCK_INDICES)),
+ block_indices_begins(inputs.at(In::BLOCK_INDICES_BEGINS)),
+ raw_k_cache(inputs.at(In::INDEX_KEY_CACHE)),
+ indexer_rope_cache(inputs.at(In::INDEX_BLOCK_ROPE_CACHE)),
+ summary_cache(inputs.at(In::BLOCK_INDEX_KEYS_CACHE)),
+ sel_indices(outputs.at(OutputIdx::SEL_INDICES)),
+ sel_count(outputs.at(OutputIdx::SEL_COUNT)) {}
+
+ PlainTensor q_idx, k_idx, rope_cos, rope_sin, q_norm_weight, k_norm_weight;
+ PlainTensor past_lens, subsequence_begins, block_indices, block_indices_begins;
+ PlainTensor raw_k_cache, indexer_rope_cache, summary_cache;
+ PlainTensor sel_indices, sel_count;
+};
+
+// The sizes of a call that follow from the shapes of the ports (the others are in Config).
+inline size_t num_tokens(const PagedPorts& p) {
+ return p.q_idx.size(0);
+}
+inline size_t num_sequences(const PagedPorts& p) {
+ OPENVINO_ASSERT(p.subsequence_begins.size(0) >= 1, "[CPU] paged_qsa_indexer: subsequence_begins must be non-empty");
+ return p.subsequence_begins.size(0) - 1;
+}
+inline size_t index_query_heads(const PagedPorts& p, const Config& c) {
+ return p.q_idx.size(1) / c.indexer_head_dim;
+}
+inline size_t index_key_heads(const PagedPorts& p, const Config& c) {
+ return p.k_idx.size(1) / c.indexer_head_dim;
+}
+
+// What a call knows about one sequence: its tokens, its page-table row and the index blocks it completes:
+// past_blocks = past_len / key_block_size were complete before, new_blocks = (past_len + q_len) / key_block_size -
+// past_blocks are completed by it.
+struct SeqPlan {
+ int64_t key_block_size; // tokens per index block
+ int64_t page_size; // tokens per page of the caches, from the shape of the key cache
+ int64_t slots_per_page; // index blocks per page
+ int64_t token_begin;
+ int64_t q_len;
+ int64_t past_len;
+ int64_t block_begin; // first entry of the sequence in block_indices
+ int64_t block_capacity; // index blocks that fit the sequence's pages
+ int64_t past_blocks;
+ int64_t new_blocks;
+
+ // The complete blocks visible to the token `v` of the call (counted from the first token of the sequence's call):
+ // those up to the block the token completes.
+ [[nodiscard]] int64_t blocks_visible(int64_t v) const {
+ return (past_len + v + 1) / key_block_size;
+ }
+ // The complete blocks of the sequence after the call.
+ [[nodiscard]] int64_t total_blocks() const {
+ return past_blocks + new_blocks;
+ }
+};
+
+inline SeqPlan seq_plan(const PagedPorts& p, const Config& c, size_t seq) {
+ const auto* subsequence_begins = p.subsequence_begins.ptr<int32_t>();
+ const auto* block_indices_begins = p.block_indices_begins.ptr<int32_t>();
+ const int64_t block_begin = block_indices_begins[seq];
+ const int64_t seq_blocks = std::max<int64_t>(block_indices_begins[seq + 1] - block_begin, 0);
+ SeqPlan plan{};
+ plan.key_block_size = static_cast<int64_t>(c.key_block_size);
+ plan.page_size = static_cast<int64_t>(p.raw_k_cache.size(2));
+ plan.slots_per_page = plan.page_size / plan.key_block_size;
+ plan.token_begin = subsequence_begins[seq];
+ plan.q_len = std::max<int64_t>(subsequence_begins[seq + 1] - plan.token_begin, 0);
+ plan.past_len = p.past_lens.ptr<int32_t>()[seq];
+ plan.block_begin = block_begin;
+ plan.block_capacity = seq_blocks * plan.slots_per_page;
+ plan.past_blocks = plan.past_len / plan.key_block_size;
+ plan.new_blocks = (plan.past_len + plan.q_len) / plan.key_block_size - plan.past_blocks;
+ return plan;
+}
+
+// What the longest sequence of the call needs: the scores of a token are for at most max_blocks complete blocks, the
+// pooling of a call is for at most max_new_blocks blocks of a sequence.
+struct SeqStats {
+ int64_t max_blocks = 0;
+ int64_t max_new_blocks = 0;
+ int64_t max_q_len = 0;
+};
+
+inline SeqStats seq_stats(const PagedPorts& p, const Config& c) {
+ SeqStats stats;
+ const auto* block_indices_begins = p.block_indices_begins.ptr<int32_t>();
+ for (size_t seq = 0; seq < num_sequences(p); seq++) {
+ OPENVINO_ASSERT(block_indices_begins[seq + 1] > block_indices_begins[seq],
+ "[CPU] paged_qsa_indexer: each sequence must have at least one cache block");
+ const auto plan = seq_plan(p, c, seq);
+ OPENVINO_ASSERT(plan.total_blocks() <= plan.block_capacity,
+ "[CPU] paged_qsa_indexer: the completed blocks do not fit the sequence's cache blocks");
+ stats.max_blocks = std::max(stats.max_blocks, plan.total_blocks());
+ stats.max_new_blocks = std::max(stats.max_new_blocks, plan.new_blocks);
+ stats.max_q_len = std::max(stats.max_q_len, plan.q_len);
+ }
+ return stats;
+}
+
+// A row of a paged cache: the physical page (an entry of block_indices) and the slot inside it.
+struct CacheAddress {
+ size_t page;
+ size_t slot;
+};
+
+// Maps a logical token position (relative to the sequence's own 0..S history) to the (page, slot) address into
+// INDEX_KEY_CACHE through the shared page table.
+inline CacheAddress token_address(const PagedPorts& p, const SeqPlan& plan, int64_t logical_pos) {
+ const int64_t page_table_idx = plan.block_begin + logical_pos / plan.page_size;
+ const auto page = static_cast<size_t>(*p.block_indices.ptr<int32_t>(static_cast<size_t>(page_table_idx)));
+ return {page, static_cast<size_t>(logical_pos % plan.page_size)};
+}
+
+// Maps a (sequence-local, 0-based) completed-block index to the (page, slot) address into BLOCK_INDEX_KEYS_CACHE /
+// INDEX_BLOCK_ROPE_CACHE.
+inline CacheAddress block_address(const PagedPorts& p, const SeqPlan& plan, int64_t block_idx) {
+ const int64_t page_table_idx = plan.block_begin + (block_idx * plan.key_block_size) / plan.page_size;
+ const auto page = static_cast<size_t>(*p.block_indices.ptr<int32_t>(static_cast<size_t>(page_table_idx)));
+ return {page, static_cast<size_t>(block_idx % plan.slots_per_page)};
+}
+
+// All floating-point ports share one precision, f32, f16 or bf16 (the op validates it). The kernel converts the rows
+// it touches, so the compute stays f32 without a whole-tensor Reorder of caches that grow every step.
+
+// The buffers of one worker thread's slice of the scratch; the phases run one after the other, so they share them.
+struct ThreadLayout {
+ size_t q_normed_off = 0; // floats: [H_iq, D_idx] normalized + rotated index queries
+ size_t row_buf_off; // floats: [D_idx] a converted row
+ size_t summary_buf_off; // floats: [D_idx] a pooled summary row
+ size_t pooled_off; // floats: [D_idx] the mean of the raw keys of a block
+ size_t cos_sin_off; // floats: [2 * rotary_dim] the interleaved cos / sin row of a block
+ size_t cos_tmp_off; // floats: [rotary_dim] a cos row
+ size_t sin_tmp_off; // floats: [rotary_dim] a sin row
+ size_t stage_off; // floats: [kStageRows, D_idx] summary rows converted to f32 (the scoring)
+ size_t score_f32_off; // floats: [blocks] the scores of the blocks of a token and selection head
+ size_t scores_off; // bytes: [blocks] (score * scale, block), what the top-k selects from
+ size_t chosen_off; // bytes: [block_topk]
+ size_t bytes;
+
+ static constexpr size_t kAlign = 64;
+ static constexpr size_t kStageRows = 4; // the rows the scoring converts at a time (qsa::kScoreRows)
+
+ ThreadLayout(size_t H_iq, size_t D_idx, size_t rotary_dim, size_t max_blocks, size_t block_topk)
+ : row_buf_off(q_normed_off + H_iq * D_idx),
+ summary_buf_off(row_buf_off + D_idx),
+ pooled_off(summary_buf_off + D_idx),
+ cos_sin_off(pooled_off + D_idx),
+ cos_tmp_off(cos_sin_off + 2 * rotary_dim),
+ sin_tmp_off(cos_tmp_off + rotary_dim),
+ stage_off(sin_tmp_off + rotary_dim),
+ score_f32_off(stage_off + kStageRows * D_idx),
+ scores_off(rnd_up((score_f32_off + max_blocks) * sizeof(float), kAlign)),
+ chosen_off(rnd_up(scores_off + max_blocks * sizeof(std::pair<float, int32_t>), kAlign)),
+ bytes(rnd_up(chosen_off + block_topk * sizeof(int32_t), kAlign)) {}
+};
+
+// The scratch of one call, one allocation (a second createScratchPadMem() could free the first's memory):
+// [ token -> sequence array, f32 norm weights | brgemm scorer's shared part | one slice per worker thread ]
+// The scorer lays out its own slices over the same space, after the kernel's phases.
+struct PagedScratchLayout {
+ ThreadLayout thread;
+ size_t norm_weights_offset;
+ size_t scorer_shared_offset;
+ size_t threads_offset;
+ size_t thread_bytes;
+ size_t total_bytes;
+
+ // `scorer_shared_bytes` / `scorer_thread_bytes`: what the brgemm scorer needs (0: there is none).
+ PagedScratchLayout(const PagedPorts& p,
+ const Config& c,
+ int64_t max_blocks,
+ size_t scorer_shared_bytes,
+ size_t scorer_thread_bytes,
+ size_t num_threads)
+ : thread(index_query_heads(p, c),
+ c.indexer_head_dim,
+ c.indexer_rotary_dim,
+ static_cast<size_t>(max_blocks),
+ c.block_topk),
+ norm_weights_offset(rnd_up(num_tokens(p) * sizeof(int32_t), ThreadLayout::kAlign)),
+ scorer_shared_offset(
+ rnd_up(norm_weights_offset + 2 * c.indexer_head_dim * sizeof(float), ThreadLayout::kAlign)),
+ threads_offset(rnd_up(scorer_shared_offset + scorer_shared_bytes, ThreadLayout::kAlign)),
+ thread_bytes(std::max(thread.bytes, scorer_thread_bytes)),
+ total_bytes(threads_offset + num_threads * thread_bytes) {}
+};
+
+} // namespace ov::intel_cpu::node::qsa::paged
+
+namespace ov::Extensions::Cpu::XARCH {
+
+// The single cross-compiled entry of the PagedQSAIndexer node: AVX-512, AVX2 or plain C++ by the CPU. `scratch` holds
+// layout.total_bytes. `brgemm` scores the blocks on brgemm (the layout was planned for it); when it is null the kernel
+// scores them itself.
+void paged_qsa_indexer_compute(const ov::intel_cpu::node::qsa::paged::PagedPorts& ports,
+ const ov::op::internal::PagedQSAIndexer::Config& config,
+ const ov::intel_cpu::node::qsa::paged::PagedScratchLayout& layout,
+ uint8_t* scratch,
+ const ov::intel_cpu::node::qsa::QsaBrgemm* brgemm,
+ const ov::intel_cpu::CpuParallelPtr& cpu_parallel);
+
+} // namespace ov::Extensions::Cpu::XARCH
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/qsa_brgemm.hpp b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/qsa_brgemm.hpp
new file mode 100644
index 00000000000..19feaecd7f4
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/qsa_brgemm.hpp
@@ -0,0 +1,346 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#pragma once
+
+// The brgemm scoring of the QSAIndexer and the PagedQSAIndexer (x64): the configuration, the kernels (shared through
+// the params cache) and the plan of the scratch. The computation itself runs inside the cross-compiled kernels
+// (qsa_indexer_brgemm_kernel.hpp), see there for the steps.
+
+#include <algorithm>
+#include <common/utils.hpp>
+#include <cpu/x64/cpu_isa_traits.hpp>
+#include <cstddef>
+#include <cstdint>
+#include <memory>
+#include <utility>
+
+#include "cache/multi_cache.h"
+#include "nodes/kernels/x64/brgemm_kernel.hpp"
+#include "onednn/iml_type_mapper.h"
+#include "openvino/core/except.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "utils/general_utils.h"
+
+namespace ov::intel_cpu::node::qsa {
+
+// The blocks one brgemm call scores: the M of the kernel (BrgemmKernel::get_mblk_size()).
+inline constexpr size_t kScoreBlockRows = 32;
+// Rows of the query tile of a call: (tokens x heads of a K head) up to this many.
+inline constexpr size_t kScoreMaxCols = 128;
+
+// Tokens one brgemm call scores together for K heads of `heads_per_key` query heads.
+inline size_t score_tokens_per_call(size_t heads_per_key) {
+ return std::max<size_t>(1, kScoreMaxCols / heads_per_key);
+}
+
+// The brgemm kernel of the scorer is a JIT product that is expensive to build and depends only on the shape of its
+// columns, the head dim and the precision: the layers of a model share them through the params cache of the graph
+// context (like the SDPA and PagedAttention kernels), and a node fetches them once when it is created, not per call.
+struct ScoreKernelKey {
+ size_t query_rows = 0; // rows of the query tile: tokens x heads of a K head
+ size_t dim = 0; // head dim, the K of the product
+ ov::element::Type precision;
+ bool is_k_q_gemm = false; // C = K.Q^T, the blocks are the A matrix (one token); else C = Q.K^T, the query tile is
+
+ [[nodiscard]] size_t hash() const {
+ size_t seed = 0;
+ seed = dnnl::impl::hash_combine(seed, query_rows);
+ seed = dnnl::impl::hash_combine(seed, dim);
+ seed = dnnl::impl::hash_combine(seed, precision.hash());
+ return dnnl::impl::hash_combine(seed, is_k_q_gemm);
+ }
+ bool operator==(const ScoreKernelKey& rhs) const {
+ return query_rows == rhs.query_rows && dim == rhs.dim && precision == rhs.precision &&
+ is_k_q_gemm == rhs.is_k_q_gemm;
+ }
+};
+
+// Whether this CPU runs the scorer for `precision` and head dim `dim`.
+inline bool score_kernel_supported(const ov::element::Type& precision, size_t dim) {
+ using namespace dnnl::impl::cpu::x64;
+ if (dim % 2 != 0) {
+ return false;
+ }
+ if (precision == ov::element::bf16) {
+ return mayiuse(avx512_core_bf16);
+ }
+ if (precision == ov::element::f16) {
+ return mayiuse(avx512_core_fp16);
+ }
+ return precision == ov::element::f32 && mayiuse(avx512_core);
+}
+
+// The number of query heads per K head when the scoring of a node with these (static) head counts, head dim and
+// precision runs on brgemm on this CPU, 0 when it does not (the node then scores in plain code). The selection heads
+// have to be covered by the K heads.
+inline size_t brgemm_score_group_size(const ov::element::Type& precision,
+ size_t query_heads,
+ size_t key_heads,
+ size_t selection_heads,
+ size_t dim) {
+ if (key_heads == 0 || query_heads % key_heads != 0 || selection_heads > key_heads ||
+ !score_kernel_supported(precision, dim)) {
+ return 0;
+ }
+ return query_heads / key_heads;
+}
+
+// The implementation type a node that scores on brgemm reports (execution graph, profiling): the matrix extension of
+// the kernels of `precision` on this CPU.
+inline impl_desc_type score_impl_type(const ov::element::Type& precision) {
+ using namespace dnnl::impl::cpu::x64;
+ const bool amx = (precision == ov::element::bf16 && mayiuse(avx512_core_amx)) ||
+ (precision == ov::element::f16 && mayiuse(avx512_core_amx_fp16));
+ return amx ? impl_desc_type::brgemm_avx512_amx : impl_desc_type::brgemm_avx512;
+}
+
+// The kernel of the q . k of 32 blocks and `query_rows` query rows, with the ReLU, from the cache; nullptr if it can
+// not be built. Two forms, by how many tokens a call scores:
+// is_k_q_gemm == false (q.k, several tokens) C[query_rows, 32] = max(0, query_tile[query_rows, D] x blocks[32, D]^T)
+// A: the query tile, B: the transposed packed blocks. A row of C is 32 scores of one token.
+// is_k_q_gemm == true (k.q, one token) C[32, query_rows] = max(0, blocks[32, D] x query_tile[query_rows, D]^T)
+// A: the blocks, read in place; B: the transposed packed query tile. A decode step does not make an extra pass
+// over the cache (packing it would double its memory traffic, the cache is what a decode step is bound by).
+inline std::shared_ptr<BrgemmKernel> get_score_kernel(const MultiCachePtr& cache,
+ const ov::element::Type& precision,
+ size_t query_rows,
+ size_t dim,
+ bool is_k_q_gemm) {
+ if (!score_kernel_supported(precision, dim)) {
+ return nullptr;
+ }
+ const auto builder = [](const ScoreKernelKey& key) -> std::shared_ptr<BrgemmKernel> {
+ if (key.is_k_q_gemm) {
+ return std::make_shared<BrgemmKernel>(kScoreBlockRows,
+ key.query_rows,
+ key.dim,
+ key.dim,
+ key.dim,
+ key.query_rows,
+ /*b_transposed=*/true,
+ key.precision,
+ /*b_accumulate=*/false,
+ /*fuse_relu=*/true);
+ }
+ return std::make_shared<BrgemmKernel>(key.query_rows,
+ kScoreBlockRows,
+ key.dim,
+ key.dim,
+ key.dim,
+ kScoreBlockRows,
+ /*b_transposed=*/true,
+ key.precision,
+ /*b_accumulate=*/false,
+ /*fuse_relu=*/true);
+ };
+ try {
+ return cache->getOrCreate(ScoreKernelKey{query_rows, dim, precision, is_k_q_gemm}, builder).first;
+ } catch (const ov::Exception&) {
+ return nullptr;
+ }
+}
+
+inline constexpr size_t kSelectBuckets = 256;
+
+// Describes what the scorer of a node needs from the layers that share it.
+class QsaBrgemm {
+public:
+ // Everything that does not change from call to call; also the key of the scorer in the params cache.
+ struct Config {
+ size_t index_query_heads = 0;
+ size_t index_key_heads = 0;
+ size_t selection_heads = 0;
+ size_t dim = 0; // channels of an index head
+ size_t rotary_dim = 0; // channels of the query rotated by RoPE
+ size_t block_topk = 0;
+ size_t num_threads = 0;
+ float eps = 0.0F;
+ float scale = 0.0F;
+ ov::element::Type precision; // of the summary blocks
+ // The chosen blocks of a row by descending score, equal scores by ascending block id (the order of
+ // SparseAttentionIndexer-17), instead of ascending block ids. Needs the scores of every token, so the tokens
+ // that take all their blocks are scored too.
+ bool order_by_score = false;
+
+ [[nodiscard]] size_t hash() const {
+ size_t seed = 0;
+ for (const size_t value :
+ {index_query_heads, index_key_heads, selection_heads, dim, rotary_dim, block_topk, num_threads}) {
+ seed = dnnl::impl::hash_combine(seed, value);
+ }
+ seed = dnnl::impl::hash_combine(seed, eps);
+ seed = dnnl::impl::hash_combine(seed, scale);
+ seed = dnnl::impl::hash_combine(seed, order_by_score);
+ return dnnl::impl::hash_combine(seed, precision.hash());
+ }
+ bool operator==(const Config& rhs) const {
+ return index_query_heads == rhs.index_query_heads && index_key_heads == rhs.index_key_heads &&
+ selection_heads == rhs.selection_heads && dim == rhs.dim && rotary_dim == rhs.rotary_dim &&
+ block_topk == rhs.block_topk && num_threads == rhs.num_threads && eps == rhs.eps &&
+ scale == rhs.scale && precision == rhs.precision && order_by_score == rhs.order_by_score;
+ }
+ };
+
+ // What a call adds to the configuration: the sizes that follow from its lengths. A handful of numbers computed per
+ // call by plan(), the scratch (of `shared_bytes` and `thread_bytes` per worker thread) is the caller's.
+ struct Plan {
+ size_t batch = 0;
+ int64_t max_current = 0; // the most tokens of a row in the call
+ int64_t max_row_blocks = 0; // the most complete blocks of a row after the call
+ size_t padded_blocks = 0; // the blocks of a score row, a multiple of the blocks of a brgemm call
+ size_t score_stride = 0; // floats between the score rows of two tokens
+ size_t score_tile_bytes = 0; // the score matrix of one tile of tokens of one row
+ size_t tiles_total = 0; // tiles of tokens of the longest row
+ size_t tiles_per_round = 0; // the tiles in flight, bounded by the memory of their score matrices
+ size_t shared_bytes = 0; // scratch shared by the threads: the score matrices of the tiles of a round
+ size_t thread_bytes = 0; // scratch of one worker thread
+ };
+
+ // The scorer of `config` from the params cache (built on first use, shared by the layers of the same
+ // configuration), nullptr if this CPU or the configuration has no brgemm scoring.
+ static std::shared_ptr<const QsaBrgemm> get(const MultiCachePtr& cache, const Config& config) {
+ if (brgemm_score_group_size(config.precision,
+ config.index_query_heads,
+ config.index_key_heads,
+ config.selection_heads,
+ config.dim) == 0) {
+ return nullptr;
+ }
+ const auto builder = [&cache](const Config& key) -> std::shared_ptr<const QsaBrgemm> {
+ const size_t heads_per_key = key.index_query_heads / key.index_key_heads;
+ const size_t tokens_per_call = score_tokens_per_call(heads_per_key);
+ // `q_k_kernel` scores a full set of tokens (query rows: tokens_per_call * heads_per_key), `k_q_kernel` a
+ // single token (heads_per_key rows): the decode step is one token wide.
+ auto q_k_kernel = get_score_kernel(cache, key.precision, tokens_per_call * heads_per_key, key.dim, false);
+ auto k_q_kernel = get_score_kernel(cache, key.precision, heads_per_key, key.dim, true);
+ if (!q_k_kernel || !k_q_kernel) {
+ return nullptr;
+ }
+ return std::make_shared<const QsaBrgemm>(key, std::move(q_k_kernel), std::move(k_q_kernel));
+ };
+ try {
+ return cache->getOrCreate(config, builder).first;
+ } catch (const ov::Exception&) {
+ return nullptr;
+ }
+ }
+
+ QsaBrgemm(const Config& config, std::shared_ptr<BrgemmKernel> q_k_kernel, std::shared_ptr<BrgemmKernel> k_q_kernel)
+ : m_config(config),
+ m_q_k_kernel(std::move(q_k_kernel)),
+ m_k_q_kernel(std::move(k_q_kernel)),
+ m_heads_per_key(config.index_query_heads / config.index_key_heads),
+ m_tokens_per_call(score_tokens_per_call(m_heads_per_key)),
+ m_tile_tokens(m_tokens_per_call * kQuerySlicesPerItem),
+ m_packed_blocks_bytes(rnd_up(m_q_k_kernel->get_scratch_b_size(), kAlign)),
+ m_packed_query_bytes(rnd_up(m_k_q_kernel->get_scratch_b_size(), kAlign)) {
+ init_thread_layout();
+ }
+
+ // The sizes of a call of `batch` rows, the longest of `max_current` tokens and with at most `max_row_blocks`
+ // complete blocks in a row.
+ [[nodiscard]] Plan plan(size_t batch, int64_t max_current, int64_t max_row_blocks) const {
+ Plan p;
+ p.batch = batch;
+ p.max_current = max_current;
+ p.max_row_blocks = max_row_blocks;
+ p.padded_blocks = rnd_up(static_cast<size_t>(max_row_blocks), kScoreBlockRows);
+ // A cache line more than the blocks: the score rows of the tokens a call writes together do not share an L1
+ // set.
+ p.score_stride = p.padded_blocks + kAlign / sizeof(float);
+ p.tiles_total = div_up(static_cast<size_t>(max_current), m_tile_tokens);
+ const size_t alloc_tokens = std::min(m_tile_tokens, static_cast<size_t>(max_current));
+ p.score_tile_bytes = rnd_up(alloc_tokens * m_config.selection_heads * p.score_stride * sizeof(float), kAlign);
+ if (needs_scoring(p) && p.score_tile_bytes != 0) {
+ p.tiles_per_round = std::clamp<size_t>(kScoreBudgetBytes / (batch * p.score_tile_bytes), 1, p.tiles_total);
+ }
+ p.shared_bytes = p.tiles_per_round * batch * p.score_tile_bytes;
+ p.thread_bytes =
+ m_select_offset + rnd_up((p.padded_blocks + 1) * sizeof(float) + kSelectBuckets * sizeof(uint32_t), kAlign);
+ return p;
+ }
+
+ struct ThreadOffsets {
+ size_t rows, query_tile, packed_blocks, packed_query, gemm_scores, workspace, scratch_a, key_chunk_stage;
+ };
+
+ // Scores are only needed when a token has more blocks than it can choose, or, to order the blocks by score, when it
+ // has any.
+ [[nodiscard]] bool needs_scoring(const Plan& plan) const {
+ return static_cast<size_t>(plan.max_row_blocks) > (m_config.order_by_score ? 0 : m_config.block_topk);
+ }
+
+ // What the kernel's runner reads (qsa_indexer_brgemm_kernel.hpp).
+ [[nodiscard]] const Config& config() const {
+ return m_config;
+ }
+ [[nodiscard]] const std::shared_ptr<BrgemmKernel>& q_k_kernel() const {
+ return m_q_k_kernel;
+ }
+ [[nodiscard]] const std::shared_ptr<BrgemmKernel>& k_q_kernel() const {
+ return m_k_q_kernel;
+ }
+ [[nodiscard]] size_t heads_per_key() const {
+ return m_heads_per_key;
+ }
+ [[nodiscard]] size_t tokens_per_call() const {
+ return m_tokens_per_call;
+ }
+ [[nodiscard]] size_t tile_tokens() const {
+ return m_tile_tokens;
+ }
+ [[nodiscard]] size_t packed_query_bytes() const {
+ return m_packed_query_bytes;
+ }
+ [[nodiscard]] const ThreadOffsets& offsets() const {
+ return m_offsets;
+ }
+ [[nodiscard]] size_t select_offset() const {
+ return m_select_offset;
+ }
+
+ static constexpr size_t kAlign = 64;
+ // Query slices (the tokens of one brgemm call each) an item prepares and scores.
+ static constexpr size_t kQuerySlicesPerItem = 4;
+ // Bound of the score matrices of the tokens in flight.
+ static constexpr size_t kScoreBudgetBytes = 32UL << 20;
+
+private:
+ // Layout of a thread slice: f32 rows | query tiles | packed blocks | packed query | brgemm output | workspace |
+ // A scratch |
+ // zero-padded chunk | selection scratch (its size follows from the call, see plan()).
+ void init_thread_layout() {
+ const size_t dim = m_config.dim;
+ const size_t element = m_config.precision.size();
+ const size_t query_rows = m_tokens_per_call * m_heads_per_key;
+ size_t offset = 0;
+ auto reserve = [&offset](size_t bytes) {
+ const size_t start = offset;
+ offset += rnd_up(bytes, kAlign);
+ return start;
+ };
+ m_offsets.rows = reserve((2 * dim + 2 * m_config.rotary_dim) * sizeof(float));
+ m_offsets.query_tile = reserve(kQuerySlicesPerItem * m_config.index_key_heads * query_rows * dim * element);
+ m_offsets.packed_blocks = reserve(m_packed_blocks_bytes);
+ m_offsets.packed_query = reserve(m_config.index_key_heads * m_packed_query_bytes);
+ m_offsets.gemm_scores = reserve(query_rows * kScoreBlockRows * sizeof(float));
+ m_offsets.workspace = reserve(BrgemmKernel::get_wsp_size());
+ m_offsets.scratch_a = reserve(std::max(m_q_k_kernel->get_scratch_a_size(), m_k_q_kernel->get_scratch_a_size()));
+ m_offsets.key_chunk_stage = reserve(kScoreBlockRows * dim * element);
+ m_select_offset = offset;
+ }
+
+ Config m_config;
+ std::shared_ptr<BrgemmKernel> m_q_k_kernel;
+ std::shared_ptr<BrgemmKernel> m_k_q_kernel;
+ size_t m_heads_per_key;
+ size_t m_tokens_per_call;
+ size_t m_tile_tokens;
+ size_t m_packed_blocks_bytes; // the B matrix of 32 blocks (several tokens)
+ size_t m_packed_query_bytes; // the B matrix of the query tile of a K head (one token)
+ ThreadOffsets m_offsets{};
+ size_t m_select_offset = 0; // the selection scratch follows the fixed part of a thread slice
+};
+
+} // namespace ov::intel_cpu::node::qsa
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/qsa_indexer_brgemm_kernel.hpp b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/qsa_indexer_brgemm_kernel.hpp
new file mode 100644
index 00000000000..1d70490ce5c
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/qsa_indexer_brgemm_kernel.hpp
@@ -0,0 +1,649 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#pragma once
+
+// Block scoring and top-k selection of the QSAIndexer and the PagedQSAIndexer on brgemm (x64). Included by the
+// cross-compiled kernels only, so it is compiled per instruction set in the namespace XARCH, like the rest of them; the
+// brgemm kernels themselves (BrgemmKernel) are compiled once, the configuration and the scratch plan are in
+// qsa_brgemm.hpp.
+//
+// A "row" is one sequence of the call (a batch entry of the dense node, a sequence of the paged one); the physical
+// layouts differ and are hidden behind `Source` (see below). Notation, per row: L tokens of the call, H_iq index query
+// heads, H_ik index key heads ("K heads"), G = H_iq / H_ik, H_sel selection heads, D head dim, Dr rotary dim, NB
+// complete key blocks.
+// Logical inputs: raw query [L, H_iq, D], RoPE tables, q_norm_weight, summary_cache [H_ik, NB, D] (one index key per
+// block). Outputs: the chosen block ids and their count per token and selection head.
+//
+// Per query token (the function that does it in brackets):
+// 1. RMSNorm of every query head (prepare_query_slices)
+// 2. RoPE of its first Dr channels: the rotated query q_rot[h], [D] (prepare_query_slices)
+// 3. dot[h, blk] = q_rot[h] . summary_cache[h / G, blk] (score_key_chunks)
+// 4. score[sel_head, blk] = scale * sum over the heads of the selection head of max(0, dot[h, blk])
+// (score_key_chunks)
+// 5. top-k: the block_topk best blocks among those visible to the token (select_token)
+//
+// Steps 1-2 run once per query slice (the tokens of one brgemm call) and give its query tile [query_rows, D],
+// query_rows = G x tokens of the slice. Steps 3-4 run per key chunk (32 blocks): one brgemm per slice,
+// C[query_rows, 32] = max(0, query_tile x blocks[32, D]^T),
+// with the blocks packed once per chunk and K head; ReLU is a post-op and the sum over the heads is plain code. A
+// single token (decode) swaps the operands, C[32, G], so the blocks are read in place.
+// A work item is `tile_tokens` tokens x a range of key chunks; prefill items select right away, decode items split the
+// chunks among threads and select in a separate pass.
+
+#include <algorithm>
+#include <cstddef>
+#include <cstdint>
+#include <functional>
+#include <memory>
+
+#include "cpu_parallel.hpp"
+#include "nodes/kernels/sparse_attn/qsa_brgemm.hpp"
+#include "nodes/kernels/sparse_attn/qsa_kernel_utils.hpp"
+#include "nodes/kernels/x64/brgemm_kernel.hpp"
+#include "openvino/core/except.hpp"
+#include "openvino/core/parallel.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "utils/general_utils.h"
+
+namespace ov::Extensions::Cpu::XARCH::qsa {
+
+using ov::intel_cpu::AmxTileState;
+using ov::intel_cpu::BrgemmKernel;
+using ov::intel_cpu::CpuParallel;
+using ov::intel_cpu::div_up;
+using ov::intel_cpu::rnd_up;
+using ov::intel_cpu::node::qsa::kScoreBlockRows;
+using ov::intel_cpu::node::qsa::kSelectBuckets;
+using ov::intel_cpu::node::qsa::QsaBrgemm;
+
+// Step 5: writes the (ascending) ids of the k blocks of the highest scores[0, n) to `chosen`, n > k > 0 (scores: the
+// [NB] row of one token and selection head). Equal scores: the lower block id wins. The k-th largest score is found by
+// a bucket selection: the scores are spread over kBuckets buckets of equal width between the smallest and the largest
+// one, a histogram finds the bucket that holds the k-th score, and the few scores of that bucket are partially sorted
+// (a skewed distribution only makes that bucket bigger). `candidates` (n + 1 floats) and `histogram` (kSelectBuckets
+// values) are scratch; the passes are branch-free as which scores qualify is as good as random.
+inline void select_top_blocks(const float* scores,
+ size_t n,
+ size_t k,
+ float* candidates,
+ uint32_t* histogram,
+ int32_t* chosen) {
+ // smallest and largest score
+ vfloat vlow = vset1(scores[0]);
+ vfloat vhigh = vlow;
+ size_t i = 0;
+ for (; i + kLanes <= n; i += kLanes) {
+ const vfloat v = vload(scores + i);
+ vlow = vmin(vlow, v);
+ vhigh = vmax(vhigh, v);
+ }
+ float low = vreduce_min(vlow);
+ float high = vreduce_max(vhigh);
+ for (; i < n; i++) {
+ low = std::min(low, scores[i]);
+ high = std::max(high, scores[i]);
+ }
+
+ constexpr auto max_bucket = static_cast<int32_t>(kSelectBuckets) - 1;
+ const float to_bucket = high > low ? static_cast<float>(kSelectBuckets) / (high - low) : 0.0F;
+ // The bucket of a score, the same arithmetic as the vector one (vbucket) so that both passes agree on it.
+ const auto bucket_of = [&](float score) {
+ return std::min(max_bucket, static_cast<int32_t>((score - low) * to_bucket));
+ };
+ const vfloat vlow_all = vset1(low);
+ const vfloat vto_bucket = vset1(to_bucket);
+
+ // histogram: the buckets of a vector of scores are computed at once, the counters are bumped one by one
+ std::fill_n(histogram, kSelectBuckets, 0U);
+ alignas(64) int32_t buckets[kLanes];
+ for (i = 0; i + kLanes <= n; i += kLanes) {
+ vstore_buckets(vload(scores + i), vlow_all, vto_bucket, max_bucket, buckets);
+ for (const int32_t bucket : buckets) {
+ histogram[bucket]++;
+ }
+ }
+ for (; i < n; i++) {
+ histogram[bucket_of(scores[i])]++;
+ }
+ // the bucket of the k-th largest score, and how many scores are above it
+ size_t above = 0;
+ int bucket = max_bucket;
+ while (above + histogram[bucket] < k) {
+ above += histogram[bucket--];
+ }
+ // the scores of that bucket
+ size_t candidate_count = 0;
+ for (i = 0; i + kLanes <= n; i += kLanes) {
+ candidate_count += vcompress_store(candidates + candidate_count,
+ vload(scores + i),
+ vbucket_mask(vload(scores + i), vlow_all, vto_bucket, max_bucket, bucket));
+ }
+ for (; i < n; i++) {
+ candidates[candidate_count] = scores[i];
+ candidate_count += bucket_of(scores[i]) == bucket ? 1 : 0;
+ }
+ const size_t rank = k - above; // 1-based rank of the k-th score among the scores of its bucket
+ std::nth_element(candidates, candidates + (rank - 1), candidates + candidate_count, std::greater<>());
+ const float threshold = candidates[rank - 1];
+ size_t greater = above;
+ for (i = 0; i < candidate_count; i++) {
+ greater += candidates[i] > threshold ? 1 : 0;
+ }
+
+ // Blocks above the threshold, then as many blocks of the threshold score as are missing, the lowest ids first.
+ // Collected ascending in the (no longer needed) candidate buffer, as the stores past the end of the chosen
+ // blocks are overwritten by the next one. A vector of scores without a tie at the threshold (the usual case)
+ // takes the blocks above it at once; one with ties goes block by block.
+ auto* const collected = reinterpret_cast<int32_t*>(candidates);
+ size_t equal_left = k - greater;
+ size_t written = 0;
+ const vfloat vthreshold = vset1(threshold);
+ for (i = 0; i + kLanes <= n; i += kLanes) {
+ const vfloat v = vload(scores + i);
+ const uint32_t above_mask = vcmp_gt(v, vthreshold);
+ const uint32_t equal_mask = vcmp_eq(v, vthreshold);
+ if (equal_mask != 0 && equal_left > 0) {
+ for (size_t lane = 0; lane < kLanes; lane++) {
+ const bool take_equal = ((equal_mask >> lane) & 1U) != 0 && equal_left > 0;
+ equal_left -= take_equal ? 1 : 0;
+ collected[written] = static_cast<int32_t>(i + lane);
+ written += (((above_mask >> lane) & 1U) != 0 || take_equal) ? 1 : 0;
+ }
+ } else {
+ written += vcompress_ids(collected + written, static_cast<int32_t>(i), above_mask);
+ }
+ }
+ for (; i < n; i++) {
+ const bool take_equal = scores[i] == threshold && equal_left > 0;
+ equal_left -= take_equal ? 1 : 0;
+ collected[written] = static_cast<int32_t>(i);
+ written += (scores[i] > threshold || take_equal) ? 1 : 0;
+ }
+ std::copy_n(collected, k, chosen);
+}
+
+// Orders `count` chosen block ids by descending score, equal scores by ascending block id: the order of
+// SparseAttentionIndexer-17. `scores` is the [NB] row of the token and selection head.
+inline void order_blocks_by_score(const float* scores, int32_t* blocks, size_t count) {
+ std::sort(blocks, blocks + count, [scores](int32_t a, int32_t b) {
+ return scores[a] != scores[b] ? scores[a] > scores[b] : a < b;
+ });
+}
+
+// The computation of a call on the scorer of the node (QsaBrgemm); `Source` is described below.
+//
+// `Source` is the layout of the call: it gives the runner the tokens of the rows, the query and RoPE rows, the blocks
+// and the place of the results, so the runner does not know whether they are dense tensors or paged caches. A row is a
+// sequence of the batch, `v` a token of its call counted from the first real token (`b`: row, `h`: query head,
+// `key_head`: K head, `sel_head`: selection head). `Source` provides (all const, called from several threads):
+// using Element = T the precision of the summary blocks (f32, f16 or bf16), also the precision
+// the query tile is rounded to
+// int64_t tokens(b) the real tokens of the call of the row
+// int64_t blocks_visible(b, v) the complete blocks visible to the token v
+// int64_t blocks(b) the complete blocks of the row after the call (>= those visible to any
+// token)
+// const float* query_row(b, v, h, buf) q[h] [D] as f32: a view, or converted into `buf` [D]
+// const float* rope_cos(b, v, buf) cos [Dr] as f32 of the token (a view, or converted into `buf` [Dr])
+// const float* rope_sin(b, v, buf) the same for sin
+// const float* q_norm_weight() the gain of the query RMSNorm, f32 [D]
+// const T* block_rows(b, key_head, first, count, stage)
+// `count` (1..32) consecutive complete blocks of the K head from the block
+// `first` as rows [count, D]: a pointer into the cache when they are
+// contiguous there, otherwise gathered into `stage` ([32, D]); a staged
+// result has zero rows from `count` on, a direct one only `count` rows
+// int32_t* selection_indices(b, v, sel_head) where the block_topk chosen block ids of the token go
+// int32_t* selection_count(b, v, sel_head) where their number goes
+class BrgemmRunner {
+public:
+ using Config = QsaBrgemm::Config;
+ using Plan = QsaBrgemm::Plan;
+
+ explicit BrgemmRunner(const QsaBrgemm& brgemm)
+ : m_brgemm(brgemm),
+ m_config(brgemm.config()),
+ m_q_k_kernel(brgemm.q_k_kernel()),
+ m_k_q_kernel(brgemm.k_q_kernel()),
+ m_heads_per_key(brgemm.heads_per_key()),
+ m_tokens_per_call(brgemm.tokens_per_call()),
+ m_tile_tokens(brgemm.tile_tokens()),
+ m_packed_query_bytes(brgemm.packed_query_bytes()),
+ m_offsets(brgemm.offsets()),
+ m_select_offset(brgemm.select_offset()) {}
+
+ // Selects the blocks of every token of the call. `shared` / `threads` are the scratch of plan.shared_bytes and of
+ // num_threads slices of plan.thread_bytes.
+ template <typename Source>
+ void run(const Plan& plan, const Source& source, void* shared, void* threads, const CpuParallel& parallel) const {
+ OPENVINO_ASSERT(ov::element::from<typename Source::Element>() == m_config.precision,
+ "QSA block scorer: the summary blocks are not of the precision of the scorer");
+ const Context<Source> ctx{source, plan, static_cast<float*>(shared), static_cast<uint8_t*>(threads), parallel};
+ if (!m_brgemm.needs_scoring(plan)) {
+ // every token sees at most block_topk blocks: all of them are chosen
+ parallel.parallel_for2d(plan.batch, static_cast<size_t>(plan.max_current), [&](size_t b, size_t v) {
+ if (static_cast<int64_t>(v) < source.tokens(b)) {
+ select_token(ctx, b, static_cast<int64_t>(v), nullptr, nullptr);
+ }
+ });
+ return;
+ }
+
+ const size_t groups_total = div_up(static_cast<size_t>(plan.max_row_blocks), kScoreBlockRows);
+ const size_t tile_alloc_tokens = std::min(m_tile_tokens, static_cast<size_t>(plan.max_current));
+ for (size_t first_tile = 0; first_tile < plan.tiles_total; first_tile += plan.tiles_per_round) {
+ const size_t tiles = std::min(plan.tiles_per_round, plan.tiles_total - first_tile);
+ // Few work items (decode, short windows): split the block range of an item among several threads.
+ const size_t splits = std::clamp<size_t>(div_up(2 * m_config.num_threads, tiles * plan.batch),
+ 1,
+ std::max<size_t>(1, groups_total / 4));
+
+ parallel.parallel_for3d(tiles, plan.batch, splits, [&](size_t tile, size_t b, size_t split) {
+ score_item(ctx, first_tile + tile, tile, b, split, splits);
+ });
+ if (splits == 1) {
+ continue; // the items selected already
+ }
+ parallel.parallel_for3d(tiles, plan.batch, tile_alloc_tokens, [&](size_t tile, size_t b, size_t t) {
+ const auto v = static_cast<int64_t>((first_tile + tile) * m_tile_tokens + t);
+ if (v < source.tokens(b)) {
+ select_token(ctx,
+ b,
+ v,
+ tile_scores(ctx, tile, b) + t * m_config.selection_heads * plan.score_stride);
+ }
+ });
+ }
+ }
+
+private:
+ template <typename Source>
+ struct Context {
+ const Source& source;
+ const Plan& plan;
+ float* score_matrices; // [tile of the round, row][tile token, selection head, block (padded stride)]
+ uint8_t* threads;
+ const CpuParallel& parallel;
+ };
+
+ // The buffers of a worker thread (see init_thread_layout()); `query_tile` and `key_chunk_stage` hold elements of
+ // the precision of the summary blocks.
+ struct ThreadScratch {
+ float* q_row; // f32 row of the query head, [D]
+ float* normed; // the row normalized and rotated, [D]
+ float* rope_cos; // f32 [Dr]
+ float* rope_sin;
+ uint8_t* query_tile; // [q_slice][K head][query_rows][D]
+ uint8_t* packed_blocks; // the B matrix of 32 blocks (several tokens)
+ uint8_t* packed_query; // [K head] B matrices of the query tile (one token)
+ float* gemm_scores; // brgemm output: [query_rows, 32 blocks], or [32 blocks, query_rows] for one token
+ uint8_t* workspace;
+ uint8_t* scratch_a;
+ uint8_t* key_chunk_stage; // zero-padded copy of the last chunk of blocks of the cache
+ float* select_candidates;
+ uint32_t* select_histogram;
+ };
+
+ // A query slice, a part of the tokens of an item: the tokens that go through one brgemm call (an item has up to
+ // kQuerySlicesPerItem of them).
+ struct QuerySlice {
+ size_t real_tokens; // tokens of the item in this query slice
+ size_t token_slots; // token slots of the brgemm call: a single token goes through the k.q kernel, else all
+ // slots
+ size_t query_rows; // rows of the query tile of the query slice: token slots x heads_per_key
+ int64_t blocks; // complete blocks visible to its last token
+ BrgemmKernel* kernel;
+ uint8_t* query; // its query tile, [K head][query_rows][D]
+ bool is_single_token; // one token (decode): the k.q kernel, the blocks are the A matrix (see get_score_kernel)
+ };
+
+ template <typename Source>
+ [[nodiscard]] float* tile_scores(const Context<Source>& ctx, size_t tile, size_t b) const {
+ return ctx.score_matrices + (tile * ctx.plan.batch + b) * (ctx.plan.score_tile_bytes / sizeof(float));
+ }
+
+ template <typename Source>
+ [[nodiscard]] ThreadScratch thread_scratch(const Context<Source>& ctx) const {
+ auto* const base = ctx.threads + static_cast<size_t>(parallel_get_thread_num()) * ctx.plan.thread_bytes;
+ ThreadScratch s{};
+ s.q_row = reinterpret_cast<float*>(base + m_offsets.rows);
+ s.normed = s.q_row + m_config.dim;
+ s.rope_cos = s.normed + m_config.dim;
+ s.rope_sin = s.rope_cos + m_config.rotary_dim;
+ s.query_tile = base + m_offsets.query_tile;
+ s.packed_blocks = base + m_offsets.packed_blocks;
+ s.packed_query = base + m_offsets.packed_query;
+ s.gemm_scores = reinterpret_cast<float*>(base + m_offsets.gemm_scores);
+ s.workspace = base + m_offsets.workspace;
+ s.scratch_a = base + m_offsets.scratch_a;
+ s.key_chunk_stage = base + m_offsets.key_chunk_stage;
+ s.select_candidates = reinterpret_cast<float*>(base + m_select_offset);
+ s.select_histogram = reinterpret_cast<uint32_t*>(s.select_candidates + ctx.plan.padded_blocks + 1);
+ return s;
+ }
+
+ // Step 5 for the token `v` of row `b`: the selection of its selection heads from `token_scores`, its [H_sel, NB]
+ // score rows (stride plan.score_stride). A token that sees at most block_topk blocks takes all of them: its scores
+ // are not needed.
+ template <typename Source>
+ void select_token(const Context<Source>& ctx, size_t b, int64_t v, const float* token_scores) const {
+ const auto s = thread_scratch(ctx);
+ select_token(ctx, b, v, token_scores, &s);
+ }
+
+ template <typename Source>
+ void select_token(const Context<Source>& ctx,
+ size_t b,
+ int64_t v,
+ const float* token_scores,
+ const ThreadScratch* s) const {
+ const auto visible = static_cast<size_t>(ctx.source.blocks_visible(b, v));
+ const size_t k = std::min(m_config.block_topk, visible);
+ for (size_t sel_head = 0; sel_head < m_config.selection_heads; sel_head++) {
+ auto* const out_row = ctx.source.selection_indices(b, v, sel_head);
+ if (visible <= m_config.block_topk) {
+ for (size_t i = 0; i < k; i++) {
+ out_row[i] = static_cast<int32_t>(i);
+ }
+ } else {
+ select_top_blocks(token_scores + sel_head * ctx.plan.score_stride,
+ visible,
+ k,
+ s->select_candidates,
+ s->select_histogram,
+ out_row);
+ }
+ if (m_config.order_by_score && k > 0) {
+ order_blocks_by_score(token_scores + sel_head * ctx.plan.score_stride, out_row, k);
+ }
+ *ctx.source.selection_count(b, v, sel_head) = static_cast<int32_t>(k);
+ }
+ }
+
+ // One work item: the tokens [tile * tile_tokens, ...) of row `b`, the `split`-th range of their key chunks.
+ // scores: [tile tokens, H_sel, NB] f32 (the scores of the tokens of the tile, step 4)
+ template <typename Source>
+ void score_item(const Context<Source>& ctx, size_t tile, size_t round_tile, size_t b, size_t split, size_t splits)
+ const {
+ const auto first_token = static_cast<int64_t>(tile * m_tile_tokens);
+ const int64_t row_tokens = ctx.source.tokens(b);
+ if (first_token >= row_tokens) {
+ return;
+ }
+ const int64_t valid = std::min<int64_t>(static_cast<int64_t>(m_tile_tokens), row_tokens - first_token);
+ const int64_t blocks = ctx.source.blocks_visible(b, first_token + valid - 1);
+ float* const scores = tile_scores(ctx, round_tile, b);
+ const auto thread = thread_scratch(ctx);
+ // an unsplit item selects itself: its scores are in the cache of this thread
+ auto select_tokens = [&]() {
+ for (int64_t t = 0; t < valid; t++) {
+ select_token(ctx,
+ b,
+ first_token + t,
+ scores + static_cast<size_t>(t) * m_config.selection_heads * ctx.plan.score_stride,
+ &thread);
+ }
+ };
+ if (!m_config.order_by_score && blocks <= static_cast<int64_t>(m_config.block_topk)) {
+ // every token of the tile takes all its blocks, and their order is the ascending one: no scores needed
+ if (splits == 1) {
+ select_tokens();
+ }
+ return;
+ }
+ const size_t key_chunks = div_up(static_cast<size_t>(blocks), kScoreBlockRows);
+ const size_t key_chunks_per_split = div_up(key_chunks, splits);
+ const size_t key_chunk_begin = split * key_chunks_per_split;
+ const size_t key_chunk_end = std::min(key_chunks, key_chunk_begin + key_chunks_per_split);
+ if (key_chunk_begin >= key_chunk_end) {
+ return;
+ }
+
+ QuerySlice q_slices[kQuerySlicesPerItem];
+ const size_t q_slice_count = div_up(static_cast<size_t>(valid), m_tokens_per_call);
+ prepare_query_slices(ctx, thread, b, first_token, valid, q_slices);
+ score_key_chunks(ctx, thread, b, key_chunk_begin, key_chunk_end, q_slices, q_slice_count, scores);
+ if (splits == 1) {
+ select_tokens();
+ }
+ }
+
+ // Steps 1 and 2, the query side: RMSNorm + RoPE of the H_iq heads of every token of the item, as the A matrix of
+ // the brgemm call that scores its token slice, per K head:
+ // query_tile[key_head] [query_rows, D] = the q_rot rows of the G heads of the K head for the token slots of the
+ // brgemm call; the row of (head h, token t) is (h % G) * token_slots + t
+ // The rows of the missing tokens of an incomplete slice are zero. The tile of a single token is also packed, as the
+ // B matrix of its brgemm call.
+ template <typename Source>
+ void prepare_query_slices(const Context<Source>& ctx,
+ const ThreadScratch& thread,
+ size_t b,
+ int64_t first_token,
+ int64_t valid,
+ QuerySlice* q_slices) const {
+ using T = typename Source::Element;
+ const Source& source = ctx.source;
+ const size_t dim = m_config.dim;
+ const size_t heads_per_key = m_heads_per_key;
+ const size_t q_slice_count = div_up(static_cast<size_t>(valid), m_tokens_per_call);
+ for (size_t q_slice_idx = 0; q_slice_idx < q_slice_count; q_slice_idx++) {
+ auto& q_slice = q_slices[q_slice_idx];
+ q_slice.query = thread.query_tile + q_slice_idx * m_config.index_key_heads * m_tokens_per_call *
+ heads_per_key * dim * sizeof(T);
+ auto* const query_tile = reinterpret_cast<T*>(q_slice.query);
+ q_slice.real_tokens =
+ std::min(m_tokens_per_call, static_cast<size_t>(valid) - q_slice_idx * m_tokens_per_call);
+ // a single token goes through the k.q kernel, anything else through the q.k one
+ q_slice.is_single_token = q_slice.real_tokens == 1;
+ q_slice.token_slots = q_slice.is_single_token ? 1 : m_tokens_per_call;
+ q_slice.query_rows = q_slice.token_slots * heads_per_key;
+ q_slice.kernel = q_slice.is_single_token ? m_k_q_kernel.get() : m_q_k_kernel.get();
+ q_slice.blocks = source.blocks_visible(
+ b,
+ first_token + static_cast<int64_t>(q_slice_idx * m_tokens_per_call + q_slice.real_tokens) - 1);
+ if (q_slice.real_tokens < q_slice.token_slots) {
+ std::fill_n(query_tile, m_config.index_key_heads * q_slice.query_rows * dim, T{}); // missing tokens
+ }
+ for (size_t token = 0; token < q_slice.real_tokens; token++) {
+ const int64_t v = first_token + static_cast<int64_t>(q_slice_idx * m_tokens_per_call + token);
+ const float* const cos_row = source.rope_cos(b, v, thread.rope_cos);
+ const float* const sin_row = source.rope_sin(b, v, thread.rope_sin);
+ for (size_t h = 0; h < m_config.index_query_heads; h++) {
+ // q[token, h, :] [D], as f32
+ const float* const q_row = source.query_row(b, v, h, thread.q_row);
+ // step 1 (RMSNorm of the [D] row: x / sqrt(mean(x^2) + eps) * q_norm_weight) and step 2 (RoPE of
+ // its first Dr channels with cos / sin of the token, [Dr] each) -> q_rot[h] [D]
+ rms_rope(q_row,
+ thread.normed,
+ source.q_norm_weight(),
+ dim,
+ m_config.rotary_dim,
+ m_config.eps,
+ cos_row,
+ sin_row);
+ // q_rot[h] is the row (h % G) * tokens + token of the tile of the K head h / G, rounded to T
+ const size_t row = (h % heads_per_key) * q_slice.token_slots + token;
+ store_row(thread.normed, query_tile + ((h / heads_per_key) * q_slice.query_rows + row) * dim, dim);
+ }
+ }
+ if (q_slice.is_single_token) {
+ for (size_t key_head = 0; key_head < m_config.index_key_heads; key_head++) {
+ q_slice.kernel->copy_buffer_b(query_tile + key_head * q_slice.query_rows * dim,
+ thread.packed_query + key_head * m_packed_query_bytes);
+ }
+ }
+ }
+ }
+
+ // Steps 3 and 4, the block side: 32 blocks at a time against every query slice, the block scores summed over the
+ // heads of a selection head into `scores` ([tile token, selection head, block]).
+ template <typename Source>
+ void score_key_chunks(const Context<Source>& ctx,
+ const ThreadScratch& thread,
+ size_t b,
+ size_t key_chunk_begin,
+ size_t key_chunk_end,
+ const QuerySlice* q_slices,
+ size_t q_slice_count,
+ float* scores) const {
+ using T = typename Source::Element;
+ const auto key_total_blocks = static_cast<size_t>(ctx.source.blocks(b));
+ // Every slice has tokens_per_call tokens but the last, which may have fewer: the item has multi-token slices
+ // (q.k, they use the packed blocks) iff its first slice is one.
+ const bool has_multi_token_slice = !q_slices[0].is_single_token;
+ AmxTileState amx_tiles;
+ for (size_t key_chunk = key_chunk_begin; key_chunk < key_chunk_end; key_chunk++) {
+ const size_t key_first_block = key_chunk * kScoreBlockRows;
+ // the chunks of an item end where its last token's blocks end, so the last slice sees every one of them
+ const size_t key_chunk_blocks = std::min(kScoreBlockRows, key_total_blocks - key_first_block);
+ for (size_t key_head = 0; key_head < m_config.index_key_heads; key_head++) {
+ const size_t sel_head = (key_head * m_config.selection_heads) / m_config.index_key_heads;
+ // the first K head of a selection head writes its scores, the others add
+ const bool first_key_head_of_sel =
+ key_head ==
+ (sel_head * m_config.index_key_heads + m_config.selection_heads - 1) / m_config.selection_heads;
+ // the 32 blocks of the chunk; the last chunk of the row may have fewer, and a source whose cache is
+ // paged may have to gather them
+ const T* const blocks = ctx.source.block_rows(b,
+ key_head,
+ key_first_block,
+ key_chunk_blocks,
+ reinterpret_cast<T*>(thread.key_chunk_stage));
+ if (has_multi_token_slice) {
+ // the blocks are the B matrix of the multi-token slices: packed once for all of them
+ m_q_k_kernel->copy_buffer_b(const_cast<T*>(blocks), thread.packed_blocks);
+ }
+ for (size_t q_slice_idx = 0; q_slice_idx < q_slice_count; q_slice_idx++) {
+ const auto& q_slice = q_slices[q_slice_idx];
+ if (static_cast<int64_t>(key_first_block) >= q_slice.blocks) {
+ continue; // no token of the slice sees these blocks
+ }
+ // the scores of the first token of the slice in `scores`
+ float* const score_out = scores +
+ (q_slice_idx * m_tokens_per_call * m_config.selection_heads + sel_head) *
+ ctx.plan.score_stride +
+ key_first_block;
+ if (q_slice.is_single_token) {
+ score_k_q_slice(thread, q_slice, blocks, key_head, first_key_head_of_sel, score_out, amx_tiles);
+ } else {
+ score_q_k_slice<T>(thread,
+ q_slice,
+ key_head,
+ first_key_head_of_sel,
+ score_out,
+ ctx.plan.score_stride,
+ amx_tiles);
+ }
+ }
+ }
+ }
+ }
+
+ // Steps 3 and 4 of a single token (k.q): gemm_scores[i, head] = max(0, blocks[i] . q_rot[head]), [32, D] x [D, G]
+ // -> [32, G]; the blocks are read in place. The score of the block i is the sum of its G consecutive values (the
+ // ReLU is a post-op of the brgemm).
+ template <typename T>
+ void score_k_q_slice(const ThreadScratch& thread,
+ const QuerySlice& q_slice,
+ const T* blocks,
+ size_t key_head,
+ bool first_key_head_of_sel,
+ float* score_out,
+ AmxTileState& amx_tiles) const {
+ q_slice.kernel->executeGemm(false,
+ const_cast<T*>(blocks),
+ thread.packed_query + key_head * m_packed_query_bytes,
+ thread.gemm_scores,
+ nullptr,
+ nullptr,
+ thread.workspace,
+ thread.scratch_a,
+ amx_tiles);
+ for (size_t i = 0; i < kScoreBlockRows; i++) {
+ const float* const row = thread.gemm_scores + i * m_heads_per_key;
+ float sum = 0.0F;
+ for (size_t g = 0; g < m_heads_per_key; g++) {
+ sum += row[g];
+ }
+ score_out[i] = first_key_head_of_sel ? sum * m_config.scale : score_out[i] + sum * m_config.scale;
+ }
+ }
+
+ // Steps 3 and 4 of several tokens (q.k), the blocks packed in thread.packed_blocks:
+ // gemm_scores[row, i] = max(0, q_rot[row] . blocks[i]), [query_rows, D] x [D, 32] -> [query_rows, 32]; the rows
+ // come in blocks of 32 and a tail.
+ template <typename T>
+ void score_q_k_slice(const ThreadScratch& thread,
+ const QuerySlice& q_slice,
+ size_t key_head,
+ bool first_key_head_of_sel,
+ float* score_out,
+ size_t score_stride,
+ AmxTileState& amx_tiles) const {
+ const size_t dim = m_config.dim;
+ const auto* const query = reinterpret_cast<const T*>(q_slice.query) + key_head * q_slice.query_rows * dim;
+ const size_t full_row_tiles = q_slice.query_rows / kScoreBlockRows;
+ for (size_t row_tile = 0; row_tile < full_row_tiles; row_tile++) {
+ q_slice.kernel->executeGemm(false,
+ const_cast<T*>(query) + row_tile * kScoreBlockRows * dim,
+ thread.packed_blocks,
+ thread.gemm_scores + row_tile * kScoreBlockRows * kScoreBlockRows,
+ nullptr,
+ nullptr,
+ thread.workspace,
+ thread.scratch_a,
+ amx_tiles);
+ }
+ if (q_slice.query_rows % kScoreBlockRows != 0) {
+ q_slice.kernel->executeGemm(true,
+ const_cast<T*>(query) + full_row_tiles * kScoreBlockRows * dim,
+ thread.packed_blocks,
+ thread.gemm_scores + full_row_tiles * kScoreBlockRows * kScoreBlockRows,
+ nullptr,
+ nullptr,
+ thread.workspace,
+ thread.scratch_a,
+ amx_tiles);
+ }
+ // step 4: for the token t, sum[i] = sum over the G heads of the K head of gemm_scores[head, t, i] (the rows
+ // of one head are consecutive tokens); then score[token t, selection head, block] = scale * sum[i] (+ the
+ // other K heads of the selection head). A row of the brgemm output is 32 consecutive scores of a token, as in
+ // `scores`: the rows are added and stored, no transpose. The stores of a partial last chunk reach the padding
+ // of the score row.
+ for (size_t t = 0; t < q_slice.real_tokens; t++) {
+ float sum[kScoreBlockRows];
+ std::copy_n(thread.gemm_scores + t * kScoreBlockRows, kScoreBlockRows, sum);
+ for (size_t g = 1; g < m_heads_per_key; g++) {
+ const float* const row = thread.gemm_scores + (g * q_slice.token_slots + t) * kScoreBlockRows;
+ for (size_t i = 0; i < kScoreBlockRows; i++) {
+ sum[i] += row[i];
+ }
+ }
+ float* const token_out = score_out + t * m_config.selection_heads * score_stride;
+ if (first_key_head_of_sel) {
+ for (size_t i = 0; i < kScoreBlockRows; i++) {
+ token_out[i] = sum[i] * m_config.scale;
+ }
+ } else {
+ for (size_t i = 0; i < kScoreBlockRows; i++) {
+ token_out[i] += sum[i] * m_config.scale;
+ }
+ }
+ }
+ }
+
+ static constexpr size_t kAlign = QsaBrgemm::kAlign;
+ static constexpr size_t kQuerySlicesPerItem = QsaBrgemm::kQuerySlicesPerItem;
+
+ const QsaBrgemm& m_brgemm;
+ const Config& m_config;
+ const std::shared_ptr<BrgemmKernel>& m_q_k_kernel;
+ const std::shared_ptr<BrgemmKernel>& m_k_q_kernel;
+ size_t m_heads_per_key;
+ size_t m_tokens_per_call;
+ size_t m_tile_tokens;
+ size_t m_packed_query_bytes; // the B matrix of the query tile of a K head (one token)
+ QsaBrgemm::ThreadOffsets m_offsets;
+ size_t m_select_offset; // the selection scratch follows the fixed part of a thread slice
+};
+
+} // namespace ov::Extensions::Cpu::XARCH::qsa
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/qsa_indexer_common.hpp b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/qsa_indexer_common.hpp
new file mode 100644
index 00000000000..f0593a4a3e4
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/qsa_indexer_common.hpp
@@ -0,0 +1,50 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#pragma once
+
+#include <algorithm>
+#include <cstdint>
+
+#include "onednn/iml_type_mapper.h"
+#include "openvino/runtime/system_conf.hpp"
+
+// What the dense QSAIndexer and the PagedQSAIndexer nodes share outside the cross-compiled kernels.
+namespace ov::intel_cpu::node::qsa {
+
+// The implementation type of a node that does not score on brgemm: the instruction set its cross-compiled kernel is
+// dispatched to on this CPU.
+inline impl_desc_type kernel_impl_type() {
+ if (ov::with_cpu_x86_avx512f()) {
+ return impl_desc_type::avx512;
+ }
+ return ov::with_cpu_x86_avx2() ? impl_desc_type::avx2 : impl_desc_type::ref;
+}
+
+// What one row of the batch contributes to a call of the dense QSAIndexer. Every quantity is derived from the row's
+// own key_length and the window length L of the call alone -- no cross-call running counter is kept.
+struct RowPlan {
+ int64_t num_padding; // left-padded positions of this call's window, skipped everywhere
+ int64_t current; // real tokens of this call
+ int64_t tail; // rows already sitting in the incomplete-block state
+ int64_t past_blocks; // complete blocks of the earlier calls
+ int64_t new_blocks; // blocks this call completes
+
+ // Complete blocks visible to the token `v` of this call (`v` counts the real tokens, left padding excluded).
+ [[nodiscard]] int64_t blocks_visible(int64_t v, int64_t ratio) const {
+ return past_blocks + (tail + v + 1) / ratio;
+ }
+};
+
+inline RowPlan make_row_plan(int64_t key_length, int64_t window, int64_t ratio) {
+ const int64_t past = std::max<int64_t>(0, key_length - window);
+ RowPlan plan{};
+ plan.current = key_length - past; // == min(window, key_length)
+ plan.num_padding = window - plan.current;
+ plan.tail = past % ratio;
+ plan.past_blocks = past / ratio;
+ plan.new_blocks = (plan.tail + plan.current) / ratio;
+ return plan;
+}
+
+} // namespace ov::intel_cpu::node::qsa
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/qsa_indexer_kernel.cpp b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/qsa_indexer_kernel.cpp
new file mode 100644
index 00000000000..4ad62ec4817
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/qsa_indexer_kernel.cpp
@@ -0,0 +1,452 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "qsa_indexer_kernel.hpp"
+
+#include <algorithm>
+#include <cstddef>
+#include <cstdint>
+#include <cstring>
+
+#include "cpu_parallel.hpp"
+#include "nodes/kernels/sparse_attn/qsa_kernel_utils.hpp"
+#include "openvino/core/except.hpp"
+#include "openvino/core/parallel.hpp"
+#include "openvino/core/type/bfloat16.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "openvino/core/type/float16.hpp"
+#include "utils/general_utils.h"
+#include "utils/plain_tensor.hpp"
+
+#ifdef OPENVINO_ARCH_X86_64
+# include "nodes/kernels/sparse_attn/qsa_brgemm.hpp"
+# include "nodes/kernels/sparse_attn/qsa_indexer_brgemm_kernel.hpp"
+#endif
+
+namespace ov::Extensions::Cpu::XARCH {
+
+namespace {
+
+using ov::intel_cpu::div_up;
+#ifdef OPENVINO_ARCH_X86_64
+using ov::intel_cpu::node::qsa::kScoreBlockRows;
+#endif
+using ov::intel_cpu::PlainTensor;
+using ov::intel_cpu::node::qsa::Config;
+using ov::intel_cpu::node::qsa::DensePorts;
+using ov::intel_cpu::node::qsa::DenseScratchLayout;
+using ov::intel_cpu::node::qsa::QsaBrgemm;
+using ov::intel_cpu::node::qsa::rope_batch;
+using ov::intel_cpu::node::qsa::row_plan;
+using ov::intel_cpu::node::qsa::RowPlan;
+using ov::intel_cpu::node::qsa::RowStats;
+using ov::intel_cpu::node::qsa::ThreadLayout;
+
+static_assert(ThreadLayout::kStageRows == qsa::kScoreRows);
+
+// The buffers of one worker thread's slice of the scratch.
+struct ThreadBuffers {
+ float* q_normed; // [H_iq, D_idx] normalized + rotated index queries (phase 1: the first row is the pooled block)
+ float* row_buf; // [D_idx] a converted row
+ float* rope_cos_sin; // [2 * rotary_dim] cos / sin of the first token of a block (phase 2: of the token)
+ float* stage; // [4, D_idx] summary rows converted to f32 (the scoring)
+ float* score_f32; // [blocks] the scores of the blocks of a token and selection head
+ qsa::BlockScore* scores; // [blocks] (score * scale, block), what the top-k selects from
+ int32_t* chosen; // [block_topk]
+};
+
+// The scratch of a call, bound to its memory.
+template <typename T>
+struct Scratch {
+ Scratch(const DensePorts& p, const DenseScratchLayout& layout, uint8_t* memory)
+ : shared(memory + layout.scorer_shared_offset),
+ threads(memory + layout.threads_offset),
+ m_layout(layout) {
+ const size_t D_idx = p.q_idx.size(3);
+ auto* const norm_weights = reinterpret_cast<float*>(memory);
+ q_norm_w = qsa::row_as_f32(p.q_norm_weight.ptr<T>(), D_idx, norm_weights);
+ k_norm_w = qsa::row_as_f32(p.k_norm_weight.ptr<T>(), D_idx, norm_weights + D_idx);
+ }
+
+ // This worker thread's slice of the scratch.
+ [[nodiscard]] ThreadBuffers thread() const {
+ const auto& t = m_layout.thread;
+ auto* const slice = threads + static_cast<size_t>(parallel_get_thread_num()) * m_layout.thread_bytes;
+ auto* const floats = reinterpret_cast<float*>(slice);
+ return {floats,
+ floats + t.row_buf_off,
+ floats + t.rope_cos_sin_off,
+ floats + t.stage_off,
+ floats + t.score_f32_off,
+ reinterpret_cast<qsa::BlockScore*>(slice + t.scores_off),
+ reinterpret_cast<int32_t*>(slice + t.chosen_off)};
+ }
+
+ const float* q_norm_w = nullptr; // f32 [D_idx] (the tensor itself when f32)
+ const float* k_norm_w = nullptr;
+ uint8_t* shared; // the brgemm scorer's scratch shared by the threads
+ uint8_t* threads; // the slices of the worker threads
+
+private:
+ const DenseScratchLayout& m_layout;
+};
+
+// The pending window of a row is [the `tail` rows of the incomplete-block state | the real tokens of this call].
+// Raw K row at pending position `pos` (a view of the tensor when it is f32, `buf` otherwise):
+template <typename T>
+const float* pending_row(const DensePorts& p, const RowPlan& plan, size_t b, size_t h, int64_t pos, float* buf) {
+ const size_t D_idx = p.q_idx.size(3);
+ if (pos < plan.tail) {
+ return qsa::row_as_f32(p.past_raw_k_in.ptr<T>(b, h, pos), D_idx, buf);
+ }
+ return qsa::row_as_f32(p.k_idx.ptr<T>(b, plan.num_padding + pos - plan.tail, h), D_idx, buf);
+}
+
+// [rope_cos, rope_sin] of the first token of the block starting at pending position `pos`, in the layout of the
+// past_incomplete_rope state:
+template <typename T>
+void get_first_token_cos_sin(const DensePorts& p,
+ const Config& c,
+ const RowPlan& plan,
+ size_t b,
+ int64_t pos,
+ float* dst) {
+ const size_t rotary_dim = c.indexer_rotary_dim;
+ if (pos < plan.tail) {
+ cvt_copy(dst, p.past_rope_in.ptr<T>(b), 1, 2 * rotary_dim, 0, 0);
+ } else {
+ const int64_t l = plan.num_padding + pos - plan.tail;
+ cvt_copy(dst, p.rope_cos.ptr<T>(rope_batch(p.rope_cos, b), l), 1, rotary_dim, 0, 0);
+ cvt_copy(dst + rotary_dim, p.rope_sin.ptr<T>(rope_batch(p.rope_sin, b), l), 1, rotary_dim, 0, 0);
+ }
+}
+
+// ---- Phase 0: the summary_cache output [B, H_ik, blocks_out, D] starts as the blocks of the earlier calls (the input
+// [B, H_ik, blocks_in, D]), followed by zeros; the selection outputs start empty (indices -1, counts 0) ----
+// The copy of a long cache is split in block ranges to use the threads (decode has a single row and head).
+template <typename T>
+void initialize_summary_cache(const DensePorts& p, const ov::intel_cpu::CpuParallel& parallel) {
+ const size_t B = p.summary_cache.size(0);
+ const size_t H_ik = p.summary_cache.size(1);
+ const size_t blocks_out = p.summary_cache.size(2);
+ const size_t blocks_in = p.summary_cache_in.size(2);
+
+ std::fill_n(p.sel_indices.ptr<int32_t>(),
+ p.sel_indices.size(0) * p.sel_indices.size(1) * p.sel_indices.size(2) * p.sel_indices.size(3),
+ -1);
+ std::fill_n(p.sel_count.ptr<int32_t>(), p.sel_count.size(0) * p.sel_count.size(1) * p.sel_count.size(2), 0);
+
+ const size_t block_bytes = p.summary_cache.size(3) * sizeof(T);
+ const size_t copy_blocks = std::min(blocks_in, blocks_out);
+ constexpr size_t kPartBytes = 256UL << 10;
+ const auto num_threads = static_cast<size_t>(ov::intel_cpu::CpuParallel::get_num_worker_threads());
+ const size_t parts = std::clamp<size_t>(div_up(blocks_out * block_bytes, kPartBytes), 1, num_threads);
+ const size_t blocks_per_part = div_up(blocks_out, parts);
+ const auto* src_base = p.summary_cache_in.ptr<uint8_t>();
+ auto* dst_base = p.summary_cache.ptr<uint8_t>();
+ parallel.parallel_for3d(B, H_ik, parts, [&](size_t b, size_t h, size_t part) {
+ const size_t begin = std::min(blocks_out, part * blocks_per_part);
+ const size_t end = std::min(blocks_out, begin + blocks_per_part);
+ auto* dst = dst_base + (b * H_ik + h) * blocks_out * block_bytes;
+ const auto* src = src_base + (b * H_ik + h) * blocks_in * block_bytes;
+ const size_t copy_end = std::min(end, copy_blocks);
+ if (begin < copy_end) {
+ std::memcpy(dst + begin * block_bytes, src + begin * block_bytes, (copy_end - begin) * block_bytes);
+ }
+ const size_t zero_begin = std::max(begin, copy_blocks);
+ if (zero_begin < end) {
+ std::memset(dst + zero_begin * block_bytes, 0, (end - zero_begin) * block_bytes);
+ }
+ });
+}
+
+// ---- Phase 1: the blocks this call completes are independent of each other. Per block (B x H_ik x new_blocks):
+// pool the mean of its `ratio` raw keys (rows [D] of the incomplete-block state or of k_idx [B, L, H_ik, D])
+// RMS pooled / sqrt(mean(pooled^2) + eps) * k_norm_weight [D]
+// RoPE the first Dr channels rotated with the cos / sin of the FIRST token of the block ([Dr] each)
+// and the result is the index key of the block: summary_cache[b, h, blk, :] ----
+template <typename T>
+void append_complete_blocks(const DensePorts& p,
+ const Config& c,
+ const RowStats& stats,
+ const Scratch<T>& scratch,
+ const ov::intel_cpu::CpuParallel& parallel) {
+ const size_t D_idx = p.q_idx.size(3);
+ const auto r = static_cast<int64_t>(c.compress_ratio);
+ parallel.parallel_for3d(
+ p.q_idx.size(0),
+ p.k_idx.size(2),
+ static_cast<size_t>(stats.max_new_blocks),
+ [&](size_t b, size_t h, size_t j) {
+ const auto plan = row_plan(p, c, b);
+ if (static_cast<int64_t>(j) >= plan.new_blocks) {
+ return;
+ }
+ const auto buf = scratch.thread();
+ float* const pooled = buf.q_normed;
+
+ const int64_t block_start = static_cast<int64_t>(j) * r;
+ std::fill_n(pooled, D_idx, 0.0F);
+ for (int64_t pos = block_start; pos < block_start + r; pos++) {
+ qsa::add_inplace(pooled, pending_row<T>(p, plan, b, h, pos, buf.row_buf), D_idx);
+ }
+ qsa::scale_inplace(pooled, 1.0F / static_cast<float>(r), D_idx);
+
+ get_first_token_cos_sin<T>(p, c, plan, b, block_start, buf.rope_cos_sin);
+ qsa::rms_rope(pooled,
+ pooled,
+ scratch.k_norm_w,
+ D_idx,
+ c.indexer_rotary_dim,
+ c.eps,
+ buf.rope_cos_sin,
+ buf.rope_cos_sin + c.indexer_rotary_dim);
+ qsa::store_row(pooled, p.summary_cache.ptr<T>(b, h, static_cast<size_t>(plan.past_blocks) + j), D_idx);
+ });
+}
+
+// ---- Phase 1b: fully overwrite the fixed-size incomplete-block state: the raw keys [B, H_ik, ratio - 1, D] of the
+// tokens after the last complete block (zero-padded) and the cos / sin [B, 2 * Dr] of the first of them ----
+template <typename T>
+void update_incomplete_block(const DensePorts& p,
+ const Config& c,
+ const Scratch<T>& scratch,
+ const ov::intel_cpu::CpuParallel& parallel) {
+ const size_t D_idx = p.q_idx.size(3);
+ const size_t H_ik = p.k_idx.size(2);
+ const auto r = static_cast<int64_t>(c.compress_ratio);
+ parallel.parallel_for(p.q_idx.size(0), [&](size_t b) {
+ const auto plan = row_plan(p, c, b);
+ const auto buf = scratch.thread();
+
+ const int64_t rest = plan.tail + plan.current - plan.new_blocks * r;
+ const int64_t rest_start = plan.new_blocks * r;
+ for (int64_t pos = 0; pos < r - 1; pos++) {
+ for (size_t h = 0; h < H_ik; h++) {
+ T* const dst = p.past_raw_k.ptr<T>(b, h, pos);
+ if (pos < rest) {
+ qsa::store_row(pending_row<T>(p, plan, b, h, rest_start + pos, buf.row_buf), dst, D_idx);
+ } else {
+ std::fill_n(dst, D_idx, T{});
+ }
+ }
+ }
+ if (rest > 0) {
+ get_first_token_cos_sin<T>(p, c, plan, b, rest_start, buf.rope_cos_sin);
+ } else {
+ std::fill_n(buf.rope_cos_sin, 2 * c.indexer_rotary_dim, 0.0F);
+ }
+ qsa::store_row(buf.rope_cos_sin, p.past_rope.ptr<T>(b), 2 * c.indexer_rotary_dim);
+ });
+}
+
+#ifdef OPENVINO_ARCH_X86_64
+// The layout of a call as the brgemm scoring sees it (see BrgemmRunner): the rows are the rows of the batch,
+// q_idx [B, L, H_iq, D], RoPE tables [1 | B, L, Dr], summary_cache [B, H_ik, NB, D] (with the blocks this call
+// completes), selection [B, H_sel, L, block_topk] / [B, H_sel, L].
+// The window of a row is left-padded: the token v of the call is at the position num_padding + v of the window.
+template <typename T>
+class DenseSource {
+public:
+ using Element = T;
+
+ DenseSource(const DensePorts& ports, const Config& config, const float* q_norm_weight)
+ : m_p(ports),
+ m_c(config),
+ m_q_norm_weight(q_norm_weight) {}
+
+ [[nodiscard]] int64_t tokens(size_t b) const {
+ return row_plan(m_p, m_c, b).current;
+ }
+ [[nodiscard]] int64_t blocks_visible(size_t b, int64_t v) const {
+ return row_plan(m_p, m_c, b).blocks_visible(v, static_cast<int64_t>(m_c.compress_ratio));
+ }
+ [[nodiscard]] int64_t blocks(size_t b) const {
+ const auto plan = row_plan(m_p, m_c, b);
+ return plan.past_blocks + plan.new_blocks;
+ }
+ [[nodiscard]] const float* query_row(size_t b, int64_t v, size_t h, float* buf) const {
+ return qsa::row_as_f32(m_p.q_idx.ptr<T>(b, position(b, v), h), m_p.q_idx.size(3), buf);
+ }
+ [[nodiscard]] const float* rope_cos(size_t b, int64_t v, float* buf) const {
+ return qsa::row_as_f32(m_p.rope_cos.ptr<T>(rope_batch(m_p.rope_cos, b), position(b, v)),
+ m_c.indexer_rotary_dim,
+ buf);
+ }
+ [[nodiscard]] const float* rope_sin(size_t b, int64_t v, float* buf) const {
+ return qsa::row_as_f32(m_p.rope_sin.ptr<T>(rope_batch(m_p.rope_sin, b), position(b, v)),
+ m_c.indexer_rotary_dim,
+ buf);
+ }
+ [[nodiscard]] const float* q_norm_weight() const {
+ return m_q_norm_weight;
+ }
+ // The blocks of a K head are contiguous in the cache: 32 of them are used in place, fewer (the end of the row) are
+ // copied into the zero-padded stage.
+ [[nodiscard]] const T* block_rows(size_t b, size_t hk, size_t first, size_t count, T* stage) const {
+ const T* rows = m_p.summary_cache.ptr<T>(b, hk, first);
+ if (count == kScoreBlockRows) {
+ return rows;
+ }
+ const size_t dim = m_p.q_idx.size(3);
+ std::copy_n(rows, count * dim, stage);
+ std::fill_n(stage + count * dim, (kScoreBlockRows - count) * dim, T{});
+ return stage;
+ }
+ [[nodiscard]] int32_t* selection_indices(size_t b, int64_t v, size_t sh) const {
+ return m_p.sel_indices.ptr<int32_t>(b, sh, position(b, v), 0);
+ }
+ [[nodiscard]] int32_t* selection_count(size_t b, int64_t v, size_t sh) const {
+ return m_p.sel_count.ptr<int32_t>(b, sh, position(b, v));
+ }
+
+private:
+ [[nodiscard]] size_t position(size_t b, int64_t v) const {
+ return static_cast<size_t>(row_plan(m_p, m_c, b).num_padding + v);
+ }
+
+ const DensePorts& m_p;
+ const Config& m_c;
+ const float* m_q_norm_weight;
+};
+
+// ---- Phase 2 on brgemm (the steps are described in qsa_indexer_brgemm_kernel.hpp) ----
+template <typename T>
+void run_brgemm_scorer(const QsaBrgemm& brgemm,
+ const DensePorts& p,
+ const Config& c,
+ const RowStats& stats,
+ const Scratch<T>& scratch,
+ const ov::intel_cpu::CpuParallel& parallel) {
+ const auto plan = brgemm.plan(p.q_idx.size(0), stats.max_current, stats.max_row_blocks);
+ const DenseSource<T> source(p, c, scratch.q_norm_w);
+ qsa::BrgemmRunner(brgemm).run(plan, source, scratch.shared, scratch.threads, parallel);
+}
+#endif
+
+// ---- Phase 2 per real token: the query RMSNorm + RoPE, then per selection head the scoring of the complete blocks
+// and the top-k ----
+template <typename T>
+void run_token_scorer(const DensePorts& p,
+ const Config& c,
+ const Scratch<T>& scratch,
+ const ov::intel_cpu::CpuParallel& parallel) {
+ const size_t D_idx = p.q_idx.size(3);
+ const size_t H_iq = p.q_idx.size(2);
+ const size_t H_ik = p.k_idx.size(2);
+ const size_t G = H_iq / H_ik; // index query heads per index key head
+ const size_t rotary_dim = c.indexer_rotary_dim;
+ const auto r = static_cast<int64_t>(c.compress_ratio);
+ const float scale = ov::intel_cpu::QSAIndexerNode::effective_scale(c);
+ parallel.parallel_for2d(p.q_idx.size(0), p.q_idx.size(1), [&](size_t b, size_t l_u) {
+ const auto plan = row_plan(p, c, b);
+ const auto l = static_cast<int64_t>(l_u);
+ if (l < plan.num_padding) {
+ return;
+ }
+ const auto buf = scratch.thread();
+ float* const rope_cos_buf = buf.rope_cos_sin;
+ float* const rope_sin_buf = rope_cos_buf + rotary_dim;
+
+ // ---- Phase 2a: per index-query head, q_idx[b, l, h, :] [D] -> RMSNorm * q_norm_weight -> RoPE of the first
+ // Dr channels with cos / sin[b, l, :] [Dr] -> q_normed[h] [D] ----
+ const float* const cos_row =
+ qsa::row_as_f32(p.rope_cos.ptr<T>(rope_batch(p.rope_cos, b), l), rotary_dim, rope_cos_buf);
+ const float* const sin_row =
+ qsa::row_as_f32(p.rope_sin.ptr<T>(rope_batch(p.rope_sin, b), l), rotary_dim, rope_sin_buf);
+ for (size_t h = 0; h < H_iq; h++) {
+ const float* const q_row = qsa::row_as_f32(p.q_idx.ptr<T>(b, l, h), D_idx, buf.row_buf);
+ qsa::rms_rope(q_row,
+ buf.q_normed + h * D_idx,
+ scratch.q_norm_w,
+ D_idx,
+ rotary_dim,
+ c.eps,
+ cos_row,
+ sin_row);
+ }
+
+ // ---- Phase 2b: per selection head sh and complete block blk visible to the token:
+ // score = scale * sum over the query heads h of sh of max(0, q_normed[h] . summary_cache[kv(h), blk])
+ // then the top-k blocks by score (ties: the lower block first) ----
+ // The complete blocks visible to this token: the earlier calls' plus those finished up to this token.
+ const int64_t n_complete = plan.blocks_visible(l - plan.num_padding, r);
+ for (size_t sh = 0; sh < c.h_sel; sh++) {
+ // The index key heads of the selection head, and so their query heads: contiguous ranges.
+ const size_t hk_begin = div_up(sh * H_ik, c.h_sel);
+ const size_t hk_end = div_up((sh + 1) * H_ik, c.h_sel);
+ size_t k = 0;
+ if (n_complete > 0) {
+ // the scores of the complete blocks, summed over the index key heads of the selection head: the
+ // blocks of a head are contiguous rows of the summary cache
+ std::fill_n(buf.score_f32, static_cast<size_t>(n_complete), 0.0F);
+ for (size_t hk = hk_begin; hk < hk_end; hk++) {
+ qsa::score_run<T>(buf.q_normed + hk * G * D_idx,
+ p.summary_cache.ptr<T>(b, hk, 0),
+ static_cast<size_t>(n_complete),
+ G,
+ D_idx,
+ buf.score_f32,
+ buf.stage);
+ }
+ for (int64_t blk = 0; blk < n_complete; blk++) {
+ buf.scores[blk] = {buf.score_f32[blk] * scale, static_cast<int32_t>(blk)};
+ }
+ k = qsa::select_topk(buf.scores,
+ buf.chosen,
+ static_cast<size_t>(n_complete),
+ c.block_topk,
+ c.order_by_score);
+ }
+
+ std::copy_n(buf.chosen, k, p.sel_indices.ptr<int32_t>(b, sh, l_u, 0));
+ *p.sel_count.ptr<int32_t>(b, sh, l_u) = static_cast<int32_t>(k);
+ }
+ });
+}
+
+// The computation of the node, T is the precision of its data ports.
+template <typename T>
+void run_indexer(const DensePorts& ports,
+ const Config& config,
+ const DenseScratchLayout& layout,
+ uint8_t* memory,
+ [[maybe_unused]] const QsaBrgemm* brgemm,
+ const ov::intel_cpu::CpuParallel& parallel) {
+ const RowStats stats = ov::intel_cpu::node::qsa::row_stats(ports, config);
+ const Scratch<T> scratch(ports, layout, memory);
+
+ initialize_summary_cache<T>(ports, parallel);
+ append_complete_blocks<T>(ports, config, stats, scratch, parallel);
+ update_incomplete_block<T>(ports, config, scratch, parallel);
+#ifdef OPENVINO_ARCH_X86_64
+ if (brgemm != nullptr) {
+ run_brgemm_scorer<T>(*brgemm, ports, config, stats, scratch, parallel);
+ return;
+ }
+#endif
+ run_token_scorer<T>(ports, config, scratch, parallel);
+}
+
+} // namespace
+
+void qsa_indexer_compute(const ov::intel_cpu::node::qsa::DensePorts& ports,
+ const ov::intel_cpu::QSAIndexerNode::Config& config,
+ const ov::intel_cpu::node::qsa::DenseScratchLayout& layout,
+ uint8_t* scratch,
+ const ov::intel_cpu::node::qsa::QsaBrgemm* brgemm,
+ const ov::intel_cpu::CpuParallelPtr& cpu_parallel) {
+ const auto precision = ports.q_idx.get_precision();
+ if (precision == ov::element::f32) {
+ run_indexer<float>(ports, config, layout, scratch, brgemm, *cpu_parallel);
+ } else if (precision == ov::element::f16) {
+ run_indexer<ov::float16>(ports, config, layout, scratch, brgemm, *cpu_parallel);
+ } else if (precision == ov::element::bf16) {
+ run_indexer<ov::bfloat16>(ports, config, layout, scratch, brgemm, *cpu_parallel);
+ } else {
+ OPENVINO_THROW("QSAIndexer: unsupported precision ", precision);
+ }
+}
+
+} // namespace ov::Extensions::Cpu::XARCH
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/qsa_indexer_kernel.hpp b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/qsa_indexer_kernel.hpp
new file mode 100644
index 00000000000..ea609f59429
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/qsa_indexer_kernel.hpp
@@ -0,0 +1,163 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+// The computation of the QSAIndexer node. One call, per row b of the batch:
+// 1. appends the window of L tokens (q_idx [B, L, H_iq, D], k_idx [B, L, H_ik, D]) to the key state: every `ratio`
+// keys complete a block, and the index key of the block (pooled keys -> RMSNorm -> partial RoPE) is stored in
+// summary_cache [B, H_ik, NB, D];
+// 2. scores, for every token of the window, the complete blocks it can see (q . index key, summed over the query
+// heads of a selection head) and keeps the block_topk best block ids: sel_indices [B, H_sel, L, block_topk],
+// sel_count [B, H_sel, L].
+// The kernel (qsa_indexer_kernel.cpp) is cross-compiled: one entry for every instruction set. This header holds what
+// the node and the kernel share: the ports, the plan of a call and the layout of its scratch.
+
+#pragma once
+
+#include <algorithm>
+#include <cstddef>
+#include <cstdint>
+#include <utility>
+#include <vector>
+
+#include "cpu_memory.h"
+#include "cpu_parallel.hpp"
+#include "nodes/kernels/sparse_attn/qsa_indexer_common.hpp"
+#include "openvino/core/except.hpp"
+#include "transformations/cpu_opset/common/op/qsa_indexer.hpp"
+#include "utils/general_utils.h"
+#include "utils/plain_tensor.hpp"
+
+namespace ov::intel_cpu::node::qsa {
+
+class QsaBrgemm; // x64 only, see qsa_brgemm.hpp
+
+using Config = ov::intel_cpu::QSAIndexerNode::Config;
+
+// The ports of the node, each taken by its own name.
+struct DensePorts {
+ using In = ov::intel_cpu::QSAIndexerNode::InputIdx;
+ using Out = ov::intel_cpu::QSAIndexerNode::OutputIdx;
+
+ DensePorts(const std::vector<MemoryPtr>& inputs, const std::vector<MemoryPtr>& outputs)
+ : q_idx(inputs.at(In::Q_IDX)),
+ k_idx(inputs.at(In::K_IDX)),
+ rope_cos(inputs.at(In::ROPE_COS)),
+ rope_sin(inputs.at(In::ROPE_SIN)),
+ key_length(inputs.at(In::KEY_LENGTH)),
+ q_norm_weight(inputs.at(In::Q_NORM_WEIGHT)),
+ k_norm_weight(inputs.at(In::K_NORM_WEIGHT)),
+ // The state inputs are read-only; the updated state lives in the matching outputs.
+ past_raw_k_in(inputs.at(In::PAST_INCOMPLETE_RAW_K)),
+ past_rope_in(inputs.at(In::PAST_INCOMPLETE_ROPE)),
+ summary_cache_in(inputs.at(In::SUMMARY_CACHE)),
+ summary_cache(outputs.at(Out::SUMMARY_CACHE)),
+ past_raw_k(outputs.at(Out::PAST_INCOMPLETE_RAW_K)),
+ past_rope(outputs.at(Out::PAST_INCOMPLETE_ROPE)),
+ sel_indices(outputs.at(Out::SEL_INDICES)),
+ sel_count(outputs.at(Out::SEL_COUNT)) {}
+
+ PlainTensor q_idx, k_idx, rope_cos, rope_sin, key_length, q_norm_weight, k_norm_weight;
+ PlainTensor past_raw_k_in, past_rope_in, summary_cache_in;
+ PlainTensor summary_cache, past_raw_k, past_rope, sel_indices, sel_count;
+};
+
+// The blocks of row b: key_length is [B] or [1] (one value shared by all the rows).
+inline RowPlan row_plan(const DensePorts& p, const Config& c, size_t b) {
+ const auto key_length = p.key_length.ptr<int32_t>()[p.key_length.size(0) == 1 ? 0 : b];
+ return make_row_plan(key_length, static_cast<int64_t>(p.q_idx.size(1)), static_cast<int64_t>(c.compress_ratio));
+}
+
+// The RoPE tables may be shared by all the batches ([1, L, Dr]): batch 0 is read for every row then.
+inline size_t rope_batch(const PlainTensor& table, size_t b) {
+ return table.size(0) == 1 ? 0 : b;
+}
+
+// What the longest row of the call needs: the largest window, the most blocks a row has after the call, the most
+// blocks it completes.
+struct RowStats {
+ int64_t max_current = 0;
+ int64_t max_row_blocks = 0;
+ int64_t max_new_blocks = 0;
+};
+
+inline RowStats row_stats(const DensePorts& p, const Config& c) {
+ RowStats stats;
+ const auto blocks_out = p.summary_cache.size(2);
+ for (size_t b = 0; b < p.q_idx.size(0); b++) {
+ const auto plan = row_plan(p, c, b);
+ OPENVINO_ASSERT(static_cast<size_t>(plan.past_blocks + plan.new_blocks) <= blocks_out,
+ "QSAIndexer: ",
+ plan.past_blocks + plan.new_blocks,
+ " blocks do not fit the summary_cache output of ",
+ blocks_out,
+ " blocks");
+ stats.max_current = std::max(stats.max_current, plan.current);
+ stats.max_row_blocks = std::max(stats.max_row_blocks, plan.past_blocks + plan.new_blocks);
+ stats.max_new_blocks = std::max(stats.max_new_blocks, plan.new_blocks);
+ }
+ return stats;
+}
+
+// The buffers of one worker thread's slice of the scratch. The phases run one after the other, so they share the
+// floats; the (score, block) pairs and the chosen ids are for the token scorer.
+struct ThreadLayout {
+ size_t row_buf_off; // floats: [D_idx] a converted row (after the [H_iq, D_idx] normalized queries)
+ size_t rope_cos_sin_off; // floats: [2 * rotary_dim] cos / sin of the first token of a block (of the token)
+ size_t stage_off; // floats: [kStageRows, D_idx] summary rows converted to f32 (the scoring)
+ size_t score_f32_off; // floats: [blocks] the scores of the blocks of a token and selection head
+ size_t scores_off; // bytes: [blocks] (score * scale, block), what the top-k selects from
+ size_t chosen_off; // bytes: [block_topk]
+ size_t bytes;
+
+ static constexpr size_t kAlign = 64;
+ static constexpr size_t kStageRows = 4; // the rows the scoring converts at a time (qsa::kScoreRows)
+
+ ThreadLayout(size_t H_iq, size_t D_idx, size_t rotary_dim, size_t max_blocks, size_t block_topk)
+ : row_buf_off(H_iq * D_idx),
+ rope_cos_sin_off(row_buf_off + D_idx),
+ stage_off(rope_cos_sin_off + 2 * rotary_dim),
+ score_f32_off(stage_off + kStageRows * D_idx),
+ scores_off(rnd_up((score_f32_off + max_blocks) * sizeof(float), kAlign)),
+ chosen_off(rnd_up(scores_off + max_blocks * sizeof(std::pair<float, int32_t>), kAlign)),
+ bytes(rnd_up(chosen_off + block_topk * sizeof(int32_t), kAlign)) {}
+};
+
+// The scratch of one call, one allocation (a second createScratchPadMem() could free the first's memory):
+// [ f32 q / k norm weights | what the brgemm scorer shares between the threads | one slice per worker thread ]
+// The scorer lays out its own slices over the same space, after the phases of the kernel have used theirs.
+struct DenseScratchLayout {
+ ThreadLayout thread;
+ size_t scorer_shared_offset;
+ size_t threads_offset;
+ size_t thread_bytes;
+ size_t total_bytes;
+
+ // `scorer_shared_bytes` / `scorer_thread_bytes`: what the brgemm scorer needs (0: there is none).
+ DenseScratchLayout(const DensePorts& p,
+ const Config& c,
+ size_t scorer_shared_bytes,
+ size_t scorer_thread_bytes,
+ size_t num_threads)
+ : thread(p.q_idx.size(2), p.q_idx.size(3), c.indexer_rotary_dim, p.summary_cache.size(2), c.block_topk),
+ scorer_shared_offset(rnd_up(2 * p.q_idx.size(3) * sizeof(float), ThreadLayout::kAlign)),
+ threads_offset(rnd_up(scorer_shared_offset + scorer_shared_bytes, ThreadLayout::kAlign)),
+ thread_bytes(std::max(thread.bytes, scorer_thread_bytes)),
+ total_bytes(threads_offset + num_threads * thread_bytes) {}
+};
+
+} // namespace ov::intel_cpu::node::qsa
+
+namespace ov::Extensions::Cpu::XARCH {
+
+// The single cross-compiled entry of the QSAIndexer node: AVX-512, AVX2 or plain C++ by the CPU. `scratch` holds
+// layout.total_bytes. `brgemm` scores the blocks on brgemm (the layout was planned for it); when it is null the kernel
+// scores them itself.
+void qsa_indexer_compute(const ov::intel_cpu::node::qsa::DensePorts& ports,
+ const ov::intel_cpu::QSAIndexerNode::Config& config,
+ const ov::intel_cpu::node::qsa::DenseScratchLayout& layout,
+ uint8_t* scratch,
+ const ov::intel_cpu::node::qsa::QsaBrgemm* brgemm,
+ const ov::intel_cpu::CpuParallelPtr& cpu_parallel);
+
+} // namespace ov::Extensions::Cpu::XARCH
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/qsa_kernel_utils.hpp b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/qsa_kernel_utils.hpp
new file mode 100644
index 00000000000..ef141e1d9a1
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/qsa_kernel_utils.hpp
@@ -0,0 +1,487 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#pragma once
+
+// The row arithmetic and the block selection of the QSAIndexer and PagedQSAIndexer kernels. It is included by
+// cross-compiled sources only, so the functions are compiled once per instruction set (AVX-512, AVX2, plain C++) in
+// the namespace XARCH. One source serves all of them: `vfloat` is a vector of `kLanes` floats (16 / 8 / 1), and the
+// same loops run on every set.
+
+#include <algorithm>
+#include <bitset>
+#include <cmath>
+#include <cstddef>
+#include <cstdint>
+#include <type_traits>
+#include <utility>
+
+#include "nodes/kernels/scaled_attn/common.hpp"
+#include "openvino/core/type/bfloat16.hpp"
+#include "openvino/core/type/float16.hpp"
+
+namespace ov::Extensions::Cpu::XARCH::qsa {
+
+#if defined(HAVE_AVX512F)
+
+using vfloat = __m512;
+inline constexpr size_t kLanes = 16;
+inline vfloat vzero() {
+ return _mm512_setzero_ps();
+}
+inline vfloat vset1(float x) {
+ return _mm512_set1_ps(x);
+}
+inline vfloat vload(const float* p) {
+ return _mm512_loadu_ps(p);
+}
+inline void vstore(float* p, vfloat v) {
+ _mm512_storeu_ps(p, v);
+}
+inline vfloat vadd(vfloat a, vfloat b) {
+ return _mm512_add_ps(a, b);
+}
+inline vfloat vsub(vfloat a, vfloat b) {
+ return _mm512_sub_ps(a, b);
+}
+inline vfloat vmul(vfloat a, vfloat b) {
+ return _mm512_mul_ps(a, b);
+}
+inline vfloat vfma(vfloat a, vfloat b, vfloat c) { // a * b + c
+ return _mm512_fmadd_ps(a, b, c);
+}
+inline float vsum(vfloat v) {
+ return _mm512_reduce_add_ps(v);
+}
+// The first n < kLanes lanes of a row; the other lanes are zero / not stored.
+inline vfloat vload_tail(const float* p, size_t n) {
+ return _mm512_maskz_loadu_ps(static_cast<__mmask16>((1U << n) - 1U), p);
+}
+inline void vstore_tail(float* p, vfloat v, size_t n) {
+ _mm512_mask_storeu_ps(p, static_cast<__mmask16>((1U << n) - 1U), v);
+}
+// Selection primitives: lanewise minimum / maximum, their reduction, comparison masks (bit l = lane l), the bucket of
+// each score (see select_top_blocks) and the compaction of the lanes of a mask.
+inline vfloat vmin(vfloat a, vfloat b) {
+ return _mm512_min_ps(a, b);
+}
+inline vfloat vmax(vfloat a, vfloat b) {
+ return _mm512_max_ps(a, b);
+}
+inline float vreduce_min(vfloat v) {
+ return _mm512_reduce_min_ps(v);
+}
+inline float vreduce_max(vfloat v) {
+ return _mm512_reduce_max_ps(v);
+}
+inline uint32_t vcmp_gt(vfloat a, vfloat b) {
+ return _mm512_cmp_ps_mask(a, b, _CMP_GT_OQ);
+}
+inline uint32_t vcmp_eq(vfloat a, vfloat b) {
+ return _mm512_cmp_ps_mask(a, b, _CMP_EQ_OQ);
+}
+// int(min(max_bucket, trunc((v - low) * to_bucket))) of every lane
+inline __m512i vbucket(vfloat v, vfloat low, vfloat to_bucket, int32_t max_bucket) {
+ const __m512i bucket = _mm512_cvttps_epi32(_mm512_mul_ps(_mm512_sub_ps(v, low), to_bucket));
+ return _mm512_min_epi32(bucket, _mm512_set1_epi32(max_bucket));
+}
+inline void vstore_buckets(vfloat v, vfloat low, vfloat to_bucket, int32_t max_bucket, int32_t* out) {
+ _mm512_storeu_si512(out, vbucket(v, low, to_bucket, max_bucket));
+}
+inline uint32_t vbucket_mask(vfloat v, vfloat low, vfloat to_bucket, int32_t max_bucket, int32_t wanted) {
+ return _mm512_cmpeq_epi32_mask(vbucket(v, low, to_bucket, max_bucket), _mm512_set1_epi32(wanted));
+}
+// Stores the lanes of `v` selected by `mask` one after the other to dst (nothing else is written), returns how many.
+inline size_t vcompress_store(float* dst, vfloat v, uint32_t mask) {
+ _mm512_mask_compressstoreu_ps(dst, static_cast<__mmask16>(mask), v);
+ return std::bitset<32>(mask).count();
+}
+// The same for the ids base, base + 1, ... of the lanes.
+inline size_t vcompress_ids(int32_t* dst, int32_t base, uint32_t mask) {
+ const __m512i ids = _mm512_add_epi32(_mm512_set1_epi32(base),
+ _mm512_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15));
+ _mm512_mask_compressstoreu_epi32(dst, static_cast<__mmask16>(mask), ids);
+ return std::bitset<32>(mask).count();
+}
+
+#elif defined(HAVE_AVX2)
+
+using vfloat = __m256;
+inline constexpr size_t kLanes = 8;
+inline vfloat vzero() {
+ return _mm256_setzero_ps();
+}
+inline vfloat vset1(float x) {
+ return _mm256_set1_ps(x);
+}
+inline vfloat vload(const float* p) {
+ return _mm256_loadu_ps(p);
+}
+inline void vstore(float* p, vfloat v) {
+ _mm256_storeu_ps(p, v);
+}
+inline vfloat vadd(vfloat a, vfloat b) {
+ return _mm256_add_ps(a, b);
+}
+inline vfloat vsub(vfloat a, vfloat b) {
+ return _mm256_sub_ps(a, b);
+}
+inline vfloat vmul(vfloat a, vfloat b) {
+ return _mm256_mul_ps(a, b);
+}
+inline vfloat vfma(vfloat a, vfloat b, vfloat c) { // a * b + c
+ return _mm256_fmadd_ps(a, b, c);
+}
+inline float vsum(vfloat v) {
+ __m128 sum = _mm_add_ps(_mm256_castps256_ps128(v), _mm256_extractf128_ps(v, 1));
+ sum = _mm_hadd_ps(sum, sum);
+ sum = _mm_hadd_ps(sum, sum);
+ return _mm_cvtss_f32(sum);
+}
+inline vfloat vload_tail(const float* p, size_t n) {
+ return _mm256_maskload_ps(p, get_mask(static_cast<int>(n)));
+}
+inline void vstore_tail(float* p, vfloat v, size_t n) {
+ _mm256_maskstore_ps(p, get_mask(static_cast<int>(n)), v);
+}
+// Selection primitives: lanewise minimum / maximum, their reduction, comparison masks (bit l = lane l), the bucket of
+// each score (see select_top_blocks) and the compaction of the lanes of a mask.
+inline vfloat vmin(vfloat a, vfloat b) {
+ return _mm256_min_ps(a, b);
+}
+inline vfloat vmax(vfloat a, vfloat b) {
+ return _mm256_max_ps(a, b);
+}
+inline float vreduce_min(vfloat v) {
+ __m128 m = _mm_min_ps(_mm256_castps256_ps128(v), _mm256_extractf128_ps(v, 1));
+ m = _mm_min_ps(m, _mm_movehl_ps(m, m));
+ m = _mm_min_ss(m, _mm_shuffle_ps(m, m, 1));
+ return _mm_cvtss_f32(m);
+}
+inline float vreduce_max(vfloat v) {
+ __m128 m = _mm_max_ps(_mm256_castps256_ps128(v), _mm256_extractf128_ps(v, 1));
+ m = _mm_max_ps(m, _mm_movehl_ps(m, m));
+ m = _mm_max_ss(m, _mm_shuffle_ps(m, m, 1));
+ return _mm_cvtss_f32(m);
+}
+inline uint32_t vcmp_gt(vfloat a, vfloat b) {
+ return static_cast<uint32_t>(_mm256_movemask_ps(_mm256_cmp_ps(a, b, _CMP_GT_OQ)));
+}
+inline uint32_t vcmp_eq(vfloat a, vfloat b) {
+ return static_cast<uint32_t>(_mm256_movemask_ps(_mm256_cmp_ps(a, b, _CMP_EQ_OQ)));
+}
+// int(min(max_bucket, trunc((v - low) * to_bucket))) of every lane
+inline __m256i vbucket(vfloat v, vfloat low, vfloat to_bucket, int32_t max_bucket) {
+ const __m256i bucket = _mm256_cvttps_epi32(_mm256_mul_ps(_mm256_sub_ps(v, low), to_bucket));
+ return _mm256_min_epi32(bucket, _mm256_set1_epi32(max_bucket));
+}
+inline void vstore_buckets(vfloat v, vfloat low, vfloat to_bucket, int32_t max_bucket, int32_t* out) {
+ _mm256_storeu_si256(reinterpret_cast<__m256i*>(out), vbucket(v, low, to_bucket, max_bucket));
+}
+inline uint32_t vbucket_mask(vfloat v, vfloat low, vfloat to_bucket, int32_t max_bucket, int32_t wanted) {
+ const __m256i equal = _mm256_cmpeq_epi32(vbucket(v, low, to_bucket, max_bucket), _mm256_set1_epi32(wanted));
+ return static_cast<uint32_t>(_mm256_movemask_ps(_mm256_castsi256_ps(equal)));
+}
+
+#else
+
+using vfloat = float;
+inline constexpr size_t kLanes = 1;
+inline vfloat vzero() {
+ return 0.0F;
+}
+inline vfloat vset1(float x) {
+ return x;
+}
+inline vfloat vload(const float* p) {
+ return *p;
+}
+inline void vstore(float* p, vfloat v) {
+ *p = v;
+}
+inline vfloat vadd(vfloat a, vfloat b) {
+ return a + b;
+}
+inline vfloat vsub(vfloat a, vfloat b) {
+ return a - b;
+}
+inline vfloat vmul(vfloat a, vfloat b) {
+ return a * b;
+}
+inline vfloat vfma(vfloat a, vfloat b, vfloat c) {
+ return a * b + c;
+}
+inline float vsum(vfloat v) {
+ return v;
+}
+// A single lane has no tail: these are never reached.
+inline vfloat vload_tail(const float* p, size_t /*n*/) {
+ return *p;
+}
+inline void vstore_tail(float* p, vfloat v, size_t /*n*/) {
+ *p = v;
+}
+// Selection primitives: lanewise minimum / maximum, their reduction, comparison masks (bit l = lane l), the bucket of
+// each score (see select_top_blocks) and the compaction of the lanes of a mask.
+inline vfloat vmin(vfloat a, vfloat b) {
+ return std::min(a, b);
+}
+inline vfloat vmax(vfloat a, vfloat b) {
+ return std::max(a, b);
+}
+inline float vreduce_min(vfloat v) {
+ return v;
+}
+inline float vreduce_max(vfloat v) {
+ return v;
+}
+inline uint32_t vcmp_gt(vfloat a, vfloat b) {
+ return a > b ? 1U : 0U;
+}
+inline uint32_t vcmp_eq(vfloat a, vfloat b) {
+ return a == b ? 1U : 0U;
+}
+inline int32_t vbucket_one(float v, float low, float to_bucket, int32_t max_bucket) {
+ return std::min(max_bucket, static_cast<int32_t>((v - low) * to_bucket));
+}
+inline void vstore_buckets(vfloat v, vfloat low, vfloat to_bucket, int32_t max_bucket, int32_t* out) {
+ out[0] = vbucket_one(v, low, to_bucket, max_bucket);
+}
+inline uint32_t vbucket_mask(vfloat v, vfloat low, vfloat to_bucket, int32_t max_bucket, int32_t wanted) {
+ return vbucket_one(v, low, to_bucket, max_bucket) == wanted ? 1U : 0U;
+}
+
+#endif
+
+#if !defined(HAVE_AVX512F)
+// Compaction without a compress instruction: every lane is stored at the write position, which advances only for the
+// selected ones (branch-free; the position past the last selected lane is written too, so dst needs one spare slot).
+inline size_t vcompress_store(float* dst, vfloat v, uint32_t mask) {
+ alignas(64) float lanes[kLanes];
+ vstore(lanes, v);
+ size_t count = 0;
+ for (size_t lane = 0; lane < kLanes; lane++) {
+ dst[count] = lanes[lane];
+ count += (mask >> lane) & 1U;
+ }
+ return count;
+}
+inline size_t vcompress_ids(int32_t* dst, int32_t base, uint32_t mask) {
+ size_t count = 0;
+ for (size_t lane = 0; lane < kLanes; lane++) {
+ dst[count] = base + static_cast<int32_t>(lane);
+ count += (mask >> lane) & 1U;
+ }
+ return count;
+}
+#endif
+
+// ---- rows of the summary / key / query tensors: f32, f16 or bf16 in memory, f32 in the registers ----
+
+// Read-only f32 view of a row of `n` values: the row itself for f32, otherwise the row converted into `buf`.
+template <typename T>
+const float* row_as_f32(const T* src, size_t n, float* buf) {
+ if constexpr (std::is_same_v<T, float>) {
+ return src;
+ } else {
+ cvt_copy(buf, src, 1, n, 0, 0);
+ return buf;
+ }
+}
+
+// dst[0, n) = src[0, n) rounded to T.
+template <typename T>
+void store_row(const float* src, T* dst, size_t n) {
+ cvt_copy(dst, src, 1, n, 0, 0);
+}
+
+// ---- row arithmetic ----
+
+// sum of x[i]^2
+inline float sum_squares(const float* x, size_t n) {
+ vfloat acc0 = vzero();
+ vfloat acc1 = vzero();
+ size_t i = 0;
+ for (; i + 2 * kLanes <= n; i += 2 * kLanes) {
+ const vfloat v0 = vload(x + i);
+ const vfloat v1 = vload(x + i + kLanes);
+ acc0 = vfma(v0, v0, acc0);
+ acc1 = vfma(v1, v1, acc1);
+ }
+ if (i + kLanes <= n) {
+ const vfloat v0 = vload(x + i);
+ acc0 = vfma(v0, v0, acc0);
+ i += kLanes;
+ }
+ if (i < n) {
+ const vfloat v0 = vload_tail(x + i, n - i);
+ acc1 = vfma(v0, v0, acc1);
+ }
+ return vsum(vadd(acc0, acc1));
+}
+
+// dst[i] += src[i]
+inline void add_inplace(float* dst, const float* src, size_t n) {
+ size_t i = 0;
+ for (; i + kLanes <= n; i += kLanes) {
+ vstore(dst + i, vadd(vload(dst + i), vload(src + i)));
+ }
+ if (i < n) {
+ vstore_tail(dst + i, vadd(vload_tail(dst + i, n - i), vload_tail(src + i, n - i)), n - i);
+ }
+}
+
+// x[i] *= factor
+inline void scale_inplace(float* x, float factor, size_t n) {
+ const vfloat vfactor = vset1(factor);
+ size_t i = 0;
+ for (; i + kLanes <= n; i += kLanes) {
+ vstore(x + i, vmul(vload(x + i), vfactor));
+ }
+ if (i < n) {
+ vstore_tail(x + i, vmul(vload_tail(x + i, n - i), vfactor), n - i);
+ }
+}
+
+// One row of D = `dim` channels in, one row out (src [dim], weight [dim], cos / sin [rotary_dim], dst [dim]):
+// 1. RMSNorm y = src / sqrt(mean(src^2) + eps) * weight
+// 2. RoPE the split-half (rotate-half) RoPE of HF Transformers over the first `rotary_dim` channels of y:
+// y_rot = y * cos + rotate_half(y) * sin, with rotate_half(y) = concat(-y[half:], y[:half]);
+// the remaining dim - rotary_dim channels are kept as they are.
+// cos / sin are already duplicated across the two halves (new_spec/qsa-prepare-17.rst). `dst` may be `src`.
+inline void rms_rope(const float* src,
+ float* dst,
+ const float* weight,
+ size_t dim,
+ size_t rotary_dim,
+ float eps,
+ const float* cos,
+ const float* sin) {
+ const float inv_rms = 1.0F / std::sqrt(sum_squares(src, dim) / static_cast<float>(dim) + eps);
+ const vfloat vinv = vset1(inv_rms);
+ size_t d = 0;
+ for (; d + kLanes <= dim; d += kLanes) {
+ vstore(dst + d, vmul(vmul(vload(src + d), vinv), vload(weight + d)));
+ }
+ if (d < dim) {
+ const size_t rest = dim - d;
+ vstore_tail(dst + d, vmul(vmul(vload_tail(src + d, rest), vinv), vload_tail(weight + d, rest)), rest);
+ }
+
+ // the pair of channels (j, j + half) is rotated by the angle of the channel j
+ const size_t half = rotary_dim / 2;
+ size_t j = 0;
+ for (; j + kLanes <= half; j += kLanes) {
+ const vfloat x0 = vload(dst + j);
+ const vfloat x1 = vload(dst + j + half);
+ vstore(dst + j, vsub(vmul(x0, vload(cos + j)), vmul(x1, vload(sin + j))));
+ vstore(dst + j + half, vadd(vmul(x1, vload(cos + j + half)), vmul(x0, vload(sin + j + half))));
+ }
+ if (j < half) {
+ const size_t rest = half - j;
+ const vfloat x0 = vload_tail(dst + j, rest);
+ const vfloat x1 = vload_tail(dst + j + half, rest);
+ vstore_tail(dst + j, vsub(vmul(x0, vload_tail(cos + j, rest)), vmul(x1, vload_tail(sin + j, rest))), rest);
+ vstore_tail(dst + j + half,
+ vadd(vmul(x1, vload_tail(cos + j + half, rest)), vmul(x0, vload_tail(sin + j + half, rest))),
+ rest);
+ }
+}
+
+// ---- block scores ----
+
+// The rows the scoring handles together: each loaded chunk of a query head is used by all of them, and their
+// accumulators are independent chains (the FMA latency would otherwise bound the loop).
+inline constexpr size_t kScoreRows = 4;
+
+// scores[i] += sum over the G query heads h of max(0, q[h] . row[i]) for R rows of D f32 channels (`row[r]` is the
+// row r), q [G, D] f32.
+template <size_t R>
+void score_rows(const float* q, const float* const* row, size_t G, size_t D, float* scores) {
+ float sum[R] = {};
+ for (size_t h = 0; h < G; h++) {
+ const float* const qh = q + h * D;
+ vfloat acc[R][2];
+ for (size_t r = 0; r < R; r++) {
+ acc[r][0] = vzero();
+ acc[r][1] = vzero();
+ }
+ size_t d = 0;
+ for (; d + 2 * kLanes <= D; d += 2 * kLanes) {
+ const vfloat q0 = vload(qh + d);
+ const vfloat q1 = vload(qh + d + kLanes);
+ for (size_t r = 0; r < R; r++) {
+ acc[r][0] = vfma(q0, vload(row[r] + d), acc[r][0]);
+ acc[r][1] = vfma(q1, vload(row[r] + d + kLanes), acc[r][1]);
+ }
+ }
+ for (; d + kLanes <= D; d += kLanes) {
+ const vfloat q0 = vload(qh + d);
+ for (size_t r = 0; r < R; r++) {
+ acc[r][0] = vfma(q0, vload(row[r] + d), acc[r][0]);
+ }
+ }
+ if (d < D) {
+ const vfloat q0 = vload_tail(qh + d, D - d);
+ for (size_t r = 0; r < R; r++) {
+ acc[r][0] = vfma(q0, vload_tail(row[r] + d, D - d), acc[r][0]);
+ }
+ }
+ for (size_t r = 0; r < R; r++) {
+ sum[r] += std::max(0.0F, vsum(vadd(acc[r][0], acc[r][1])));
+ }
+ }
+ for (size_t r = 0; r < R; r++) {
+ scores[r] += sum[r];
+ }
+}
+
+// scores[i] += sum over the G query heads h of max(0, q[h] . rows[i]), for the n summary rows ([n, D] of the type T)
+// of one index key head and its G query heads q ([G, D] f32). The rows are converted to f32 once (they are shared by
+// the heads) into `stage`, kScoreRows * D floats (not touched for f32 rows).
+template <typename T>
+void score_run(const float* q, const T* rows, size_t n, size_t G, size_t D, float* scores, float* stage) {
+ size_t i = 0;
+ for (; i + kScoreRows <= n; i += kScoreRows) {
+ const float* row[kScoreRows];
+ for (size_t r = 0; r < kScoreRows; r++) {
+ row[r] = row_as_f32(rows + (i + r) * D, D, stage + r * D);
+ }
+ score_rows<kScoreRows>(q, row, G, D, scores + i);
+ }
+ for (; i < n; i++) {
+ const float* const row = row_as_f32(rows + i * D, D, stage);
+ score_rows<1>(q, &row, G, D, scores + i);
+ }
+}
+
+// ---- block selection ----
+
+// The (score, block id) of a complete block.
+using BlockScore = std::pair<float, int32_t>;
+
+// Writes the ids of the k = min(block_topk, num_blocks) blocks of the highest scores[0, num_blocks) to `chosen` and
+// returns k. Equal scores: the lower block id wins. The blocks are in ascending id order, or in descending score order
+// (equal scores: the lower id first) with order_by_score. `scores` is reordered.
+inline size_t select_topk(BlockScore* scores,
+ int32_t* chosen,
+ size_t num_blocks,
+ size_t block_topk,
+ bool order_by_score) {
+ const size_t k = std::min(block_topk, num_blocks);
+ std::partial_sort(scores, scores + k, scores + num_blocks, [](const BlockScore& lhs, const BlockScore& rhs) {
+ if (lhs.first != rhs.first) {
+ return lhs.first > rhs.first;
+ }
+ return lhs.second < rhs.second;
+ });
+ for (size_t i = 0; i < k; i++) {
+ chosen[i] = scores[i].second;
+ }
+ if (!order_by_score) {
+ std::sort(chosen, chosen + k);
+ }
+ return k;
+}
+
+} // namespace ov::Extensions::Cpu::XARCH::qsa
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_attn_kernel.hpp b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_attn_kernel.hpp
new file mode 100644
index 00000000000..61c8576ea64
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_attn_kernel.hpp
@@ -0,0 +1,314 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#pragma once
+
+// SIMD (no AMX) products of the query heads of one GQA group with a run of key / value rows. The heads share the K/V
+// rows, so each row is converted once for all of them. AVX512 tiles four heads (AVX2: two); leftovers use
+// dot_product_block / attn_acc_value_block.
+//
+// qk_scores_gqa: scores[head, r] = q[head] . keys[r]
+// pv_accumulate_gqa: acc[head, :] += sum_r weights[head, r] * values[r, :]
+
+#include <cstddef>
+
+#include "nodes/kernels/scaled_attn/common.hpp"
+#include "nodes/kernels/scaled_attn/paged_attn_kernel.hpp"
+#include "openvino/core/type/bfloat16.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "openvino/core/type/float16.hpp"
+#include "utils/plain_tensor.hpp"
+
+namespace ov::Extensions::Cpu::XARCH {
+
+// Calls f(T{}) with the C++ type of the floating-point precision `prec` (f32 unless bf16 / f16).
+template <typename F>
+void visit_float_type(ov::element::Type prec, const F& f) {
+ if (prec == ov::element::bf16) {
+ f(ov::bfloat16{});
+ } else if (prec == ov::element::f16) {
+ f(ov::float16{});
+ } else {
+ f(float{});
+ }
+}
+
+// scores[head * score_stride + r] = q[head, :] . keys[r, :] for head < num_q_heads, r < rows.
+// q: f32 [num_q_heads, head_size]; keys: [rows, head_size] contiguous. The block kernels of paged_attn_kernel.hpp take
+// non-const pointers but only read them, hence the const_casts below.
+template <typename T>
+inline void qk_scores_gqa(const float* q,
+ size_t num_q_heads,
+ size_t head_size,
+ const T* keys,
+ size_t rows,
+ float* scores,
+ size_t score_stride) {
+ constexpr auto prec = ov::intel_cpu::precision_of<T>::value;
+ size_t h = 0;
+#if defined(HAVE_AVX512F)
+ // 4 heads x 4 rows: 16 independent accumulators, a key vector is loaded and converted once for the 4 heads
+ for (; h + 4 <= num_q_heads; h += 4) {
+ const float* q0 = q + h * head_size;
+ const float* q1 = q0 + head_size;
+ const float* q2 = q1 + head_size;
+ const float* q3 = q2 + head_size;
+ float* s0 = scores + h * score_stride;
+ size_t r = 0;
+ for (; r + 4 <= rows; r += 4) {
+ const T* k0 = keys + r * head_size;
+ const T* k1 = k0 + head_size;
+ const T* k2 = k1 + head_size;
+ const T* k3 = k2 + head_size;
+ __m512 acc[4][4];
+ for (size_t i = 0; i < 4; i++) {
+ for (size_t j = 0; j < 4; j++) {
+ acc[i][j] = _mm512_setzero_ps();
+ }
+ }
+ size_t d = 0;
+ for (; d + vec_len_f32_avx512 <= head_size; d += vec_len_f32_avx512) {
+ const __m512 key[4] = {mm512_uni_loadu_ps(k0 + d),
+ mm512_uni_loadu_ps(k1 + d),
+ mm512_uni_loadu_ps(k2 + d),
+ mm512_uni_loadu_ps(k3 + d)};
+ const __m512 query[4] = {_mm512_loadu_ps(q0 + d),
+ _mm512_loadu_ps(q1 + d),
+ _mm512_loadu_ps(q2 + d),
+ _mm512_loadu_ps(q3 + d)};
+ for (size_t i = 0; i < 4; i++) {
+ for (size_t j = 0; j < 4; j++) {
+ acc[i][j] = _mm512_fmadd_ps(key[j], query[i], acc[i][j]);
+ }
+ }
+ }
+ for (size_t i = 0; i < 4; i++) {
+ const float* qi = q0 + i * head_size;
+ for (size_t j = 0; j < 4; j++) {
+ const T* kj = keys + (r + j) * head_size;
+ float sum = _mm512_reduce_add_ps(acc[i][j]);
+ for (size_t t = d; t < head_size; t++) {
+ sum += qi[t] * static_cast<float>(kj[t]);
+ }
+ s0[i * score_stride + r + j] = sum;
+ }
+ }
+ }
+ // the rows left over
+ for (size_t i = 0; r < rows && i < 4; i++) {
+ dot_product_block<float, prec>(const_cast<float*>(q0) + i * head_size,
+ const_cast<T*>(keys) + r * head_size,
+ s0 + i * score_stride + r,
+ head_size,
+ rows - r,
+ 0);
+ }
+ }
+#elif defined(HAVE_AVX2)
+ // 2 heads x 4 rows: 8 independent accumulators (16 registers), a key vector is loaded and converted once for the 2
+ // heads
+ for (; h + 2 <= num_q_heads; h += 2) {
+ const float* q0 = q + h * head_size;
+ const float* q1 = q0 + head_size;
+ float* s0 = scores + h * score_stride;
+ size_t r = 0;
+ for (; r + 4 <= rows; r += 4) {
+ const T* k0 = keys + r * head_size;
+ const T* k1 = k0 + head_size;
+ const T* k2 = k1 + head_size;
+ const T* k3 = k2 + head_size;
+ __m256 acc[2][4];
+ for (size_t i = 0; i < 2; i++) {
+ for (size_t j = 0; j < 4; j++) {
+ acc[i][j] = _mm256_setzero_ps();
+ }
+ }
+ size_t d = 0;
+ for (; d + vec_len_f32_avx2 <= head_size; d += vec_len_f32_avx2) {
+ const __m256 key[4] = {mm256_uni_loadu_ps(k0 + d),
+ mm256_uni_loadu_ps(k1 + d),
+ mm256_uni_loadu_ps(k2 + d),
+ mm256_uni_loadu_ps(k3 + d)};
+ const __m256 query[2] = {_mm256_loadu_ps(q0 + d), _mm256_loadu_ps(q1 + d)};
+ for (size_t i = 0; i < 2; i++) {
+ for (size_t j = 0; j < 4; j++) {
+ acc[i][j] = _mm256_fmadd_ps(key[j], query[i], acc[i][j]);
+ }
+ }
+ }
+ for (size_t i = 0; i < 2; i++) {
+ const float* qi = q0 + i * head_size;
+ for (size_t j = 0; j < 4; j++) {
+ const T* kj = keys + (r + j) * head_size;
+ hsum(acc[i][j]);
+ float sum = _mm256_cvtss_f32(acc[i][j]);
+ for (size_t t = d; t < head_size; t++) {
+ sum += qi[t] * static_cast<float>(kj[t]);
+ }
+ s0[i * score_stride + r + j] = sum;
+ }
+ }
+ }
+ // the rows left over
+ for (size_t i = 0; r < rows && i < 2; i++) {
+ dot_product_block<float, prec>(const_cast<float*>(q0) + i * head_size,
+ const_cast<T*>(keys) + r * head_size,
+ s0 + i * score_stride + r,
+ head_size,
+ rows - r,
+ 0);
+ }
+ }
+#endif
+ // the heads left over, and every head without SIMD (the scalar block kernel)
+ for (; h < num_q_heads; h++) {
+ dot_product_block<float, prec>(const_cast<float*>(q) + h * head_size,
+ const_cast<T*>(keys),
+ scores + h * score_stride,
+ head_size,
+ rows,
+ 0);
+ }
+}
+
+// acc[head, :] += sum_r weights[head * weight_stride + r] * values[r, :] for head < num_q_heads, r < rows.
+// acc: f32 [num_q_heads, value_size]; values: [rows, value_size] contiguous.
+template <typename T>
+inline void pv_accumulate_gqa(float* acc,
+ size_t num_q_heads,
+ size_t value_size,
+ const float* weights,
+ size_t weight_stride,
+ const T* values,
+ size_t rows) {
+ constexpr auto prec = ov::intel_cpu::precision_of<T>::value;
+ size_t h = 0;
+#if defined(HAVE_AVX512F)
+ // 4 heads x 4 column vectors: 16 independent accumulators, a value vector is loaded and converted once for the 4
+ // heads and a weight is broadcast once for the 4 column vectors
+ for (; h + 4 <= num_q_heads; h += 4) {
+ float* a0 = acc + h * value_size;
+ const float* w0 = weights + h * weight_stride;
+ size_t d = 0;
+ for (; d + 4 * vec_len_f32_avx512 <= value_size; d += 4 * vec_len_f32_avx512) {
+ __m512 a[4][4];
+ for (size_t i = 0; i < 4; i++) {
+ for (size_t j = 0; j < 4; j++) {
+ a[i][j] = _mm512_loadu_ps(a0 + i * value_size + d + j * vec_len_f32_avx512);
+ }
+ }
+ for (size_t r = 0; r < rows; r++) {
+ const T* v = values + r * value_size + d;
+ const __m512 value[4] = {mm512_uni_loadu_ps(v),
+ mm512_uni_loadu_ps(v + vec_len_f32_avx512),
+ mm512_uni_loadu_ps(v + 2 * vec_len_f32_avx512),
+ mm512_uni_loadu_ps(v + 3 * vec_len_f32_avx512)};
+ for (size_t i = 0; i < 4; i++) {
+ const __m512 w = _mm512_set1_ps(w0[i * weight_stride + r]);
+ for (size_t j = 0; j < 4; j++) {
+ a[i][j] = _mm512_fmadd_ps(w, value[j], a[i][j]);
+ }
+ }
+ }
+ for (size_t i = 0; i < 4; i++) {
+ for (size_t j = 0; j < 4; j++) {
+ _mm512_storeu_ps(a0 + i * value_size + d + j * vec_len_f32_avx512, a[i][j]);
+ }
+ }
+ }
+ // the columns left over: one vector at a time for the 4 heads, then the last few as scalars
+ for (; d + vec_len_f32_avx512 <= value_size; d += vec_len_f32_avx512) {
+ __m512 a[4];
+ for (size_t i = 0; i < 4; i++) {
+ a[i] = _mm512_loadu_ps(a0 + i * value_size + d);
+ }
+ for (size_t r = 0; r < rows; r++) {
+ const __m512 value = mm512_uni_loadu_ps(values + r * value_size + d);
+ for (size_t i = 0; i < 4; i++) {
+ a[i] = _mm512_fmadd_ps(_mm512_set1_ps(w0[i * weight_stride + r]), value, a[i]);
+ }
+ }
+ for (size_t i = 0; i < 4; i++) {
+ _mm512_storeu_ps(a0 + i * value_size + d, a[i]);
+ }
+ }
+ for (; d < value_size; d++) {
+ for (size_t i = 0; i < 4; i++) {
+ for (size_t r = 0; r < rows; r++) {
+ a0[i * value_size + d] +=
+ w0[i * weight_stride + r] * static_cast<float>(values[r * value_size + d]);
+ }
+ }
+ }
+ }
+#elif defined(HAVE_AVX2)
+ // 2 heads x 4 column vectors: 8 independent accumulators (16 registers), a value vector is loaded and converted
+ // once for the 2 heads and a weight is broadcast once for the 4 column vectors
+ for (; h + 2 <= num_q_heads; h += 2) {
+ float* a0 = acc + h * value_size;
+ const float* w0 = weights + h * weight_stride;
+ size_t d = 0;
+ for (; d + 4 * vec_len_f32_avx2 <= value_size; d += 4 * vec_len_f32_avx2) {
+ __m256 a[2][4];
+ for (size_t i = 0; i < 2; i++) {
+ for (size_t j = 0; j < 4; j++) {
+ a[i][j] = _mm256_loadu_ps(a0 + i * value_size + d + j * vec_len_f32_avx2);
+ }
+ }
+ for (size_t r = 0; r < rows; r++) {
+ const T* v = values + r * value_size + d;
+ const __m256 value[4] = {mm256_uni_loadu_ps(v),
+ mm256_uni_loadu_ps(v + vec_len_f32_avx2),
+ mm256_uni_loadu_ps(v + 2 * vec_len_f32_avx2),
+ mm256_uni_loadu_ps(v + 3 * vec_len_f32_avx2)};
+ for (size_t i = 0; i < 2; i++) {
+ const __m256 w = _mm256_set1_ps(w0[i * weight_stride + r]);
+ for (size_t j = 0; j < 4; j++) {
+ a[i][j] = _mm256_fmadd_ps(w, value[j], a[i][j]);
+ }
+ }
+ }
+ for (size_t i = 0; i < 2; i++) {
+ for (size_t j = 0; j < 4; j++) {
+ _mm256_storeu_ps(a0 + i * value_size + d + j * vec_len_f32_avx2, a[i][j]);
+ }
+ }
+ }
+ // the columns left over: one vector at a time for the 2 heads, then the last few as scalars
+ for (; d + vec_len_f32_avx2 <= value_size; d += vec_len_f32_avx2) {
+ __m256 a[2];
+ for (size_t i = 0; i < 2; i++) {
+ a[i] = _mm256_loadu_ps(a0 + i * value_size + d);
+ }
+ for (size_t r = 0; r < rows; r++) {
+ const __m256 value = mm256_uni_loadu_ps(values + r * value_size + d);
+ for (size_t i = 0; i < 2; i++) {
+ a[i] = _mm256_fmadd_ps(_mm256_set1_ps(w0[i * weight_stride + r]), value, a[i]);
+ }
+ }
+ for (size_t i = 0; i < 2; i++) {
+ _mm256_storeu_ps(a0 + i * value_size + d, a[i]);
+ }
+ }
+ for (; d < value_size; d++) {
+ for (size_t i = 0; i < 2; i++) {
+ for (size_t r = 0; r < rows; r++) {
+ a0[i * value_size + d] +=
+ w0[i * weight_stride + r] * static_cast<float>(values[r * value_size + d]);
+ }
+ }
+ }
+ }
+#endif
+ // the heads left over, and every head without SIMD (the scalar block kernel)
+ for (; h < num_q_heads; h++) {
+ attn_acc_value_block<T, prec>(acc + h * value_size,
+ weights + h * weight_stride,
+ const_cast<T*>(values),
+ value_size,
+ rows,
+ 0);
+ }
+}
+
+} // namespace ov::Extensions::Cpu::XARCH
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_brgemm.hpp b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_brgemm.hpp
new file mode 100644
index 00000000000..f43c40d4609
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_brgemm.hpp
@@ -0,0 +1,201 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#pragma once
+
+// Shared by the nodes and the sparse attention kernels (SparsePA, SparseSDPA): the head pack, the brgemm kernels and
+// their scratch layout. The tile computation is in sparse_brgemm_kernel.hpp.
+
+// Vocabulary: head pack = query heads sharing a K/V head and a selection head (the M of the products); selected run =
+// consecutive selected blocks, gathered by one copy; gather tile = up to kGatherTileRows key rows; brgemm row block =
+// kBrgemmRowBlock rows per brgemm call.
+
+#include <algorithm>
+#include <cstddef>
+#include <memory>
+#include <numeric>
+
+#include "openvino/core/type/element_type.hpp"
+#include "utils/general_utils.h"
+
+#ifdef OPENVINO_ARCH_X86_64
+# include "nodes/kernels/x64/brgemm_kernel.hpp"
+#endif
+
+namespace ov::Extensions::Cpu {
+
+/// @brief Key rows of one brgemm call: the N of the QK kernel and the K of the P.V kernels. It is the blocking of
+/// oneDNN brgemm (N_blk and K_blk of BrgemmKernel).
+constexpr size_t kBrgemmRowBlock = 32;
+
+/// @brief Key rows of one gather tile: the most rows an item gathers before processing them (a multiple of
+/// kBrgemmRowBlock). Bounds the scratch of an item (and keeps it in cache) whatever the width of the selection.
+constexpr size_t kGatherTileRows = 128;
+
+/// @brief A decode uses the brgemm path of the head pack, not per-head SIMD items, when its selection holds at least
+/// this many K + V bytes (rows x (k + v head size) x element size): brgemm wins from about 2 MB, SIMD below 1 MB.
+constexpr size_t kBrgemmDecodeMinBytes = 3 * 512 * 1024;
+
+/// @brief Row stride of the attention weights in elements of the 16-bit data type. The weights overwrite the f32 scores
+/// in place (a row of `tile_rows` floats becomes `tile_rows` 16-bit values at the start of the same row), so the P.V
+/// kernels read rows that are `2 * tile_rows` 16-bit elements apart. See WeightLayout in sparse_brgemm_kernel.hpp.
+inline size_t weights_row_stride(size_t tile_rows) {
+ return 2 * tile_rows;
+}
+
+/// @brief Query heads that share both K/V rows and the selected blocks, so a work item can process them together:
+/// q_head_pack_size = gcd(q_heads_per_k_head, q_heads_per_sel_head) with q_heads_per_k_head = q_head_num / k_head_num
+/// and q_heads_per_sel_head = q_head_num / sel_head_num (query head h reads K head h / q_heads_per_k_head and uses
+/// selection head h / q_heads_per_sel_head). sel_head_num of 1 or k_head_num gives the whole K-head group, q_head_num
+/// gives 1.
+inline size_t max_q_head_pack_size(size_t q_head_num, size_t k_head_num, size_t sel_head_num) {
+ return std::gcd(q_head_num / k_head_num, q_head_num / sel_head_num);
+}
+
+/// @brief The brgemm kernels of the prefill path (BrgemmKernel instances owned by the node) whose M is the query-head
+/// pack. Null when the node did not build them (no AMX, data type other than bf16/f16, pack of one head).
+struct SparseBrgemm {
+ void* qk = nullptr; ///< scores[pack, row block] = query[pack, k_head_size] x keys[row block, k_head_size]^T
+ void* pv_overwrite =
+ nullptr; ///< acc[pack, v_head_size] = weights[pack, row block] x values[row block, v_head_size]
+ void* pv_accumulate = nullptr; ///< the same, accumulating into acc (beta = 1)
+ size_t tile_rows = 0; ///< rows of a gather tile (a multiple of kBrgemmRowBlock): the score row stride in floats
+ ov::element::Type prec = ov::element::dynamic; ///< bf16 / f16: the matrix input type of the kernels
+ [[nodiscard]] bool enabled() const {
+ return qk != nullptr;
+ }
+};
+
+/// @brief Scratch sizes of the brgemm kernels (bytes), used by SparseBrgemmLayout.
+struct SparseBrgemmSizes {
+ size_t tile_rows = 0; ///< 0 when the brgemm path is not used
+ size_t scratch_a = 0;
+ size_t scratch_b = 0;
+ size_t wsp = 0;
+};
+
+/// @brief Scratch the brgemm kernels of `brgemm` need per thread (zeros when the path is not used).
+inline SparseBrgemmSizes sparse_brgemm_sizes([[maybe_unused]] const SparseBrgemm& brgemm) {
+#ifdef OPENVINO_ARCH_X86_64
+ if (brgemm.enabled()) {
+ const auto* qk = static_cast<const ov::intel_cpu::BrgemmKernel*>(brgemm.qk);
+ const auto* pv = static_cast<const ov::intel_cpu::BrgemmKernel*>(brgemm.pv_overwrite);
+ return {brgemm.tile_rows,
+ std::max(qk->get_scratch_a_size(), pv->get_scratch_a_size()),
+ std::max(qk->get_scratch_b_size(), pv->get_scratch_b_size()),
+ ov::intel_cpu::BrgemmKernel::get_wsp_size()};
+ }
+#endif
+ return {};
+}
+
+/// @brief Bytes rounded up to the 64-byte alignment of the parts of a per-thread scratch block.
+inline size_t aligned(size_t bytes) {
+ constexpr size_t alignment = 64;
+ return ov::intel_cpu::div_up(bytes, alignment) * alignment;
+}
+
+/// @brief Byte layout of the state of one head pack in the per-thread scratch, shared by the SIMD and brgemm paths;
+/// every part is 64-byte aligned. `offset` is where it starts inside the thread's scratch, `total` the end of it.
+struct PackStateLayout {
+ size_t q_rows = 0; ///< data-type[pack, k_head_size]: the pack's query rows, when they are not contiguous
+ size_t acc = 0; ///< float[pack, v_head_size]: attention accumulators of the pack
+ size_t running_max = 0; ///< float[pack]: online-softmax maximum per query head
+ size_t running_sum = 0; ///< float[pack]: online-softmax sum per query head
+ size_t total = 0;
+
+ PackStateLayout() = default;
+ /// @param copy_query true when the query rows of a pack are not contiguous in the query tensor, so the item copies
+ /// them into q_rows
+ PackStateLayout(size_t offset,
+ size_t k_head_size,
+ size_t v_head_size,
+ size_t max_pack_size,
+ size_t data_size,
+ bool copy_query)
+ : q_rows(offset),
+ acc(q_rows + aligned(copy_query ? max_pack_size * k_head_size * data_size : 0)),
+ running_max(acc + aligned(max_pack_size * v_head_size * sizeof(float))),
+ running_sum(running_max + aligned(max_pack_size * sizeof(float))),
+ total(running_sum + aligned(max_pack_size * sizeof(float))) {}
+};
+
+/// @brief Byte layout of the buffers of the brgemm path in the per-thread scratch (the gather tile, the scores /
+/// weights and the brgemm scratch); every part is 64-byte aligned. `offset` is where it starts inside the thread's
+/// scratch, `total` the end of it.
+struct SparseBrgemmLayout {
+ size_t k_rows = 0; ///< data-type[tile_rows, k_head_size] gathered key rows of the tile
+ size_t v_rows = 0; ///< data-type[tile_rows, v_head_size] gathered value rows of the tile
+ size_t k_ptrs = 0; ///< const void*[tile_rows] where the key row of each tile row is (the cache, or k_rows)
+ size_t v_ptrs = 0; ///< const void*[tile_rows] the same for the value rows
+ size_t weights = 0; ///< float[pack, tile_rows] scores, then (data type, in place) weights, see weights_row_stride
+ size_t brg_a = 0; ///< A scratch
+ size_t brg_b = 0; ///< packed B scratch
+ size_t brg_wsp = 0; ///< workspace
+ size_t total = 0;
+
+ SparseBrgemmLayout() = default;
+ SparseBrgemmLayout(size_t offset,
+ size_t k_head_size,
+ size_t v_head_size,
+ size_t max_pack_size,
+ size_t data_size,
+ const SparseBrgemmSizes& sizes)
+ : k_rows(offset),
+ v_rows(k_rows + aligned(sizes.tile_rows * k_head_size * data_size)),
+ k_ptrs(v_rows + aligned(sizes.tile_rows * v_head_size * data_size)),
+ v_ptrs(k_ptrs + aligned(sizes.tile_rows * sizeof(void*))),
+ weights(v_ptrs + aligned(sizes.tile_rows * sizeof(void*))),
+ brg_a(weights + aligned(max_pack_size * sizes.tile_rows * sizeof(float))),
+ brg_b(brg_a + aligned(sizes.scratch_a)),
+ brg_wsp(brg_b + aligned(sizes.scratch_b)),
+ total(brg_wsp + aligned(sizes.wsp)) {}
+};
+
+#ifdef OPENVINO_ARCH_X86_64
+/// @brief The brgemm kernels of one node: built once, shared read-only by the worker threads.
+struct SparseBrgemmKernels {
+ std::shared_ptr<ov::intel_cpu::BrgemmKernel> qk;
+ std::shared_ptr<ov::intel_cpu::BrgemmKernel> pv_overwrite;
+ std::shared_ptr<ov::intel_cpu::BrgemmKernel> pv_accumulate;
+ SparseBrgemm handle;
+
+ /// A pack of several query heads is the M of the products; the kernels run it as an M tail, so fewer than the 32
+ /// rows of an M block.
+ static bool supports_pack(size_t pack) {
+ return pack > 1 && pack < ov::intel_cpu::BrgemmKernel::get_mblk_size();
+ }
+
+ SparseBrgemmKernels() = default;
+ SparseBrgemmKernels(size_t pack, size_t k_head_size, size_t v_head_size, size_t tile_rows, ov::element::Type prec) {
+ qk = std::make_shared<ov::intel_cpu::BrgemmKernel>(pack,
+ kBrgemmRowBlock,
+ k_head_size,
+ k_head_size,
+ k_head_size,
+ tile_rows,
+ /*b_transposed=*/true,
+ prec);
+ pv_overwrite = std::make_shared<ov::intel_cpu::BrgemmKernel>(pack,
+ v_head_size,
+ kBrgemmRowBlock,
+ weights_row_stride(tile_rows),
+ v_head_size,
+ v_head_size,
+ /*b_transposed=*/false,
+ prec);
+ pv_accumulate = std::make_shared<ov::intel_cpu::BrgemmKernel>(pack,
+ v_head_size,
+ kBrgemmRowBlock,
+ weights_row_stride(tile_rows),
+ v_head_size,
+ v_head_size,
+ /*b_transposed=*/false,
+ prec,
+ /*b_accumulate=*/true);
+ handle = {qk.get(), pv_overwrite.get(), pv_accumulate.get(), tile_rows, prec};
+ }
+};
+#endif
+
+} // namespace ov::Extensions::Cpu
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_brgemm_kernel.hpp b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_brgemm_kernel.hpp
new file mode 100644
index 00000000000..93a53a375b0
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_brgemm_kernel.hpp
@@ -0,0 +1,408 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#pragma once
+
+// The AMX prefill computation shared by the sparse attention kernels: the query heads that share the K/V head and the
+// selected blocks (a pack) are the M of oneDNN brgemm products, over the item's selected key rows in tiles of at most
+// SparseBrgemm::tile_rows rows (a gather tile, see the vocabulary in sparse_brgemm.hpp):
+// 1. QK: scores[pack, rows] = query[pack, k_head_size] x keys[rows, k_head_size]^T
+// 2. softmax: online over the tiles (running max / sum per head), weights = exp(scale * scores - max)
+// 3. P.V: acc[pack, v_head_size] += weights[pack, rows] x values[rows, v_head_size]
+// The kernels only differ in how the rows of a tile are gathered (paged or dense, plain or dequantized).
+
+#include <algorithm>
+#include <cmath>
+#include <cstddef>
+#include <cstring>
+#include <limits>
+
+#include "nodes/kernels/scaled_attn/common.hpp"
+#include "nodes/kernels/scaled_attn/softmax_kernel.hpp"
+#include "nodes/kernels/sparse_attn/sparse_brgemm.hpp"
+#include "utils/general_utils.h"
+
+#ifdef OPENVINO_ARCH_X86_64
+# include "nodes/kernels/scaled_attn/transpose_kernel.hpp"
+# include "nodes/kernels/x64/brgemm_kernel.hpp"
+#endif
+
+namespace ov::Extensions::Cpu::XARCH {
+
+/// @brief scores[r] *= scale for r < kv_len; returns the maximum of the scaled scores.
+inline float scale_and_max(float* scores, size_t kv_len, float scale) {
+ size_t r = 0;
+ float max_value = -std::numeric_limits<float>::infinity();
+#if defined(HAVE_AVX512F)
+ const auto v_scale = _mm512_set1_ps(scale);
+ auto v_max = _mm512_set1_ps(max_value);
+ for (; r + 16 <= kv_len; r += 16) {
+ const auto v = _mm512_mul_ps(_mm512_loadu_ps(scores + r), v_scale);
+ _mm512_storeu_ps(scores + r, v);
+ v_max = _mm512_max_ps(v_max, v);
+ }
+ max_value = _mm512_reduce_max_ps(v_max);
+#endif
+ for (; r < kv_len; r++) {
+ scores[r] *= scale;
+ max_value = std::max(max_value, scores[r]);
+ }
+ return max_value;
+}
+
+#ifdef OPENVINO_ARCH_X86_64
+
+/// @brief The query heads of a pack and their running softmax state, for the tile functions below.
+struct BrgemmPack {
+ const void* query; ///< [pack_size, k_head_size] query rows, in the data type, contiguous
+ size_t pack_size; ///< query heads of the pack
+ size_t k_head_size;
+ size_t v_head_size;
+ float scale;
+ float* acc; ///< [pack_size, v_head_size] attention accumulators (unnormalized)
+ float* running_max; ///< [pack_size] online-softmax maximum
+ float* running_sum; ///< [pack_size] online-softmax sum
+};
+
+/// @brief The attention scores and weights of the heads of a pack, which share one buffer: the QK products write f32
+/// scores, the softmax scales them and converts them in place to the 16-bit weights that the P.V products read. A
+/// head's scores are `tile_rows` floats long and its weights start at the same address, so the weights of consecutive
+/// heads are weights_row_stride(tile_rows) = 2 * tile_rows elements apart. This is the one place that states the
+/// invariant.
+template <typename T>
+struct WeightLayout {
+ static_assert(sizeof(T) == 2, "the brgemm weights are 16-bit data (bf16 / f16)");
+ float* storage; // [pack_size, tile_rows] floats
+ size_t tile_rows;
+
+ [[nodiscard]] float* scores(size_t head) const {
+ return storage + head * tile_rows;
+ }
+ [[nodiscard]] T* weights(size_t head) const {
+ return reinterpret_cast<T*>(storage) + head * weights_row_stride(tile_rows);
+ }
+};
+
+/// @brief The buffers of one gather tile, carved from the thread's scratch (see SparseBrgemmLayout).
+template <typename T>
+struct BrgemmBuffers {
+ ov::intel_cpu::BrgemmKernel* qk;
+ ov::intel_cpu::BrgemmKernel* pv_overwrite;
+ ov::intel_cpu::BrgemmKernel* pv_accumulate;
+ T* k_rows; // [tile_rows, k_head_size] stage of dequantized key rows (and the zero row that pads the last block)
+ T* v_rows; // [tile_rows, v_head_size] the same for the value rows
+ const T** k_ptrs; // [tile_rows] where the key row of each tile row is: the cache, or k_rows
+ const T** v_ptrs; // [tile_rows] the same for the value rows
+ WeightLayout<T> weights;
+ void* wsp;
+ void* scratch_a;
+ void* scratch_b; // packed B of one brgemm row block
+
+ [[nodiscard]] size_t tile_rows() const {
+ return weights.tile_rows;
+ }
+};
+
+// B operand packing straight from the cache rows: each row is read through its own pointer (copy_buffer_b needs one
+// contiguous matrix) and written in the layout of copy_buffer_b and of PagedAttention's pack_32NxK / transpose_16NxK:
+// 16-bit row-major VNNI B[k / 2][ldb][2], ldb = N rounded up to 32.
+
+/// @brief Whether the packing below can be used: AVX512, 16-bit rows of a multiple of 32 elements (the widths of the
+/// vector loads). Other head sizes gather the rows and use copy_buffer_b.
+[[nodiscard]] inline bool fused_pack_supported([[maybe_unused]] size_t k_head_size,
+ [[maybe_unused]] size_t v_head_size) {
+# if defined(HAVE_AVX512F)
+ return k_head_size % 32 == 0 && v_head_size % 32 == 0;
+# else
+ return false;
+# endif
+}
+
+# if defined(HAVE_AVX512F)
+/// @brief B operand of the QK product (keys, b_transposed, N = 32): dst[d][n] = the 32-bit pair d of the key row n, so
+/// a 32 x (k_head_size / 2) transpose of 32-bit values, 16 x 16 at a time.
+template <typename T>
+void pack_k_block(const T* const* kv_ptrs, size_t k_head_size, T* dst) {
+ static_assert(sizeof(T) == 2, "the rows are packed as 16-bit data (bf16 / f16)");
+ auto* out = reinterpret_cast<uint32_t*>(dst);
+ const size_t pairs = k_head_size / 2;
+ for (size_t half = 0; half < 2; half++) {
+ const auto* const* r = reinterpret_cast<const uint32_t* const*>(kv_ptrs + half * 16);
+ for (size_t d = 0; d < pairs; d += 16) {
+ __m512i r0 = _mm512_loadu_si512(r[0] + d);
+ __m512i r1 = _mm512_loadu_si512(r[1] + d);
+ __m512i r2 = _mm512_loadu_si512(r[2] + d);
+ __m512i r3 = _mm512_loadu_si512(r[3] + d);
+ __m512i r4 = _mm512_loadu_si512(r[4] + d);
+ __m512i r5 = _mm512_loadu_si512(r[5] + d);
+ __m512i r6 = _mm512_loadu_si512(r[6] + d);
+ __m512i r7 = _mm512_loadu_si512(r[7] + d);
+ __m512i r8 = _mm512_loadu_si512(r[8] + d);
+ __m512i r9 = _mm512_loadu_si512(r[9] + d);
+ __m512i ra = _mm512_loadu_si512(r[10] + d);
+ __m512i rb = _mm512_loadu_si512(r[11] + d);
+ __m512i rc = _mm512_loadu_si512(r[12] + d);
+ __m512i rd = _mm512_loadu_si512(r[13] + d);
+ __m512i re = _mm512_loadu_si512(r[14] + d);
+ __m512i rf = _mm512_loadu_si512(r[15] + d);
+ transpose_m512i_16x16(r0, r1, r2, r3, r4, r5, r6, r7, r8, r9, ra, rb, rc, rd, re, rf);
+ uint32_t* o = out + d * 32 + half * 16;
+ _mm512_storeu_si512(o, r0);
+ _mm512_storeu_si512(o + 32, r1);
+ _mm512_storeu_si512(o + 2 * 32, r2);
+ _mm512_storeu_si512(o + 3 * 32, r3);
+ _mm512_storeu_si512(o + 4 * 32, r4);
+ _mm512_storeu_si512(o + 5 * 32, r5);
+ _mm512_storeu_si512(o + 6 * 32, r6);
+ _mm512_storeu_si512(o + 7 * 32, r7);
+ _mm512_storeu_si512(o + 8 * 32, r8);
+ _mm512_storeu_si512(o + 9 * 32, r9);
+ _mm512_storeu_si512(o + 10 * 32, ra);
+ _mm512_storeu_si512(o + 11 * 32, rb);
+ _mm512_storeu_si512(o + 12 * 32, rc);
+ _mm512_storeu_si512(o + 13 * 32, rd);
+ _mm512_storeu_si512(o + 14 * 32, re);
+ _mm512_storeu_si512(o + 15 * 32, rf);
+ }
+ }
+}
+
+/// @brief B operand of the P.V product (values, K = 32 rows): the row pair (2i, 2i + 1) interleaved element by element
+/// into the row i of dst, whose stride is 2 * v_head_size elements.
+template <typename T>
+void pack_v_block(const T* const* kv_ptrs, size_t v_head_size, T* dst) {
+ static_assert(sizeof(T) == 2, "the rows are packed as 16-bit data (bf16 / f16)");
+ static const uint64_t idx[8] = {0, 4, 1, 5, 2, 6, 3, 7};
+ const auto midx = _mm512_loadu_si512(idx);
+ auto* out_row = reinterpret_cast<uint16_t*>(dst);
+ for (size_t i = 0; i < 16; i++) {
+ const auto* row_a = reinterpret_cast<const uint16_t*>(kv_ptrs[2 * i]);
+ const auto* row_b = reinterpret_cast<const uint16_t*>(kv_ptrs[2 * i + 1]);
+ for (size_t k = 0; k < v_head_size; k += 32) {
+ const auto a = _mm512_permutexvar_epi64(midx, _mm512_loadu_si512(row_a + k));
+ const auto b = _mm512_permutexvar_epi64(midx, _mm512_loadu_si512(row_b + k));
+ _mm512_storeu_si512(out_row + 2 * k, _mm512_unpacklo_epi16(a, b));
+ _mm512_storeu_si512(out_row + 2 * k + 32, _mm512_unpackhi_epi16(a, b));
+ }
+ out_row += 2 * v_head_size;
+ }
+}
+# else
+template <typename T>
+void pack_k_block([[maybe_unused]] const T* const* kv_ptrs,
+ [[maybe_unused]] size_t k_head_size,
+ [[maybe_unused]] T* dst) {
+ OPENVINO_THROW("[CPU] sparse attention: the fused key packing needs AVX512");
+}
+template <typename T>
+void pack_v_block([[maybe_unused]] const T* const* kv_ptrs,
+ [[maybe_unused]] size_t v_head_size,
+ [[maybe_unused]] T* dst) {
+ OPENVINO_THROW("[CPU] sparse attention: the fused value packing needs AVX512");
+}
+# endif
+
+/// Phase 1: scores[head, kv] = query[head] . keys[kv] for the pack's heads and every row block of the tile. The keys
+/// of a row block are packed into the AMX layout once for all the heads of the pack.
+template <typename T>
+void qk_scores_brgemm(const BrgemmPack& p, const BrgemmBuffers<T>& b, size_t tile_kv_len_pad) {
+ ov::intel_cpu::AmxTileState tiles; // the row blocks share one tile configuration
+ const bool fused = fused_pack_supported(p.k_head_size, p.v_head_size);
+ for (size_t tile_kv_start = 0; tile_kv_start < tile_kv_len_pad; tile_kv_start += kBrgemmRowBlock) {
+ if (fused) {
+ pack_k_block<T>(b.k_ptrs + tile_kv_start, p.k_head_size, static_cast<T*>(b.scratch_b));
+ } else {
+ b.qk->copy_buffer_b(b.k_rows + tile_kv_start * p.k_head_size, b.scratch_b);
+ }
+ b.qk->executeGemm(true,
+ const_cast<void*>(p.query),
+ b.scratch_b,
+ b.weights.scores(0) + tile_kv_start,
+ nullptr,
+ nullptr,
+ b.wsp,
+ b.scratch_a,
+ tiles);
+ }
+}
+
+/// Phase 2: online-softmax step of every head over the tile's KV entries (vectorized): rescales the head's state to the
+/// new maximum (not for the first tile, whose state is empty) and turns the scores into weights, converted to T in
+/// place. The padding entries get weight 0.
+template <typename T>
+void softmax_brgemm(const BrgemmPack& p,
+ const BrgemmBuffers<T>& b,
+ size_t tile_kv_len,
+ size_t tile_kv_len_pad,
+ bool first_tile) {
+ for (size_t head = 0; head < p.pack_size; head++) {
+ float* scores = b.weights.scores(head);
+ const float new_max = std::max(p.running_max[head], scale_and_max(scores, tile_kv_len, p.scale));
+ if (!first_tile) {
+ const float corr = std::exp(p.running_max[head] - new_max);
+ p.running_sum[head] *= corr;
+ float* acc = p.acc + head * p.v_head_size;
+ for (size_t d = 0; d < p.v_head_size; d++) {
+ acc[d] *= corr;
+ }
+ }
+ float sum = 0.0F;
+ exp_reduce_sum(scores, new_max, tile_kv_len, sum);
+ p.running_sum[head] = (first_tile ? 0.0F : p.running_sum[head]) + sum;
+ p.running_max[head] = new_max;
+ std::fill(scores + tile_kv_len, scores + tile_kv_len_pad, 0.0F);
+ cvt_copy(b.weights.weights(head), scores, 1, tile_kv_len_pad, 0, 0);
+ }
+}
+
+/// Phase 3: acc[head] (+)= weights[head] . values for the pack's heads, over the row blocks of the tile. The values of
+/// a row block are packed into the AMX layout once for all the heads of the pack. The first row block of the first tile
+/// overwrites acc (beta = 0), every other one accumulates (beta = 1).
+template <typename T>
+void pv_accumulate_brgemm(const BrgemmPack& p, const BrgemmBuffers<T>& b, size_t tile_kv_len_pad, bool first_tile) {
+ ov::intel_cpu::AmxTileState tiles; // the row blocks share one tile configuration
+ const bool fused = fused_pack_supported(p.k_head_size, p.v_head_size);
+ for (size_t tile_kv_start = 0; tile_kv_start < tile_kv_len_pad; tile_kv_start += kBrgemmRowBlock) {
+ if (fused) {
+ pack_v_block<T>(b.v_ptrs + tile_kv_start, p.v_head_size, static_cast<T*>(b.scratch_b));
+ } else {
+ b.pv_overwrite->copy_buffer_b(b.v_rows + tile_kv_start * p.v_head_size, b.scratch_b);
+ }
+ (first_tile && tile_kv_start == 0 ? b.pv_overwrite : b.pv_accumulate)
+ ->executeGemm(true,
+ b.weights.weights(0) + tile_kv_start,
+ b.scratch_b,
+ p.acc,
+ nullptr,
+ nullptr,
+ b.wsp,
+ b.scratch_a,
+ tiles);
+ }
+}
+
+/// @brief Attention of the pack's heads over one tile of `tile_kv_len` gathered KV entries in b.k_rows / b.v_rows
+/// (1 <= tile_kv_len <= tile_rows): phases 1-3 above, updating the pack's running state. The padding of the last row
+/// block is zeroed here.
+template <typename T>
+void attention_over_tile(const BrgemmPack& p, const BrgemmBuffers<T>& b, size_t tile_kv_len, bool first_tile) {
+ const size_t tile_kv_len_pad = ov::intel_cpu::rnd_up(tile_kv_len, kBrgemmRowBlock);
+ if (fused_pack_supported(p.k_head_size, p.v_head_size)) {
+ // the padding entries of the last block all read one row of zeros
+ if (tile_kv_len_pad > tile_kv_len) {
+ T* const zero_k = b.k_rows + tile_kv_len * p.k_head_size;
+ T* const zero_v = b.v_rows + tile_kv_len * p.v_head_size;
+ std::memset(zero_k, 0, p.k_head_size * sizeof(T));
+ std::memset(zero_v, 0, p.v_head_size * sizeof(T));
+ std::fill(b.k_ptrs + tile_kv_len, b.k_ptrs + tile_kv_len_pad, zero_k);
+ std::fill(b.v_ptrs + tile_kv_len, b.v_ptrs + tile_kv_len_pad, zero_v);
+ }
+ } else {
+ std::memset(b.k_rows + tile_kv_len * p.k_head_size,
+ 0,
+ (tile_kv_len_pad - tile_kv_len) * p.k_head_size * sizeof(T));
+ std::memset(b.v_rows + tile_kv_len * p.v_head_size,
+ 0,
+ (tile_kv_len_pad - tile_kv_len) * p.v_head_size * sizeof(T));
+ }
+ qk_scores_brgemm<T>(p, b, tile_kv_len_pad);
+ softmax_brgemm<T>(p, b, tile_kv_len, tile_kv_len_pad, first_tile);
+ pv_accumulate_brgemm<T>(p, b, tile_kv_len_pad, first_tile);
+}
+
+/// @brief The rows gathered into the current tile of an item so far.
+struct TileState {
+ size_t rows = 0;
+ bool first_tile = true;
+};
+
+/// @brief Processes the current tile if it holds rows and starts the next one.
+template <typename T>
+void flush_tile(const BrgemmPack& p, const BrgemmBuffers<T>& b, TileState& tile) {
+ if (tile.rows == 0) {
+ return;
+ }
+ attention_over_tile<T>(p, b, tile.rows, tile.first_tile);
+ tile.rows = 0;
+ tile.first_tile = false;
+}
+
+// A "row source" (PagedRowSource, DenseRowSource) is the layout specific part of an item:
+// visible(kpos0, n): how many of rows [kpos0, kpos0 + n) the query attends (a prefix)
+// rows(kpos0, n, k_ptr, v_ptr, k_stage, v_stage): points k_ptr[i] / v_ptr[i] at row kpos0 + i of the cache, or of
+// k_stage / v_stage when it was dequantized there
+
+/// @brief Gathers the visible part of the run [kpos0, kpos0 + n) into the current tile, processing the tile whenever it
+/// is full: a run that does not fit in the rest of the tile continues in the next one.
+template <typename T, typename RowSource>
+void gather_run(const RowSource& src,
+ const BrgemmPack& pack,
+ const BrgemmBuffers<T>& b,
+ TileState& tile,
+ int64_t kpos0,
+ int64_t n) {
+ n = src.visible(kpos0, n);
+ while (n > 0) {
+ const auto take = std::min<int64_t>(n, static_cast<int64_t>(b.tile_rows() - tile.rows));
+ T* const k_stage = b.k_rows + tile.rows * pack.k_head_size;
+ T* const v_stage = b.v_rows + tile.rows * pack.v_head_size;
+ src.template rows<T>(kpos0,
+ static_cast<size_t>(take),
+ b.k_ptrs + tile.rows,
+ b.v_ptrs + tile.rows,
+ k_stage,
+ v_stage);
+ if (!fused_pack_supported(pack.k_head_size, pack.v_head_size)) {
+ // copy_buffer_b reads one contiguous matrix: bring the rows of the run into the tile buffers
+ for (int64_t i = 0; i < take; i++) {
+ T* const k_dst = k_stage + i * pack.k_head_size;
+ T* const v_dst = v_stage + i * pack.v_head_size;
+ if (b.k_ptrs[tile.rows + i] != k_dst) {
+ std::memcpy(k_dst, b.k_ptrs[tile.rows + i], pack.k_head_size * sizeof(T));
+ }
+ if (b.v_ptrs[tile.rows + i] != v_dst) {
+ std::memcpy(v_dst, b.v_ptrs[tile.rows + i], pack.v_head_size * sizeof(T));
+ }
+ }
+ }
+ tile.rows += static_cast<size_t>(take);
+ kpos0 += take;
+ n -= take;
+ if (tile.rows == b.tile_rows()) {
+ flush_tile<T>(pack, b, tile);
+ }
+ }
+}
+
+/// @brief The selection of an item: the selected blocks (ids of blocks of key_block_size rows, in any order) and the
+/// causal tail (the incomplete last block of the query, `tail_rows` rows from `tail_start`).
+struct BrgemmSelection {
+ const int32_t* block_ids;
+ size_t nblocks;
+ int64_t first_pos; ///< position of block 0
+ int64_t key_block_size;
+ int64_t tail_start;
+ int64_t tail_rows;
+};
+
+/// @brief Attention of the pack's heads over the item's whole selection with AMX matrix products: the rows are gathered
+/// into tiles (the layout specific part is the row source) and every full tile, then the last partial one, goes through
+/// attention_over_tile(), whose online softmax carries the state across the tiles. It leaves the unnormalized attention
+/// in pack.acc and the softmax denominators in pack.running_sum (all 0 when nothing is visible); the caller normalizes
+/// and stores the output.
+template <typename T, typename RowSource>
+void attention_over_selection_tiles(const RowSource& src,
+ const BrgemmPack& pack,
+ const BrgemmBuffers<T>& b,
+ const BrgemmSelection& sel) {
+ TileState tile;
+ for (size_t i = 0; i < sel.nblocks; i++) {
+ gather_run<T>(src, pack, b, tile, sel.first_pos + sel.block_ids[i] * sel.key_block_size, sel.key_block_size);
+ }
+ gather_run<T>(src, pack, b, tile, sel.tail_start, sel.tail_rows);
+ flush_tile<T>(pack, b, tile);
+}
+
+#endif // OPENVINO_ARCH_X86_64
+
+} // namespace ov::Extensions::Cpu::XARCH
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_kernel_cache.hpp b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_kernel_cache.hpp
new file mode 100644
index 00000000000..63dae7d3839
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_kernel_cache.hpp
@@ -0,0 +1,69 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+// Kernel cache of the sparse attention nodes: the brgemm kernels depend only on the shapes and the data type, so nodes
+// with the same parameters (e.g. the attention layers of a model) share them through the graph context's params cache.
+
+#ifdef OPENVINO_ARCH_X86_64
+
+# include <common/utils.hpp>
+# include <cstddef>
+# include <memory>
+
+# include "cache/multi_cache.h"
+# include "nodes/kernels/sparse_attn/sparse_brgemm.hpp"
+# include "openvino/core/type/element_type.hpp"
+
+namespace ov::intel_cpu::node {
+
+/// @brief Parameters of the brgemm kernels (see SparseBrgemmKernels).
+struct SparseBrgemmKey {
+ size_t pack = 0;
+ size_t k_head_size = 0;
+ size_t v_head_size = 0;
+ size_t tile_rows = 0;
+ ov::element::Type prec;
+
+ [[nodiscard]] size_t hash() const {
+ using namespace dnnl::impl;
+ size_t seed = 0;
+ seed = hash_combine(seed, pack);
+ seed = hash_combine(seed, k_head_size);
+ seed = hash_combine(seed, v_head_size);
+ seed = hash_combine(seed, tile_rows);
+ seed = hash_combine(seed, prec.hash());
+ return seed;
+ }
+ bool operator==(const SparseBrgemmKey& rhs) const {
+ return pack == rhs.pack && k_head_size == rhs.k_head_size && v_head_size == rhs.v_head_size &&
+ tile_rows == rhs.tile_rows && prec == rhs.prec;
+ }
+};
+
+/// @brief The brgemm kernels for the pack of query heads, created once per set of parameters. The
+/// result is a copy of the cached bundle: it shares the kernels, and its handle points at them.
+inline ov::Extensions::Cpu::SparseBrgemmKernels get_sparse_brgemm_kernels(const MultiCachePtr& cache,
+ size_t pack,
+ size_t k_head_size,
+ size_t v_head_size,
+ size_t tile_rows,
+ ov::element::Type prec) {
+ const SparseBrgemmKey key{pack, k_head_size, v_head_size, tile_rows, prec};
+ auto builder = [](const SparseBrgemmKey& k) {
+ return std::make_shared<ov::Extensions::Cpu::SparseBrgemmKernels>(k.pack,
+ k.k_head_size,
+ k.v_head_size,
+ k.tile_rows,
+ k.prec);
+ };
+ auto result = cache->getOrCreate(key, builder);
+ OPENVINO_ASSERT(result.first, "Sparse attention brgemm kernels creation fails");
+ return *result.first;
+}
+
+} // namespace ov::intel_cpu::node
+
+#endif // OPENVINO_ARCH_X86_64
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_pa_kernel.cpp b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_pa_kernel.cpp
new file mode 100644
index 00000000000..50ac6231135
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_pa_kernel.cpp
@@ -0,0 +1,733 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#include "nodes/kernels/sparse_attn/sparse_pa_kernel.hpp"
+
+#include <algorithm>
+#include <cmath>
+#include <cstddef>
+#include <cstdint>
+#include <cstring>
+#include <limits>
+#include <type_traits>
+#include <utility>
+
+#include "cpu_parallel.hpp"
+#include "nodes/kernels/scaled_attn/attn_quant_kernel.hpp"
+#include "nodes/kernels/scaled_attn/common.hpp"
+#include "nodes/kernels/scaled_attn/executor_pa_common.hpp"
+#include "nodes/kernels/scaled_attn/paged_attn_kernel.hpp"
+#include "nodes/kernels/scaled_attn/softmax_kernel.hpp"
+#include "nodes/kernels/sparse_attn/sparse_attn_kernel.hpp"
+#include "nodes/kernels/sparse_attn/sparse_brgemm.hpp"
+#include "nodes/kernels/sparse_attn/sparse_brgemm_kernel.hpp"
+#ifdef OPENVINO_ARCH_X86_64
+# include "nodes/kernels/x64/brgemm_kernel.hpp"
+#endif
+#include "openvino/core/except.hpp"
+#include "openvino/core/parallel.hpp"
+#include "openvino/core/type/bfloat16.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "openvino/core/type/float16.hpp"
+#include "utils/plain_tensor.hpp"
+
+namespace ov::Extensions::Cpu::XARCH {
+
+using ov::intel_cpu::PlainTensor;
+
+namespace {
+
+// ---- quantized (u8/u4) paged cache access, same layouts as PagedAttention (see SparsePAQuant) ----
+
+// Dequantizes `n` consecutive by-token rows [slot0, slot0 + n) of one (physical block, kv head) into dst[n, D].
+template <typename TDST, ov::element::Type_t PREC>
+void dequant_rows_by_token(const PlainTensor& cache,
+ size_t phys_block,
+ size_t kv,
+ size_t slot0,
+ size_t n,
+ size_t D,
+ size_t group_size,
+ TDST* dst) {
+ constexpr size_t sub_byte_multiplier = get_sub_byte_multiplier(PREC);
+ constexpr size_t params_offset = sizeof(float) * 2;
+ const size_t gs = group_size ? group_size : D;
+ const auto* s = cache.ptr<uint8_t, PREC>(phys_block, kv, slot0);
+ for (size_t r = 0; r < n; r++) {
+ size_t src_offset = 0;
+ for (size_t d = 0; d < D; d += gs) {
+ const auto* params = reinterpret_cast<const float*>(s + src_offset);
+ attn_dequant_kernel<TDST, PREC>(s + src_offset + params_offset, dst + d, gs, params);
+ src_offset += gs / sub_byte_multiplier + params_offset;
+ }
+ s += src_offset;
+ dst += D;
+ }
+}
+
+// Dequantizes `n` consecutive rows [slot0, slot0 + n) of a by-channel key page: the page head holds the
+// per-channel scales and zero points, followed by the quantized [block_size, S] rows.
+template <typename TDST, ov::element::Type_t PREC>
+void dequant_key_rows_by_channel(const PlainTensor& cache,
+ size_t phys_block,
+ size_t kv,
+ size_t slot0,
+ size_t n,
+ size_t S,
+ TDST* dst) {
+ constexpr size_t sub_byte_multiplier = get_sub_byte_multiplier(PREC);
+ const auto* page = cache.ptr<uint8_t, PREC>(phys_block, kv);
+ const auto* scales = reinterpret_cast<const float*>(page);
+ const float* zps = scales + S;
+ const uint8_t* data = page + sizeof(float) * 2 * S;
+ const size_t row_stride = S / sub_byte_multiplier;
+ attn_dequant_by_channel_kernel<TDST, PREC>(data + slot0 * row_stride, dst, n, S, row_stride, S, scales, zps);
+}
+
+// The cache precision is a template parameter of the kernels below; each *_rows function picks u8 or u4 at runtime.
+
+template <typename TDST, ov::element::Type_t PREC>
+void dequant_k_rows_prec(const SparsePAQuant& quant,
+ const PlainTensor& cache,
+ size_t phys_block,
+ size_t kv,
+ size_t slot0,
+ size_t n,
+ size_t S,
+ TDST* dst) {
+ if (quant.key_bychannel) {
+ dequant_key_rows_by_channel<TDST, PREC>(cache, phys_block, kv, slot0, n, S, dst);
+ } else {
+ dequant_rows_by_token<TDST, PREC>(cache, phys_block, kv, slot0, n, S, quant.key_group_size, dst);
+ }
+}
+
+template <typename TDST>
+void dequant_k_rows(const SparsePAQuant& quant,
+ const PlainTensor& cache,
+ size_t phys_block,
+ size_t kv,
+ size_t slot0,
+ size_t n,
+ size_t S,
+ TDST* dst) {
+ if (quant.key_prec == ov::element::u4) {
+ dequant_k_rows_prec<TDST, ov::element::u4>(quant, cache, phys_block, kv, slot0, n, S, dst);
+ } else {
+ dequant_k_rows_prec<TDST, ov::element::u8>(quant, cache, phys_block, kv, slot0, n, S, dst);
+ }
+}
+
+template <typename TDST>
+void dequant_v_rows(const SparsePAQuant& quant,
+ const PlainTensor& cache,
+ size_t phys_block,
+ size_t kv,
+ size_t slot0,
+ size_t n,
+ size_t Sv,
+ TDST* dst) {
+ if (quant.value_prec == ov::element::u4) {
+ dequant_rows_by_token<TDST, ov::element::u4>(cache, phys_block, kv, slot0, n, Sv, quant.value_group_size, dst);
+ } else {
+ dequant_rows_by_token<TDST, ov::element::u8>(cache, phys_block, kv, slot0, n, Sv, quant.value_group_size, dst);
+ }
+}
+
+template <ov::element::Type_t PREC>
+void dot_key_rows_by_token_prec(const SparsePAQuant& quant,
+ const PlainTensor& cache,
+ size_t phys_block,
+ size_t kv,
+ size_t slot0,
+ size_t rows,
+ size_t S,
+ float* q,
+ float* scores) {
+ auto* k = cache.ptr<uint8_t, PREC>(phys_block, kv, slot0);
+ const size_t gs = quant.key_group_size ? quant.key_group_size : S;
+ dot_product_block_quantized<float, PREC>(q, k, scores, S, false, rows, gs);
+}
+
+// scores[j] = dot(q, key row slot0 + j) for by-token key rows, straight from the quantized cache.
+void dot_key_rows_by_token(const SparsePAQuant& quant,
+ const PlainTensor& cache,
+ size_t phys_block,
+ size_t kv,
+ size_t slot0,
+ size_t rows,
+ size_t S,
+ float* q,
+ float* scores) {
+ if (quant.key_prec == ov::element::u4) {
+ dot_key_rows_by_token_prec<ov::element::u4>(quant, cache, phys_block, kv, slot0, rows, S, q, scores);
+ } else {
+ dot_key_rows_by_token_prec<ov::element::u8>(quant, cache, phys_block, kv, slot0, rows, S, q, scores);
+ }
+}
+
+template <ov::element::Type_t PREC>
+void acc_value_rows_by_token_prec(const SparsePAQuant& quant,
+ const PlainTensor& cache,
+ size_t phys_block,
+ size_t kv,
+ size_t slot0,
+ size_t rows,
+ size_t Sv,
+ float* weights,
+ float* out) {
+ auto* v = cache.ptr<uint8_t, PREC>(phys_block, kv, slot0);
+ const size_t gs = quant.value_group_size ? quant.value_group_size : Sv;
+ attn_acc_value_block_quantized<float, PREC>(out, weights, v, Sv, false, rows, gs);
+}
+
+// out += sum_j weights[j] * (value row slot0 + j), straight from the quantized cache (value is always by-token).
+void acc_value_rows_by_token(const SparsePAQuant& quant,
+ const PlainTensor& cache,
+ size_t phys_block,
+ size_t kv,
+ size_t slot0,
+ size_t rows,
+ size_t Sv,
+ float* weights,
+ float* out) {
+ if (quant.value_prec == ov::element::u4) {
+ acc_value_rows_by_token_prec<ov::element::u4>(quant, cache, phys_block, kv, slot0, rows, Sv, weights, out);
+ } else {
+ acc_value_rows_by_token_prec<ov::element::u8>(quant, cache, phys_block, kv, slot0, rows, Sv, weights, out);
+ }
+}
+
+// ---- the items of a call ----
+// Brgemm tokens (sequences of several new tokens, and decode tokens with a large selection) take the AMX head-pack
+// path, the others SIMD items; `token_ids` lists brgemm tokens first. With little SIMD work every query head is its
+// own item (`fallback_pack` 1).
+struct WorkList {
+ const int32_t* token_ids = nullptr;
+ size_t brgemm_tokens = 0;
+ size_t fallback_tokens = 0;
+ size_t brgemm_pack = 1; ///< query heads of one item of a brgemm token
+ size_t fallback_pack = 1; ///< query heads of one item of a fallback token
+};
+
+// ---- everything the sparse attention work items read from the arguments, see sparse_pa_compute() ----
+
+struct SparsePAArgs {
+ const PlainTensor& query;
+ const PlainTensor& key_cache;
+ const PlainTensor& value_cache;
+ const PlainTensor& block_indices;
+ const PlainTensor& block_indices_begins;
+ const PlainTensor& subsequence_begins;
+ const PlainTensor& past_lens;
+ const PlainTensor& sel_indices;
+ const PlainTensor& sel_count;
+ PlainTensor& out;
+ size_t q_head_num;
+ size_t k_head_num;
+ size_t k_head_size; // == q_head_size
+ size_t v_head_size;
+ size_t key_block_size;
+ size_t page_size; // tokens per physical cache block
+ size_t sel_head_num;
+ bool causal;
+ float scale;
+ const SparsePAQuant& quant;
+ size_t max_run_rows; // most key rows of one run, see SparsePAScratchLayout
+ const SparseBrgemm& brgemm;
+ uint8_t* scratch;
+ size_t scratch_bytes_per_thread;
+ WorkList work;
+};
+
+// State of one work item: a query token and a pack of `pack_size` consecutive query heads sharing K/V rows and selected
+// blocks. Holds the sequence's cache location, the pack's scratch and each head's running online-softmax state.
+struct PackWork {
+ const PlainTensor& key_cache;
+ const PlainTensor& value_cache;
+ const int32_t* block_table; // physical block ids of the sequence
+ const SparsePAQuant& quant;
+ size_t k_head_size;
+ size_t v_head_size;
+ size_t k_head; // the K/V head every query head of the pack reads
+ size_t pack_size; // query heads of the pack
+ int64_t key_block_size;
+ int64_t page_size;
+ int64_t token_pos; // logical position of the query token
+ int64_t valid_max; // exclusive bound on the valid logical positions of the sequence
+ int64_t max_run_rows;
+ bool causal;
+ float scale;
+ const void* query; // [pack_size, k_head_size] query rows in the data type of the query
+ float* q; // the same rows in f32
+ float* acc; // [pack_size, v_head_size] attention accumulators
+ float* running_max;
+ float* running_sum;
+ float* run_scores; // [pack_size, max_run_rows] scores, then weights, of a run of key rows
+ float* k_run; // quantized caches: [max_run_rows, k_head_size] dequantized key run
+ float* v_run; // quantized caches: [max_run_rows, v_head_size] dequantized value run
+};
+
+// Index of the sequence whose tokens contain `token`.
+size_t find_sequence(const PlainTensor& subsequence_begins, size_t token) {
+ const auto* begins = subsequence_begins.ptr<int32_t>();
+ const auto* end = begins + subsequence_begins.size(0);
+ return static_cast<size_t>(std::upper_bound(begins, end, static_cast<int32_t>(token)) - begins) - 1;
+}
+
+// Maps a logical KV position of the sequence to the physical (block, slot) address in the caches through the shared
+// page table. A selected key_block_size-wide span never crosses a physical block boundary (page_size % key_block_size
+// == 0 is enforced by the op and the node).
+std::pair<size_t, size_t> physical_address(const PackWork& w, int64_t logical_pos) {
+ return {static_cast<size_t>(w.block_table[logical_pos / w.page_size]),
+ static_cast<size_t>(logical_pos % w.page_size)};
+}
+
+// ---- The phases of attention over a run of key rows, for the heads of the pack (one head is a pack of one) ----
+// 1. qk_scores_gqa: scores = query . keys^T
+// 2. online_softmax: weights = softmax(scale * scores), rescaling the running (max, sum, acc)
+// 3. pv_accumulate_gqa: acc += weights . values
+// attention_over_* run them for a run, the selected blocks or the causal tail.
+
+// Phase 2: online-softmax step of query head `head` over its scores[0, rows) of one run of key rows: rescales the
+// head's state to the new maximum and turns the scores into weights in place (vectorized exp).
+void online_softmax(PackWork& w, size_t head, size_t rows) {
+ float* scores = w.run_scores + head * static_cast<size_t>(w.max_run_rows);
+ float* acc = w.acc + head * w.v_head_size;
+ const float new_max = std::max(w.running_max[head], scale_and_max(scores, rows, w.scale));
+ const float corr = std::exp(w.running_max[head] - new_max);
+ w.running_sum[head] *= corr;
+ for (size_t d = 0; d < w.v_head_size; d++) {
+ acc[d] *= corr;
+ }
+ float sum = 0.0F;
+ exp_reduce_sum(scores, new_max, rows, sum);
+ w.running_sum[head] += sum;
+ w.running_max[head] = new_max;
+}
+
+// Plain caches: attention over up to `n` consecutive logical positions [kpos0, kpos0 + n), all inside one physical
+// page, for every query head of the pack: no per-row conversion and one page-table lookup.
+template <typename T>
+void attention_over_run_plain(PackWork& w, int64_t kpos0, int64_t n) {
+ const auto [phys_block, slot] = physical_address(w, kpos0);
+ const auto rows = static_cast<size_t>(n);
+ T* key_rows = w.key_cache.ptr<T>(phys_block, w.k_head, slot);
+ T* value_rows = w.value_cache.ptr<T>(phys_block, w.k_head, slot);
+ const auto score_stride = static_cast<size_t>(w.max_run_rows);
+ qk_scores_gqa<T>(w.q, w.pack_size, w.k_head_size, key_rows, rows, w.run_scores, score_stride);
+ for (size_t head = 0; head < w.pack_size; head++) {
+ online_softmax(w, head, rows);
+ }
+ pv_accumulate_gqa<T>(w.acc, w.pack_size, w.v_head_size, w.run_scores, score_stride, value_rows, rows);
+}
+
+// Quantized caches. A one-head pack reads by-token rows directly with PagedAttention's fused block kernels (by-channel
+// keys are dequantized first: those kernels walk a whole page). A multi-head pack dequantizes the run's K and V to f32
+// once for all its heads.
+
+// Phase 0: dequantize the rows a fused kernel cannot read in place.
+void dequantize_run(PackWork& w, size_t phys_block, size_t slot, size_t rows, bool fused_keys, bool fused_values) {
+ if (!fused_keys) {
+ dequant_k_rows<float>(w.quant, w.key_cache, phys_block, w.k_head, slot, rows, w.k_head_size, w.k_run);
+ }
+ if (!fused_values) {
+ dequant_v_rows<float>(w.quant, w.value_cache, phys_block, w.k_head, slot, rows, w.v_head_size, w.v_run);
+ }
+}
+
+// Quantized caches: attention over a run of rows inside one physical page. A fused phase (one-head pack) reads the
+// quantized rows in place, the other one uses the dequantized f32 run through the head-pack kernels.
+void attention_over_run_quant(PackWork& w, int64_t kpos0, int64_t n) {
+ const auto [phys_block, slot] = physical_address(w, kpos0);
+ const auto rows = static_cast<size_t>(n);
+ const bool fused_keys = w.pack_size == 1 && !w.quant.key_bychannel;
+ const bool fused_values = w.pack_size == 1;
+ const auto score_stride = static_cast<size_t>(w.max_run_rows);
+ dequantize_run(w, phys_block, slot, rows, fused_keys, fused_values);
+ if (fused_keys) {
+ dot_key_rows_by_token(w.quant, w.key_cache, phys_block, w.k_head, slot, rows, w.k_head_size, w.q, w.run_scores);
+ } else {
+ qk_scores_gqa<float>(w.q, w.pack_size, w.k_head_size, w.k_run, rows, w.run_scores, score_stride);
+ }
+ for (size_t head = 0; head < w.pack_size; head++) {
+ online_softmax(w, head, rows);
+ }
+ if (fused_values) {
+ acc_value_rows_by_token(w.quant,
+ w.value_cache,
+ phys_block,
+ w.k_head,
+ slot,
+ rows,
+ w.v_head_size,
+ w.run_scores,
+ w.acc);
+ } else {
+ pv_accumulate_gqa<float>(w.acc, w.pack_size, w.v_head_size, w.run_scores, score_stride, w.v_run, rows);
+ }
+}
+
+// Number of rows of the run [kpos0, kpos0 + n) that the query may see.
+int64_t visible_rows(const PackWork& w, int64_t kpos0, int64_t n) {
+ const int64_t limit = w.causal ? std::min(w.valid_max, w.token_pos + 1) : w.valid_max;
+ return kpos0 < 0 ? 0 : std::max<int64_t>(std::min(n, limit - kpos0), 0);
+}
+
+// Attention over up to `n` consecutive logical positions [kpos0, kpos0 + n) that lie inside one physical page, clamped
+// to the positions the query may see.
+void attention_over_run(PackWork& w, int64_t kpos0, int64_t n) {
+ n = visible_rows(w, kpos0, n);
+ if (n == 0) {
+ return;
+ }
+ if (w.quant.enabled()) {
+ attention_over_run_quant(w, kpos0, n);
+ } else {
+ // The query rows are f32 here, so only the cache rows need their own type (f16 next to f32 data, like
+ // PagedAttention; the rows are converted in registers).
+ visit_float_type(w.key_cache.get_precision(), [&](auto cache_tag) {
+ attention_over_run_plain<decltype(cache_tag)>(w, kpos0, n);
+ });
+ }
+}
+
+// Attention over the selected complete blocks: adjacent blocks of the same physical page form one run (up to
+// max_run_rows rows), so the block kernels see as many rows per call as possible.
+void attention_selected_blocks_simd(PackWork& w, const int32_t* block_ids, size_t nblocks) {
+ const int64_t page_blocks = w.page_size / w.key_block_size;
+ const int64_t max_run_blocks = std::max<int64_t>(w.max_run_rows / w.key_block_size, 1);
+ size_t i = 0;
+ while (i < nblocks) {
+ const int64_t first = block_ids[i];
+ int64_t run_blocks = 1;
+ while (i + run_blocks < nblocks && run_blocks < max_run_blocks &&
+ block_ids[i + run_blocks] == first + run_blocks &&
+ (first + run_blocks) / page_blocks == first / page_blocks) {
+ run_blocks++;
+ }
+ attention_over_run(w, first * w.key_block_size, run_blocks * w.key_block_size);
+ i += static_cast<size_t>(run_blocks);
+ }
+}
+
+// sel_indices/sel_count only ever carry *complete* selected blocks -- the producer never encodes the current
+// incomplete trailing block. When causal, the consumer derives and attends that tail itself from the query's own
+// logical position; it is empty at a block boundary.
+void attention_causal_tail_simd(PackWork& w) {
+ if (w.causal) {
+ const int64_t tail_start = ((w.token_pos + 1) / w.key_block_size) * w.key_block_size;
+ attention_over_run(w, tail_start, w.token_pos - tail_start + 1);
+ }
+}
+
+#ifdef OPENVINO_ARCH_X86_64
+// ---- prefill with AMX matrix products over the whole selection of a work item ----
+
+// The rows of the paged caches for the shared tile loop (sparse_brgemm_kernel.hpp): a run of rows is contiguous inside
+// one physical page; plain caches are copied, quantized ones dequantized, into the tile.
+struct PagedRowSource {
+ const PackWork& w;
+
+ [[nodiscard]] int64_t visible(int64_t kpos0, int64_t n) const {
+ return visible_rows(w, kpos0, n);
+ }
+
+ template <typename T>
+ void rows(int64_t kpos0, size_t n, const T** k_ptr, const T** v_ptr, T* k_stage, T* v_stage) const {
+ const auto [phys_block, slot] = physical_address(w, kpos0);
+ const T* k_src = k_stage;
+ const T* v_src = v_stage;
+ if (w.quant.enabled()) {
+ dequant_k_rows<T>(w.quant, w.key_cache, phys_block, w.k_head, slot, n, w.k_head_size, k_stage);
+ dequant_v_rows<T>(w.quant, w.value_cache, phys_block, w.k_head, slot, n, w.v_head_size, v_stage);
+ } else {
+ k_src = w.key_cache.ptr<T>(phys_block, w.k_head, slot);
+ v_src = w.value_cache.ptr<T>(phys_block, w.k_head, slot);
+ }
+ for (size_t i = 0; i < n; i++) {
+ k_ptr[i] = k_src + i * w.k_head_size;
+ v_ptr[i] = v_src + i * w.v_head_size;
+ }
+ }
+};
+
+// Attention of the pack's heads over the whole selection (blocks and causal tail) with AMX brgemm, M = the pack's
+// heads, over gathered rows (see attention_over_selection_tiles). Leaves unnormalized attention in w.acc and the
+// softmax denominators in w.running_sum; the caller normalizes and stores.
+template <typename T>
+void attention_full_selection_brgemm(
+ const SparsePAArgs& a,
+ PackWork& w,
+ uint8_t* ws, // NOLINT(readability-non-const-parameter): the buffers it carves are written
+ const SparsePAScratchLayout& layout,
+ const int32_t* block_ids,
+ size_t nblocks) {
+ const auto& lay = layout.brgemm;
+ const BrgemmBuffers<T> b{static_cast<ov::intel_cpu::BrgemmKernel*>(a.brgemm.qk),
+ static_cast<ov::intel_cpu::BrgemmKernel*>(a.brgemm.pv_overwrite),
+ static_cast<ov::intel_cpu::BrgemmKernel*>(a.brgemm.pv_accumulate),
+ reinterpret_cast<T*>(ws + lay.k_rows),
+ reinterpret_cast<T*>(ws + lay.v_rows),
+ reinterpret_cast<const T**>(ws + lay.k_ptrs),
+ reinterpret_cast<const T**>(ws + lay.v_ptrs),
+ {reinterpret_cast<float*>(ws + lay.weights), a.brgemm.tile_rows},
+ ws + lay.brg_wsp,
+ ws + lay.brg_a,
+ ws + lay.brg_b};
+ const BrgemmPack
+ pack{w.query, w.pack_size, w.k_head_size, w.v_head_size, w.scale, w.acc, w.running_max, w.running_sum};
+ const int64_t tail_start = ((w.token_pos + 1) / w.key_block_size) * w.key_block_size;
+ const BrgemmSelection selection{block_ids, nblocks, 0, w.key_block_size, tail_start, w.token_pos - tail_start + 1};
+ attention_over_selection_tiles<T>(PagedRowSource{w}, pack, b, selection);
+}
+#endif // OPENVINO_ARCH_X86_64
+
+// One work item: attention of one query token and one head pack, on the brgemm path (whole selection at once) or the
+// SIMD path (selected blocks run by run, then the causal tail).
+template <typename T>
+void attention_work_item(const SparsePAArgs& a,
+ const SparsePAScratchLayout& layout,
+ size_t token,
+ size_t pack,
+ size_t pack_size,
+ bool brgemm_item) {
+ const auto* subsequence_begins = a.subsequence_begins.ptr<int32_t>();
+ const size_t seq = find_sequence(a.subsequence_begins, token);
+ if (seq + 1 >= a.subsequence_begins.size(0)) {
+ return; // not a token of any sequence
+ }
+ const int32_t token_begin = subsequence_begins[seq];
+ const int32_t token_end = subsequence_begins[seq + 1];
+ const int32_t block_begin = a.block_indices_begins.ptr<int32_t>()[seq];
+ OPENVINO_ASSERT(a.block_indices_begins.ptr<int32_t>()[seq + 1] > block_begin,
+ "[CPU] sparse_pa: each sequence must have at least one cache block");
+ const int64_t past_len = a.past_lens.ptr<int32_t>()[seq];
+
+ // The query heads of a pack share the K head and the selection head of the pack's first query head.
+ const size_t first_head = pack * pack_size;
+ const size_t k_head = first_head / (a.q_head_num / a.k_head_num);
+ const size_t sel_head = first_head / (a.q_head_num / a.sel_head_num);
+
+ // Per-thread scratch, see SparsePAScratchLayout.
+ uint8_t* ws = a.scratch + static_cast<size_t>(parallel_get_thread_num()) * a.scratch_bytes_per_thread;
+ PackWork w{a.key_cache,
+ a.value_cache,
+ a.block_indices.ptr<int32_t>() + block_begin,
+ a.quant,
+ a.k_head_size,
+ a.v_head_size,
+ k_head,
+ pack_size,
+ static_cast<int64_t>(a.key_block_size),
+ static_cast<int64_t>(a.page_size),
+ past_len + (static_cast<int32_t>(token) - token_begin),
+ // Enforced unconditionally (not just under causal) so a non-causal gather never reads an unallocated
+ // or stale slot in the physical pages.
+ past_len + (token_end - token_begin),
+ static_cast<int64_t>(a.max_run_rows),
+ a.causal,
+ a.scale,
+ a.query.ptr<T>(token, first_head * a.k_head_size),
+ reinterpret_cast<float*>(ws + layout.q),
+ reinterpret_cast<float*>(ws + layout.pack.acc),
+ reinterpret_cast<float*>(ws + layout.pack.running_max),
+ reinterpret_cast<float*>(ws + layout.pack.running_sum),
+ reinterpret_cast<float*>(ws + layout.scores),
+ reinterpret_cast<float*>(ws + layout.k_run),
+ reinterpret_cast<float*>(ws + layout.v_run)};
+ cvt_copy(w.q, a.query.ptr<T>(token, first_head * a.k_head_size), 1, w.pack_size * a.k_head_size, 0, 0);
+ std::fill_n(w.acc, w.pack_size * a.v_head_size, 0.0F);
+ std::fill_n(w.running_max, w.pack_size, -std::numeric_limits<float>::infinity());
+ std::fill_n(w.running_sum, w.pack_size, 0.0F);
+
+ // One query per selection row, so the row of a token is its global token index.
+ const int32_t* block_ids = a.sel_indices.ptr<int32_t>(token, sel_head);
+ const auto nblocks = static_cast<size_t>(*a.sel_count.ptr<int32_t>(token, sel_head));
+ OPENVINO_ASSERT(nblocks <= a.sel_indices.size(2),
+ "[CPU] sparse_pa: block_count exceeds the width of block_indices");
+ bool done = false;
+#ifdef OPENVINO_ARCH_X86_64
+ // The brgemm items (prefill, or a decode with enough selected bytes, see kBrgemmDecodeMinBytes) of a pack of query
+ // heads with 16-bit data on AMX: matrix products over the whole selection.
+ if constexpr (!std::is_same_v<T, float>) {
+ if (brgemm_item && a.brgemm.enabled() && pack_size > 1 && a.causal) {
+ attention_full_selection_brgemm<T>(a, w, ws, layout, block_ids, nblocks);
+ done = true;
+ }
+ }
+#endif
+ if (!done) {
+ attention_selected_blocks_simd(w, block_ids, nblocks);
+ attention_causal_tail_simd(w);
+ }
+
+ for (size_t head = 0; head < w.pack_size; head++) {
+ float* acc = w.acc + head * a.v_head_size;
+ const float inv_sum = w.running_sum[head] > 0.0F ? 1.0F / w.running_sum[head] : 0.0F;
+ for (size_t d = 0; d < a.v_head_size; d++) {
+ acc[d] *= inv_sum;
+ }
+ cvt_copy(a.out.ptr<T>(token, (first_head + head) * a.v_head_size), acc, 1, a.v_head_size, 0, 0);
+ }
+}
+
+// Sparse attention of every (global query token, query head pack) item of the work list, in parallel: the brgemm items
+// first, then the fallback items.
+template <typename T>
+void sparse_pa_impl(const SparsePAArgs& a, const ov::intel_cpu::CpuParallelPtr& cpu_parallel) {
+ const SparsePAScratchLayout layout(a.k_head_size,
+ a.v_head_size,
+ a.max_run_rows,
+ max_q_head_pack_size(a.q_head_num, a.k_head_num, a.sel_head_num),
+ sizeof(T),
+ a.quant,
+ sparse_brgemm_sizes(a.brgemm));
+ OPENVINO_ASSERT(layout.total <= a.scratch_bytes_per_thread, "[CPU] sparse_pa: scratch is too small");
+ const auto& work = a.work;
+ const size_t brgemm_per_token = a.q_head_num / work.brgemm_pack;
+ const size_t fallback_per_token = a.q_head_num / work.fallback_pack;
+ const size_t brgemm_items = work.brgemm_tokens * brgemm_per_token;
+ cpu_parallel->parallel_for(brgemm_items + work.fallback_tokens * fallback_per_token, [&](size_t item) {
+ if (item < brgemm_items) {
+ attention_work_item<T>(a,
+ layout,
+ work.token_ids[item / brgemm_per_token],
+ item % brgemm_per_token,
+ work.brgemm_pack,
+ true);
+ } else {
+ const size_t fallback_item = item - brgemm_items;
+ attention_work_item<T>(a,
+ layout,
+ work.token_ids[work.brgemm_tokens + fallback_item / fallback_per_token],
+ fallback_item % fallback_per_token,
+ work.fallback_pack,
+ false);
+ }
+ });
+}
+
+} // namespace
+
+void sparse_pa_compute(const ov::intel_cpu::PlainTensor& query,
+ const ov::intel_cpu::PlainTensor& key_cache,
+ const 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& subsequence_begins,
+ const ov::intel_cpu::PlainTensor& past_lens,
+ const ov::intel_cpu::PlainTensor& sel_indices,
+ const ov::intel_cpu::PlainTensor& sel_count,
+ ov::intel_cpu::PlainTensor& out,
+ size_t q_head_num,
+ size_t k_head_num,
+ size_t k_head_size,
+ size_t v_head_size,
+ size_t key_block_size,
+ size_t sel_head_num,
+ bool causal,
+ float scale,
+ const SparsePAQuant& quant,
+ size_t max_run_rows,
+ const SparseBrgemm& brgemm,
+ uint8_t* scratch,
+ size_t scratch_bytes_per_thread,
+ int32_t* token_ids,
+ const ov::intel_cpu::CpuParallelPtr& cpu_parallel) {
+ const auto data_prc = query.get_precision();
+ OPENVINO_ASSERT(out.get_precision() == data_prc, "[CPU] sparse_pa: query/output precisions must match");
+ // Plain caches: the query precision, or f16 next to f32 data like PagedAttention (read in place, no conversion
+ // pass). The AMX tiles are built for the query precision, so a cache of another type uses the SIMD heads.
+ const bool cache_is_data = key_cache.get_precision() == data_prc && value_cache.get_precision() == data_prc;
+ OPENVINO_ASSERT(quant.enabled() || cache_is_data ||
+ (data_prc == ov::element::f32 && key_cache.get_precision() == ov::element::f16 &&
+ value_cache.get_precision() == ov::element::f16),
+ "[CPU] sparse_pa: plain caches must have the query precision, or f16 with f32 data");
+ const bool tiles = brgemm.enabled() && (quant.enabled() || cache_is_data);
+ OPENVINO_ASSERT(!brgemm.enabled() || brgemm.prec == data_prc,
+ "[CPU] sparse_pa: the brgemm kernels must be built for the query precision");
+ OPENVINO_ASSERT(scratch != nullptr && token_ids != nullptr, "[CPU] sparse_pa: scratch must not be null");
+ OPENVINO_ASSERT(subsequence_begins.size(0) >= 1, "[CPU] sparse_pa: subsequence_begins must be non-empty");
+
+ // The work list: the tokens of sequences with several new tokens first (brgemm items when the node built the
+ // kernels), then the rest (fallback items); both id lists share the node's `token_ids` buffer (one id per token).
+ const size_t max_pack_size = max_q_head_pack_size(q_head_num, k_head_num, sel_head_num);
+ const auto* begins = subsequence_begins.ptr<int32_t>();
+ const size_t sequences = subsequence_begins.size(0) - 1;
+ const size_t tokens = query.size(0);
+ const auto in_range = [tokens](int32_t token) {
+ return static_cast<size_t>(token) < tokens;
+ };
+ // A decode token (a sequence of one new token) is a brgemm item too when its selection holds enough K / V bytes
+ // (plain caches; a quantized cache would be dequantized into the tile first).
+ const bool decode_brgemm =
+ tiles && !quant.enabled() &&
+ sel_indices.size(2) * key_block_size * (k_head_size + v_head_size) * brgemm.prec.size() >=
+ kBrgemmDecodeMinBytes;
+ const auto is_brgemm_sequence = [&](size_t seq) {
+ return tiles && (begins[seq + 1] - begins[seq] > 1 || decode_brgemm);
+ };
+ WorkList work;
+ work.token_ids = token_ids;
+ for (size_t seq = 0; seq < sequences; seq++) {
+ for (int32_t token = begins[seq]; token < begins[seq + 1] && in_range(token); token++) {
+ if (is_brgemm_sequence(seq)) {
+ token_ids[work.brgemm_tokens++] = token;
+ }
+ }
+ }
+ for (size_t seq = 0; seq < sequences; seq++) {
+ if (!is_brgemm_sequence(seq)) {
+ for (int32_t token = begins[seq]; token < begins[seq + 1] && in_range(token); token++) {
+ token_ids[work.brgemm_tokens + work.fallback_tokens++] = token;
+ }
+ }
+ }
+ work.brgemm_pack = max_pack_size;
+ const size_t fallback_items = work.fallback_tokens * (q_head_num / max_pack_size);
+ work.fallback_pack =
+ fallback_items >= 2 * static_cast<size_t>(cpu_parallel->get_num_worker_threads()) ? max_pack_size : 1;
+
+ // The physical page size: the key cache's dim 2 for plain caches; for quantized caches the node passes the real
+ // size, since by-channel key pages carry extra parameter rows in dim 2.
+ const size_t page_size = quant.block_size ? quant.block_size : key_cache.size(2);
+ const SparsePAArgs args{query,
+ key_cache,
+ value_cache,
+ block_indices,
+ block_indices_begins,
+ subsequence_begins,
+ past_lens,
+ sel_indices,
+ sel_count,
+ out,
+ q_head_num,
+ k_head_num,
+ k_head_size,
+ v_head_size,
+ key_block_size,
+ page_size,
+ sel_head_num,
+ causal,
+ scale,
+ quant,
+ max_run_rows,
+ brgemm,
+ scratch,
+ scratch_bytes_per_thread,
+ work};
+
+ // The data type is dispatched once; everything below works on T.
+ if (data_prc == ov::element::f32) {
+ sparse_pa_impl<float>(args, cpu_parallel);
+ } else if (data_prc == ov::element::f16) {
+ sparse_pa_impl<ov::float16>(args, cpu_parallel);
+ } else if (data_prc == ov::element::bf16) {
+ sparse_pa_impl<ov::bfloat16>(args, cpu_parallel);
+ } else {
+ OPENVINO_THROW("[CPU] sparse_pa: unsupported precision ", data_prc);
+ }
+}
+
+} // namespace ov::Extensions::Cpu::XARCH
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_pa_kernel.hpp b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_pa_kernel.hpp
new file mode 100644
index 00000000000..501bed58904
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_pa_kernel.hpp
@@ -0,0 +1,126 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+
+#include "cpu_parallel.hpp"
+#include "nodes/kernels/sparse_attn/sparse_brgemm.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "utils/general_utils.h"
+#include "utils/plain_tensor.hpp"
+
+// Defined outside XARCH, like QuantizeParam, so the cross-compiled dispatcher can name it in the signature.
+namespace ov::Extensions::Cpu {
+
+/// @brief Layout of quantized (u8/u4) paged KV caches, matching PagedAttention (see executor_pa.cpp):
+/// - by-token (key or value): each row is a sequence of groups `[scale f32][zp f32][group data]`, so the row
+/// holds `S + 8 * groups` elements (u8) or `S + 16 * groups` (u4); `*_group_size == 0` means one group per row.
+/// - by-channel (key only): each page is `f32 scale[S] | f32 zp[S] | data[block_size, S]`.
+/// The caches are either both quantized (`enabled()`) or both plain f32/f16/bf16. The node writes the current-step
+/// K/V into quantized caches before calling the kernel, so the kernel only reads them.
+struct SparsePAQuant {
+ ov::element::Type key_prec = ov::element::dynamic; ///< u8/u4 if the key cache is quantized, else dynamic
+ ov::element::Type value_prec = ov::element::dynamic;
+ size_t key_group_size = 0;
+ size_t value_group_size = 0;
+ bool key_bychannel = false;
+ size_t block_size = 0; ///< tokens per page, without by-channel parameter rows; 0 means key_cache dim 2
+
+ [[nodiscard]] bool enabled() const {
+ return key_prec != ov::element::dynamic;
+ }
+};
+
+/// @brief Byte layout of the per-thread scratch of the sparse PA kernel. The node allocates one such block per worker
+/// thread (so nothing is allocated while computing) and the kernel carves it up with the same layout. Every part is
+/// 64-byte aligned. Sizes are for the largest query-head pack, max_q_head_pack_size().
+struct SparsePAScratchLayout {
+ // Shared by every path: the state of the head pack (accumulators, running softmax maximum / sum).
+ PackStateLayout pack;
+
+ // SIMD path (run by run).
+ size_t q = 0; ///< float[pack, k_head_size]: query rows of the pack, f32
+ size_t scores = 0; ///< float[pack, max_run_rows]: scores, then weights, of a run of key rows
+ size_t k_run = 0; ///< quantized caches: float[max_run_rows, k_head_size] dequantized key run
+ size_t v_run = 0; ///< quantized caches, pack > 1: float[max_run_rows, v_head_size] dequantized value run
+
+ // Brgemm path: the gather tile, the scores / weights and the brgemm scratch.
+ SparseBrgemmLayout brgemm;
+
+ size_t total = 0; ///< bytes per thread
+
+ /// @param max_run_rows most key rows of one run: the page size when adjacent selected blocks are merged inside a
+ /// page, key_block_size when they are not
+ /// @param max_pack_size max_q_head_pack_size()
+ /// @param data_size size in bytes of the query/key/value data type
+ SparsePAScratchLayout(size_t k_head_size,
+ size_t v_head_size,
+ size_t max_run_rows,
+ size_t max_pack_size,
+ size_t data_size,
+ const SparsePAQuant& quant,
+ const SparseBrgemmSizes& brgemm_sizes = {})
+ : pack(0, k_head_size, v_head_size, max_pack_size, data_size, false),
+ q(pack.total),
+ scores(q + aligned(max_pack_size * k_head_size * sizeof(float))),
+ k_run(scores + aligned(max_pack_size * max_run_rows * sizeof(float))),
+ v_run(k_run + aligned(key_run_rows(quant, max_pack_size, max_run_rows) * k_head_size * sizeof(float))),
+ brgemm(v_run + aligned(value_run_rows(quant, max_pack_size, max_run_rows) * v_head_size * sizeof(float)),
+ k_head_size,
+ v_head_size,
+ max_pack_size,
+ data_size,
+ brgemm_sizes),
+ total(brgemm.total) {}
+
+private:
+ // Quantized keys are dequantized to f32 for by-channel keys and for packs; values for packs.
+ static size_t key_run_rows(const SparsePAQuant& quant, size_t max_pack_size, size_t max_run_rows) {
+ return quant.enabled() && (quant.key_bychannel || max_pack_size > 1) ? max_run_rows : 0;
+ }
+ static size_t value_run_rows(const SparsePAQuant& quant, size_t max_pack_size, size_t max_run_rows) {
+ return quant.enabled() && max_pack_size > 1 ? max_run_rows : 0;
+ }
+};
+
+} // namespace ov::Extensions::Cpu
+
+namespace ov::Extensions::Cpu::XARCH {
+
+// Single cross-compiled entry point for ov::intel_cpu::node::SparsePA (see sparse_pa.h for the algorithm
+// description). The node writes the current-step K/V into the caches first (paged_attn_memcpy /
+// paged_attn_quantkv, parallel over token x kv head), so this reads them: it parallelizes the sparse attention over
+// (global query token, query head), with one preallocated scratch block per worker thread (SparsePAScratchLayout).
+// Query and output share one floating-point type (f32/f16/bf16); plain caches have it too, or are f16 next to f32
+// data (like PagedAttention); quantized caches are described by `quant`. The physical page size is quant.block_size, or
+// the key cache's dim 2 for plain caches.
+void sparse_pa_compute(const ov::intel_cpu::PlainTensor& query,
+ const ov::intel_cpu::PlainTensor& key_cache,
+ const 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& subsequence_begins,
+ const ov::intel_cpu::PlainTensor& past_lens,
+ const ov::intel_cpu::PlainTensor& sel_indices,
+ const ov::intel_cpu::PlainTensor& sel_count,
+ ov::intel_cpu::PlainTensor& out,
+ size_t q_head_num,
+ size_t k_head_num,
+ size_t k_head_size,
+ size_t v_head_size,
+ size_t key_block_size,
+ size_t sel_head_num,
+ bool causal,
+ float scale,
+ const SparsePAQuant& quant,
+ size_t max_run_rows,
+ const SparseBrgemm& brgemm,
+ uint8_t* scratch,
+ size_t scratch_bytes_per_thread,
+ int32_t* token_ids,
+ const ov::intel_cpu::CpuParallelPtr& cpu_parallel);
+
+} // namespace ov::Extensions::Cpu::XARCH
\ No newline at end of file
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_sdpa_kernel.cpp b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_sdpa_kernel.cpp
new file mode 100644
index 00000000000..036b3017e60
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_sdpa_kernel.cpp
@@ -0,0 +1,550 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#include "nodes/kernels/sparse_attn/sparse_sdpa_kernel.hpp"
+
+#include <algorithm>
+#include <cmath>
+#include <cstddef>
+#include <cstdint>
+#include <cstring>
+#include <limits>
+#include <type_traits>
+
+#include "cpu_parallel.hpp"
+#include "nodes/kernels/scaled_attn/attn_quant_kernel.hpp"
+#include "nodes/kernels/scaled_attn/common.hpp"
+#include "nodes/kernels/scaled_attn/softmax_kernel.hpp"
+#include "nodes/kernels/sparse_attn/sparse_attn_kernel.hpp"
+#include "nodes/kernels/sparse_attn/sparse_brgemm.hpp"
+#include "nodes/kernels/sparse_attn/sparse_brgemm_kernel.hpp"
+#include "nodes/kernels/sparse_attn/sparse_sdpa_scratch.hpp"
+#ifdef OPENVINO_ARCH_X86_64
+# include "nodes/kernels/x64/brgemm_kernel.hpp"
+#endif
+#include "openvino/core/except.hpp"
+#include "openvino/core/parallel.hpp"
+#include "openvino/core/type/bfloat16.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "openvino/core/type/float16.hpp"
+#include "utils/plain_tensor.hpp"
+
+namespace ov::Extensions::Cpu::XARCH {
+
+using ov::intel_cpu::PlainTensor;
+
+namespace {
+
+// QUERY / KEY / VALUE / output share one precision T (the op validates it); only the rows touched are converted to
+// f32, never whole tensors. cvt_copy() vectorizes only inside a cross-compiled translation unit, which this file is.
+
+// Dequantizes `n` consecutive rows of the quantized cache (b, kv), starting at `pos`, into `dst` ([n, D], DstT).
+// Every row is made of D / group_size groups, each with its own {scale, zero point}.
+template <typename DstT>
+void dequant_rows(const PlainTensor& cache,
+ const SparseKVQuant& quant,
+ size_t b,
+ size_t kv,
+ size_t pos,
+ size_t n,
+ size_t D,
+ DstT* dst) {
+ if (quant.by_channel) {
+ // the rows of a group share the per-channel scale / zero point: dequantize the range group by group
+ const size_t group_size = quant.group_size;
+ for (size_t r = 0; r < n;) {
+ const size_t p = pos + r;
+ const size_t g = p / group_size;
+ const size_t rows = std::min(n - r, (g + 1) * group_size - p);
+ attn_dequant_by_channel_kernel<DstT, ov::element::u8>(cache.ptr_v(b, kv, p),
+ dst + r * D,
+ rows,
+ D,
+ cache.stride(2),
+ D,
+ quant.scale_zp->ptr<float>(g * 2, b, kv),
+ quant.scale_zp->ptr<float>(g * 2 + 1, b, kv));
+ r += rows;
+ }
+ return;
+ }
+ const bool is_u4 = quant.prec == ov::element::u4;
+ const size_t group_size = quant.group_size;
+ const size_t group_bytes = is_u4 ? group_size / 2 : group_size;
+ const size_t groups = D / group_size;
+ for (size_t r = 0; r < n; r++) {
+ const auto* row = static_cast<const uint8_t*>(cache.ptr_v(b, kv, pos + r));
+ const float* szp = quant.scale_zp->ptr<float>(pos + r, b, kv);
+ DstT* out = dst + r * D;
+ for (size_t g = 0; g < groups; g++) {
+ if (is_u4) {
+ attn_dequant_kernel<DstT, ov::element::u4>(row + g * group_bytes,
+ out + g * group_size,
+ group_size,
+ szp + g * 2);
+ } else {
+ attn_dequant_kernel<DstT, ov::element::u8>(row + g * group_bytes,
+ out + g * group_size,
+ group_size,
+ szp + g * 2);
+ }
+ }
+ }
+}
+
+// ---- Decode path (all but the brgemm prefill). One item = (batch, query, pack of heads sharing a K and a selection
+// head). Adjacent selected blocks form a run; K/V are read (or dequantized) once per pack and every head runs an online
+// softmax.
+
+struct DecodeItem {
+ const PlainTensor& query;
+ const PlainTensor& key;
+ const PlainTensor& value;
+ const SparseKVQuant& key_quant;
+ const SparseKVQuant& value_quant;
+ size_t b;
+ size_t kv; // K / V head of the pack
+ size_t first_head; // first query head of the pack
+ size_t l; // query index
+ size_t pack; // query heads of the pack
+ size_t Dh;
+ size_t Dv;
+ size_t Bk;
+ size_t S;
+ int64_t pad; // physical start of the real (non-padded) history
+ int64_t valid_end; // one past the last position the query may attend: S, or the query position + 1 when causal
+ float scale;
+ size_t max_run_rows;
+ size_t score_stride;
+ float* q; // [pack, Dh] f32 query rows
+ float* acc;
+ float* run_max;
+ float* run_sum;
+ float* scores; // [pack, score_stride]
+ float* dequant; // f32 rows of K, then of V, of a quantized cache
+};
+
+// Rows of [kpos0, kpos0 + n) the query attends (a prefix: the history ends at valid_end).
+inline int64_t visible_rows(const DecodeItem& it, int64_t kpos0, int64_t n) {
+ return kpos0 < it.pad ? 0 : std::max<int64_t>(std::min(n, it.valid_end - kpos0), 0);
+}
+
+// Online-softmax step of one head over scores[0, rows), of which the first `valid` rows are attended: rescales the
+// running state to the new maximum and turns the scores into weights in place. Rows from `valid` get weight 0.
+inline void softmax_step(DecodeItem& it, size_t head, size_t rows, size_t valid) {
+ float* scores = it.scores + head * it.score_stride;
+ float* acc = it.acc + head * it.Dv;
+ const float new_max = std::max(it.run_max[head], scale_and_max(scores, valid, it.scale));
+ if (new_max > it.run_max[head]) {
+ // corr == 0 for the first run (run_max == -inf), where acc and run_sum are still zero
+ const float corr = std::exp(it.run_max[head] - new_max);
+ it.run_sum[head] *= corr;
+ for (size_t d = 0; d < it.Dv; d++) {
+ acc[d] *= corr;
+ }
+ it.run_max[head] = new_max;
+ }
+ float sum = 0.0F;
+ exp_reduce_sum(scores, new_max, valid, sum);
+ it.run_sum[head] += sum;
+ std::fill(scores + valid, scores + rows, 0.0F);
+}
+
+// Attention over up to `n` consecutive rows from the physical position kpos0, clamped to the rows the query attends. A
+// quantized cache is dequantized into f32 rows (as the SIMD kernels of scaled_attn compute in float); plain rows are T.
+// The rows are converted once and multiplied with all the heads of the pack (one head is a pack of one).
+template <typename T>
+void attend_run(DecodeItem& it, int64_t kpos0, int64_t n) {
+ n = visible_rows(it, kpos0, n);
+ if (n <= 0) {
+ return;
+ }
+ const auto rows = static_cast<size_t>(n);
+ const auto pos = static_cast<size_t>(kpos0);
+ float* k_run = it.dequant;
+ float* v_run = it.dequant + it.score_stride * it.Dh;
+ if (it.key_quant.enabled()) {
+ dequant_rows<float>(it.key, it.key_quant, it.b, it.kv, pos, rows, it.Dh, k_run);
+ qk_scores_gqa<float>(it.q, it.pack, it.Dh, k_run, rows, it.scores, it.score_stride);
+ } else {
+ qk_scores_gqa<T>(it.q, it.pack, it.Dh, it.key.ptr<T>(it.b, it.kv, pos), rows, it.scores, it.score_stride);
+ }
+ for (size_t head = 0; head < it.pack; head++) {
+ softmax_step(it, head, rows, rows);
+ }
+ if (it.value_quant.enabled()) {
+ dequant_rows<float>(it.value, it.value_quant, it.b, it.kv, pos, rows, it.Dv, v_run);
+ pv_accumulate_gqa<float>(it.acc, it.pack, it.Dv, it.scores, it.score_stride, v_run, rows);
+ } else {
+ pv_accumulate_gqa<T>(it.acc,
+ it.pack,
+ it.Dv,
+ it.scores,
+ it.score_stride,
+ it.value.ptr<T>(it.b, it.kv, pos),
+ rows);
+ }
+}
+
+// Attention over the blocks that start at the positions start(0 .. count), in any order: consecutive blocks that are
+// adjacent form one run of at most max_run_rows rows (each of the others is a run of its own).
+template <typename T, typename StartFn>
+void attend_blocks(DecodeItem& it, size_t count, StartFn start) {
+ const auto Bk = static_cast<int64_t>(it.Bk);
+ const auto max_run_blocks = std::max<int64_t>(static_cast<int64_t>(it.max_run_rows) / Bk, 1);
+ size_t i = 0;
+ while (i < count) {
+ const int64_t first = start(i);
+ int64_t run_blocks = 1;
+ while (i + run_blocks < count && run_blocks < max_run_blocks &&
+ start(i + run_blocks) == first + run_blocks * Bk) {
+ run_blocks++;
+ }
+ attend_run<T>(it, first, run_blocks * Bk);
+ i += static_cast<size_t>(run_blocks);
+ }
+}
+
+#ifdef OPENVINO_ARCH_X86_64
+// ---- AMX prefill over a pack of query heads (sparse_brgemm_kernel.hpp) ----
+
+// The dense caches for the shared tile loop: the key/value rows of (batch b, kv head) are contiguous in positions; the
+// rows [pad, row_limit) are the ones the query attends.
+struct DenseRowSource {
+ const PlainTensor& key;
+ const PlainTensor& value;
+ const SparseKVQuant& key_quant;
+ const SparseKVQuant& value_quant;
+ size_t b;
+ size_t kv;
+ size_t k_head_size;
+ size_t v_head_size;
+ int64_t pad;
+ int64_t row_limit;
+
+ [[nodiscard]] int64_t visible(int64_t kpos0, int64_t n) const {
+ return kpos0 < pad ? 0 : std::max<int64_t>(std::min(kpos0 + n, row_limit) - kpos0, 0);
+ }
+
+ template <typename T>
+ void rows(int64_t kpos0, size_t n, const T** k_ptr, const T** v_ptr, T* k_stage, T* v_stage) const {
+ const auto pos = static_cast<size_t>(kpos0);
+ const T* k_src = k_stage;
+ if (key_quant.enabled()) {
+ dequant_rows<T>(key, key_quant, b, kv, pos, n, k_head_size, k_stage);
+ } else {
+ k_src = key.ptr<T>(b, kv, pos);
+ }
+ const T* v_src = v_stage;
+ if (value_quant.enabled()) {
+ dequant_rows<T>(value, value_quant, b, kv, pos, n, v_head_size, v_stage);
+ } else {
+ v_src = value.ptr<T>(b, kv, pos);
+ }
+ for (size_t i = 0; i < n; i++) {
+ k_ptr[i] = k_src + i * k_head_size;
+ v_ptr[i] = v_src + i * v_head_size;
+ }
+ }
+};
+
+struct SdpaBrgemmArgs {
+ const PlainTensor& query;
+ const PlainTensor& key;
+ const PlainTensor& value;
+ const PlainTensor& sel_indices;
+ const PlainTensor& sel_count;
+ PlainTensor& out;
+ size_t Hq;
+ size_t Hkv;
+ size_t Dh;
+ size_t Dv;
+ size_t Bk;
+ size_t H_sel;
+ float scale;
+ const int32_t* key_length;
+ size_t key_length_batch_stride;
+ const SparseKVQuant& key_quant;
+ const SparseKVQuant& value_quant;
+ const SparseBrgemm& brgemm;
+ const PackStateLayout& pack_layout;
+ const SparseBrgemmLayout& layout;
+ uint8_t* scratch;
+ size_t bytes_per_thread;
+ size_t pack_size;
+};
+
+// One work item: causal attention of query l of batch b for the pack `pack_index` of query heads that share a K head
+// and a selection head, over its selected blocks and its causal tail.
+template <typename T>
+void attention_item_brgemm(const SdpaBrgemmArgs& a, size_t b, size_t l, size_t pack_index) {
+ const size_t first_head = pack_index * a.pack_size;
+ const size_t kv = first_head / (a.Hq / a.Hkv);
+ const size_t sh = first_head / (a.Hq / a.H_sel);
+ const auto S = static_cast<int64_t>(a.key.size(2));
+ // Bottom-right-aligned logical position of the query, see the decode loop of sparse_sdpa_compute().
+ const int64_t token_pos = S - static_cast<int64_t>(a.query.size(2)) + static_cast<int64_t>(l);
+ const int64_t pad = a.key_length ? S - static_cast<int64_t>(a.key_length[a.key_length_batch_stride * b]) : 0;
+
+ uint8_t* ws = a.scratch + static_cast<size_t>(parallel_get_thread_num()) * a.bytes_per_thread;
+ const auto& lay = a.layout;
+ const auto& pack_lay = a.pack_layout;
+ auto* q_rows = reinterpret_cast<T*>(ws + pack_lay.q_rows);
+ for (size_t head = 0; head < a.pack_size; head++) {
+ std::memcpy(q_rows + head * a.Dh, a.query.ptr<T>(b, first_head + head, l), a.Dh * sizeof(T));
+ }
+ auto* acc = reinterpret_cast<float*>(ws + pack_lay.acc);
+ auto* running_max = reinterpret_cast<float*>(ws + pack_lay.running_max);
+ auto* running_sum = reinterpret_cast<float*>(ws + pack_lay.running_sum);
+ std::fill_n(acc, a.pack_size * a.Dv, 0.0F);
+ std::fill_n(running_max, a.pack_size, -std::numeric_limits<float>::infinity());
+ std::fill_n(running_sum, a.pack_size, 0.0F);
+
+ const BrgemmBuffers<T> buffers{static_cast<ov::intel_cpu::BrgemmKernel*>(a.brgemm.qk),
+ static_cast<ov::intel_cpu::BrgemmKernel*>(a.brgemm.pv_overwrite),
+ static_cast<ov::intel_cpu::BrgemmKernel*>(a.brgemm.pv_accumulate),
+ reinterpret_cast<T*>(ws + lay.k_rows),
+ reinterpret_cast<T*>(ws + lay.v_rows),
+ reinterpret_cast<const T**>(ws + lay.k_ptrs),
+ reinterpret_cast<const T**>(ws + lay.v_ptrs),
+ {reinterpret_cast<float*>(ws + lay.weights), a.brgemm.tile_rows},
+ ws + lay.brg_wsp,
+ ws + lay.brg_a,
+ ws + lay.brg_b};
+ const BrgemmPack pack{q_rows, a.pack_size, a.Dh, a.Dv, a.scale, acc, running_max, running_sum};
+
+ // sel_indices / sel_count carry complete selected blocks only; the incomplete trailing block of the query is
+ // attended as the causal tail, from the pad-aligned start of its block up to the query position.
+ const auto nblocks = static_cast<size_t>(*a.sel_count.ptr<int32_t>(b, sh, l));
+ OPENVINO_ASSERT(nblocks <= a.sel_indices.size(3),
+ "[CPU] sparse_sdpa: block_count exceeds the width of block_indices");
+ const auto key_block_size = static_cast<int64_t>(a.Bk);
+ const int64_t tail_start = pad + ((token_pos - pad + 1) / key_block_size) * key_block_size;
+ const BrgemmSelection selection{a.sel_indices.ptr<int32_t>(b, sh, l),
+ nblocks,
+ pad,
+ key_block_size,
+ tail_start,
+ std::max<int64_t>(token_pos - tail_start + 1, 0)};
+ const DenseRowSource
+ src{a.key, a.value, a.key_quant, a.value_quant, b, kv, a.Dh, a.Dv, pad, std::min(S, token_pos + 1)};
+ attention_over_selection_tiles<T>(src, pack, buffers, selection);
+
+ for (size_t head = 0; head < a.pack_size; head++) {
+ float* head_acc = acc + head * a.Dv;
+ const float inv_sum = running_sum[head] > 0.0F ? 1.0F / running_sum[head] : 0.0F;
+ for (size_t d = 0; d < a.Dv; d++) {
+ head_acc[d] *= inv_sum;
+ }
+ cvt_copy(a.out.ptr<T>(b, first_head + head, l), head_acc, 1, a.Dv, 0, 0);
+ }
+}
+
+// Causal prefill (more than one query) of packs of query heads with bf16 / f16 data on AMX, parallel over (batch,
+// query, pack).
+template <typename T>
+void sparse_sdpa_brgemm(const SdpaBrgemmArgs& a, const ov::intel_cpu::CpuParallelPtr& cpu_parallel) {
+ cpu_parallel->parallel_for3d(a.query.size(0),
+ a.query.size(2),
+ a.Hq / a.pack_size,
+ [&](size_t b, size_t l, size_t pack_index) {
+ attention_item_brgemm<T>(a, b, l, pack_index);
+ });
+}
+#endif // OPENVINO_ARCH_X86_64
+
+} // namespace
+
+void sparse_sdpa_compute(const ov::intel_cpu::PlainTensor& query,
+ const ov::intel_cpu::PlainTensor& key,
+ const ov::intel_cpu::PlainTensor& value,
+ const ov::intel_cpu::PlainTensor& sel_indices,
+ const ov::intel_cpu::PlainTensor& sel_count,
+ ov::intel_cpu::PlainTensor& out,
+ size_t num_heads,
+ size_t num_kv_heads,
+ size_t k_head_size,
+ size_t v_head_size,
+ size_t sel_block_size,
+ size_t h_sel,
+ bool causal,
+ float scale,
+ float* scratch_floats,
+ size_t per_thread_floats,
+ const SparseBrgemm& brgemm,
+ const PackStateLayout& pack_layout,
+ const SparseBrgemmLayout& brgemm_layout,
+ uint8_t* brgemm_scratch,
+ size_t brgemm_bytes_per_thread,
+ const int32_t* key_length,
+ size_t key_length_batch_stride,
+ const SparseKVQuant& key_quant,
+ const SparseKVQuant& value_quant,
+ const ov::intel_cpu::CpuParallelPtr& cpu_parallel) {
+ const size_t q_per_sel = num_heads / h_sel;
+ const size_t group = num_heads / num_kv_heads;
+
+ const size_t B = query.size(0);
+ const size_t L = query.size(2);
+ const size_t S = key.size(2);
+
+#ifdef OPENVINO_ARCH_X86_64
+ // Prefill, or a decode whose selection holds enough K / V bytes (kBrgemmDecodeMinBytes): the query heads sharing a
+ // K head and a selection head are one item of matrix products over the gathered rows. Other decodes keep the loop
+ // below.
+ // A quantized cache stays on the per-head SIMD loop: its rows would be dequantized into the tiles first, which made
+ // the decode 16-35% slower than the SIMD loop (u8, 2-4 MiB of K / V per item).
+ const bool decode_brgemm =
+ !key_quant.enabled() && !value_quant.enabled() &&
+ sel_indices.size(3) * sel_block_size * (k_head_size + v_head_size) * brgemm.prec.size() >=
+ kBrgemmDecodeMinBytes;
+ if (brgemm.enabled() && causal && (L > 1 || decode_brgemm)) {
+ const SdpaBrgemmArgs args{query,
+ key,
+ value,
+ sel_indices,
+ sel_count,
+ out,
+ num_heads,
+ num_kv_heads,
+ k_head_size,
+ v_head_size,
+ sel_block_size,
+ h_sel,
+ scale,
+ key_length,
+ key_length_batch_stride,
+ key_quant,
+ value_quant,
+ brgemm,
+ pack_layout,
+ brgemm_layout,
+ brgemm_scratch,
+ brgemm_bytes_per_thread,
+ max_q_head_pack_size(num_heads, num_kv_heads, h_sel)};
+ // The brgemm path reads the query and the output as the brgemm's data type, and so the key and value unless
+ // the cache is compressed (u8 / u4 rows, dequantized on the fly).
+ OPENVINO_ASSERT(query.get_precision() == brgemm.prec && out.get_precision() == brgemm.prec &&
+ (key_quant.enabled() || key.get_precision() == brgemm.prec) &&
+ (value_quant.enabled() || value.get_precision() == brgemm.prec),
+ "[CPU] sparse_sdpa: the brgemm path requires the query, output and plain key and value of "
+ "the brgemm precision");
+ OPENVINO_ASSERT(brgemm_scratch != nullptr && brgemm_layout.total <= brgemm_bytes_per_thread,
+ "[CPU] sparse_sdpa: the brgemm scratch is missing or too small");
+ if (brgemm.prec == ov::element::bf16) {
+ sparse_sdpa_brgemm<ov::bfloat16>(args, cpu_parallel);
+ } else {
+ sparse_sdpa_brgemm<ov::float16>(args, cpu_parallel);
+ }
+ return;
+ }
+#endif
+
+ // Query heads sharing a K head and a selection head form one item: the rows are read once for all of them. With too
+ // little work for the threads (a decode of few sequences) every head is its own item.
+ const size_t max_pack = max_q_head_pack_size(num_heads, num_kv_heads, h_sel);
+ const SdpaDecodeScratch layout(k_head_size,
+ v_head_size,
+ max_pack,
+ sel_block_size,
+ key_quant.enabled() || value_quant.enabled());
+ OPENVINO_ASSERT(layout.total <= per_thread_floats, "[CPU] sparse_sdpa: scratch is too small");
+ // Items are (b, pack, l). A pack shares the chunk split and the K/V reads but divides the item count, so use packs
+ // only with at least 2 items per worker thread; otherwise every query head is its own item.
+ const size_t pack =
+ B * L * (num_heads / max_pack) >= 2 * static_cast<size_t>(cpu_parallel->get_num_worker_threads()) ? max_pack
+ : 1;
+
+ const auto run_decode = [&](auto type_tag) {
+ using T = decltype(type_tag);
+ cpu_parallel->parallel_for3d(B, num_heads / pack, L, [&](size_t b, size_t pack_index, size_t l) {
+ // Bottom-right-aligned logical position: the query at index l aligns with the last l-th
+ // position of the dense [0, S) key/value history. Invariant to left-padding since
+ // pad[b] + p == token_pos for the spec's logical query position p.
+ const int64_t token_pos = static_cast<int64_t>(S) - static_cast<int64_t>(L) + static_cast<int64_t>(l);
+ const size_t first_head = pack_index * pack;
+ const size_t sh = first_head / q_per_sel;
+ const size_t kv = first_head / group;
+ // Physical start of batch b's real (non-padded) history; 0 when key_length is absent.
+ const int64_t pad =
+ key_length ? static_cast<int64_t>(S) - static_cast<int64_t>(key_length[key_length_batch_stride * b])
+ : 0;
+
+ const auto tid = static_cast<size_t>(parallel_get_thread_num());
+ float* const row = scratch_floats + tid * per_thread_floats;
+ DecodeItem it{query,
+ key,
+ value,
+ key_quant,
+ value_quant,
+ b,
+ kv,
+ first_head,
+ l,
+ pack,
+ k_head_size,
+ v_head_size,
+ sel_block_size,
+ S,
+ pad,
+ causal ? std::min(static_cast<int64_t>(S), token_pos + 1) : static_cast<int64_t>(S),
+ scale,
+ layout.max_run_rows,
+ layout.score_stride,
+ row + layout.q,
+ row + layout.acc,
+ row + layout.run_max,
+ row + layout.run_sum,
+ row + layout.scores,
+ row + layout.dequant};
+ for (size_t head = 0; head < pack; head++) {
+ cvt_copy(it.q + head * k_head_size, query.ptr<T>(b, first_head + head, l), 1, k_head_size, 0, 0);
+ }
+ std::fill(it.acc, it.acc + pack * v_head_size, 0.0F);
+ std::fill(it.run_max, it.run_max + pack, -std::numeric_limits<float>::infinity());
+ std::fill(it.run_sum, it.run_sum + pack, 0.0F);
+
+ const int32_t* block_ids = sel_indices.ptr<int32_t>(b, sh, l);
+ // The count comes from the producer of the selection: a negative one becomes a huge size_t, so it fails
+ // here too.
+ const auto nblocks = static_cast<size_t>(*sel_count.ptr<int32_t>(b, sh, l));
+ OPENVINO_ASSERT(nblocks <= sel_indices.size(3),
+ "[CPU] sparse_sdpa: block_count exceeds the width of block_indices");
+ const auto block_start = [&](size_t i) {
+ return pad + static_cast<int64_t>(block_ids[i]) * static_cast<int64_t>(sel_block_size);
+ };
+ attend_blocks<T>(it, nblocks, block_start);
+
+ // sel_indices/sel_count only ever carry *complete* selected blocks -- the producer never
+ // encodes the current incomplete trailing block. When causal, this consumer must derive and
+ // attend that tail itself from the query's own logical position.
+ if (causal) {
+ const int64_t tail_start = pad + (((token_pos - pad + 1) / static_cast<int64_t>(sel_block_size)) *
+ static_cast<int64_t>(sel_block_size));
+ attend_run<T>(it, tail_start, token_pos - tail_start + 1);
+ }
+
+ for (size_t head = 0; head < pack; head++) {
+ float* acc = it.acc + head * v_head_size;
+ const float inv_sum = it.run_sum[head] > 0.0F ? 1.0F / it.run_sum[head] : 0.0F;
+ for (size_t d = 0; d < v_head_size; d++) {
+ acc[d] *= inv_sum;
+ }
+ cvt_copy(out.ptr<T>(b, first_head + head, l), acc, 1, v_head_size, 0, 0);
+ }
+ });
+ };
+ visit_float_type(query.get_precision(), run_decode);
+}
+
+void sparse_kv_dequantize_rows(const ov::intel_cpu::PlainTensor& cache,
+ const SparseKVQuant& quant,
+ size_t b,
+ size_t h,
+ size_t L,
+ size_t D,
+ float* dst) {
+ dequant_rows<float>(cache, quant, b, h, 0, L, D, dst);
+}
+
+} // namespace ov::Extensions::Cpu::XARCH
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_sdpa_kernel.hpp b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_sdpa_kernel.hpp
new file mode 100644
index 00000000000..430a2bdac4f
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_sdpa_kernel.hpp
@@ -0,0 +1,81 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+
+#include "cpu_parallel.hpp"
+#include "nodes/kernels/sparse_attn/sparse_brgemm.hpp"
+#include "nodes/kernels/sparse_attn/sparse_sdpa_scratch.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "utils/plain_tensor.hpp"
+
+namespace ov::Extensions::Cpu {
+
+// Describes how the key (or value) cache rows are stored. A plain cache is read as is (any of f32/f16/bf16, see
+// load_row_f32() in the kernel). A quantized cache (u8 / u4, per-token groups of `group_size` elements) holds the
+// quantized rows in `cache` and the {scale, zero point} pairs of the groups in `scale_zp`, laid out as
+// [L, B, H, 2 * D / group_size] -- the layout written by attn_quant_by_token() -- and the rows that are touched are
+// dequantized on the fly: only the selected blocks and the causal tail, never the whole history.
+// With `by_channel` (u8 only) the groups run along L instead: `group_size` consecutive tokens share one
+// {scale, zero point} per channel, and `scale_zp` is [2 * ceil(L / group_size), B, H, D] -- the layout written by
+// attn_quant_by_channel(): row 2 * g holds the scales of group g, row 2 * g + 1 its zero points.
+struct SparseKVQuant {
+ ov::element::Type prec = ov::element::dynamic; // u8 / u4, anything else means "not quantized"
+ size_t group_size = 0; // elements of a row per group, or tokens per group when by_channel
+ bool by_channel = false;
+ const ov::intel_cpu::PlainTensor* scale_zp = nullptr;
+
+ // A compressed cache needs the scale / zero point tensor and a group; the by-channel layout exists for u8 only.
+ [[nodiscard]] bool enabled() const {
+ return scale_zp != nullptr && group_size > 0 &&
+ (prec == ov::element::u8 || (prec == ov::element::u4 && !by_channel));
+ }
+};
+
+} // namespace ov::Extensions::Cpu
+
+namespace ov::Extensions::Cpu::XARCH {
+
+// Single cross-compiled entry point of SparseSDPA (see sparse_sdpa.h). The node marshals the MemoryPtrs and the
+// scratch, which needs GraphContext, then calls this once. The SIMD decode, the brgemm prefill and the row conversion
+// stay in sparse_sdpa_kernel.cpp so the per-ISA clones vectorize them.
+void sparse_sdpa_compute(const ov::intel_cpu::PlainTensor& query,
+ const ov::intel_cpu::PlainTensor& key,
+ const ov::intel_cpu::PlainTensor& value,
+ const ov::intel_cpu::PlainTensor& sel_indices,
+ const ov::intel_cpu::PlainTensor& sel_count,
+ ov::intel_cpu::PlainTensor& out,
+ size_t num_heads,
+ size_t num_kv_heads,
+ size_t k_head_size,
+ size_t v_head_size,
+ size_t sel_block_size,
+ size_t h_sel,
+ bool causal,
+ float scale,
+ float* scratch_floats,
+ size_t per_thread_floats,
+ const SparseBrgemm& brgemm,
+ const PackStateLayout& pack_layout,
+ const SparseBrgemmLayout& brgemm_layout,
+ uint8_t* brgemm_scratch,
+ size_t brgemm_bytes_per_thread,
+ const int32_t* key_length,
+ size_t key_length_batch_stride,
+ const SparseKVQuant& key_quant,
+ const SparseKVQuant& value_quant,
+ const ov::intel_cpu::CpuParallelPtr& cpu_parallel);
+
+// Dequantizes the rows [0, L) of the quantized cache (b, h) into dense f32 rows, `dst` is [L, D].
+void sparse_kv_dequantize_rows(const ov::intel_cpu::PlainTensor& cache,
+ const SparseKVQuant& quant,
+ size_t b,
+ size_t h,
+ size_t L,
+ size_t D,
+ float* dst);
+
+} // namespace ov::Extensions::Cpu::XARCH
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_sdpa_scratch.hpp b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_sdpa_scratch.hpp
new file mode 100644
index 00000000000..f26bb964f69
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/sparse_attn/sparse_sdpa_scratch.hpp
@@ -0,0 +1,50 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#pragma once
+
+#include <algorithm>
+#include <cstddef>
+
+#include "utils/general_utils.h"
+
+namespace ov::Extensions::Cpu {
+
+// Per-thread scratch of the decode path, for the largest head pack of one item:
+// q[pack, Dh] | acc[pack, Dv] | run_max[pack] | run_sum[pack] | scores[pack, score_stride] | dequantized rows
+// score_stride is max_run_rows, the widest run of adjacent blocks; the last region holds a quantized cache's K, then V
+// rows.
+struct SdpaDecodeScratch {
+ static constexpr size_t kMaxRunRows = 128; // rows of adjacent selected blocks attended by one run (>= Bk)
+
+ size_t max_run_rows = 0;
+ size_t score_stride = 0;
+ size_t q = 0;
+ size_t acc = 0;
+ size_t run_max = 0;
+ size_t run_sum = 0;
+ size_t scores = 0;
+ size_t dequant = 0;
+ size_t total = 0; // floats per thread, a multiple of 16
+
+ SdpaDecodeScratch() = default;
+ SdpaDecodeScratch(size_t Dh, size_t Dv, size_t max_pack, size_t Bk, bool quantized)
+ : max_run_rows(Bk * std::max<size_t>(kMaxRunRows / Bk, 1)),
+ score_stride(max_run_rows) {
+ size_t offset = 0;
+ auto take = [&offset](size_t floats) {
+ const size_t start = offset;
+ offset += ov::intel_cpu::rnd_up(floats, size_t{16});
+ return start;
+ };
+ q = take(max_pack * Dh);
+ acc = take(max_pack * Dv);
+ run_max = take(max_pack);
+ run_sum = take(max_pack);
+ scores = take(max_pack * score_stride);
+ dequant = take(quantized ? score_stride * (Dh + Dv) : 0);
+ total = offset;
+ }
+};
+
+} // namespace ov::Extensions::Cpu
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/x64/brgemm_kernel.cpp b/src/plugins/intel_cpu/src/nodes/kernels/x64/brgemm_kernel.cpp
index 49236a403fa..943fa594bd1 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/x64/brgemm_kernel.cpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/x64/brgemm_kernel.cpp
@@ -44,7 +44,8 @@ BrgemmKernel::BrgemmKernel(size_t M,
size_t ldc,
bool b_transposed,
ov::element::Type inType,
- bool b_accumulate)
+ bool b_accumulate,
+ bool fuse_relu)
: BrgemmKernel(M,
N,
K,
@@ -56,7 +57,8 @@ BrgemmKernel::BrgemmKernel(size_t M,
inType,
ov::element::dynamic,
BrgemmKernel::ScaleType::NONE,
- b_accumulate) {}
+ b_accumulate,
+ fuse_relu) {}
BrgemmKernel::BrgemmKernel(size_t M,
size_t N,
@@ -69,7 +71,8 @@ BrgemmKernel::BrgemmKernel(size_t M,
ov::element::Type inType,
ov::element::Type DType,
BrgemmKernel::ScaleType bScaleType,
- bool b_accumulate)
+ bool b_accumulate,
+ bool fuse_relu)
: M(M),
M_blk(matmulOptimalM),
M_tail(M % M_blk),
@@ -83,7 +86,8 @@ BrgemmKernel::BrgemmKernel(size_t M,
inType(inType),
DType(DType),
bScaleType(bScaleType),
- b_accumulate(b_accumulate) {
+ b_accumulate(b_accumulate),
+ post_relu(fuse_relu) {
if (none_of(inType, ov::element::i8, ov::element::bf16, ov::element::f16, ov::element::f32)) {
THROW_ERROR("brgemm kernel only supports i8, f16, bf16, f32");
}
@@ -282,6 +286,14 @@ void BrgemmKernel::init_brgemm(brgemmCtx& ctx,
status = memory_desc_init_by_strides(Dmd, /* ndims = */ 2, dims, dnnl_data_type_t::dnnl_f32, strides);
attr.scales_.set(DNNL_ARG_WEIGHTS, 2);
status = brgemm_desc_set_postops(&brgDesc, &attr, &Dmd, ldd, data_type::undef);
+ } else if (post_relu) {
+ dnnl::impl::primitive_attr_t attr;
+ memory_desc_t Dmd;
+ dims_t dims{static_cast<dnnl_dim_t>(ctx.M), static_cast<dnnl_dim_t>(ctx.N)};
+ dims_t strides{static_cast<dnnl_dim_t>(ldd), static_cast<dnnl_dim_t>(1)};
+ status = memory_desc_init_by_strides(Dmd, /* ndims = */ 2, dims, dnnl_data_type_t::dnnl_f32, strides);
+ attr.post_ops_.append_eltwise(1.0F, alg_kind::eltwise_relu, 0.0F, 0.0F);
+ status = brgemm_desc_set_postops(&brgDesc, &attr, &Dmd, ldd, data_type::undef);
}
if (status != dnnl_success) {
@@ -460,7 +472,25 @@ void BrgemmKernel::executeGemm(bool is_M_tail,
execute_without_scale(is_M_tail, a, b, c, wsp, scratch_a);
}
-void BrgemmKernel::execute_without_scale(bool is_M_tail, void* a, void* b, void* c, void* wsp, void* scratch_a) {
+void BrgemmKernel::executeGemm(bool is_M_tail,
+ void* a,
+ void* b,
+ void* c,
+ [[maybe_unused]] void* d,
+ [[maybe_unused]] float* scale_b,
+ void* wsp,
+ void* scratch_a,
+ AmxTileState& tiles) {
+ execute_without_scale(is_M_tail, a, b, c, wsp, scratch_a, &tiles);
+}
+
+void BrgemmKernel::execute_without_scale(bool is_M_tail,
+ void* a,
+ void* b,
+ void* c,
+ void* wsp,
+ void* scratch_a,
+ AmxTileState* tiles) {
auto* ptr_A = reinterpret_cast<uint8_t*>(a);
auto* ptr_C = reinterpret_cast<uint8_t*>(c);
auto* ptr_scartch_a = reinterpret_cast<uint8_t*>(scratch_a);
@@ -509,15 +539,18 @@ void BrgemmKernel::execute_without_scale(bool is_M_tail, void* a, void* b, void*
auto* weight_ptr = ptr_scartch_b + B_stride;
auto C_stride = n * count_N * ov::element::f32.size();
auto* out_ptr = ptr_C + C_stride;
+ // the ReLU post-op runs with the last K step of the result block (in place: C is also D)
+ const bool do_post = post_relu && ((k == 0 && K_tail == 0) || k == 1);
callBrgemm(brgemmCtx,
brgKernels[getBrgIdx(mIdx, k, n)],
local_a_ptr,
weight_ptr,
out_ptr,
- nullptr,
+ do_post ? out_ptr : nullptr,
nullptr,
wsp,
- false);
+ do_post,
+ tiles);
// stride K, N if body kernel is executed.
if (k == 0) {
count_K = brgemmCtx.K * brgemmCtx.LDB;
@@ -538,8 +571,9 @@ void BrgemmKernel::callBrgemm(brgemmCtx& ctx,
void* Dout,
const float* bScale,
void* wsp,
- bool doPostops) {
- if (ctx.is_with_amx) {
+ bool doPostops,
+ AmxTileState* tiles) {
+ if (ctx.is_with_amx && (tiles == nullptr || tiles->needs_configure(ctx.palette))) {
amx_tile_configure(ctx.palette);
}
if (doPostops) {
@@ -582,9 +616,33 @@ void BrgemmKernelQuantized::executeGemm(bool is_M_tail,
float* scale_b,
void* wsp,
void* scratch_a) {
+ execute_scaled(is_M_tail, a, b, c, d, scale_b, wsp, scratch_a, nullptr);
+}
+
+void BrgemmKernelQuantized::executeGemm(bool is_M_tail,
+ void* a,
+ void* b,
+ void* c,
+ void* d,
+ float* scale_b,
+ void* wsp,
+ void* scratch_a,
+ AmxTileState& tiles) {
+ execute_scaled(is_M_tail, a, b, c, d, scale_b, wsp, scratch_a, &tiles);
+}
+
+void BrgemmKernelQuantized::execute_scaled(bool is_M_tail,
+ void* a,
+ void* b,
+ void* c,
+ void* d,
+ float* scale_b,
+ void* wsp,
+ void* scratch_a,
+ AmxTileState* tiles) {
// If no scale is provided, run kernel without post-scales
if (scale_b == nullptr) {
- execute_without_scale(is_M_tail, a, b, c, wsp, scratch_a);
+ execute_without_scale(is_M_tail, a, b, c, wsp, scratch_a, tiles);
return;
}
auto* ptr_A = reinterpret_cast<uint8_t*>(a);
@@ -646,7 +704,8 @@ void BrgemmKernelQuantized::executeGemm(bool is_M_tail,
d_ptr,
scale_b + n * count_N,
wsp,
- do_post);
+ do_post,
+ tiles);
// stride K, N if body kernel is executed.
if (k == 0) {
count_K = brgemmCtx.K * brgemmCtx.LDB;
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/x64/brgemm_kernel.hpp b/src/plugins/intel_cpu/src/nodes/kernels/x64/brgemm_kernel.hpp
index cc662da4966..3b81330944c 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/x64/brgemm_kernel.hpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/x64/brgemm_kernel.hpp
@@ -8,10 +8,32 @@
#include <cpu/x64/matmul/brgemm_matmul_copy_utils.hpp>
#include <cpu/x64/matmul/brgemm_matmul_utils.hpp>
#include <cstddef>
+#include <cstring>
#include <openvino/core/type/element_type.hpp>
namespace ov::intel_cpu {
+// Which AMX palette the calling thread's tiles hold, to skip redundant configurations of back-to-back brgemm calls (a
+// ldtilecfg each), like prev_ker_idx of the oneDNN brgemm primitives. Make it a local of the loop that runs the
+// calls, so it starts out "unknown", and pass it to every executeGemm() of the loop; the thread must not run other
+// AMX code that changes the tile configuration (oneDNN primitives, calls without the state) between those calls.
+class AmxTileState {
+public:
+ // Whether `palette` has to be loaded on the tile hardware; remembers it as the configured one.
+ bool needs_configure(const char* palette) {
+ if (m_configured && std::memcmp(m_palette, palette, sizeof(m_palette)) == 0) {
+ return false;
+ }
+ std::memcpy(m_palette, palette, sizeof(m_palette));
+ m_configured = true;
+ return true;
+ }
+
+private:
+ char m_palette[dnnl::impl::cpu::x64::AMX_PALETTE_SIZE] = {};
+ bool m_configured = false;
+};
+
class BrgemmKernel {
public:
enum ScaleType : uint8_t { NONE, PER_CHANNEL, PER_TENSOR };
@@ -23,6 +45,8 @@ public:
// ldb is the leading dimension for B matrix
// ldc is the leading dimension for C matrix
// b_transpose indicates wheter B matrix is transposed.
+ // fuse_relu applies ReLU to the result as a brgemm post-op: C = max(0, A * B). BrgemmKernelQuantized has no such
+ // option: its post-op slot is taken by the scales.
BrgemmKernel(size_t M,
size_t N,
size_t K,
@@ -31,7 +55,8 @@ public:
size_t ldc,
bool b_transposed = false,
ov::element::Type inType = ov::element::bf16,
- bool b_accumulate = false);
+ bool b_accumulate = false,
+ bool fuse_relu = false);
virtual ~BrgemmKernel() = default;
@@ -46,6 +71,16 @@ public:
// scratch_a, pointer to store temp a
virtual void
executeGemm(bool is_M_tail, void* a, void* b, void* c, void* d, float* scale_b, void* wsp, void* scratch_a);
+ // The same, configuring the AMX tiles only when `tiles` does not hold the palette of the call already
+ virtual void executeGemm(bool is_M_tail,
+ void* a,
+ void* b,
+ void* c,
+ void* d,
+ float* scale_b,
+ void* wsp,
+ void* scratch_a,
+ AmxTileState& tiles);
void copy_buffer_b(void* b, void* scratch_b);
// bytes needed to place scratch buffer a
@@ -83,7 +118,8 @@ protected:
ov::element::Type inType,
ov::element::Type DType,
ScaleType bScaleType,
- bool b_accumulate);
+ bool b_accumulate,
+ bool fuse_relu = false);
size_t M = 0, M_blk = 0, M_tail = 0;
size_t K = 0, K_blk = 0, K_tail = 0, N = 0, N_blk = 0, N_tail = 0;
size_t lda = 0, ldb = 0, ldc = 0, ldd = 0;
@@ -98,6 +134,7 @@ protected:
ScaleType bScaleType = ScaleType::NONE;
bool is_avx_f16_only = false;
bool b_accumulate = false;
+ bool post_relu = false;
static constexpr size_t MHA_BRGEMM_KERNELS_NUM = 8;
static constexpr size_t matmulOptimalM = 32;
struct brgemmCtx {
@@ -117,7 +154,13 @@ protected:
static size_t getBrgIdx(size_t mIdx, size_t kIdx, size_t nIdx) {
return mIdx * 4 + kIdx * 2 + nIdx;
}
- void execute_without_scale(bool is_M_tail, void* a, void* b, void* c, void* wsp, void* scratch_a);
+ void execute_without_scale(bool is_M_tail,
+ void* a,
+ void* b,
+ void* c,
+ void* wsp,
+ void* scratch_a,
+ AmxTileState* tiles = nullptr);
void init_brgemm(brgemmCtx& ctx, std::unique_ptr<dnnl::impl::cpu::x64::brgemm_kernel_t>& brgKernel, bool use_amx);
// LDA, LDB is used for stride of target memory
void init_brgemm_copy_a(std::unique_ptr<dnnl::impl::cpu::x64::matmul::jit_brgemm_matmul_copy_a_t>& brgCopyKernel,
@@ -149,7 +192,8 @@ protected:
void* Dout,
const float* bScale,
void* wsp,
- bool doPostops);
+ bool doPostops,
+ AmxTileState* tiles = nullptr);
};
class BrgemmKernelQuantized : public BrgemmKernel {
@@ -172,5 +216,25 @@ public:
// execute by m_blk + scale
void executeGemm(bool is_M_tail, void* a, void* b, void* c, void* d, float* scale_b, void* wsp, void* scratch_a)
override;
+ void executeGemm(bool is_M_tail,
+ void* a,
+ void* b,
+ void* c,
+ void* d,
+ float* scale_b,
+ void* wsp,
+ void* scratch_a,
+ AmxTileState& tiles) override;
+
+private:
+ void execute_scaled(bool is_M_tail,
+ void* a,
+ void* b,
+ void* c,
+ void* d,
+ float* scale_b,
+ void* wsp,
+ void* scratch_a,
+ AmxTileState* tiles);
};
} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/nodes/memory.cpp b/src/plugins/intel_cpu/src/nodes/memory.cpp
index 2d8d4f9f320..f640434c728 100644
--- a/src/plugins/intel_cpu/src/nodes/memory.cpp
+++ b/src/plugins/intel_cpu/src/nodes/memory.cpp
@@ -48,6 +48,7 @@
#include "shape_inference/shape_inference_cpu.hpp"
#include "shape_inference/shape_inference_internal_dyn.hpp"
#include "shape_inference/shape_inference_pass_through.hpp"
+#include "sparse_sdpa.h"
#include "transformations/cpu_opset/common/op/read_value_with_subgraph.hpp"
#include "utils/general_utils.h"
@@ -1158,7 +1159,7 @@ void MemoryInputSDPA::runDynamic([[maybe_unused]] dnnl::stream strm) {
}
void MemoryInputSDPA::resolveInPlaceEdges(Edge::LOOK look) {
- if (getParentEdgeAt(0)) {
+ if (!getParentEdges().empty()) {
ov::intel_cpu::node::Input::resolveInPlaceEdges(look);
} else {
auto memDesc = getBaseMemDescAtOutputPort(0);
@@ -1173,6 +1174,73 @@ void MemoryInputSDPA::resolveInPlaceEdges(Edge::LOOK look) {
}
}
+MemoryInputSparseSDPA::MemoryInputSparseSDPA(const std::string& id,
+ const std::string& name,
+ const std::string& type,
+ const Shape& output_shape,
+ const ov::element::Type& output_prc,
+ const GraphContext::CPtr& context,
+ const std::optional<std::vector<Shape>>& input_shape,
+ const std::optional<std::vector<ov::element::Type>>& input_prc,
+ const std::shared_ptr<SparseSDPA>& sparseNode)
+ : MemoryInputSDPA(id, name, type, output_shape, output_prc, context, input_shape, input_prc, nullptr),
+ m_sparseNode(sparseNode) {}
+
+void MemoryInputSparseSDPA::createPrimitive() {
+ // MemoryInputSDPA::createPrimitive() looks for the (absent) SDPA node
+ MemoryInputBase::createPrimitive(); // NOLINT(bugprone-parent-virtual-call): skips MemoryInputSDPA on purpose
+ auto sparseNode = m_sparseNode.lock();
+ for (auto&& edge : getChildEdgesAtPort(0)) { // always only one child port
+ if (edge->getChild() == sparseNode) {
+ m_sparse_port_idx = edge->getOutputNum();
+ break;
+ }
+ }
+ CPU_NODE_ASSERT(m_sparse_port_idx != -1, getName(), " should be connected to SparseSDPA node.");
+}
+
+void MemoryInputSparseSDPA::assignStateHook() {
+ auto currentState = getAssignedState();
+ auto sparseNode = m_sparseNode.lock();
+ CPU_NODE_ASSERT(sparseNode, "SparseSDPA node is not available");
+ auto kvState = std::dynamic_pointer_cast<VariableStateKVcache>(currentState);
+ CPU_NODE_ASSERT(kvState, "Unexpected state type: ", currentState->get_name());
+ sparseNode->assignState(kvState, m_sparse_port_idx);
+}
+
+MemStatePtr MemoryInputSparseSDPA::makeState() const {
+ // assume ov::Tensor is always dense
+ auto original_desc =
+ std::make_shared<CpuBlockedMemoryDesc>(getOriginalOutputPrecisionAtPort(0), outputShapes.at(0));
+
+ auto state_name = getId();
+ // Remove suffix with pair ID. Internal information.
+ auto suffix_idx = state_name.find("/id=");
+ if (suffix_idx != std::string::npos) {
+ state_name = state_name.substr(0, suffix_idx);
+ }
+
+ auto node = m_sparseNode.lock();
+ CPU_NODE_ASSERT(node, "SparseSDPA node is not available");
+ const auto sparse_inputs = node->getOriginalInputsNumber();
+ // port convention: K = inputNumber - 2, V = inputNumber - 1, both cached in the same precision
+ CPU_NODE_ASSERT(any_of(static_cast<size_t>(m_sparse_port_idx), sparse_inputs - 2, sparse_inputs - 1),
+ getName(),
+ " is connected to an unexpected port of SparseSDPA: ",
+ m_sparse_port_idx);
+ const bool is_key = m_sparse_port_idx == static_cast<int>(sparse_inputs - 2);
+ const auto& spec = is_key ? node->getKeySpec() : node->getValueSpec();
+ auto internal_desc =
+ ArbitraryOrderDescCreator(SparseSDPA::getKVCacheOrder()).createSharedDesc(spec.precision, outputShapes.at(0));
+
+ // the quantization parameters matter for a compressed cache only
+ ov::Extensions::Cpu::CacheSpec quant_param;
+ if (SparseSDPA::isQuantizedCache(spec)) {
+ quant_param = spec;
+ }
+ return std::make_shared<VariableStateKVcacheBHLS>(state_name, original_desc, internal_desc, quant_param);
+}
+
MemoryInputSingle::MemoryInputSingle(const std::string& id,
const std::string& name,
const std::string& type,
diff --git a/src/plugins/intel_cpu/src/nodes/memory.hpp b/src/plugins/intel_cpu/src/nodes/memory.hpp
index aa1dded7592..370efa9c5ca 100644
--- a/src/plugins/intel_cpu/src/nodes/memory.hpp
+++ b/src/plugins/intel_cpu/src/nodes/memory.hpp
@@ -34,6 +34,7 @@ namespace ov::intel_cpu::node {
class MemoryOutputBase;
class MemoryInputBase;
class ScaledDotProductAttention;
+class SparseSDPA;
class MemoryStatesRegister {
public:
@@ -298,4 +299,29 @@ private:
std::weak_ptr<ScaledDotProductAttention> m_sdpaNode;
int m_child_port_idx = -1;
};
+
+// MemoryInput replacement for the KV cache states of SparseSDPA (SparseAttentionWithKVCache), the counterpart of
+// MemoryInputSDPA. It reuses the shape handling of MemoryInputSDPA (runDynamic, resolveInPlaceEdges) and replaces
+// the SDPA specific parts: the consumer node, and the state, which is a BHLS float KV cache.
+class MemoryInputSparseSDPA : public MemoryInputSDPA {
+public:
+ MemoryInputSparseSDPA(const std::string& id,
+ const std::string& name,
+ const std::string& type,
+ const Shape& output_shape,
+ const ov::element::Type& output_prc,
+ const GraphContext::CPtr& context,
+ const std::optional<std::vector<Shape>>& input_shape,
+ const std::optional<std::vector<ov::element::Type>>& input_prc,
+ const std::shared_ptr<SparseSDPA>& sparseNode);
+
+ void createPrimitive() override;
+ MemStatePtr makeState() const override;
+
+private:
+ void assignStateHook() override;
+
+ std::weak_ptr<SparseSDPA> m_sparseNode;
+ int m_sparse_port_idx = -1;
+};
} // namespace ov::intel_cpu::node
diff --git a/src/plugins/intel_cpu/src/nodes/paged_qsa_indexer.cpp b/src/plugins/intel_cpu/src/nodes/paged_qsa_indexer.cpp
new file mode 100644
index 00000000000..b694d04a7f8
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/paged_qsa_indexer.cpp
@@ -0,0 +1,201 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "paged_qsa_indexer.h"
+
+#include <cstddef>
+#include <cstdint>
+#include <memory>
+#include <oneapi/dnnl/dnnl_common.hpp>
+#include <string>
+#include <vector>
+
+#include "cpu_memory.h"
+#include "graph_context.h"
+#include "memory_desc/cpu_blocked_memory_desc.h"
+#include "memory_desc/cpu_memory_desc.h"
+#include "node.h"
+#include "nodes/kernels/sparse_attn/paged_qsa_indexer_kernel.hpp"
+#include "nodes/kernels/sparse_attn/qsa_indexer_common.hpp"
+#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/paged_qsa_indexer.hpp"
+#include "shape_inference/shape_inference_cpu.hpp"
+
+#ifdef OPENVINO_ARCH_X86_64
+# include "cpu_types.h"
+# include "nodes/kernels/sparse_attn/qsa_brgemm.hpp"
+#endif
+
+namespace ov::intel_cpu::node {
+
+namespace {
+
+using InputIdx = ov::op::internal::PagedQSAIndexer::InputIdx;
+using OutputIdx = qsa::paged::OutputIdx;
+
+} // namespace
+
+PagedQSAIndexer::PagedQSAIndexer(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);
+ }
+ const auto paged_qsa_indexer = ov::as_type_ptr<const ov::op::internal::PagedQSAIndexer>(op);
+ OPENVINO_ASSERT(paged_qsa_indexer, "Expected PagedQSAIndexer node");
+ m_config = paged_qsa_indexer->get_config();
+}
+
+void PagedQSAIndexer::initSupportedPrimitiveDescriptors() {
+ if (!supportedPrimitiveDescriptors.empty()) {
+ return;
+ }
+ // Every floating-point port is echoed at the precision negotiated upstream (the op validates it is the same), so
+ // the growing caches need no Reorder: the kernel converts rows itself. The page-table and index inputs stay i32;
+ // the outputs are i32.
+ std::vector<PortConfigurator> in_port_configs;
+ for (size_t i = 0; i < getParentEdges().size(); ++i) {
+ const bool is_i32_port = i == InputIdx::PAST_LENS || i == InputIdx::SUBSEQUENCE_BEGINS ||
+ i == InputIdx::BLOCK_INDICES || i == InputIdx::BLOCK_INDICES_BEGINS;
+ const ov::element::Type precision = is_i32_port ? ov::element::i32 : getOriginalInputPrecisionAtPort(i);
+ in_port_configs.emplace_back(LayoutType::ncsp, precision, getInputShapeAtPort(i), false, -1);
+ }
+ std::vector<PortConfigurator> out_port_configs;
+ for (size_t i = 0; i < OutputIdx::COUNT; ++i) {
+ out_port_configs.emplace_back(LayoutType::ncsp, ov::element::i32, getOutputShapeAtPort(i), false, -1);
+ }
+ addSupportedPrimDesc(in_port_configs, out_port_configs, impl_desc_type::ref_any);
+}
+
+void PagedQSAIndexer::createPrimitive() {
+ m_impl = qsa::kernel_impl_type();
+#ifdef OPENVINO_ARCH_X86_64
+ const auto summary_precision = getSrcMemoryAtPort(InputIdx::BLOCK_INDEX_KEYS_CACHE)->getDesc().getPrecision();
+ // Scoring on brgemm where the CPU, the precisions and the head counts allow it. Query and key rows are
+ // [tokens, heads * dim] with a dynamic token count. The brgemm products need the query in the summary precision,
+ // so it is used only when it already has it.
+ const auto& c = m_config;
+ const auto query_precision = getSrcMemoryAtPort(InputIdx::INDEX_QUERY)->getDesc().getPrecision();
+ const auto q_width = getInputShapeAtPort(InputIdx::INDEX_QUERY).getDims()[1];
+ const auto k_width = getInputShapeAtPort(InputIdx::RAW_INDEX_KEYS).getDims()[1];
+ if (q_width != Shape::UNDEFINED_DIM && k_width != Shape::UNDEFINED_DIM && c.indexer_head_dim != 0 &&
+ query_precision == summary_precision) {
+ const size_t q_heads = q_width / c.indexer_head_dim;
+ const size_t k_heads = k_width / c.indexer_head_dim;
+ if (k_heads != 0 && q_heads % k_heads == 0) {
+ m_brgemm = qsa::QsaBrgemm::get(
+ context->getParamsCache(),
+ qsa::QsaBrgemm::Config{q_heads,
+ k_heads,
+ c.num_selection_heads,
+ c.indexer_head_dim,
+ c.indexer_rotary_dim,
+ c.block_topk,
+ static_cast<size_t>(context->getCpuParallel()->get_num_worker_threads()),
+ c.epsilon,
+ ov::op::internal::PagedQSAIndexer::effective_scale(c),
+ summary_precision});
+ }
+ }
+ if (m_brgemm) {
+ m_impl = qsa::score_impl_type(summary_precision);
+ }
+#endif
+ Node::createPrimitive();
+ getSelectedPrimitiveDescriptor()->setImplementationType(m_impl);
+}
+
+void PagedQSAIndexer::execute([[maybe_unused]] const dnnl::stream& strm) {
+ std::vector<MemoryPtr> inputs(getParentEdges().size());
+ for (size_t i = 0; i < inputs.size(); ++i) {
+ inputs[i] = getSrcMemoryAtPort(i);
+ }
+ std::vector<MemoryPtr> outputs(OutputIdx::COUNT);
+ for (size_t i = 0; i < outputs.size(); ++i) {
+ outputs[i] = getDstMemoryAtPort(i);
+ }
+ const qsa::paged::PagedPorts ports(inputs, outputs);
+ const auto cpu_parallel = context->getCpuParallel();
+ const auto stats = qsa::paged::seq_stats(ports, m_config);
+
+ // The calls that have complete blocks to score go to the brgemm scorer, which plans its scratch from the sizes of
+ // the call; the other calls are scored by the kernel itself.
+ const qsa::QsaBrgemm* brgemm = nullptr;
+ size_t scorer_shared_bytes = 0;
+ size_t scorer_thread_bytes = 0;
+#ifdef OPENVINO_ARCH_X86_64
+ if (m_brgemm && stats.max_blocks > 0) {
+ const auto plan = m_brgemm->plan(qsa::paged::num_sequences(ports), stats.max_q_len, stats.max_blocks);
+ brgemm = m_brgemm.get();
+ scorer_shared_bytes = plan.shared_bytes;
+ scorer_thread_bytes = plan.thread_bytes;
+ }
+#endif
+ const qsa::paged::PagedScratchLayout layout(ports,
+ m_config,
+ stats.max_blocks,
+ scorer_shared_bytes,
+ scorer_thread_bytes,
+ static_cast<size_t>(cpu_parallel->get_num_worker_threads()));
+ const auto scratch = context->getScratchPad()->createScratchPadMem(
+ std::make_shared<CpuBlockedMemoryDesc>(ov::element::u8, Shape{layout.total_bytes}));
+
+ ov::Extensions::Cpu::XARCH::paged_qsa_indexer_compute(ports,
+ m_config,
+ layout,
+ scratch->getDataAs<uint8_t>(),
+ brgemm,
+ cpu_parallel);
+}
+
+bool PagedQSAIndexer::isSupportedOperation(const std::shared_ptr<const ov::Node>& op,
+ std::string& errorMessage) noexcept {
+ try {
+ const auto paged_qsa_indexer = ov::as_type_ptr<const ov::op::internal::PagedQSAIndexer>(op);
+ if (!paged_qsa_indexer) {
+ errorMessage = "Only PagedQSAIndexer operation is supported";
+ return false;
+ }
+ static constexpr size_t float_ports[] = {InputIdx::INDEX_QUERY,
+ InputIdx::RAW_INDEX_KEYS,
+ InputIdx::ROPE_COS,
+ InputIdx::ROPE_SIN,
+ InputIdx::Q_NORM_WEIGHT,
+ InputIdx::K_NORM_WEIGHT,
+ InputIdx::INDEX_KEY_CACHE,
+ InputIdx::INDEX_BLOCK_ROPE_CACHE,
+ InputIdx::BLOCK_INDEX_KEYS_CACHE};
+ for (auto port : float_ports) {
+ const auto prec = op->get_input_element_type(port);
+ if (prec != ov::element::f32 && prec != ov::element::f16 && prec != ov::element::bf16) {
+ errorMessage = "PagedQSAIndexer CPU implementation only supports f32, f16, or bf16 data inputs.";
+ return false;
+ }
+ }
+ static constexpr size_t i32_ports[] = {InputIdx::PAST_LENS,
+ InputIdx::SUBSEQUENCE_BEGINS,
+ InputIdx::BLOCK_INDICES,
+ InputIdx::BLOCK_INDICES_BEGINS};
+ for (auto port : i32_ports) {
+ if (op->get_input_element_type(port) != ov::element::i32) {
+ errorMessage = "PagedQSAIndexer CPU implementation requires i32 index inputs.";
+ return false;
+ }
+ }
+ std::string reason;
+ if (!ov::op::internal::PagedQSAIndexer::validate_config(paged_qsa_indexer->get_config(), reason)) {
+ errorMessage = "PagedQSAIndexer configuration is invalid: " + reason;
+ return false;
+ }
+ } catch (...) {
+ return false;
+ }
+ return true;
+}
+
+} // namespace ov::intel_cpu::node
diff --git a/src/plugins/intel_cpu/src/nodes/paged_qsa_indexer.h b/src/plugins/intel_cpu/src/nodes/paged_qsa_indexer.h
new file mode 100644
index 00000000000..c12a1ab782b
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/paged_qsa_indexer.h
@@ -0,0 +1,61 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <memory>
+#include <oneapi/dnnl/dnnl_common.hpp>
+#include <string>
+
+#include "cpu_types.h"
+#include "graph_context.h"
+#include "node.h"
+#include "onednn/iml_type_mapper.h"
+#include "openvino/core/node.hpp"
+#include "openvino/op/paged_qsa_indexer.hpp"
+
+namespace ov::intel_cpu::node::qsa {
+class QsaBrgemm; // x64 only, see kernels/sparse_attn/qsa_brgemm.hpp
+} // namespace ov::intel_cpu::node::qsa
+
+namespace ov::intel_cpu::node {
+
+/// @brief CPU implementation of ov::op::internal::PagedQSAIndexer (paged-cache
+/// complete-block plan producer for Qwen Sparse Attention).
+///
+/// Same per-token math as the dense QSAIndexer node (query RMSNorm + partial RoPE, raw-K
+/// append, completed-block summary pooling, per-selection-head scoring + top-k), but every
+/// cache access (index_key_cache, index_block_rope_cache, block_index_keys_cache) is addressed
+/// through the shared PagedAttention page table (block_indices/block_indices_begins/
+/// subsequence_begins/past_lens) instead of a flat dense [B, ...] layout.
+class PagedQSAIndexer : public Node {
+public:
+ PagedQSAIndexer(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context);
+
+ void getSupportedDescriptors() override {}
+ [[nodiscard]] bool created() const override {
+ return getType() == Type::PagedQSAIndexer;
+ }
+ [[nodiscard]] bool needPrepareParams() const override {
+ return false;
+ }
+ void executeDynamicImpl(const dnnl::stream& strm) override {
+ execute(strm);
+ }
+ void initSupportedPrimitiveDescriptors() override;
+ void execute(const dnnl::stream& strm) override;
+ void createPrimitive() override;
+ static bool isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept;
+
+private:
+ // The computation is the cross-compiled kernel paged_qsa_indexer_compute (AVX-512 / AVX2 / plain C++ by the CPU);
+ // the scoring of the blocks runs on brgemm instead where the CPU, the precisions and the head counts allow it.
+ ov::op::internal::PagedQSAIndexer::Config m_config;
+#ifdef OPENVINO_ARCH_X86_64
+ std::shared_ptr<const qsa::QsaBrgemm> m_brgemm; // null: the kernel scores the blocks itself
+#endif
+ impl_desc_type m_impl = impl_desc_type::ref;
+};
+
+} // namespace ov::intel_cpu::node
diff --git a/src/plugins/intel_cpu/src/nodes/qsa_indexer.cpp b/src/plugins/intel_cpu/src/nodes/qsa_indexer.cpp
new file mode 100644
index 00000000000..6990d1b327e
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/qsa_indexer.cpp
@@ -0,0 +1,261 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "qsa_indexer.h"
+
+#include <algorithm>
+#include <cstddef>
+#include <cstdint>
+#include <functional>
+#include <memory>
+#include <oneapi/dnnl/dnnl_common.hpp>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+#include "cpu_memory.h"
+#include "cpu_types.h"
+#include "graph_context.h"
+#include "memory_desc/cpu_blocked_memory_desc.h"
+#include "memory_desc/cpu_memory_desc.h"
+#include "node.h"
+#include "nodes/kernels/sparse_attn/qsa_indexer_common.hpp"
+#include "nodes/kernels/sparse_attn/qsa_indexer_kernel.hpp"
+#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 "shape_inference/shape_inference_cpu.hpp"
+#include "shape_inference/shape_inference_status.hpp"
+#include "transformations/cpu_opset/common/op/qsa_indexer.hpp"
+
+#ifdef OPENVINO_ARCH_X86_64
+# include "nodes/kernels/sparse_attn/qsa_brgemm.hpp"
+# include "utils/plain_tensor.hpp"
+#endif
+
+namespace ov::intel_cpu::node {
+
+namespace {
+
+using InputIdx = ov::intel_cpu::QSAIndexerNode::InputIdx;
+using OutputIdx = ov::intel_cpu::QSAIndexerNode::OutputIdx;
+
+// Output shapes of QSAIndexer: everything follows the input shapes, but the summary_cache block count of the longest
+// row, which is read from the key_length values.
+class QSAIndexerShapeInfer : public ShapeInferEmptyPads {
+public:
+ explicit QSAIndexerShapeInfer(const ov::intel_cpu::QSAIndexerNode::Config& config) : m_config(config) {}
+
+ Result infer(const std::vector<std::reference_wrapper<const VectorDims>>& input_shapes,
+ const std::unordered_map<size_t, MemoryPtr>& data_dependency) override {
+ const auto& q_dims = input_shapes[InputIdx::Q_IDX].get();
+ const auto& summary_dims = input_shapes[InputIdx::SUMMARY_CACHE].get();
+ const size_t batch = q_dims[0];
+ const auto& key_length = data_dependency.at(InputIdx::KEY_LENGTH);
+ const auto* key_length_p = key_length->getDataAs<const int32_t>();
+ // key_length is [batch] or [1] (the same length for all the rows)
+ const size_t key_length_count = input_shapes[InputIdx::KEY_LENGTH].get()[0];
+ int64_t longest = 0;
+ for (size_t b = 0; b < key_length_count; b++) {
+ longest = std::max<int64_t>(longest, key_length_p[b]);
+ }
+ const auto num_blocks = static_cast<size_t>(longest / static_cast<int64_t>(m_config.compress_ratio));
+ return {{{batch, m_config.h_sel, q_dims[1], m_config.block_topk},
+ {batch, m_config.h_sel, q_dims[1]},
+ {batch, summary_dims[1], num_blocks, summary_dims[3]},
+ input_shapes[InputIdx::PAST_INCOMPLETE_RAW_K].get(),
+ input_shapes[InputIdx::PAST_INCOMPLETE_ROPE].get()},
+ ShapeInferStatus::success};
+ }
+
+ [[nodiscard]] port_mask_t get_port_mask() const override {
+ return 1U << InputIdx::KEY_LENGTH;
+ }
+
+private:
+ ov::intel_cpu::QSAIndexerNode::Config m_config;
+};
+
+class QSAIndexerShapeInferFactory : public ShapeInferFactory {
+public:
+ explicit QSAIndexerShapeInferFactory(const std::shared_ptr<ov::Node>& op) {
+ if (const auto qsa_indexer = ov::as_type_ptr<const ov::intel_cpu::QSAIndexerNode>(op)) {
+ m_config = qsa_indexer->get_config();
+ }
+ }
+
+ [[nodiscard]] ShapeInferPtr makeShapeInfer() const override {
+ return std::make_shared<QSAIndexerShapeInfer>(m_config);
+ }
+
+private:
+ ov::intel_cpu::QSAIndexerNode::Config m_config;
+};
+
+} // namespace
+
+QSAIndexer::QSAIndexer(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context)
+ : Node(op, context, QSAIndexerShapeInferFactory(op)) {
+ std::string errorMessage;
+ if (!isSupportedOperation(op, errorMessage)) {
+ OPENVINO_THROW_NOT_IMPLEMENTED(errorMessage);
+ }
+ const auto qsa_indexer = ov::as_type_ptr<const ov::intel_cpu::QSAIndexerNode>(op);
+ OPENVINO_ASSERT(qsa_indexer, "Expected QSAIndexer node");
+ m_config = qsa_indexer->get_config();
+}
+
+void QSAIndexer::initSupportedPrimitiveDescriptors() {
+ if (!supportedPrimitiveDescriptors.empty()) {
+ return;
+ }
+ // Every floating-point port (data inputs, state inputs and state outputs) is declared with the
+ // precision of Q_IDX, so the kernel sees a single precision (a mismatching edge gets a Reorder).
+ // KEY_LENGTH stays i32 -- reordering it to f32 would numerically convert the index values.
+ // sel_indices/sel_count are i32; the state outputs never share memory with their inputs: the update is
+ // out-of-place.
+ const auto data_precision = getOriginalInputPrecisionAtPort(InputIdx::Q_IDX);
+
+ std::vector<PortConfigurator> in_port_configs;
+ for (size_t i = 0; i < getParentEdges().size(); ++i) {
+ const ov::element::Type precision = i == InputIdx::KEY_LENGTH ? ov::element::i32 : data_precision;
+ in_port_configs.emplace_back(LayoutType::ncsp, precision, getInputShapeAtPort(i), false, -1);
+ }
+ std::vector<PortConfigurator> out_port_configs;
+ for (size_t i = 0; i < OutputIdx::COUNT; ++i) {
+ const bool is_index = i == OutputIdx::SEL_INDICES || i == OutputIdx::SEL_COUNT;
+ out_port_configs.emplace_back(LayoutType::ncsp,
+ is_index ? ov::element::i32 : data_precision,
+ getOutputShapeAtPort(i),
+ false,
+ -1);
+ }
+ addSupportedPrimDesc(in_port_configs, out_port_configs, impl_desc_type::ref_any);
+}
+
+void QSAIndexer::createPrimitive() {
+ m_impl = qsa::kernel_impl_type();
+#ifdef OPENVINO_ARCH_X86_64
+ const auto precision = getSrcMemoryAtPort(InputIdx::Q_IDX)->getDesc().getPrecision();
+ // The scoring on brgemm where the CPU, the precision and the head counts allow it; the head counts are static, the
+ // batch and the window are not. The scorer is shared by the layers of the same configuration.
+ const auto& c = m_config;
+ const size_t q_heads = getInputShapeAtPort(InputIdx::Q_IDX).getDims()[2];
+ const size_t k_heads = getInputShapeAtPort(InputIdx::K_IDX).getDims()[2];
+ if (q_heads != Shape::UNDEFINED_DIM && k_heads != Shape::UNDEFINED_DIM) {
+ m_brgemm = qsa::QsaBrgemm::get(
+ context->getParamsCache(),
+ qsa::QsaBrgemm::Config{q_heads,
+ k_heads,
+ c.h_sel,
+ c.indexer_head_dim,
+ c.indexer_rotary_dim,
+ c.block_topk,
+ static_cast<size_t>(context->getCpuParallel()->get_num_worker_threads()),
+ c.eps,
+ QSAIndexerNode::effective_scale(c),
+ precision,
+ c.order_by_score});
+ }
+ if (m_brgemm) {
+ m_impl = qsa::score_impl_type(precision);
+ }
+#endif
+ Node::createPrimitive();
+ getSelectedPrimitiveDescriptor()->setImplementationType(m_impl);
+}
+
+void QSAIndexer::execute([[maybe_unused]] const dnnl::stream& strm) {
+ std::vector<MemoryPtr> inputs(getParentEdges().size());
+ for (size_t i = 0; i < inputs.size(); ++i) {
+ inputs[i] = getSrcMemoryAtPort(i);
+ }
+ std::vector<MemoryPtr> outputs(OutputIdx::COUNT);
+ for (size_t i = 0; i < outputs.size(); ++i) {
+ outputs[i] = getDstMemoryAtPort(i);
+ }
+ const qsa::DensePorts ports(inputs, outputs);
+ const auto cpu_parallel = context->getCpuParallel();
+
+ // The calls that have complete blocks to score go to the brgemm scorer, which plans its scratch from the sizes of
+ // the call; the other calls are scored by the kernel itself.
+ const qsa::QsaBrgemm* brgemm = nullptr;
+ size_t scorer_shared_bytes = 0;
+ size_t scorer_thread_bytes = 0;
+#ifdef OPENVINO_ARCH_X86_64
+ if (m_brgemm && ports.summary_cache.size(2) > 0) {
+ const auto stats = qsa::row_stats(ports, m_config);
+ const auto plan = m_brgemm->plan(ports.q_idx.size(0), stats.max_current, stats.max_row_blocks);
+ brgemm = m_brgemm.get();
+ scorer_shared_bytes = plan.shared_bytes;
+ scorer_thread_bytes = plan.thread_bytes;
+ }
+#endif
+ const qsa::DenseScratchLayout layout(ports,
+ m_config,
+ scorer_shared_bytes,
+ scorer_thread_bytes,
+ static_cast<size_t>(cpu_parallel->get_num_worker_threads()));
+ const auto scratch = context->getScratchPad()->createScratchPadMem(
+ std::make_shared<CpuBlockedMemoryDesc>(ov::element::u8, Shape{layout.total_bytes}));
+
+ ov::Extensions::Cpu::XARCH::qsa_indexer_compute(ports,
+ m_config,
+ layout,
+ scratch->getDataAs<uint8_t>(),
+ brgemm,
+ cpu_parallel);
+}
+
+bool QSAIndexer::isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept {
+ try {
+ const auto qsa_indexer = ov::as_type_ptr<const ov::intel_cpu::QSAIndexerNode>(op);
+ if (!qsa_indexer) {
+ errorMessage = "Only QSAIndexer operation is supported";
+ return false;
+ }
+ static constexpr size_t float_ports[] = {InputIdx::Q_IDX,
+ InputIdx::K_IDX,
+ InputIdx::ROPE_COS,
+ InputIdx::ROPE_SIN,
+ InputIdx::Q_NORM_WEIGHT,
+ InputIdx::K_NORM_WEIGHT,
+ InputIdx::SUMMARY_CACHE,
+ InputIdx::PAST_INCOMPLETE_RAW_K,
+ InputIdx::PAST_INCOMPLETE_ROPE};
+ // All floating-point ports share one precision (the fusion pass converts the graph to that).
+ const auto data_precision = op->get_input_element_type(InputIdx::Q_IDX);
+ if (data_precision != ov::element::f32 && data_precision != ov::element::f16 &&
+ data_precision != ov::element::bf16) {
+ errorMessage = "QSAIndexer CPU implementation only supports f32, f16, or bf16 data inputs.";
+ return false;
+ }
+ for (auto port : float_ports) {
+ if (op->get_input_element_type(port) != data_precision) {
+ errorMessage = "QSAIndexer CPU implementation requires all floating-point inputs to have the same "
+ "precision.";
+ return false;
+ }
+ }
+ static constexpr size_t i32_ports[] = {InputIdx::KEY_LENGTH};
+ for (auto port : i32_ports) {
+ if (op->get_input_element_type(port) != ov::element::i32) {
+ errorMessage = "QSAIndexer CPU implementation requires i32 index inputs.";
+ return false;
+ }
+ }
+ std::string reason;
+ if (!ov::intel_cpu::QSAIndexerNode::validate_config(qsa_indexer->get_config(), reason)) {
+ errorMessage = "QSAIndexer configuration is invalid: " + reason;
+ return false;
+ }
+ } catch (...) {
+ return false;
+ }
+ return true;
+}
+
+} // namespace ov::intel_cpu::node
diff --git a/src/plugins/intel_cpu/src/nodes/qsa_indexer.h b/src/plugins/intel_cpu/src/nodes/qsa_indexer.h
new file mode 100644
index 00000000000..d4c7a844d6c
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/qsa_indexer.h
@@ -0,0 +1,85 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstddef>
+#include <memory>
+#include <oneapi/dnnl/dnnl_common.hpp>
+#include <string>
+
+#include "cpu_types.h"
+#include "graph_context.h"
+#include "node.h"
+#include "onednn/iml_type_mapper.h"
+#include "openvino/core/node.hpp"
+#include "transformations/cpu_opset/common/op/qsa_indexer.hpp"
+
+namespace ov::intel_cpu::node::qsa {
+class QsaBrgemm; // x64 only, see kernels/sparse_attn/qsa_brgemm.hpp
+} // namespace ov::intel_cpu::node::qsa
+
+namespace ov::intel_cpu::node {
+
+/// @brief CPU implementation of ov::intel_cpu::QSAIndexerNode (padding-aware,
+/// non-paged, caller-owned-cache block-level indexer for Qwen Sparse Attention).
+///
+/// Unlike QSAIndexer, this op is fed a per-row `key_length` (total valid length, past + current,
+/// after this call) instead of a `past_lens` running counter: `past`/`current`/block-append-offset
+/// are all derived per row from `key_length` and this call's window length alone, so divergent
+/// per-row batches and intra-call left-padding are handled without any extra persisted state.
+/// `past_incomplete_raw_k` / `past_incomplete_rope` are FIXED-size (not growing) caller-owned
+/// state tensors holding the current incomplete block's raw rows / reference RoPE coefficients;
+/// they are fully rewritten every call rather than grown. The three state inputs
+/// (`summary_cache`, `past_incomplete_raw_k`, `past_incomplete_rope`) are never modified: the
+/// updated states are written to dedicated outputs for an outside Assign to consume. `summary_cache` grows like
+/// QSAPrepare-17's `block_index_keys`: the output has max(key_length) / key_block_size blocks, so the output shape
+/// depends on the `key_length` values. All floating-point ports (inputs and state outputs) share one
+/// precision (f32, f16 or bf16, that of `q_idx`); compute is always performed in fp32.
+/// `sel_indices`/`sel_count` are always i32.
+class QSAIndexer : public Node {
+ using InputIdx = ov::intel_cpu::QSAIndexerNode::InputIdx;
+
+public:
+ QSAIndexer(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context);
+
+ void getSupportedDescriptors() override {}
+ [[nodiscard]] bool created() const override {
+ return getType() == Type::QSAIndexer;
+ }
+ [[nodiscard]] bool needPrepareParams() const override {
+ return false;
+ }
+ // summary_cache is empty on the first call (no earlier blocks), the node still has to run then.
+ [[nodiscard]] bool isExecutable() const override {
+ for (size_t i = 0; i < getParentEdges().size(); i++) {
+ if (i != InputIdx::SUMMARY_CACHE && isInputTensorAtPortEmpty(i)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ // The summary_cache output shape depends on the key_length values, not only on the input shapes.
+ [[nodiscard]] bool needShapeInfer() const override {
+ return true;
+ }
+ void executeDynamicImpl(const dnnl::stream& strm) override {
+ execute(strm);
+ }
+ void initSupportedPrimitiveDescriptors() override;
+ void execute(const dnnl::stream& strm) override;
+ void createPrimitive() override;
+ static bool isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept;
+
+private:
+ // The computation is the cross-compiled kernel qsa_indexer_compute (AVX-512 / AVX2 / plain C++ by the CPU); the
+ // scoring of the blocks runs on brgemm instead where the CPU, the precision and the head counts allow it.
+ ov::intel_cpu::QSAIndexerNode::Config m_config;
+#ifdef OPENVINO_ARCH_X86_64
+ std::shared_ptr<const qsa::QsaBrgemm> m_brgemm; // null: the kernel scores the blocks itself
+#endif
+ impl_desc_type m_impl = impl_desc_type::ref;
+};
+
+} // namespace ov::intel_cpu::node
diff --git a/src/plugins/intel_cpu/src/nodes/sparse_pa.cpp b/src/plugins/intel_cpu/src/nodes/sparse_pa.cpp
new file mode 100644
index 00000000000..2df37791796
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/sparse_pa.cpp
@@ -0,0 +1,477 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "sparse_pa.h"
+
+#include <algorithm>
+#include <cstddef>
+#include <cstdint>
+#include <memory>
+#include <oneapi/dnnl/dnnl_common.hpp>
+#include <string>
+#include <vector>
+
+#include "cpu_memory.h"
+#include "cpu_shape.h"
+#include "graph_context.h"
+#include "memory_desc/cpu_blocked_memory_desc.h"
+#include "memory_desc/cpu_memory_desc.h"
+#include "node.h"
+#include "nodes/kernels/scaled_attn/attn_memcpy.hpp"
+#include "nodes/kernels/scaled_attn/attn_quant.hpp"
+#include "nodes/kernels/sparse_attn/sparse_brgemm.hpp"
+#include "nodes/kernels/sparse_attn/sparse_pa_kernel.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/parallel.hpp"
+#include "openvino/core/partial_shape.hpp"
+#include "openvino/core/shape.hpp"
+#include "openvino/core/type.hpp"
+#include "openvino/core/type/bfloat16.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "openvino/core/type/float16.hpp"
+#include "openvino/op/paged_sparse_attention.hpp"
+#include "shape_inference/shape_inference_cpu.hpp"
+#include "utils/plain_tensor.hpp"
+
+#ifdef OPENVINO_ARCH_X86_64
+# include <cpu/x64/cpu_isa_traits.hpp>
+
+# include "nodes/kernels/sparse_attn/sparse_kernel_cache.hpp"
+#endif
+
+namespace ov::intel_cpu::node {
+
+SparsePA::SparsePA(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);
+ }
+ const auto sparse_pa = ov::as_type_ptr<const ov::op::internal::PagedSparseAttention>(op);
+ OPENVINO_ASSERT(sparse_pa, "Expected PagedSparseAttention node");
+ if (!deriveConfig(*sparse_pa, m_config, errorMessage)) {
+ OPENVINO_THROW(errorMessage);
+ }
+}
+
+bool SparsePA::deriveQuant(std::string& reason) {
+ const auto key_prec = getOriginalInputPrecisionAtPort(InputIdx::KEY_CACHE);
+ const auto value_prec = getOriginalInputPrecisionAtPort(InputIdx::VALUE_CACHE);
+ const auto& key_dims = getInputShapeAtPort(InputIdx::KEY_CACHE).getDims();
+ const auto& value_dims = getInputShapeAtPort(InputIdx::VALUE_CACHE).getDims();
+ m_quant = {};
+ if (key_prec != ov::element::u8 && key_prec != ov::element::u4) {
+ // Plain caches: the page size is read from the cache shape by the kernel.
+ return true;
+ }
+ for (const auto dim : {key_dims[2], key_dims[3], value_dims[2], value_dims[3]}) {
+ if (dim == Shape::UNDEFINED_DIM) {
+ reason = "SparsePA CPU implementation requires static page and head dims of quantized caches.";
+ return false;
+ }
+ }
+ const auto& cfg = context->getConfig();
+ const size_t Dh = m_config.k_head_size;
+ const size_t Dv = m_config.v_head_size;
+ // Both u8 and u4 store scale and zero point as f32; u4 counts them in half-byte elements.
+ const size_t key_params = sizeof(float) * 2 * (key_prec == ov::element::u4 ? 2 : 1);
+ const size_t value_params = sizeof(float) * 2 * (value_prec == ov::element::u4 ? 2 : 1);
+ m_quant.key_prec = key_prec;
+ m_quant.value_prec = value_prec;
+ m_quant.key_bychannel = PagedAttention::isQuantByChannel(cfg.keyCacheQuantMode, key_prec, true);
+ // A group size of 0 means one group per row; PagedAttention resolves it the same way before quantizing.
+ m_quant.key_group_size = cfg.keyCacheGroupSize ? cfg.keyCacheGroupSize : Dh;
+ m_quant.value_group_size = cfg.valueCacheGroupSize ? cfg.valueCacheGroupSize : Dv;
+ if (PagedAttention::isQuantByChannel(cfg.valueCacheQuantMode, value_prec, false)) {
+ reason = "SparsePA CPU implementation does not support by-channel quantized value caches.";
+ return false;
+ }
+ if (value_prec != ov::element::u8 && value_prec != ov::element::u4) {
+ reason = "SparsePA CPU implementation requires the key and value caches to be both quantized or both plain.";
+ return false;
+ }
+
+ // The page size is key_cache dim 2, plus parameter rows for by-channel keys.
+ if (m_quant.key_bychannel) {
+ if (key_dims[3] != Dh || key_dims[2] <= key_params || (key_prec == ov::element::u4 && Dh % 2 != 0)) {
+ reason = "SparsePA: by-channel key cache shape does not match the head size and quantization parameters.";
+ return false;
+ }
+ m_quant.block_size = key_dims[2] - key_params;
+ } else {
+ const size_t gs = m_quant.key_group_size;
+ if (Dh % gs != 0 || key_dims[3] != Dh + key_params * (Dh / gs)) {
+ reason = "SparsePA: by-token key cache shape does not match the head size and group size.";
+ return false;
+ }
+ m_quant.block_size = key_dims[2];
+ }
+ const size_t vgs = m_quant.value_group_size;
+ if (Dv % vgs != 0 || value_dims[3] != Dv + value_params * (Dv / vgs) || value_dims[2] != m_quant.block_size) {
+ reason = "SparsePA: value cache shape does not match the head size, group size and key page size.";
+ return false;
+ }
+ if (m_quant.block_size % m_config.key_block_size != 0) {
+ reason = "SparsePA: the cache page size must be divisible by key_block_size.";
+ return false;
+ }
+ return true;
+}
+
+size_t SparsePA::writeKVSlotMappingBytes(size_t tokens) {
+ return ov::Extensions::Cpu::aligned(tokens * sizeof(int32_t));
+}
+
+size_t SparsePA::writeKVScratchBytes(size_t tokens, size_t block_size) const {
+ const auto& c = m_config;
+ size_t bytes = writeKVSlotMappingBytes(tokens);
+ if (m_quant.enabled() && m_quant.key_bychannel) {
+ bytes += static_cast<size_t>(parallel_get_max_threads()) * block_size * c.num_heads *
+ std::max(c.k_head_size, c.v_head_size) * sizeof(float);
+ }
+ return bytes;
+}
+
+void SparsePA::writeKV(uint8_t* scratch) {
+ PlainTensor key(getSrcMemoryAtPort(InputIdx::KEY));
+ PlainTensor value(getSrcMemoryAtPort(InputIdx::VALUE));
+ PlainTensor key_cache(getSrcMemoryAtPort(InputIdx::KEY_CACHE));
+ PlainTensor value_cache(getSrcMemoryAtPort(InputIdx::VALUE_CACHE));
+ PlainTensor past_lens(getSrcMemoryAtPort(InputIdx::PAST_LENS));
+ PlainTensor subsequence_begins(getSrcMemoryAtPort(InputIdx::SUBSEQUENCE_BEGINS));
+ PlainTensor block_indices(getSrcMemoryAtPort(InputIdx::BLOCK_INDICES));
+ PlainTensor block_indices_begins(getSrcMemoryAtPort(InputIdx::BLOCK_INDICES_BEGINS));
+ const auto& c = m_config;
+ const size_t block_size = m_quant.enabled() ? m_quant.block_size : key_cache.size(2);
+
+ // Physical slot (block * block_size + offset) of every new token, as PagedAttention builds it.
+ const size_t tokens = key.size(0);
+ PlainTensor slot_mapping;
+ slot_mapping.resize<int32_t>({tokens}, reinterpret_cast<int32_t*>(scratch));
+ size_t idx = 0;
+ for (size_t seq = 0; seq < past_lens.size(0); seq++) {
+ const int32_t q_len = subsequence_begins.ptr<int32_t>()[seq + 1] - subsequence_begins.ptr<int32_t>()[seq];
+ const int32_t past = past_lens.ptr<int32_t>()[seq];
+ const int32_t first_block = block_indices_begins.ptr<int32_t>()[seq];
+ for (int32_t j = 0; j < q_len; j++) {
+ const auto pos = static_cast<size_t>(past) + static_cast<size_t>(j);
+ const auto block = static_cast<size_t>(block_indices.ptr<int32_t>()[first_block + pos / block_size]);
+ slot_mapping.ptr<int32_t>()[idx++] = static_cast<int32_t>(block * block_size + pos % block_size);
+ }
+ }
+
+ const auto key_4d = key.reshape({tokens, c.num_kv_heads, 1, c.k_head_size});
+ const auto value_4d = value.reshape({tokens, c.num_kv_heads, 1, c.v_head_size});
+ if (!m_quant.enabled()) {
+ ov::Extensions::Cpu::XARCH::paged_attn_memcpy(key_4d,
+ value_4d,
+ key_cache,
+ value_cache,
+ slot_mapping,
+ context->getCpuParallel());
+ return;
+ }
+ ov::Extensions::Cpu::QuantizeParam quant_param{m_quant.key_bychannel,
+ false,
+ false,
+ m_quant.key_group_size,
+ m_quant.value_group_size};
+ PlainTensor temp_buffer;
+ if (m_quant.key_bychannel) {
+ temp_buffer.resize<float>({static_cast<size_t>(parallel_get_max_threads()),
+ block_size,
+ c.num_heads,
+ std::max(c.k_head_size, c.v_head_size)},
+ reinterpret_cast<float*>(scratch + writeKVSlotMappingBytes(tokens)));
+ }
+ ov::Extensions::Cpu::XARCH::paged_attn_quantkv(key_4d,
+ value_4d,
+ key_cache,
+ value_cache,
+ past_lens,
+ subsequence_begins,
+ block_indices,
+ block_indices_begins,
+ slot_mapping,
+ temp_buffer,
+ quant_param,
+ context->getCpuParallel());
+}
+
+bool SparsePA::deriveConfig(const ov::op::internal::PagedSparseAttention& op, Config& config, std::string& reason) {
+ const auto& query_ps = op.get_input_partial_shape(InputIdx::QUERY);
+ const auto& key_ps = op.get_input_partial_shape(InputIdx::KEY);
+ const auto& value_ps = op.get_input_partial_shape(InputIdx::VALUE);
+ const auto& key_cache_ps = op.get_input_partial_shape(InputIdx::KEY_CACHE);
+ const auto& selected_ps = op.get_input_partial_shape(InputIdx::SELECTED_BLOCK_INDICES);
+ const auto rank_is = [](const ov::PartialShape& ps, int64_t rank) {
+ return ps.rank().is_static() && ps.rank().get_length() == rank;
+ };
+ if (!rank_is(query_ps, 2) || !rank_is(key_ps, 2) || !rank_is(value_ps, 2) || !rank_is(key_cache_ps, 4) ||
+ !rank_is(selected_ps, 3) || !query_ps[1].is_static() || !key_ps[1].is_static() || !value_ps[1].is_static() ||
+ !key_cache_ps[1].is_static() || !selected_ps[1].is_static()) {
+ reason = "PagedSparseAttention CPU implementation requires static head dimensions.";
+ return false;
+ }
+ const auto query_width = static_cast<size_t>(query_ps[1].get_length());
+ const auto key_width = static_cast<size_t>(key_ps[1].get_length());
+ const auto value_width = static_cast<size_t>(value_ps[1].get_length());
+ config.num_kv_heads = static_cast<size_t>(key_cache_ps[1].get_length());
+ config.num_selection_heads = static_cast<size_t>(selected_ps[1].get_length());
+ // The head sizes are derived from the widths of the flattened inputs: they must split evenly.
+ if (config.num_kv_heads == 0 || key_width % config.num_kv_heads != 0 || value_width % config.num_kv_heads != 0) {
+ reason = "PagedSparseAttention: key and value widths must be multiples of the number of KV heads.";
+ return false;
+ }
+ config.k_head_size = key_width / config.num_kv_heads;
+ config.v_head_size = value_width / config.num_kv_heads;
+ if (config.k_head_size == 0 || config.v_head_size == 0 || query_width % config.k_head_size != 0) {
+ reason = "PagedSparseAttention: the query width must be a multiple of the key head size.";
+ return false;
+ }
+ config.num_heads = query_width / config.k_head_size;
+ if (config.num_heads == 0 || config.num_heads % config.num_kv_heads != 0) {
+ reason = "PagedSparseAttention: the number of query heads must be a multiple of the number of KV heads.";
+ return false;
+ }
+ config.key_block_size = static_cast<size_t>(op.get_key_block_size());
+ config.causal = true;
+ if (config.num_selection_heads != 1 && config.num_selection_heads != config.num_kv_heads &&
+ config.num_selection_heads != config.num_heads) {
+ reason = "PagedSparseAttention CPU implementation requires 1, num_kv_heads, or num_heads selection heads.";
+ return false;
+ }
+ return true;
+}
+
+void SparsePA::createPrimitive() {
+ [[maybe_unused]] const auto Dh = m_config.k_head_size;
+ // The page size is KEY_CACHE's dim 2; if it is dynamic the merge-unit/page fit can't be decided.
+ // By-channel quantized key pages carry parameter rows in dim 2, so quantized caches use the derived page size.
+ const auto page_size =
+ m_quant.enabled() ? m_quant.block_size : getInputShapeAtPort(InputIdx::KEY_CACHE).getDims()[2];
+ // Adjacent selected blocks of one page are attended as one run of up to a page of rows; with a dynamic page size
+ // every block is its own run.
+ m_max_run_rows = page_size != Shape::UNDEFINED_DIM ? page_size : m_config.key_block_size;
+#ifdef OPENVINO_ARCH_X86_64
+ // AMX matrix products over the selected rows of a work item (see sparse_brgemm_kernel.hpp), for the prefill and the
+ // decode of a large selection: bf16 / f16 data on hardware with the matching AMX, a pack of several query heads
+ // (the M of the products), and the causal selection.
+ const auto query_prec = getOriginalInputPrecisionAtPort(InputIdx::QUERY);
+ const bool amx =
+ (query_prec == ov::element::bf16 && dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::amx_bf16)) ||
+ (query_prec == ov::element::f16 && dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::amx_fp16));
+ const size_t pack = ov::Extensions::Cpu::max_q_head_pack_size(m_config.num_heads,
+ m_config.num_kv_heads,
+ m_config.num_selection_heads);
+ if (amx && m_config.causal && ov::Extensions::Cpu::SparseBrgemmKernels::supports_pack(pack)) {
+ m_brgemm = get_sparse_brgemm_kernels(context->getParamsCache(),
+ pack,
+ Dh,
+ m_config.v_head_size,
+ ov::Extensions::Cpu::kGatherTileRows,
+ query_prec);
+ }
+#endif
+}
+
+ov::Extensions::Cpu::SparsePAScratchLayout SparsePA::scratchLayout() const {
+#ifdef OPENVINO_ARCH_X86_64
+ const auto brgemm_sizes = ov::Extensions::Cpu::sparse_brgemm_sizes(m_brgemm.handle);
+#else
+ const ov::Extensions::Cpu::SparseBrgemmSizes brgemm_sizes{};
+#endif
+ return {m_config.k_head_size,
+ m_config.v_head_size,
+ m_max_run_rows,
+ ov::Extensions::Cpu::max_q_head_pack_size(m_config.num_heads,
+ m_config.num_kv_heads,
+ m_config.num_selection_heads),
+ getOriginalInputPrecisionAtPort(InputIdx::QUERY).size(),
+ m_quant,
+ brgemm_sizes};
+}
+
+void SparsePA::initSupportedPrimitiveDescriptors() {
+ if (!supportedPrimitiveDescriptors.empty()) {
+ return;
+ }
+ // The cache layout depends on the cache precisions, which are final only now (after EnforceInferencePrecision).
+ std::string errorMessage;
+ if (!deriveQuant(errorMessage)) {
+ OPENVINO_THROW_NOT_IMPLEMENTED(errorMessage);
+ }
+ // Float ports keep the precision settled upstream: the caches grow every step, so a Reorder would convert the
+ // whole history each call. The page table and selection inputs are i32; SCALE keeps its own precision and is read
+ // as f32. Plain caches: the query type, or f16 next to f32 data like PagedAttention.
+ if (!m_quant.enabled()) {
+ const auto query_prec = getOriginalInputPrecisionAtPort(InputIdx::QUERY);
+ const auto cache_prec = getOriginalInputPrecisionAtPort(InputIdx::KEY_CACHE);
+ CPU_NODE_ASSERT(cache_prec == query_prec || (query_prec == ov::element::f32 && cache_prec == ov::element::f16),
+ "plain caches must have the query precision, or f16 with an f32 query, but got ",
+ cache_prec,
+ " caches with a ",
+ query_prec,
+ " query");
+ }
+ std::vector<PortConfigurator> inPortConfigs;
+ for (size_t i = 0; i < getParentEdges().size(); ++i) {
+ const bool is_i32_port = i == InputIdx::BLOCK_INDICES || i == InputIdx::BLOCK_INDICES_BEGINS ||
+ i == InputIdx::SUBSEQUENCE_BEGINS || i == InputIdx::PAST_LENS ||
+ i == InputIdx::SELECTED_BLOCK_INDICES || i == InputIdx::SELECTED_BLOCK_COUNT;
+ const ov::element::Type precision = is_i32_port ? ov::element::i32 : getOriginalInputPrecisionAtPort(i);
+ inPortConfigs.emplace_back(LayoutType::ncsp, precision, getInputShapeAtPort(i), false, -1);
+ }
+ std::vector<PortConfigurator> outPortConfigs = {
+ PortConfigurator{LayoutType::ncsp, getOriginalOutputPrecisionAtPort(0), getOutputShapeAtPort(0), false, -1}};
+ addSupportedPrimDesc(inPortConfigs, outPortConfigs, impl_desc_type::ref);
+}
+
+void SparsePA::execute([[maybe_unused]] const dnnl::stream& strm) {
+ const auto& c = m_config;
+
+ PlainTensor query(getSrcMemoryAtPort(InputIdx::QUERY));
+ PlainTensor key_cache(getSrcMemoryAtPort(InputIdx::KEY_CACHE));
+ PlainTensor value_cache(getSrcMemoryAtPort(InputIdx::VALUE_CACHE));
+ PlainTensor block_indices(getSrcMemoryAtPort(InputIdx::BLOCK_INDICES));
+ PlainTensor block_indices_begins(getSrcMemoryAtPort(InputIdx::BLOCK_INDICES_BEGINS));
+ PlainTensor subsequence_begins(getSrcMemoryAtPort(InputIdx::SUBSEQUENCE_BEGINS));
+ PlainTensor past_lens(getSrcMemoryAtPort(InputIdx::PAST_LENS));
+ PlainTensor sel_indices(getSrcMemoryAtPort(InputIdx::SELECTED_BLOCK_INDICES));
+ PlainTensor sel_count(getSrcMemoryAtPort(InputIdx::SELECTED_BLOCK_COUNT));
+ float scale = 0.0F;
+ switch (getParentEdgeAt(InputIdx::SCALE)->getMemory().getPrecision()) {
+ case ov::element::bf16:
+ scale = static_cast<float>(*getSrcDataAtPortAs<const ov::bfloat16>(InputIdx::SCALE));
+ break;
+ case ov::element::f16:
+ scale = static_cast<float>(*getSrcDataAtPortAs<const ov::float16>(InputIdx::SCALE));
+ break;
+ default:
+ scale = *getSrcDataAtPortAs<const float>(InputIdx::SCALE);
+ break;
+ }
+ PlainTensor out(getDstMemoryAtPort(0));
+
+ // The width of selected_block_indices is only needed by phase 2 (it sizes the AMX run decomposition), so it need
+ // not be static.
+ const auto layout = scratchLayout();
+ // Phase 2 scratch: one block per worker thread, then one token id per token for the kernel's work list (see
+ // WorkList).
+ const size_t thread_scratch_bytes =
+ static_cast<size_t>(context->getCpuParallel()->get_num_worker_threads()) * layout.total;
+ const size_t attention_bytes = thread_scratch_bytes + query.size(0) * sizeof(int32_t);
+ // Phase 1 scratch (the slot mapping and the by-channel requantization buffer). The phases are separated by a
+ // barrier, so they share the start of one scratchpad request: a second request would free the first one's memory.
+ const size_t block_size = m_quant.enabled() ? m_quant.block_size : key_cache.size(2);
+ const size_t write_bytes = writeKVScratchBytes(query.size(0), block_size);
+ const auto scratch = context->getScratchPad()->createScratchPadMem(
+ std::make_shared<CpuBlockedMemoryDesc>(ov::element::u8,
+ ov::intel_cpu::Shape{std::max(attention_bytes, write_bytes)}));
+
+ // Phase 1: write the current K/V into the caches (parallel over token x kv head); it completes before phase 2,
+ // the sparse attention, reads them.
+ writeKV(scratch->getDataAs<uint8_t>());
+ // Phase 2: sparse attention, parallel over (query token, query head pack), with per-thread scratch that the kernel
+ // carves with the same layout.
+ ov::Extensions::Cpu::XARCH::sparse_pa_compute(
+ query,
+ key_cache,
+ value_cache,
+ block_indices,
+ block_indices_begins,
+ subsequence_begins,
+ past_lens,
+ sel_indices,
+ sel_count,
+ out,
+ c.num_heads,
+ c.num_kv_heads,
+ c.k_head_size,
+ c.v_head_size,
+ c.key_block_size,
+ c.num_selection_heads,
+ c.causal,
+ scale,
+ m_quant,
+ m_max_run_rows,
+#ifdef OPENVINO_ARCH_X86_64
+ m_brgemm.handle,
+#else
+ ov::Extensions::Cpu::SparseBrgemm{},
+#endif
+ scratch->getDataAs<uint8_t>(),
+ layout.total,
+ reinterpret_cast<int32_t*>(scratch->getDataAs<uint8_t>() + thread_scratch_bytes),
+ context->getCpuParallel());
+}
+
+bool SparsePA::isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept {
+ try {
+ const auto sparse_pa = ov::as_type_ptr<const ov::op::internal::PagedSparseAttention>(op);
+ if (!sparse_pa) {
+ errorMessage = "Only PagedSparseAttention operation is supported";
+ return false;
+ }
+ for (const auto port : {InputIdx::QUERY, InputIdx::KEY, InputIdx::VALUE}) {
+ const auto prec = op->get_input_element_type(port);
+ if (prec != ov::element::f32 && prec != ov::element::f16 && prec != ov::element::bf16) {
+ errorMessage = "SparsePA CPU implementation only supports f32, f16, or bf16 query, key and value.";
+ return false;
+ }
+ }
+ // The caches are either both plain f32/f16/bf16 or both quantized to u8/u4 (see SparsePAQuant).
+ const auto is_plain = [](const ov::element::Type& prec) {
+ return prec == ov::element::f32 || prec == ov::element::f16 || prec == ov::element::bf16;
+ };
+ const auto is_quantized = [](const ov::element::Type& prec) {
+ return prec == ov::element::u8 || prec == ov::element::u4;
+ };
+ const auto key_cache_prec = op->get_input_element_type(InputIdx::KEY_CACHE);
+ const auto value_cache_prec = op->get_input_element_type(InputIdx::VALUE_CACHE);
+ // Whether the plain cache type fits the query type is checked on the precisions the graph settles on (see
+ // initSupportedPrimitiveDescriptors): the inference precision may still change the query type.
+ if (is_plain(key_cache_prec) && key_cache_prec != value_cache_prec) {
+ errorMessage = "SparsePA CPU implementation requires the plain key and value caches to have one type.";
+ return false;
+ }
+ if ((!is_plain(key_cache_prec) || !is_plain(value_cache_prec)) &&
+ (!is_quantized(key_cache_prec) || !is_quantized(value_cache_prec))) {
+ errorMessage =
+ "SparsePA CPU implementation requires both caches to be plain f32/f16/bf16 or both quantized to u8/u4.";
+ return false;
+ }
+ // The op already requires the page table and selection plan to be i32 (or dynamic).
+ static constexpr size_t i32_ports[] = {InputIdx::BLOCK_INDICES,
+ InputIdx::BLOCK_INDICES_BEGINS,
+ InputIdx::SUBSEQUENCE_BEGINS,
+ InputIdx::PAST_LENS,
+ InputIdx::SELECTED_BLOCK_INDICES,
+ InputIdx::SELECTED_BLOCK_COUNT};
+ for (auto port : i32_ports) {
+ if (op->get_input_element_type(port) != ov::element::i32) {
+ errorMessage = "SparsePA CPU implementation requires i32 index inputs.";
+ return false;
+ }
+ }
+ // Sinks are not supported yet: SINKS must be an empty tensor.
+ const auto& sinks_ps = op->get_input_partial_shape(InputIdx::SINKS);
+ if (!sinks_ps.is_static() || ov::shape_size(sinks_ps.to_shape()) != 0) {
+ errorMessage = "SparsePA CPU implementation does not support sinks.";
+ return false;
+ }
+ Config config;
+ if (!deriveConfig(*sparse_pa, config, errorMessage)) {
+ return false;
+ }
+ } catch (...) {
+ return false;
+ }
+ return true;
+}
+
+} // namespace ov::intel_cpu::node
diff --git a/src/plugins/intel_cpu/src/nodes/sparse_pa.h b/src/plugins/intel_cpu/src/nodes/sparse_pa.h
new file mode 100644
index 00000000000..34b6fd4ea41
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/sparse_pa.h
@@ -0,0 +1,121 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <memory>
+#include <oneapi/dnnl/dnnl_common.hpp>
+#include <string>
+
+#include "cpu_memory.h"
+#include "cpu_types.h"
+#include "graph_context.h"
+#include "node.h"
+#include "nodes/kernels/sparse_attn/sparse_pa_kernel.hpp"
+#include "openvino/core/node.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "openvino/op/paged_sparse_attention.hpp"
+#include "utils/plain_tensor.hpp"
+
+namespace ov::intel_cpu::node {
+
+/// @brief CPU implementation of ov::op::internal::PagedSparseAttention (paged-cache sparse-
+/// attention consumer for Qwen Sparse Attention).
+///
+/// Writes the current-step K/V into the caller-owned paged main KV cache addressed through
+/// the shared PagedAttention page table, then performs the same scalar online-softmax
+/// selected-block + causal-tail attention as the dense SparseSDPA node, with every K/V read
+/// resolved through that same page table instead of a flat dense `[B, Hkv, S, D]` cache.
+/// SCALE is a runtime input; sinks are not supported yet (SINKS must be an empty tensor). The op has one
+/// query per selection row, so the per-sequence selection row offsets are subsequence_begins.
+/// Selected-block QK^T has a bf16/f16 AMX fast path mirroring SparseSDPA's, adapted for the
+/// paged cache: merge runs are additionally capped at physical-page boundaries, since two
+/// logically-adjacent selected blocks are only guaranteed memory-contiguous within the same
+/// physical page.
+class SparsePA : public Node {
+public:
+ /// @brief Input order of ov::op::internal::PagedSparseAttention.
+ struct InputIdx {
+ static constexpr size_t QUERY = 0; ///< [tokens, num_heads*k_head_size]
+ static constexpr size_t KEY = 1; ///< [tokens, num_kv_heads*k_head_size], current step
+ static constexpr size_t VALUE = 2; ///< [tokens, num_kv_heads*v_head_size], current step
+ static constexpr size_t KEY_CACHE = 3; ///< [num_blocks, num_kv_heads, page_size, k_head_size]
+ static constexpr size_t VALUE_CACHE = 4; ///< [num_blocks, num_kv_heads, page_size, v_head_size]
+ static constexpr size_t PAST_LENS = 5; ///< [num_sequences]
+ static constexpr size_t SUBSEQUENCE_BEGINS = 6; ///< [num_sequences+1]
+ static constexpr size_t BLOCK_INDICES = 7; ///< [total_logical_blocks]
+ static constexpr size_t BLOCK_INDICES_BEGINS = 8; ///< [num_sequences+1]
+ static constexpr size_t SELECTED_BLOCK_INDICES = 9; ///< [tokens, num_selection_heads, K_max]
+ static constexpr size_t SELECTED_BLOCK_COUNT = 10; ///< [tokens, num_selection_heads]
+ static constexpr size_t SCALE = 11; ///< scalar
+ static constexpr size_t SINKS = 12; ///< [num_heads], or an empty tensor (no sinks)
+ };
+
+ SparsePA(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context);
+
+ void getSupportedDescriptors() override {}
+ [[nodiscard]] bool created() const override {
+ return getType() == Type::SparsePA;
+ }
+ [[nodiscard]] bool needPrepareParams() const override {
+ return false;
+ }
+ // Only the token-major inputs gate execution: SINKS (and the optional SELECTED_BLOCK_MASK) is an
+ // empty tensor when unused, which must not make the node skip.
+ [[nodiscard]] bool neverExecute() const override {
+ const auto* pd = getSelectedPrimitiveDescriptor();
+ return pd->hasZeroInputDimsAtPort(InputIdx::QUERY) || pd->hasZeroInputDimsAtPort(InputIdx::KEY) ||
+ pd->hasZeroInputDimsAtPort(InputIdx::VALUE);
+ }
+ [[nodiscard]] bool isExecutable() const override {
+ return !isInputTensorAtPortEmpty(InputIdx::QUERY) && !isInputTensorAtPortEmpty(InputIdx::KEY) &&
+ !isInputTensorAtPortEmpty(InputIdx::VALUE);
+ }
+ void executeDynamicImpl(const dnnl::stream& strm) override {
+ execute(strm);
+ }
+ void initSupportedPrimitiveDescriptors() override;
+ void execute(const dnnl::stream& strm) override;
+ void createPrimitive() override;
+ static bool isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept;
+
+private:
+ /// @brief Kernel parameters derived from the static input shapes. The key/value widths are used for the head
+ /// sizes rather than the cache shapes, whose last two dims are padded when the caches are quantized.
+ struct Config {
+ size_t num_heads = 0;
+ size_t num_kv_heads = 0;
+ size_t num_selection_heads = 1; ///< 1, num_kv_heads, or num_heads
+ size_t k_head_size = 0;
+ size_t v_head_size = 0;
+ size_t key_block_size = 0;
+ bool causal = true;
+ };
+ static bool deriveConfig(const ov::op::internal::PagedSparseAttention& op, Config& config, std::string& reason);
+ /// @brief Validates the cache layout against the plugin's KV-cache quantization settings and fills m_quant. The
+ /// quantized cache shapes (padded head size or page size) follow PagedAttention, see SparsePAQuant.
+ bool deriveQuant(std::string& reason);
+ /// @brief Writes the current-step K/V into the paged caches (parallel over token x kv head), quantizing them for
+ /// u8/u4 caches. The attention kernel only reads the caches, so this is its barrier-separated first phase.
+ /// @param scratch at least writeKVScratchBytes() bytes, 64-byte aligned: the slot mapping and the by-channel
+ /// requantization buffer live there, not in the node
+ void writeKV(uint8_t* scratch);
+ /// @brief Bytes of the slot mapping of `tokens` tokens in the scratch of writeKV(), aligned to keep what follows it
+ /// aligned.
+ [[nodiscard]] static size_t writeKVSlotMappingBytes(size_t tokens);
+ /// @brief Bytes of scratch writeKV() needs for `tokens` tokens and caches of `block_size` rows per page.
+ [[nodiscard]] size_t writeKVScratchBytes(size_t tokens, size_t block_size) const;
+ /// @brief Per-thread scratch layout of the kernel for a selected_block_indices width.
+ [[nodiscard]] ov::Extensions::Cpu::SparsePAScratchLayout scratchLayout() const;
+
+ Config m_config{};
+ ov::Extensions::Cpu::SparsePAQuant m_quant{};
+#ifdef OPENVINO_ARCH_X86_64
+ // AMX matrix products of the prefill path (empty when the node is not eligible), see SparseBrgemm.
+ ov::Extensions::Cpu::SparseBrgemmKernels m_brgemm;
+#endif
+ size_t m_max_run_rows = 0; // most key rows of one run, see SparsePAScratchLayout
+};
+
+} // namespace ov::intel_cpu::node
\ No newline at end of file
diff --git a/src/plugins/intel_cpu/src/nodes/sparse_sdpa.cpp b/src/plugins/intel_cpu/src/nodes/sparse_sdpa.cpp
new file mode 100644
index 00000000000..b02587c3a82
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/sparse_sdpa.cpp
@@ -0,0 +1,661 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "sparse_sdpa.h"
+
+#include <cmath>
+#include <cstddef>
+#include <cstdint>
+#include <cstring>
+#include <functional>
+#include <memory>
+#include <oneapi/dnnl/dnnl_common.hpp>
+#include <string>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+
+#include "config.h"
+#include "cpu_memory.h"
+#include "cpu_shape.h"
+#include "cpu_types.h"
+#include "graph_context.h"
+#include "memory_desc/blocked_memory_desc.h"
+#include "memory_desc/cpu_blocked_memory_desc.h"
+#include "memory_desc/cpu_memory_desc.h"
+#include "memory_state.h"
+#include "node.h"
+#include "nodes/common/cpu_convert.h"
+#include "nodes/kernels/scaled_attn/attn_memcpy.hpp"
+#include "nodes/kernels/scaled_attn/attn_quant.hpp"
+#include "nodes/kernels/scaled_attn/cache_spec.hpp"
+#include "nodes/kernels/sparse_attn/sparse_brgemm.hpp"
+#include "nodes/kernels/sparse_attn/sparse_sdpa_kernel.hpp"
+#include "nodes/kernels/sparse_attn/sparse_sdpa_scratch.hpp"
+#include "onednn/iml_type_mapper.h"
+#include "openvino/core/dimension.hpp"
+#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/sparse_attention.hpp"
+#include "openvino/runtime/internal_properties.hpp"
+#include "shape_inference/shape_inference.hpp"
+#include "shape_inference/shape_inference_cpu.hpp"
+#include "shape_inference/shape_inference_status.hpp"
+#include "transformations/cpu_opset/common/op/sparse_attention_with_kv_cache.hpp"
+#include "utils/general_utils.h"
+#include "utils/plain_tensor.hpp"
+
+#ifdef OPENVINO_ARCH_X86_64
+# include <cpu/x64/cpu_isa_traits.hpp>
+
+# include "nodes/kernels/sparse_attn/sparse_kernel_cache.hpp"
+#endif
+
+namespace ov::intel_cpu::node {
+
+namespace {
+
+using SparseAttentionOp = ov::op::v17::SparseAttention;
+using SparseAttentionKVOp = ov::intel_cpu::SparseAttentionWithKVCache;
+
+// Input order of ov::op::v17::SparseAttention.
+struct InputIdx {
+ static constexpr size_t QUERY = 0; // [N, H, L, E]
+ static constexpr size_t KEY = 1; // [N, Hkv, S, E]
+ static constexpr size_t VALUE = 2; // [N, Hkv, S, Ev]
+ static constexpr size_t SEL_INDICES = 3; // block_indices [N, Hs, L, KB]
+ static constexpr size_t SEL_COUNT = 4; // block_count [N, Hs, L]
+ static constexpr size_t KEY_LENGTH = 5; // optional [N] or [1]
+ static constexpr size_t COUNT_MIN = 5;
+};
+
+// Shape inference of SparseAttentionWithKVCache from the input shapes only: the state inputs may be stubs without data
+// (a state without an initial value), so the generic fallback that reads the data of every input cannot be used.
+// attention [N, H, L, Ev]; present_key / present_value [beam_idx, Hkv, L0 + L, E / Ev]
+class SparseSDPAKVShapeInfer : public ShapeInferEmptyPads {
+public:
+ IShapeInfer::Result infer(const std::vector<std::reference_wrapper<const VectorDims>>& input_shapes,
+ [[maybe_unused]] const std::unordered_map<size_t, MemoryPtr>& data_dependency) override {
+ const auto inputs_size = input_shapes.size();
+ OPENVINO_ASSERT(inputs_size >= SparseAttentionKVOp::InputIdx::COUNT_MIN,
+ "SparseSDPAKVShapeInfer: unexpected number of inputs: ",
+ inputs_size);
+ const auto& cur_k = input_shapes[SparseAttentionKVOp::InputIdx::CUR_KEY].get();
+ const auto& cur_v = input_shapes[SparseAttentionKVOp::InputIdx::CUR_VALUE].get();
+ const auto& beam_idx = input_shapes[inputs_size - 3].get();
+ auto present_k = input_shapes[inputs_size - 2].get();
+ auto present_v = input_shapes[inputs_size - 1].get();
+ for (auto* present : {&present_k, &present_v}) {
+ (*present)[0] = beam_idx[0];
+ }
+ present_k[2] += cur_k[2];
+ present_v[2] += cur_v[2];
+
+ VectorDims out = input_shapes[SparseAttentionKVOp::InputIdx::QUERY].get();
+ out[3] = cur_v[3];
+ return {{std::move(out), std::move(present_k), std::move(present_v)}, ShapeInferStatus::success};
+ }
+
+ [[nodiscard]] port_mask_t get_port_mask() const override {
+ return EMPTY_PORT_MASK;
+ }
+};
+
+class SparseSDPAShapeInferFactory : public ShapeInferFactory {
+public:
+ explicit SparseSDPAShapeInferFactory(std::shared_ptr<ov::Node> op) : m_op(std::move(op)) {}
+
+ [[nodiscard]] ShapeInferPtr makeShapeInfer() const override {
+ if (ov::is_type<SparseAttentionKVOp>(m_op)) {
+ return std::make_shared<SparseSDPAKVShapeInfer>();
+ }
+ return make_shape_inference(m_op);
+ }
+
+private:
+ std::shared_ptr<ov::Node> m_op;
+};
+
+// BHLS KV cache descriptor with the logical length L; the capacity cap_L >= L along L is carried by the strides.
+std::shared_ptr<CpuBlockedMemoryDesc> make_bhls_cache_desc(ov::element::Type prec,
+ size_t B,
+ size_t H,
+ size_t L,
+ size_t S,
+ size_t cap_L) {
+ const VectorDims dims{B, H, L, S};
+ return std::make_shared<CpuBlockedMemoryDesc>(prec,
+ Shape(dims),
+ dims,
+ VectorDims{0, 1, 2, 3},
+ 0,
+ VectorDims{},
+ VectorDims{H * cap_L * S, cap_L * S, S, 1});
+}
+
+} // namespace
+
+SparseSDPA::SparseSDPA(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context)
+ : Node(op, context, SparseSDPAShapeInferFactory(op)) {
+ std::string errorMessage;
+ if (!isSupportedOperation(op, errorMessage)) {
+ OPENVINO_THROW_NOT_IMPLEMENTED(errorMessage);
+ }
+ if (const auto kv_op = ov::as_type_ptr<const SparseAttentionKVOp>(op)) {
+ m_fuse_concat = true;
+ m_base_inputs = op->get_input_size() - 3;
+ // a side is compressed when the hint asks for u8 / u4 and the head size is static; the keys are quantized
+ // by channel when that mode is requested (u8 only). Everything else (by-channel u4, TurboQuant, f16 / i8
+ // hints) leaves the side a plain cache
+ const auto& cpu_config = context->getConfig();
+ auto make_spec = [&](ov::element::Type hint,
+ size_t group_size,
+ const ov::Dimension& head_dim,
+ bool by_channel,
+ ov::internal::CacheQuantAlgorithm alg) {
+ ov::Extensions::Cpu::CacheSpec spec;
+ spec.alg = ov::internal::CacheQuantAlgorithm::SCALAR;
+ spec.by_channel = false;
+ spec.precision = ov::element::dynamic; // plain cache: set in initSupportedPrimitiveDescriptors
+ spec.group_size = head_dim.is_static() ? static_cast<size_t>(head_dim.get_length()) : 0;
+ if (none_of(hint, ov::element::u8, ov::element::u4) || spec.group_size == 0 ||
+ alg == ov::internal::CacheQuantAlgorithm::TURBO) {
+ return spec;
+ }
+ const size_t head = spec.group_size;
+ // same rule as SDPA: the group is the whole head unless the configured size divides it; for by-channel
+ // quantization the group is a number of tokens
+ const size_t group = (group_size == 0 || head % group_size != 0) ? head : group_size;
+ if (by_channel) {
+ if (hint != ov::element::u8) {
+ return spec;
+ }
+ spec.by_channel = true;
+ } else if (hint == ov::element::u4 && group % 2 != 0) {
+ return spec;
+ }
+ spec.precision = hint;
+ spec.group_size = group;
+ return spec;
+ };
+ m_key_spec = make_spec(cpu_config.keyCachePrecision,
+ cpu_config.keyCacheGroupSize,
+ op->get_input_partial_shape(InputIdx::KEY)[3],
+ cpu_config.keyCacheQuantMode == ov::intel_cpu::Config::CacheQuantMode::BY_CHANNEL,
+ cpu_config.keyCacheQuantAlg);
+ m_value_spec = make_spec(cpu_config.valueCachePrecision,
+ cpu_config.valueCacheGroupSize,
+ op->get_input_partial_shape(InputIdx::VALUE)[3],
+ false,
+ cpu_config.valueCacheQuantAlg);
+ m_key_block_size = static_cast<size_t>(kv_op->get_config().key_block_size);
+ m_causal = kv_op->get_config().causal;
+ } else {
+ const auto sparse_attention = ov::as_type_ptr<const SparseAttentionOp>(op);
+ OPENVINO_ASSERT(sparse_attention, "Expected SparseAttention node");
+ m_base_inputs = op->get_input_size();
+ m_key_block_size = static_cast<size_t>(sparse_attention->get_key_block_size());
+ m_causal = sparse_attention->get_causal();
+ }
+ m_scale = 1.0F / std::sqrt(static_cast<float>(op->get_input_partial_shape(InputIdx::QUERY)[3].get_length()));
+}
+
+void SparseSDPA::createPrimitive() {
+ [[maybe_unused]] const auto Dh = static_cast<size_t>(getInputShapeAtPort(InputIdx::QUERY).getDims()[3]);
+#ifdef OPENVINO_ARCH_X86_64
+ // The matrix type of the AMX prefill: bf16 / f16 when QUERY, KEY and VALUE are natively that type end to end (the
+ // cache of the stateful form is always kept in the query's precision) and the CPU has the matching AMX.
+ ov::element::Type amx_type = ov::element::dynamic;
+ {
+ const auto qprec = getOriginalInputPrecisionAtPort(InputIdx::QUERY);
+ const auto kprec = m_fuse_concat ? m_cache_prec : getOriginalInputPrecisionAtPort(InputIdx::KEY);
+ const auto vprec = m_fuse_concat ? m_cache_prec : getOriginalInputPrecisionAtPort(InputIdx::VALUE);
+ if (qprec == kprec && qprec == vprec && qprec == ov::element::bf16 &&
+ dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::amx_bf16)) {
+ amx_type = ov::element::bf16;
+ } else if (qprec == kprec && qprec == vprec && qprec == ov::element::f16 &&
+ dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::amx_fp16)) {
+ amx_type = ov::element::f16;
+ }
+ }
+ // Prefill over packs of query heads (brgemm products, whose M is the pack): it needs the AMX type, a causal op and
+ // static head counts.
+ const auto q_heads = getInputShapeAtPort(InputIdx::QUERY).getDims()[1];
+ const auto k_heads = getInputShapeAtPort(InputIdx::KEY).getDims()[1];
+ const auto sel_heads = getInputShapeAtPort(InputIdx::SEL_INDICES).getDims()[1];
+ const auto Dv = getInputShapeAtPort(InputIdx::VALUE).getDims()[3];
+ if (amx_type != ov::element::dynamic && m_causal &&
+ none_of(Shape::UNDEFINED_DIM, q_heads, k_heads, sel_heads, Dv)) {
+ const size_t pack = ov::Extensions::Cpu::max_q_head_pack_size(q_heads, k_heads, sel_heads);
+ if (ov::Extensions::Cpu::SparseBrgemmKernels::supports_pack(pack)) {
+ m_brgemm = get_sparse_brgemm_kernels(context->getParamsCache(),
+ pack,
+ Dh,
+ Dv,
+ ov::Extensions::Cpu::kGatherTileRows,
+ amx_type);
+ }
+ }
+#endif
+}
+
+void SparseSDPA::initSupportedPrimitiveDescriptors() {
+ if (!supportedPrimitiveDescriptors.empty()) {
+ return;
+ }
+ if (m_fuse_concat) {
+ // The plain cache and the current-step K / V follow the query precision, final only now (after
+ // EnforceInferencePrecision); a compressed side keeps u8 / u4.
+ m_cache_prec = getOriginalInputPrecisionAtPort(InputIdx::QUERY);
+ for (auto* spec : {&m_key_spec, &m_value_spec}) {
+ if (!isQuantizedCache(*spec)) {
+ spec->precision = m_cache_prec;
+ }
+ }
+ }
+ // QUERY / KEY / VALUE are echoed at whatever precision (f32/f16/bf16) was negotiated
+ // upstream -- the reference kernel reads them through load_row_f32() rather than hardcoding
+ // f32, since the dense caches grow every step and forcing a whole-tensor Reorder on every call
+ // would redo that conversion for the entire history each time. SEL_INDICES / SEL_COUNT are
+ // always i32 (enforced by the op's shape inference).
+ if (m_fuse_concat) {
+ // Same layout as ScaledDotProductAttention with fuse_concat: the state inputs keep the precision of the
+ // MemoryInput nodes feeding them (no reorders, they are only proxies of the state), the cache outputs carry
+ // the shapes only and are consumed by MemoryOutputStub.
+ std::vector<PortConfigurator> stateInConfigs;
+ for (size_t i = 0; i < getParentEdges().size(); ++i) {
+ ov::element::Type precision;
+ if (i == InputIdx::SEL_INDICES || i == InputIdx::SEL_COUNT || i == InputIdx::KEY_LENGTH ||
+ i == m_base_inputs) {
+ precision = ov::element::i32; // the index ports and beam_idx
+ } else if (i > m_base_inputs) {
+ precision = getParentEdgeAt(i)->getParent()->getOriginalOutputPrecisionAtPort(0);
+ } else if (i == InputIdx::KEY || i == InputIdx::VALUE) {
+ precision = m_cache_prec;
+ } else {
+ precision = getOriginalInputPrecisionAtPort(i);
+ }
+ stateInConfigs.emplace_back(LayoutType::ncsp, precision, getInputShapeAtPort(i), false, -1);
+ }
+ const auto past_k_prec = getParentEdgeAt(m_base_inputs + 1)->getParent()->getOriginalOutputPrecisionAtPort(0);
+ const auto past_v_prec = getParentEdgeAt(m_base_inputs + 2)->getParent()->getOriginalOutputPrecisionAtPort(0);
+ std::vector<PortConfigurator> stateOutConfigs = {
+ PortConfigurator{LayoutType::ncsp, getOriginalOutputPrecisionAtPort(0), getOutputShapeAtPort(0), false, -1},
+ PortConfigurator{LayoutType::ncsp, past_k_prec, getOutputShapeAtPort(1), false, -1},
+ PortConfigurator{LayoutType::ncsp, past_v_prec, getOutputShapeAtPort(2), false, -1}};
+ addSupportedPrimDesc(stateInConfigs, stateOutConfigs, impl_desc_type::ref);
+ return;
+ }
+ std::vector<PortConfigurator> inPortConfigs;
+ for (size_t i = 0; i < getParentEdges().size(); ++i) {
+ const bool is_index_port = i == InputIdx::SEL_INDICES || i == InputIdx::SEL_COUNT || i == InputIdx::KEY_LENGTH;
+ const ov::element::Type precision = is_index_port ? ov::element::i32 : getOriginalInputPrecisionAtPort(i);
+ inPortConfigs.emplace_back(LayoutType::ncsp, precision, getInputShapeAtPort(i), false, -1);
+ }
+ std::vector<PortConfigurator> outPortConfigs = {
+ PortConfigurator{LayoutType::ncsp, getOriginalOutputPrecisionAtPort(0), getOutputShapeAtPort(0), false, -1}};
+ addSupportedPrimDesc(inPortConfigs, outPortConfigs, impl_desc_type::ref);
+}
+
+void SparseSDPA::execute([[maybe_unused]] const dnnl::stream& strm) {
+ PlainTensor query(getSrcMemoryAtPort(InputIdx::QUERY));
+ PlainTensor key;
+ PlainTensor value;
+ ov::Extensions::Cpu::SparseKVQuant key_quant;
+ ov::Extensions::Cpu::SparseKVQuant value_quant;
+ if (m_fuse_concat) {
+ updateKVCache();
+ key.reset(m_k_state->internal_state_mem());
+ value.reset(m_v_state->internal_state_mem());
+ if (isQuantizedCache(m_key_spec)) {
+ key_quant = {m_key_spec.precision,
+ m_key_spec.group_size,
+ m_key_spec.by_channel,
+ &m_k_state->get_scale_zp()};
+ }
+ if (isQuantizedCache(m_value_spec)) {
+ value_quant = {m_value_spec.precision,
+ m_value_spec.group_size,
+ m_value_spec.by_channel,
+ &m_v_state->get_scale_zp()};
+ }
+ } else {
+ key.reset(getSrcMemoryAtPort(InputIdx::KEY));
+ value.reset(getSrcMemoryAtPort(InputIdx::VALUE));
+ }
+ PlainTensor sel_indices(getSrcMemoryAtPort(InputIdx::SEL_INDICES));
+ PlainTensor sel_count(getSrcMemoryAtPort(InputIdx::SEL_COUNT));
+ PlainTensor out(getDstMemoryAtPort(0));
+
+ const size_t Hq = query.size(1);
+ const size_t Hkv = key.size(1);
+ const size_t Dh = query.size(3);
+ const size_t Dv = value.size(3);
+ const size_t Bk = m_key_block_size;
+ const size_t H_sel = sel_indices.size(1);
+ const bool causal = m_causal;
+
+ const bool has_key_length = m_base_inputs > InputIdx::KEY_LENGTH;
+ PlainTensor key_length;
+ const int32_t* key_length_ptr = nullptr;
+ size_t key_length_batch_stride = 0;
+ if (has_key_length) {
+ key_length.reset(getSrcMemoryAtPort(InputIdx::KEY_LENGTH));
+ key_length_ptr = key_length.ptr<int32_t>(0);
+ key_length_batch_stride = key_length.size(0) == 1 ? 0 : 1;
+ }
+
+ // Per-thread decode scratch (see SdpaDecodeScratch), then the per-thread buffers of the brgemm prefill. The
+ // DnnlScratchPad is one shared, grow-only buffer: a second request that grows it frees the first, so ONE combined
+ // request is sliced by byte offset.
+ const ov::Extensions::Cpu::SdpaDecodeScratch decode_scratch(
+ Dh,
+ Dv,
+ ov::Extensions::Cpu::max_q_head_pack_size(Hq, Hkv, H_sel),
+ Bk,
+ key_quant.enabled() || value_quant.enabled());
+ const size_t per_thread_floats = decode_scratch.total;
+ const auto num_threads = static_cast<size_t>(context->getCpuParallel()->get_num_worker_threads());
+ const size_t float_bytes = num_threads * per_thread_floats * sizeof(float);
+ const size_t float_bytes_aligned = ov::Extensions::Cpu::aligned(float_bytes);
+ // Second region: the per-thread buffers of the brgemm prefill (64-byte aligned parts): the state of the head pack,
+ // then the gather tile and the brgemm scratch (see PackStateLayout, SparseBrgemmLayout).
+ ov::Extensions::Cpu::PackStateLayout pack_layout;
+ ov::Extensions::Cpu::SparseBrgemmLayout brgemm_layout;
+ size_t brgemm_bytes_per_thread = 0;
+#ifdef OPENVINO_ARCH_X86_64
+ if (m_brgemm.handle.enabled()) {
+ const size_t max_pack = ov::Extensions::Cpu::max_q_head_pack_size(Hq, Hkv, H_sel);
+ const size_t data_size = query.get_precision().size();
+ pack_layout = ov::Extensions::Cpu::PackStateLayout(0, Dh, Dv, max_pack, data_size, true);
+ brgemm_layout =
+ ov::Extensions::Cpu::SparseBrgemmLayout(pack_layout.total,
+ Dh,
+ Dv,
+ max_pack,
+ data_size,
+ ov::Extensions::Cpu::sparse_brgemm_sizes(m_brgemm.handle));
+ brgemm_bytes_per_thread = brgemm_layout.total;
+ }
+#endif
+ const size_t brgemm_offset = float_bytes_aligned;
+ auto scratch_desc = std::make_shared<CpuBlockedMemoryDesc>(
+ ov::element::u8,
+ ov::intel_cpu::Shape{brgemm_offset + num_threads * brgemm_bytes_per_thread});
+ const MemoryPtr scratch = context->getScratchPad()->createScratchPadMem(scratch_desc);
+ auto* const scratch_base_bytes = scratch->getDataAs<uint8_t>();
+ auto* const scratch_base = reinterpret_cast<float*>(scratch_base_bytes);
+ uint8_t* const brgemm_base = brgemm_bytes_per_thread > 0 ? scratch_base_bytes + brgemm_offset : nullptr;
+
+ ov::Extensions::Cpu::XARCH::sparse_sdpa_compute(query,
+ key,
+ value,
+ sel_indices,
+ sel_count,
+ out,
+ Hq,
+ Hkv,
+ Dh,
+ Dv,
+ Bk,
+ H_sel,
+ causal,
+ m_scale,
+ scratch_base,
+ per_thread_floats,
+#ifdef OPENVINO_ARCH_X86_64
+ m_brgemm.handle,
+#else
+ ov::Extensions::Cpu::SparseBrgemm{},
+#endif
+ pack_layout,
+ brgemm_layout,
+ brgemm_base,
+ brgemm_bytes_per_thread,
+ key_length_ptr,
+ key_length_batch_stride,
+ key_quant,
+ value_quant,
+ context->getCpuParallel());
+}
+
+void SparseSDPA::assignState(const std::shared_ptr<VariableStateKVcache>& state, int idx) {
+ CPU_NODE_ASSERT(m_fuse_concat, "has no KV cache states");
+ const auto input_number = getOriginalInputsNumber();
+ if (input_number - 2 == static_cast<size_t>(idx)) {
+ m_k_state = state;
+ } else if (input_number - 1 == static_cast<size_t>(idx)) {
+ m_v_state = state;
+ } else {
+ CPU_NODE_THROW("Unexpected idx ",
+ idx,
+ " for a state in a node with type: ",
+ getTypeStr(),
+ " and name ",
+ getName());
+ }
+}
+
+// Appends the current step's key/value to the cache states, in place whenever the capacity of the buffers allows it.
+// The buffers are plain BHLS with a capacity along L carried by their strides (see make_bhls_cache_desc), so the rows
+// of every (b, h) are contiguous along L, which is what the AMX path of the kernel relies on.
+void SparseSDPA::updateKVCache() {
+ CPU_NODE_ASSERT(m_k_state && m_v_state, "has null input states");
+ const auto& cpu_parallel = context->getCpuParallel();
+
+ PlainTensor cur_k(getSrcMemoryAtPort(InputIdx::KEY));
+ PlainTensor cur_v(getSrcMemoryAtPort(InputIdx::VALUE));
+ const size_t B = cur_k.size(0);
+ const size_t H = cur_k.size(1);
+ const size_t L1 = cur_k.size(2);
+ CPU_NODE_ASSERT(cur_v.size(0) == B && cur_v.size(1) == H && cur_v.size(2) == L1,
+ "key and value of the current step have different shapes");
+
+ const bool is_reset = m_k_state->is_reset_state();
+ CPU_NODE_ASSERT(is_reset == m_v_state->is_reset_state(),
+ "key and value states are expected to be reset together, but only ",
+ (is_reset ? m_v_state->get_name() : m_k_state->get_name()),
+ " is not reset");
+
+ // The state inputs are proxies of the states: their shapes tell the length (and batch) of the cache so far.
+ const size_t beam_port = m_base_inputs;
+ const size_t L0 = getParentEdgeAt(beam_port + 2)->getMemory().getStaticDims().at(2);
+ CPU_NODE_ASSERT(B * (L0 + L1) > 0, "B or (L0+L1) is zero, B: ", B, ", L0: ", L0, ", L1: ", L1);
+ const size_t L = L0 + L1;
+ const bool has_past = !is_reset && L0 > 0;
+
+ const auto beam_mem = getSrcMemoryAtPort(beam_port);
+ CPU_NODE_ASSERT(beam_mem->getStaticDims().at(0) == B, "beam_idx size is not equal to the batch size: ", B);
+ const auto* beam = beam_mem->getDataAs<const int32_t>();
+ const size_t B_past = has_past ? getParentEdgeAt(beam_port + 2)->getMemory().getStaticDims().at(0) : B;
+ // The beam table of the SDPA state is not used here: when the rows are not in the natural order
+ // the cache is physically reordered (a rare path: beam search steps).
+ bool need_gather = has_past && B_past != B;
+ for (size_t b = 0; has_past && !need_gather && b < B; b++) {
+ need_gather = beam[b] != static_cast<int32_t>(b);
+ }
+ if (need_gather) {
+ for (size_t b = 0; b < B; b++) {
+ CPU_NODE_ASSERT(beam[b] >= 0 && static_cast<size_t>(beam[b]) < B_past, "beam_idx is out of range");
+ }
+ }
+
+ auto update = [&](const std::shared_ptr<VariableStateKVcache>& state,
+ const PlainTensor& cur,
+ size_t init_port,
+ const ov::Extensions::Cpu::CacheSpec& spec) {
+ const auto prec = spec.precision;
+ const bool quantized = isQuantizedCache(spec);
+ const size_t S = cur.size(3);
+ // {scale, zero point} of the groups, laid out as attn_quant_by_token() / attn_quant_by_channel() and the
+ // dequantization of the kernel read it; it is not permuted along with the cache:
+ // - by token: [capacity of L, B, H, 2 * S / group_size]
+ // - by channel: [2 * ceil(capacity of L / group_size), B, H, S]
+ const bool by_channel = quantized && spec.by_channel;
+ size_t szp_cols = 0;
+ if (quantized) {
+ szp_cols = by_channel ? S : 2 * S / spec.group_size;
+ }
+ auto szp_rows = [&](size_t length) {
+ return by_channel ? 2 * div_up(length, spec.group_size) : length;
+ };
+ auto mem = state->internal_state_mem();
+
+ // the buffer is reused when it is a BHLS buffer of the same B, H, S and has enough capacity
+ size_t cap_L = 0;
+ bool reusable = false;
+ if (mem && !mem->getShape().hasZeroDims() && mem->getPrecision() == prec && !need_gather) {
+ const auto& dims = mem->getStaticDims();
+ const auto& strides = mem->getDescWithType<BlockedMemoryDesc>()->getStrides();
+ if (dims.size() == 4 && dims[0] == B && dims[1] == H && dims[3] == S && strides[3] == 1 &&
+ strides[2] == S && strides[1] % S == 0) {
+ cap_L = strides[1] / S;
+ reusable = cap_L >= L && (!has_past || dims[2] == L0);
+ if (reusable && quantized) {
+ const auto& szp = state->get_scale_zp();
+ reusable = szp && szp.size(0) == szp_rows(cap_L) && szp.size(1) == B && szp.size(2) == H &&
+ szp.size(3) == szp_cols;
+ }
+ }
+ }
+
+ if (reusable) {
+ mem->redefineDesc(make_bhls_cache_desc(prec, B, H, L, S, cap_L));
+ } else {
+ cap_L = 2 * L;
+ auto new_mem = std::make_shared<Memory>(getEngine(), make_bhls_cache_desc(prec, B, H, cap_L, S, cap_L));
+ PlainTensor new_szp;
+ if (quantized) {
+ new_szp.resize<float>({szp_rows(cap_L), B, H, szp_cols});
+ }
+ if (has_past) {
+ CPU_NODE_ASSERT(mem && mem->getPrecision() == prec, "has no past state of the expected precision");
+ PlainTensor old_cache(mem);
+ PlainTensor new_cache(new_mem);
+ CPU_NODE_ASSERT(old_cache.size(1) == H && old_cache.size(2) == L0 && old_cache.size(3) == S,
+ "past state shape does not match the current key/value");
+ // rows of a (b, h) are contiguous along L; a u4 element takes half a byte
+ const size_t row_bytes = L0 * S * prec.bitwidth() / 8;
+ cpu_parallel->parallel_for2d(B, H, [&](size_t b, size_t h) {
+ const size_t b_src = need_gather ? static_cast<size_t>(beam[b]) : b;
+ std::memcpy(new_cache.ptr_v(b, h, 0), old_cache.ptr_v(b_src, h, 0), row_bytes);
+ });
+ if (quantized) {
+ const auto& old_szp = state->get_scale_zp();
+ const size_t past_rows = szp_rows(L0);
+ CPU_NODE_ASSERT(old_szp && old_szp.size(0) >= past_rows && old_szp.size(1) == B_past &&
+ old_szp.size(2) == H && old_szp.size(3) == szp_cols,
+ "past scale / zero point does not match the current key/value");
+ cpu_parallel->parallel_for3d(past_rows, B, H, [&](size_t pos, size_t b, size_t h) {
+ const size_t b_src = need_gather ? static_cast<size_t>(beam[b]) : b;
+ std::memcpy(new_szp.ptr<float>(pos, b, h),
+ old_szp.ptr<float>(pos, b_src, h),
+ szp_cols * sizeof(float));
+ });
+ }
+ }
+ new_mem->redefineDesc(make_bhls_cache_desc(prec, B, H, L, S, cap_L));
+ state->assign_internal_state(new_mem);
+ if (quantized) {
+ state->set_scale_zp(new_szp);
+ }
+ mem = new_mem;
+ }
+ state->assign_internal_state_max_size(B * H * cap_L * S);
+
+ // by channel the quantization of the tokens already in the last (partial) group is redone together with
+ // the new ones, see attn_quant_by_channel()
+ auto quantize = [&](const PlainTensor& src, const PlainTensor& dst, const PlainTensor& szp, size_t from) {
+ if (by_channel) {
+ ov::Extensions::Cpu::XARCH::attn_quant_by_channel(src, dst, szp, from, spec.group_size, cpu_parallel);
+ } else {
+ ov::Extensions::Cpu::XARCH::attn_quant_by_token(src, dst, szp, from, spec.group_size, cpu_parallel);
+ }
+ };
+ PlainTensor cache(mem);
+ if (is_reset && L0 > 0) {
+ // the state was reset (or never set) and has an initial value: it is provided by the state input
+ PlainTensor init(getSrcMemoryAtPort(init_port));
+ CPU_NODE_ASSERT(init.size(0) == B && init.size(1) == H && init.size(2) == L0 && init.size(3) == S,
+ "the initial state shape does not match the current key/value");
+ if (quantized) {
+ quantize(init, cache, state->get_scale_zp(), 0);
+ } else {
+ cpu_parallel->parallel_for2d(B, H, [&](size_t b, size_t h) {
+ cpu_convert(init.ptr_v(b, h, 0), cache.ptr_v(b, h, 0), init.get_precision(), prec, L0 * S);
+ });
+ }
+ }
+ if (quantized) {
+ quantize(cur, cache, state->get_scale_zp(), L0);
+ } else {
+ ov::Extensions::Cpu::XARCH::attn_memcpy2d(cur, cache, L0, cpu_parallel);
+ }
+ };
+ update(m_k_state, cur_k, beam_port + 1, m_key_spec);
+ update(m_v_state, cur_v, beam_port + 2, m_value_spec);
+}
+
+bool SparseSDPA::isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept {
+ try {
+ if (const auto kv_op = ov::as_type_ptr<const SparseAttentionKVOp>(op)) {
+ const auto& cfg = kv_op->get_config();
+ if (cfg.query_block_size != 1 || cfg.key_block_size <= 0) {
+ errorMessage = "SparseAttentionWithKVCache CPU implementation only supports query_block_size == 1 and "
+ "a positive key_block_size.";
+ return false;
+ }
+ const auto& q_ps = op->get_input_partial_shape(InputIdx::QUERY);
+ if (q_ps.rank().is_dynamic() || q_ps.size() != 4 || q_ps[3].is_dynamic()) {
+ errorMessage = "SparseAttentionWithKVCache CPU implementation requires a 4D query with a static head "
+ "size.";
+ return false;
+ }
+ const auto q_prec = op->get_input_element_type(InputIdx::QUERY);
+ if (none_of(q_prec, ov::element::f32, ov::element::f16, ov::element::bf16)) {
+ errorMessage = "SparseAttentionWithKVCache CPU implementation only supports f32, f16, or bf16 query.";
+ return false;
+ }
+ return true;
+ }
+ const auto sparse_attention = ov::as_type_ptr<const SparseAttentionOp>(op);
+ if (!sparse_attention) {
+ errorMessage = "Only SparseAttention or SparseAttentionWithKVCache operations are supported";
+ return false;
+ }
+ if (op->get_input_size() != InputIdx::COUNT_MIN && op->get_input_size() != InputIdx::COUNT_MIN + 1) {
+ errorMessage = "SparseAttention CPU implementation only supports the 5-input form or the 6-input form "
+ "(with key_length); the scale and sinks inputs are not supported.";
+ return false;
+ }
+ if (sparse_attention->get_query_block_size() != 1) {
+ errorMessage = "SparseAttention CPU implementation only supports query_block_size == 1.";
+ return false;
+ }
+ if (sparse_attention->get_key_block_size() <= 0) {
+ errorMessage = "SparseAttention key_block_size must be positive.";
+ return false;
+ }
+ const auto& q_shape = op->get_input_partial_shape(InputIdx::QUERY);
+ if (q_shape.rank().is_dynamic() || q_shape[3].is_dynamic()) {
+ errorMessage = "SparseAttention CPU implementation requires a static query head size.";
+ return false;
+ }
+ static constexpr size_t float_ports[] = {InputIdx::QUERY, InputIdx::KEY, InputIdx::VALUE};
+ for (auto port : float_ports) {
+ const auto prec = op->get_input_element_type(port);
+ if (prec != ov::element::f32 && prec != ov::element::f16 && prec != ov::element::bf16) {
+ errorMessage = "SparseAttention CPU implementation only supports f32, f16, or bf16 data inputs.";
+ return false;
+ }
+ }
+ } catch (...) {
+ return false;
+ }
+ return true;
+}
+
+} // namespace ov::intel_cpu::node
diff --git a/src/plugins/intel_cpu/src/nodes/sparse_sdpa.h b/src/plugins/intel_cpu/src/nodes/sparse_sdpa.h
new file mode 100644
index 00000000000..1b89c8a8d92
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/sparse_sdpa.h
@@ -0,0 +1,116 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <memory>
+#include <oneapi/dnnl/dnnl_common.hpp>
+#include <string>
+#include <vector>
+
+#include "cpu_memory.h"
+#include "cpu_types.h"
+#include "graph_context.h"
+#include "memory_state.h"
+#include "node.h"
+#include "nodes/kernels/scaled_attn/cache_spec.hpp"
+#include "nodes/kernels/sparse_attn/sparse_brgemm.hpp"
+#include "openvino/core/node.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "openvino/op/sparse_attention.hpp"
+
+namespace ov::intel_cpu::node {
+
+/// @brief CPU implementation of ov::op::v17::SparseAttention: block-sparse group-query attention over a dense
+/// `[B, Hkv, S, D]` K/V cache, with the selection from a producer such as QSAIndexer. Causal: query l is at S - L + l.
+/// The SparseAttentionWithKVCache form keeps the cache in VariableStateKVcacheBHLS states, plain or u8 / u4.
+class SparseSDPA : public Node {
+public:
+ SparseSDPA(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context);
+
+ void getSupportedDescriptors() override {}
+ [[nodiscard]] bool created() const override {
+ return getType() == Type::SparseSDPA;
+ }
+ [[nodiscard]] bool needPrepareParams() const override {
+ return false;
+ }
+ // The state inputs of the stateful form are proxies and have zero length on the first step.
+ [[nodiscard]] bool isExecutable() const override {
+ if (!m_fuse_concat) {
+ return Node::isExecutable();
+ }
+ for (size_t i = 0; i < m_base_inputs + 1; i++) { // + beam_idx
+ if (isInputTensorAtPortEmpty(i)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ void executeDynamicImpl(const dnnl::stream& strm) override {
+ execute(strm);
+ }
+ void initSupportedPrimitiveDescriptors() override;
+ void execute(const dnnl::stream& strm) override;
+ void createPrimitive() override;
+ static bool isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept;
+
+ // true for SparseAttentionWithKVCache, the form that owns the KV cache states
+ [[nodiscard]] bool isStateful() const {
+ return m_fuse_concat;
+ }
+
+ // KV cache state interface, consumed by MemoryInputSparseSDPA (only meaningful for SparseAttentionWithKVCache).
+ void assignState(const std::shared_ptr<VariableStateKVcache>& state, int idx);
+ [[nodiscard]] static std::vector<size_t> getKVCacheOrder() {
+ return {0, 1, 2, 3}; // BHLS: the kernels read rows along L contiguously
+ }
+ [[nodiscard]] ov::element::Type getKeyCachePrecision() const {
+ return m_key_spec.precision;
+ }
+ [[nodiscard]] ov::element::Type getValueCachePrecision() const {
+ return m_value_spec.precision;
+ }
+ [[nodiscard]] const ov::Extensions::Cpu::CacheSpec& getKeySpec() const {
+ return m_key_spec;
+ }
+ [[nodiscard]] const ov::Extensions::Cpu::CacheSpec& getValueSpec() const {
+ return m_value_spec;
+ }
+ [[nodiscard]] static bool isQuantizedCache(const ov::Extensions::Cpu::CacheSpec& spec) {
+ return spec.precision == ov::element::u8 || spec.precision == ov::element::u4;
+ }
+
+private:
+ // Appends the current step's key/value to the key/value states.
+ void updateKVCache();
+
+ // SparseAttentionWithKVCache: the last three inputs are beam_idx, past_key, past_value.
+ bool m_fuse_concat = false;
+ // number of the leading (non-stateful) inputs: 5 or 6
+ size_t m_base_inputs = 0;
+ // precision of the plain (not quantized) cache and the precision the quantized cache is decoded to: the query's
+ ov::element::Type m_cache_prec = ov::element::f32;
+ // the stored precision of the key / value cache (m_cache_prec, u8 or u4) and its quantization parameters
+ ov::Extensions::Cpu::CacheSpec m_key_spec;
+ ov::Extensions::Cpu::CacheSpec m_value_spec;
+ std::shared_ptr<VariableStateKVcache> m_k_state;
+ std::shared_ptr<VariableStateKVcache> m_v_state;
+
+ size_t m_key_block_size = 0;
+ bool m_causal = true;
+ float m_scale = 0.0F;
+
+ // No persistent scratch MemoryPtr member, on purpose: the DnnlScratchPad is one shared, grow-only buffer, so a
+ // later createScratchPadMem() that grows it frees the memory of an earlier one. execute() makes exactly one
+ // combined request and never holds a pointer across it.
+
+#ifdef OPENVINO_ARCH_X86_64
+ // AMX matrix products of the prefill over a pack of query heads (empty when the node is not eligible: no AMX, a non
+ // bf16/f16 cache, a non-causal op, dynamic head counts or a pack of one head), see SparseBrgemm.
+ ov::Extensions::Cpu::SparseBrgemmKernels m_brgemm;
+#endif
+};
+
+} // namespace ov::intel_cpu::node
diff --git a/src/plugins/intel_cpu/src/nodes_factory.cpp b/src/plugins/intel_cpu/src/nodes_factory.cpp
index 3262aa19a09..35a5a88f26b 100644
--- a/src/plugins/intel_cpu/src/nodes_factory.cpp
+++ b/src/plugins/intel_cpu/src/nodes_factory.cpp
@@ -123,8 +123,12 @@
# include "nodes/interaction.h"
# include "nodes/llm_mlp.h"
# include "nodes/paged_attn.h"
+# include "nodes/paged_qsa_indexer.h"
# include "nodes/qkv_proj.h"
+# include "nodes/qsa_indexer.h"
# include "nodes/rms_norm.h"
+# include "nodes/sparse_pa.h"
+# include "nodes/sparse_sdpa.h"
#endif
#if defined(OPENVINO_ARCH_ARM64)
@@ -256,6 +260,7 @@ Node::NodesFactory::NodesFactory() : Factory("NodesFactory") {
INTEL_CPU_NODE(SelectiveSSM, Type::SelectiveSSM);
INTEL_CPU_NODE(PagedSelectiveSSM, Type::PagedSelectiveSSM);
INTEL_CPU_NODE(PagedCausalConv1D, Type::PagedCausalConv1D);
+
#if defined(OPENVINO_ARCH_X86_64)
INTEL_CPU_NODE(FakeQuantize, Type::FakeQuantize);
INTEL_CPU_NODE(GridSample, Type::GridSample);
@@ -264,6 +269,10 @@ Node::NodesFactory::NodesFactory() : Factory("NodesFactory") {
INTEL_CPU_NODE(QKVProjection, Type::QKVProjection);
INTEL_CPU_NODE(PagedAttention, Type::PagedAttention);
INTEL_CPU_NODE(RMSNorm, Type::RMS);
+ INTEL_CPU_NODE(QSAIndexer, Type::QSAIndexer);
+ INTEL_CPU_NODE(SparseSDPA, Type::SparseSDPA);
+ INTEL_CPU_NODE(PagedQSAIndexer, Type::PagedQSAIndexer);
+ INTEL_CPU_NODE(SparsePA, Type::SparsePA);
#elif defined(OPENVINO_ARCH_ARM64)
INTEL_CPU_NODE(FakeQuantize, Type::FakeQuantize);
INTEL_CPU_NODE(PagedAttention, Type::PagedAttention);
diff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/qsa_indexer.cpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/qsa_indexer.cpp
new file mode 100644
index 00000000000..5d75db3a3c8
--- /dev/null
+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/qsa_indexer.cpp
@@ -0,0 +1,293 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "qsa_indexer.hpp"
+
+#include <algorithm>
+#include <cmath>
+#include <cstddef>
+#include <cstdint>
+#include <initializer_list>
+#include <memory>
+#include <string>
+
+#include "openvino/core/attribute_visitor.hpp"
+#include "openvino/core/except.hpp"
+#include "openvino/core/node.hpp"
+#include "openvino/core/node_vector.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "openvino/core/validation_util.hpp"
+#include "openvino/op/op.hpp"
+#include "transformations/itt.hpp"
+
+namespace ov::intel_cpu {
+
+namespace {
+// The kernels read every integer input as int32_t.
+void check_i32_input(const ov::Node* node, size_t idx, const char* name, int64_t rank) {
+ const auto& et = node->get_input_element_type(idx);
+ const auto& ps = node->get_input_partial_shape(idx);
+ NODE_VALIDATION_CHECK(node,
+ et.is_dynamic() || et == element::i32,
+ node->get_type_name(),
+ " expects an i32 ",
+ name,
+ " input, got ",
+ et);
+ NODE_VALIDATION_CHECK(node,
+ ps.rank().compatible(rank),
+ node->get_type_name(),
+ " expects a rank-",
+ rank,
+ " ",
+ name,
+ " input, got ",
+ ps);
+}
+
+void check_shape(const ov::Node* node, size_t idx, const char* name, const ov::PartialShape& expected) {
+ const auto& ps = node->get_input_partial_shape(idx);
+ NODE_VALIDATION_CHECK(node,
+ ps.compatible(expected),
+ node->get_type_name(),
+ " expects ",
+ name,
+ " shaped ",
+ expected,
+ ", got ",
+ ps);
+}
+
+// [batch | 1, length, rot]: a single table is shared by all the batches.
+void check_rope_table_shape(const ov::Node* node,
+ size_t idx,
+ const char* name,
+ const ov::Dimension& batch,
+ const ov::Dimension& length,
+ const ov::Dimension& rot) {
+ const auto& ps = node->get_input_partial_shape(idx);
+ NODE_VALIDATION_CHECK(
+ node,
+ ps.compatible(ov::PartialShape{batch, length, rot}) || ps.compatible(ov::PartialShape{1, length, rot}),
+ node->get_type_name(),
+ " expects ",
+ name,
+ " shaped [",
+ batch,
+ " or 1, ",
+ length,
+ ", ",
+ rot,
+ "], got ",
+ ps);
+}
+
+// All floating-point inputs share one element type: the CPU kernel is instantiated for that precision, so
+// converting the other ports is the job of whoever builds the op.
+void check_float_inputs(const ov::Node* node, std::initializer_list<size_t> indices) {
+ auto data_type = ov::element::dynamic;
+ for (auto idx : indices) {
+ const auto& et = node->get_input_element_type(idx);
+ NODE_VALIDATION_CHECK(node,
+ et.is_dynamic() || et.is_real(),
+ node->get_type_name(),
+ " expects a floating-point input at index ",
+ idx,
+ ", got ",
+ et);
+ NODE_VALIDATION_CHECK(node,
+ ov::element::Type::merge(data_type, data_type, et),
+ node->get_type_name(),
+ " expects all floating-point inputs to have the same element type, input ",
+ idx,
+ " is ",
+ et,
+ " but the others are ",
+ data_type);
+ }
+}
+
+ov::Dimension dim_at(const ov::PartialShape& ps, size_t axis) {
+ return ps.rank().is_static() && ps.size() > axis ? ps[axis] : ov::Dimension::dynamic();
+}
+} // namespace
+
+QSAIndexerNode::QSAIndexerNode(const ov::OutputVector& args, const Config& config) : Op(args), m_config(config) {
+ constructor_validate_and_infer_types();
+}
+
+bool QSAIndexerNode::validate_config(const Config& c, std::string& reason) {
+ if (c.compress_ratio < 2) {
+ reason = "compress_ratio must be at least 2";
+ return false;
+ }
+ if (c.block_topk == 0) {
+ reason = "block_topk must be positive";
+ return false;
+ }
+ if (c.h_sel == 0) {
+ reason = "h_sel must be positive";
+ return false;
+ }
+ if (c.indexer_head_dim == 0) {
+ reason = "indexer_head_dim must be positive";
+ return false;
+ }
+ if (c.indexer_rotary_dim == 0 || c.indexer_rotary_dim % 2 != 0 || c.indexer_rotary_dim > c.indexer_head_dim) {
+ reason = "indexer_rotary_dim must be positive, even and not exceed indexer_head_dim";
+ return false;
+ }
+ if (!std::isfinite(c.scale) || c.scale < 0.0F) {
+ reason = "scale must be positive (0 selects the default 1 / sqrt(indexer_head_dim))";
+ return false;
+ }
+ return true;
+}
+
+float QSAIndexerNode::effective_scale(const Config& c) {
+ return c.scale > 0.0F ? c.scale : 1.0F / std::sqrt(static_cast<float>(c.indexer_head_dim));
+}
+
+size_t QSAIndexerNode::get_index_query_heads() const {
+ const auto& ps = get_input_partial_shape(InputIdx::Q_IDX);
+ OPENVINO_ASSERT(ps.rank().is_static() && ps.size() == 4 && ps[2].is_static(),
+ "QSAIndexer: q_idx shape is not static");
+ return static_cast<size_t>(ps[2].get_length());
+}
+
+size_t QSAIndexerNode::get_index_key_heads() const {
+ const auto& ps = get_input_partial_shape(InputIdx::K_IDX);
+ OPENVINO_ASSERT(ps.rank().is_static() && ps.size() == 4 && ps[2].is_static(),
+ "QSAIndexer: k_idx shape is not static");
+ return static_cast<size_t>(ps[2].get_length());
+}
+
+bool QSAIndexerNode::visit_attributes(ov::AttributeVisitor& visitor) {
+ INTERNAL_OP_SCOPE(QSAIndexer_visit_attributes);
+ visitor.on_attribute("compress_ratio", m_config.compress_ratio);
+ visitor.on_attribute("block_topk", m_config.block_topk);
+ visitor.on_attribute("h_sel", m_config.h_sel);
+ visitor.on_attribute("indexer_rotary_dim", m_config.indexer_rotary_dim);
+ visitor.on_attribute("indexer_head_dim", m_config.indexer_head_dim);
+ visitor.on_attribute("eps", m_config.eps);
+ visitor.on_attribute("scale", m_config.scale);
+ visitor.on_attribute("order_by_score", m_config.order_by_score);
+ return true;
+}
+
+void QSAIndexerNode::validate_and_infer_types() {
+ INTERNAL_OP_SCOPE(QSAIndexer_validate_and_infer_types);
+ NODE_VALIDATION_CHECK(this,
+ get_input_size() == InputIdx::COUNT,
+ "QSAIndexer expects ",
+ InputIdx::COUNT,
+ " inputs, got ",
+ get_input_size());
+
+ std::string reason;
+ NODE_VALIDATION_CHECK(this, validate_config(m_config, reason), "QSAIndexer configuration is invalid: ", reason);
+
+ const auto& q_idx_ps = get_input_partial_shape(InputIdx::Q_IDX);
+ const auto& k_idx_ps = get_input_partial_shape(InputIdx::K_IDX);
+ NODE_VALIDATION_CHECK(this,
+ q_idx_ps.rank().is_dynamic() || q_idx_ps.size() == 4,
+ "QSAIndexer expects a rank-4 [B, L, H_iq, D_idx] q_idx input, got ",
+ q_idx_ps);
+ NODE_VALIDATION_CHECK(this,
+ k_idx_ps.rank().is_dynamic() || k_idx_ps.size() == 4,
+ "QSAIndexer expects a rank-4 [B, L, H_ik, D_idx] k_idx input, got ",
+ k_idx_ps);
+ check_float_inputs(this,
+ {InputIdx::Q_IDX,
+ InputIdx::K_IDX,
+ InputIdx::ROPE_COS,
+ InputIdx::ROPE_SIN,
+ InputIdx::Q_NORM_WEIGHT,
+ InputIdx::K_NORM_WEIGHT,
+ InputIdx::SUMMARY_CACHE,
+ InputIdx::PAST_INCOMPLETE_RAW_K,
+ InputIdx::PAST_INCOMPLETE_ROPE});
+
+ const auto r = static_cast<int64_t>(m_config.compress_ratio);
+ const ov::Dimension di(static_cast<int64_t>(m_config.indexer_head_dim));
+ const ov::Dimension rot(static_cast<int64_t>(m_config.indexer_rotary_dim));
+ const ov::Dimension rope_tail(static_cast<int64_t>(2 * m_config.indexer_rotary_dim));
+ const ov::Dimension tail_len(r - 1);
+ const auto batch = dim_at(q_idx_ps, 0);
+ const auto length = dim_at(q_idx_ps, 1);
+ const auto h_ik = dim_at(k_idx_ps, 2);
+
+ check_shape(this, InputIdx::Q_IDX, "q_idx", ov::PartialShape{batch, length, -1, di});
+ check_shape(this, InputIdx::K_IDX, "k_idx", ov::PartialShape{batch, length, h_ik, di});
+ // The RoPE tables are shared by all the batches when their batch is 1.
+ check_rope_table_shape(this, InputIdx::ROPE_COS, "rope_cos", batch, length, rot);
+ check_rope_table_shape(this, InputIdx::ROPE_SIN, "rope_sin", batch, length, rot);
+ check_shape(this, InputIdx::Q_NORM_WEIGHT, "q_norm_weight", ov::PartialShape{di});
+ check_shape(this, InputIdx::K_NORM_WEIGHT, "k_norm_weight", ov::PartialShape{di});
+
+ check_i32_input(this, InputIdx::KEY_LENGTH, "key_length", 1);
+ // [batch] or [1]: a single length is shared by all the rows.
+ const auto& key_length_ps = get_input_partial_shape(InputIdx::KEY_LENGTH);
+ NODE_VALIDATION_CHECK(
+ this,
+ key_length_ps.compatible(ov::PartialShape{batch}) || key_length_ps.compatible(ov::PartialShape{1}),
+ get_type_name(),
+ " expects key_length shaped [",
+ batch,
+ " or 1], got ",
+ key_length_ps);
+
+ // summary_cache holds only the blocks of the earlier calls (Bp is free); the output carries all the blocks.
+ check_shape(this, InputIdx::SUMMARY_CACHE, "summary_cache", ov::PartialShape{batch, h_ik, -1, di});
+ check_shape(this,
+ InputIdx::PAST_INCOMPLETE_RAW_K,
+ "past_incomplete_raw_k",
+ ov::PartialShape{batch, h_ik, tail_len, di});
+ check_shape(this, InputIdx::PAST_INCOMPLETE_ROPE, "past_incomplete_rope", ov::PartialShape{batch, rope_tail});
+
+ if (q_idx_ps.rank().is_static() && q_idx_ps.size() == 4 && q_idx_ps[2].is_static() && h_ik.is_static()) {
+ const auto h_iq = static_cast<size_t>(q_idx_ps[2].get_length());
+ const auto h_ik_value = static_cast<size_t>(h_ik.get_length());
+ NODE_VALIDATION_CHECK(this,
+ h_ik_value != 0 && h_iq % h_ik_value == 0,
+ "QSAIndexer: H_iq must be a positive multiple of H_ik.");
+ NODE_VALIDATION_CHECK(this,
+ m_config.h_sel == 1 || m_config.h_sel == h_ik_value,
+ "QSAIndexer: h_sel must be 1 or H_ik.");
+ }
+
+ const ov::PartialShape sel_indices_ps{batch,
+ ov::Dimension(static_cast<int64_t>(m_config.h_sel)),
+ length,
+ ov::Dimension(static_cast<int64_t>(m_config.block_topk))};
+ const ov::PartialShape sel_count_ps{batch, ov::Dimension(static_cast<int64_t>(m_config.h_sel)), length};
+
+ set_output_size(OutputIdx::COUNT);
+ set_output_type(OutputIdx::SEL_INDICES, element::i32, sel_indices_ps);
+ set_output_type(OutputIdx::SEL_COUNT, element::i32, sel_count_ps);
+ // The state updates are out-of-place: the incomplete-block outputs mirror their inputs.
+ // The blocks of the longest row: known only from the key_length values.
+ auto num_blocks = ov::Dimension::dynamic();
+ if (const auto key_length = ov::util::get_constant_from_source(input_value(InputIdx::KEY_LENGTH))) {
+ const auto lengths = key_length->cast_vector<int64_t>();
+ const auto longest = lengths.empty() ? int64_t{0} : *std::max_element(lengths.begin(), lengths.end());
+ num_blocks = ov::Dimension(std::max<int64_t>(longest, 0) / r);
+ }
+ set_output_type(OutputIdx::SUMMARY_CACHE,
+ get_input_element_type(InputIdx::SUMMARY_CACHE),
+ ov::PartialShape{batch, h_ik, num_blocks, di});
+ set_output_type(OutputIdx::PAST_INCOMPLETE_RAW_K,
+ get_input_element_type(InputIdx::PAST_INCOMPLETE_RAW_K),
+ get_input_partial_shape(InputIdx::PAST_INCOMPLETE_RAW_K));
+ set_output_type(OutputIdx::PAST_INCOMPLETE_ROPE,
+ get_input_element_type(InputIdx::PAST_INCOMPLETE_ROPE),
+ get_input_partial_shape(InputIdx::PAST_INCOMPLETE_ROPE));
+}
+
+std::shared_ptr<Node> QSAIndexerNode::clone_with_new_inputs(const ov::OutputVector& new_args) const {
+ check_new_args_count(this, new_args);
+ return std::make_shared<QSAIndexerNode>(new_args, m_config);
+}
+
+} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/qsa_indexer.hpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/qsa_indexer.hpp
new file mode 100644
index 00000000000..5527b31a9be
--- /dev/null
+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/qsa_indexer.hpp
@@ -0,0 +1,113 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#pragma once
+
+#include <cstddef>
+#include <memory>
+#include <string>
+
+#include "openvino/core/node.hpp"
+#include "openvino/op/op.hpp"
+
+namespace ov::intel_cpu {
+
+/// \brief Padding-aware, non-paged, caller-owned-cache complete-block plan producer for Qwen
+/// Sparse Attention (QSA). See `qsa-indexer-v2.rst` for the normative contract.
+///
+/// Unlike `QSAIndexer`, every B x L query/key token need not be real: `key_length` tells this op,
+/// per row, the total number of valid (past + current) key tokens *after* this call, and any
+/// leading rows of this call's L-wide window beyond that count are treated as left-padding and
+/// skipped (no pooling contribution, no selection). `past`/`current`/block-append-offset are all
+/// derived per row from `key_length` and `L` alone -- the caller advances no running counter of
+/// its own between calls, unlike `QSAIndexer`'s `past_lens`.
+///
+/// Reads no page table and owns no opaque runtime state: its logical cache state is three
+/// caller-owned dense tensors (`summary_cache`, `past_incomplete_raw_k`, `past_incomplete_rope`).
+/// The update is NOT in place: the inputs are never modified, and the updated values of the three
+/// states are produced as outputs so that an outside Assign can write them back to the variables.
+/// `summary_cache` follows the QSAPrepare-17 `block_index_keys` contract: the input holds the blocks
+/// of the earlier calls ([B, H_ik, Bp, D_idx]) and the output holds the blocks of the longest row after this
+/// call ([B, H_ik, max(key_length) / key_block_size, D_idx]), i.e. it grows without any caller-managed
+/// capacity (rows with fewer blocks are zero-filled past their last block). `past_incomplete_raw_k` /
+/// `past_incomplete_rope` are FIXED size (`key_block_size - 1` rows / one row respectively), fully overwritten
+/// every call, and keep their input shape.
+///
+/// \ingroup ov_ops_cpp_api
+class QSAIndexerNode : public ov::op::Op {
+public:
+ OPENVINO_OP("QSAIndexer", "cpu_plugin_opset");
+
+ /// @brief Fixed input order of the QSAIndexerNode op. All state cache ports are grouped at
+ /// the end, after every plain-data/weight input.
+ struct InputIdx {
+ static constexpr size_t Q_IDX = 0; ///< [B, L, H_iq, D_idx]
+ static constexpr size_t K_IDX = 1; ///< [B, L, H_ik, D_idx], may include left-padding rows
+ static constexpr size_t ROPE_COS = 2; ///< [B or 1, L, indexer_rotary_dim]
+ static constexpr size_t ROPE_SIN = 3; ///< [B or 1, L, indexer_rotary_dim]
+ static constexpr size_t KEY_LENGTH = 4; ///< [B] i32, read-only; total valid length after this call
+ static constexpr size_t Q_NORM_WEIGHT = 5; ///< [D_idx]
+ static constexpr size_t K_NORM_WEIGHT = 6; ///< [D_idx]
+ static constexpr size_t SUMMARY_CACHE = 7; ///< [B, H_ik, Bp, D_idx], state input, blocks of earlier calls
+ static constexpr size_t PAST_INCOMPLETE_RAW_K =
+ 8; ///< [B, H_ik, key_block_size - 1, D_idx], state input, fixed size
+ static constexpr size_t PAST_INCOMPLETE_ROPE =
+ 9; ///< [B, 2 * indexer_rotary_dim], rope_cos then rope_sin of the incomplete block's first token, state
+ ///< input, fixed size
+
+ static constexpr size_t COUNT = 10;
+ };
+
+ /// @brief Fixed output order of the QSAIndexerNode op. The three state outputs are the updated
+ /// values of the matching state inputs (same element type; summary_cache grows, see the class comment).
+ struct OutputIdx {
+ static constexpr size_t SEL_INDICES = 0; ///< [B, H_sel, L, block_topk] i32
+ static constexpr size_t SEL_COUNT = 1; ///< [B, H_sel, L] i32
+ static constexpr size_t SUMMARY_CACHE = 2; ///< [B, H_ik, max(key_length) / key_block_size, D_idx]
+ static constexpr size_t PAST_INCOMPLETE_RAW_K = 3; ///< updated past_incomplete_raw_k (input shape)
+ static constexpr size_t PAST_INCOMPLETE_ROPE = 4; ///< updated past_incomplete_rope (input shape)
+
+ static constexpr size_t COUNT = 5;
+ };
+
+ struct Config {
+ size_t compress_ratio = 4; ///< r (key_block_size), at least 2
+ size_t block_topk = 0; ///< K_max, required
+ size_t h_sel = 1; ///< 1 or H_ik
+ size_t indexer_rotary_dim = 0; ///< positive, even, <= indexer_head_dim
+ size_t indexer_head_dim = 0; ///< D_idx
+ float eps = 1e-6F; ///< RMSNorm epsilon
+ float scale = 0.0F; ///< positive score multiplier; 0 selects the default 1 / sqrt(indexer_head_dim)
+ /// Order of the selected blocks of a row in `sel_indices`. false: ascending block ids, the cheaper order that
+ /// the sparse attention kernels prefer (adjacent blocks are attended in one go); true: the order of
+ /// SparseAttentionIndexer-17, by descending score and, for equal scores, by ascending block id. It needs the
+ /// scores of every token, also of those that take all their blocks.
+ bool order_by_score = false;
+ };
+
+ QSAIndexerNode() = default;
+ QSAIndexerNode(const ov::OutputVector& args, const Config& config);
+
+ 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;
+
+ const Config& get_config() const {
+ return m_config;
+ }
+
+ static bool validate_config(const Config& config, std::string& reason);
+
+ /// `scale`, or its 1 / sqrt(indexer_head_dim) default when unset (0).
+ static float effective_scale(const Config& config);
+
+ /// H_iq, derived from q_idx's static shape (last dim / indexer_head_dim). Never cached.
+ size_t get_index_query_heads() const;
+ /// H_ik, derived from k_idx's static shape (last dim / indexer_head_dim). Never cached.
+ size_t get_index_key_heads() const;
+
+private:
+ Config m_config{};
+};
+
+} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/sparse_attention_with_kv_cache.cpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/sparse_attention_with_kv_cache.cpp
new file mode 100644
index 00000000000..acaf174c922
--- /dev/null
+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/sparse_attention_with_kv_cache.cpp
@@ -0,0 +1,98 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "sparse_attention_with_kv_cache.hpp"
+
+#include <memory>
+
+#include "openvino/core/attribute_visitor.hpp"
+#include "openvino/core/dimension.hpp"
+#include "openvino/core/node.hpp"
+#include "openvino/core/node_vector.hpp"
+#include "openvino/core/partial_shape.hpp"
+#include "openvino/op/op.hpp"
+#include "transformations/itt.hpp"
+
+namespace ov::intel_cpu {
+
+SparseAttentionWithKVCache::SparseAttentionWithKVCache(const OutputVector& args, const Config& cfg)
+ : Op(args),
+ m_config(cfg) {
+ constructor_validate_and_infer_types();
+}
+
+std::shared_ptr<ov::Node> SparseAttentionWithKVCache::clone_with_new_inputs(const ov::OutputVector& new_args) const {
+ INTERNAL_OP_SCOPE(SparseAttentionWithKVCache_with_new_inputs);
+ check_new_args_count(this, new_args);
+ return std::make_shared<SparseAttentionWithKVCache>(new_args, m_config);
+}
+
+void SparseAttentionWithKVCache::validate_and_infer_types() {
+ INTERNAL_OP_SCOPE(SparseAttentionWithKVCache_validate_and_infer_types);
+ const auto input_num = get_input_size();
+ NODE_VALIDATION_CHECK(this,
+ input_num == InputIdx::COUNT_MIN || input_num == InputIdx::COUNT_MAX,
+ "The number of inputs must be ",
+ InputIdx::COUNT_MIN,
+ " or ",
+ InputIdx::COUNT_MAX,
+ ". Got: ",
+ input_num);
+ NODE_VALIDATION_CHECK(this, m_config.key_block_size > 0, "key_block_size must be positive.");
+
+ const auto beam_idx_idx = input_num - 3;
+ const auto past_k_idx = input_num - 2;
+ const auto past_v_idx = input_num - 1;
+
+ const auto& q_ps = get_input_partial_shape(InputIdx::QUERY);
+ const auto& cur_k_ps = get_input_partial_shape(InputIdx::CUR_KEY);
+ const auto& cur_v_ps = get_input_partial_shape(InputIdx::CUR_VALUE);
+ auto past_k_ps = get_input_partial_shape(past_k_idx);
+ auto past_v_ps = get_input_partial_shape(past_v_idx);
+ const auto& beam_idx_ps = get_input_partial_shape(beam_idx_idx);
+
+ NODE_VALIDATION_CHECK(this, q_ps.rank().is_dynamic() || q_ps.size() == 4, "query must be 4D [N, H, L, E].");
+ NODE_VALIDATION_CHECK(this, cur_k_ps.rank().is_dynamic() || cur_k_ps.size() == 4, "key must be 4D.");
+ NODE_VALIDATION_CHECK(this, cur_v_ps.rank().is_dynamic() || cur_v_ps.size() == 4, "value must be 4D.");
+ NODE_VALIDATION_CHECK(this, past_k_ps.rank().is_dynamic() || past_k_ps.size() == 4, "past key must be 4D.");
+ NODE_VALIDATION_CHECK(this, past_v_ps.rank().is_dynamic() || past_v_ps.size() == 4, "past value must be 4D.");
+
+ // present = concat(gather(past, beam_idx, axis 0), cur, axis 2): the batch comes from beam_idx.
+ auto make_present = [&](ov::PartialShape past_ps, const ov::PartialShape& cur_ps) {
+ if (past_ps.rank().is_dynamic()) {
+ return past_ps;
+ }
+ if (beam_idx_ps.rank().is_static() && beam_idx_ps.size() == 1) {
+ past_ps[0] = beam_idx_ps[0];
+ }
+ if (cur_ps.rank().is_static()) {
+ past_ps[2] += cur_ps[2];
+ } else {
+ past_ps[2] = ov::Dimension::dynamic();
+ }
+ return past_ps;
+ };
+ auto present_k_ps = make_present(past_k_ps, cur_k_ps);
+ auto present_v_ps = make_present(past_v_ps, cur_v_ps);
+
+ ov::PartialShape out_ps = q_ps;
+ if (out_ps.rank().is_static() && cur_v_ps.rank().is_static()) {
+ out_ps[3] = cur_v_ps[3];
+ }
+ set_output_type(0, get_input_element_type(InputIdx::QUERY), out_ps);
+ set_output_type(1, get_input_element_type(past_k_idx), present_k_ps);
+ set_output_type(2, get_input_element_type(past_v_idx), present_v_ps);
+}
+
+bool SparseAttentionWithKVCache::visit_attributes(ov::AttributeVisitor& visitor) {
+ INTERNAL_OP_SCOPE(SparseAttentionWithKVCache_visit_attributes);
+ visitor.start_structure("config");
+ visitor.on_attribute("key_block_size", m_config.key_block_size);
+ visitor.on_attribute("query_block_size", m_config.query_block_size);
+ visitor.on_attribute("causal", m_config.causal);
+ visitor.finish_structure();
+ return true;
+}
+
+} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/sparse_attention_with_kv_cache.hpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/sparse_attention_with_kv_cache.hpp
new file mode 100644
index 00000000000..989b650bb21
--- /dev/null
+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/sparse_attention_with_kv_cache.hpp
@@ -0,0 +1,80 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+#include <memory>
+
+#include "openvino/core/attribute_visitor.hpp"
+#include "openvino/core/node.hpp"
+#include "openvino/core/node_vector.hpp"
+#include "openvino/op/op.hpp"
+
+namespace ov::intel_cpu {
+
+/// \brief ov::op::v17::SparseAttention fused with the KV cache update (Gather(beam) + Concat + Assign).
+///
+/// Counterpart of ScaledDotProductAttentionWithKVCache (fuse_concat == true) for the sparse attention op.
+/// The key/value cache lives in the plugin's KV cache variable states instead of in a Concat output, so the
+/// cache is appended in place and never copied as a whole on every step.
+///
+/// Inputs (the last three are the stateful part, always in this order):
+/// 0 query [N, H, L, E]
+/// 1 cur_key [N, Hkv, L, E] current step key, the cache is cat(past_key, cur_key) along axis 2
+/// 2 cur_value [N, Hkv, L, Ev] current step value, the cache is cat(past_value, cur_value) along axis 2
+/// 3 block_indices [N, Hs, L, KB]
+/// 4 block_count [N, Hs, L]
+/// 5 key_length [N] or [1], optional (the 8-input form has no key_length)
+/// n-3 beam_idx [N]
+/// n-2 past_key [N, Hkv, L0, E] output of the ReadValue of the key state
+/// n-1 past_value [N, Hkv, L0, Ev] output of the ReadValue of the value state
+///
+/// Outputs: 0 attention [N, H, L, Ev]; 1 present_key [N, Hkv, L0 + L, E] and 2 present_value
+/// [N, Hkv, L0 + L, Ev], to be consumed by the Assign nodes of the key/value states.
+///
+/// \ingroup ov_ops_cpp_api
+class SparseAttentionWithKVCache : public ov::op::Op {
+public:
+ OPENVINO_OP("SparseAttentionWithKVCache", "cpu_plugin_opset");
+
+ /// @brief Fixed positions of the leading inputs; the state inputs are addressed from the end.
+ struct InputIdx {
+ static constexpr size_t QUERY = 0;
+ static constexpr size_t CUR_KEY = 1;
+ static constexpr size_t CUR_VALUE = 2;
+ static constexpr size_t BLOCK_INDICES = 3;
+ static constexpr size_t BLOCK_COUNT = 4;
+ static constexpr size_t KEY_LENGTH = 5; ///< optional
+ static constexpr size_t COUNT_MIN = 5 + 3;
+ static constexpr size_t COUNT_MAX = 6 + 3;
+ };
+
+ struct Config {
+ int64_t key_block_size = 1;
+ int64_t query_block_size = 1;
+ bool causal = true;
+ };
+
+ SparseAttentionWithKVCache() = default;
+ SparseAttentionWithKVCache(const OutputVector& args, const Config& cfg);
+
+ std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& new_args) const override;
+ bool visit_attributes(AttributeVisitor& visitor) override;
+ void validate_and_infer_types() override;
+
+ const Config& get_config() const {
+ return m_config;
+ }
+
+ [[nodiscard]] bool has_key_length() const {
+ return get_input_size() == InputIdx::COUNT_MAX;
+ }
+
+private:
+ Config m_config;
+};
+
+} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/sparse_attention_kv_cache_fusion.cpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/sparse_attention_kv_cache_fusion.cpp
new file mode 100644
index 00000000000..fa7b572e334
--- /dev/null
+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/sparse_attention_kv_cache_fusion.cpp
@@ -0,0 +1,219 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "sparse_attention_kv_cache_fusion.hpp"
+
+#include <algorithm>
+#include <initializer_list>
+#include <memory>
+#include <vector>
+
+#include "openvino/cc/pass/itt.hpp"
+#include "openvino/core/graph_util.hpp"
+#include "openvino/core/node.hpp"
+#include "openvino/core/node_output.hpp"
+#include "openvino/core/node_vector.hpp"
+#include "openvino/core/rt_info.hpp"
+#include "openvino/core/type.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "openvino/op/assign.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/sparse_attention.hpp"
+#include "openvino/op/util/gather_base.hpp"
+#include "openvino/op/util/read_value_base.hpp"
+#include "openvino/op/util/shape_of_base.hpp"
+#include "openvino/pass/matcher_pass.hpp"
+#include "openvino/pass/pattern/matcher.hpp"
+#include "openvino/pass/pattern/op/label.hpp"
+#include "openvino/pass/pattern/op/optional.hpp"
+#include "openvino/pass/pattern/op/or.hpp"
+#include "openvino/pass/pattern/op/pattern.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "openvino/util/pp.hpp"
+#include "transformations/cpu_opset/common/op/sparse_attention_with_kv_cache.hpp"
+
+using namespace ov::pass;
+
+namespace ov::intel_cpu {
+
+SparseAttentionKVCacheFusion::SparseAttentionKVCacheFusion() {
+ MATCHER_SCOPE(SparseAttentionKVCacheFusion);
+ using namespace ov::pass::pattern;
+
+ auto beam_idx = any_input(type_matches(element::i32) && shape_matches("[?]"));
+ auto cur_q = any_input();
+ auto cur_k = any_input();
+ auto cur_v = any_input();
+ auto block_indices = any_input();
+ auto block_count = any_input();
+ auto key_length = any_input();
+
+ // The cache history is only read through ShapeOf, Convert and Gather.
+ auto only_cache_consumers = [](const ov::Output<ov::Node>& out) {
+ const auto children = out.get_target_inputs();
+ return std::all_of(children.begin(), children.end(), [](const ov::Input<ov::Node>& child) {
+ return ov::is_type_any_of<ov::op::util::ShapeOfBase, ov::op::v0::Convert, ov::op::util::GatherBase>(
+ child.get_node());
+ });
+ };
+ auto past_k = wrap_type<ov::op::util::ReadValueBase>(only_cache_consumers);
+ auto past_v = wrap_type<ov::op::util::ReadValueBase>(only_cache_consumers);
+ // The Convert dies with the fusion, so it must not have other consumers.
+ auto convert_past_k = optional<ov::op::v0::Convert>({past_k}, consumers_count(1));
+ auto convert_past_v = optional<ov::op::v0::Convert>({past_v}, consumers_count(1));
+
+ // The beam axis is the batch axis of the cache; both caches are reordered by the same beam_idx (the label).
+ auto beam_gather = consumers_count(1) && [](const ov::Output<ov::Node>& out) {
+ const auto* gather = ov::as_type<ov::op::util::GatherBase>(out.get_node());
+ return gather != nullptr && gather->get_batch_dims() == 0;
+ };
+ auto axis_k = wrap_type<ov::op::v0::Constant>(value_matches("0"));
+ auto axis_v = wrap_type<ov::op::v0::Constant>(value_matches("0"));
+ auto gather_k = wrap_type<ov::op::util::GatherBase>({convert_past_k, beam_idx, axis_k}, beam_gather);
+ auto gather_v = wrap_type<ov::op::util::GatherBase>({convert_past_v, beam_idx, axis_v}, beam_gather);
+
+ // key/value are [N, Hkv, S, E] and are concatenated along S (the axis may be negative). The Concat feeds the
+ // SparseAttention, the Assign (maybe through a Convert) and optionally a ShapeOf.
+ auto concat_s = rank_equals(4) && [](const ov::Output<ov::Node>& out) {
+ const auto* concat = ov::as_type<ov::op::v0::Concat>(out.get_node());
+ if (concat == nullptr || (concat->get_axis() != 2 && concat->get_axis() != -2)) {
+ return false;
+ }
+ const auto children = out.get_target_inputs();
+ return children.size() == 2 ||
+ (children.size() == 3 && std::any_of(children.begin(), children.end(), [](const ov::Input<ov::Node>& c) {
+ return ov::is_type<ov::op::util::ShapeOfBase>(c.get_node());
+ }));
+ };
+ auto concat_k = wrap_type<ov::op::v0::Concat>({gather_k, cur_k}, concat_s);
+ auto concat_v = wrap_type<ov::op::v0::Concat>({gather_v, cur_v}, concat_s);
+
+ // The fused op supports the 5/6-input forms only (no scale / sinks) with query_block_size == 1.
+ auto single_query_block = [](const ov::Output<ov::Node>& out) {
+ const auto* sparse = ov::as_type<ov::op::v17::SparseAttention>(out.get_node());
+ return sparse != nullptr && sparse->get_query_block_size() == 1;
+ };
+ auto sparse0 = wrap_type<ov::op::v17::SparseAttention>({cur_q, concat_k, concat_v, block_indices, block_count},
+ single_query_block);
+ auto sparse1 =
+ wrap_type<ov::op::v17::SparseAttention>({cur_q, concat_k, concat_v, block_indices, block_count, key_length},
+ single_query_block);
+ auto sparse = sparse0 | sparse1;
+
+ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](Matcher& m) {
+ const auto& pattern_map = m.get_pattern_value_map();
+ const auto sparse_node = ov::as_type_ptr<ov::op::v17::SparseAttention>(m.get_match_root());
+ const auto concat_k_node = ov::as_type_ptr<ov::op::v0::Concat>(pattern_map.at(concat_k).get_node_shared_ptr());
+ const auto concat_v_node = ov::as_type_ptr<ov::op::v0::Concat>(pattern_map.at(concat_v).get_node_shared_ptr());
+ const auto gather_k_node =
+ ov::as_type_ptr<ov::op::util::GatherBase>(pattern_map.at(gather_k).get_node_shared_ptr());
+ const auto gather_v_node =
+ ov::as_type_ptr<ov::op::util::GatherBase>(pattern_map.at(gather_v).get_node_shared_ptr());
+ const auto past_k_node =
+ ov::as_type_ptr<ov::op::util::ReadValueBase>(pattern_map.at(past_k).get_node_shared_ptr());
+ const auto past_v_node =
+ ov::as_type_ptr<ov::op::util::ReadValueBase>(pattern_map.at(past_v).get_node_shared_ptr());
+ if (m_processed_k_variable_ids.count(past_k_node->get_variable_id()) != 0 ||
+ m_processed_v_variable_ids.count(past_v_node->get_variable_id()) != 0) {
+ return false;
+ }
+
+ auto find_assign =
+ [&](const ov::Output<ov::Node>& out, ov::op::v6::Assign*& assign, ov::op::v0::Convert*& cvt) {
+ for (const auto& to : out.get_target_inputs()) {
+ auto* to_node = to.get_node();
+ if (auto* convert = ov::as_type<ov::op::v0::Convert>(to_node)) {
+ auto cvt_targets = convert->get_output_target_inputs(0);
+ if (cvt_targets.size() == 1) {
+ to_node = cvt_targets.begin()->get_node();
+ cvt = convert;
+ }
+ }
+ assign = ov::as_type<ov::op::v6::Assign>(to_node);
+ if (assign) {
+ return true;
+ }
+ }
+ return false;
+ };
+ ov::op::v6::Assign* assign_k_node = nullptr;
+ ov::op::v6::Assign* assign_v_node = nullptr;
+ ov::op::v0::Convert* assign_cvt_k_node = nullptr;
+ ov::op::v0::Convert* assign_cvt_v_node = nullptr;
+ if (!find_assign(concat_k_node, assign_k_node, assign_cvt_k_node) ||
+ past_k_node->get_variable_id() != assign_k_node->get_variable_id()) {
+ return false;
+ }
+ if (!find_assign(concat_v_node, assign_v_node, assign_cvt_v_node) ||
+ past_v_node->get_variable_id() != assign_v_node->get_variable_id()) {
+ return false;
+ }
+
+ OutputVector args = {pattern_map.at(cur_q),
+ pattern_map.at(cur_k),
+ pattern_map.at(cur_v),
+ pattern_map.at(block_indices),
+ pattern_map.at(block_count)};
+ if (pattern_map.count(key_length)) {
+ args.push_back(pattern_map.at(key_length));
+ }
+ args.push_back(pattern_map.at(beam_idx));
+ args.push_back(gather_k_node->input_value(0));
+ args.push_back(gather_v_node->input_value(0));
+
+ SparseAttentionWithKVCache::Config config;
+ config.key_block_size = sparse_node->get_key_block_size();
+ config.query_block_size = sparse_node->get_query_block_size();
+ config.causal = sparse_node->get_causal();
+
+ auto new_node = std::make_shared<SparseAttentionWithKVCache>(args, config);
+ new_node->set_friendly_name(sparse_node->get_friendly_name());
+ copy_runtime_info(sparse_node, new_node);
+ ov::replace_node(sparse_node, {new_node->output(0)});
+
+ if (assign_cvt_k_node) {
+ assign_cvt_k_node->set_arguments({new_node->output(1)});
+ } else {
+ assign_k_node->set_arguments({new_node->output(1)});
+ }
+ if (assign_cvt_v_node) {
+ assign_cvt_v_node->set_arguments({new_node->output(2)});
+ } else {
+ assign_v_node->set_arguments({new_node->output(2)});
+ }
+
+ // Without this reroute the dead Concat keeps the old Gather alive as a MemoryInput child, and
+ // MatchSparseSdpaKvCache rejects non-{SparseSDPA, ShapeOf} children.
+ auto reroute_shape_of_consumers = [](const std::shared_ptr<Node>& concat_node,
+ const ov::Output<ov::Node>& replacement) {
+ std::vector<ov::Input<Node>> shape_of_inputs;
+ for (const auto& target : concat_node->get_output_target_inputs(0)) {
+ if (ov::is_type<ov::op::util::ShapeOfBase>(target.get_node())) {
+ shape_of_inputs.push_back(target);
+ }
+ }
+ for (const auto& inp : shape_of_inputs) {
+ inp.replace_source_output(replacement);
+ }
+ };
+ reroute_shape_of_consumers(concat_k_node, new_node->output(1));
+ reroute_shape_of_consumers(concat_v_node, new_node->output(2));
+
+ // ReadValue -> [Convert] -> SparseAttentionWithKVCache -> [Convert] -> Assign must stay a plain
+ // MemoryInput/MemoryOutput pair for MatchSparseSdpaKvCache, so no init subgraph is fused into it.
+ past_k_node->get_rt_info()["DisableInitSubgraphFusing"] = true;
+ past_v_node->get_rt_info()["DisableInitSubgraphFusing"] = true;
+
+ m_processed_k_variable_ids.insert(past_k_node->get_variable_id());
+ m_processed_v_variable_ids.insert(past_v_node->get_variable_id());
+ return true;
+ };
+
+ auto m = std::make_shared<ov::pass::pattern::Matcher>(sparse, matcher_name);
+ this->register_matcher(m, callback);
+}
+
+} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/sparse_attention_kv_cache_fusion.hpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/sparse_attention_kv_cache_fusion.hpp
new file mode 100644
index 00000000000..70e6452eba4
--- /dev/null
+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/sparse_attention_kv_cache_fusion.hpp
@@ -0,0 +1,34 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <string>
+#include <unordered_set>
+
+#include "openvino/pass/matcher_pass.hpp"
+
+namespace ov::intel_cpu {
+
+/// \brief Fuses the KV cache update feeding ov::op::v17::SparseAttention into one SparseAttentionWithKVCache op:
+///
+/// ReadValue -> [Convert] -> Gather(beam_idx) -> Concat(cur) -> SparseAttention (key, value inputs)
+/// \-> [Convert] -> Assign
+///
+/// This is the sparse counterpart of StatefulSDPAFusion. The fused op keeps the cache in the plugin's KV cache
+/// states (see MatchSparseSdpaKvCache), so the history is not copied by the Concat on every step. Only the
+/// canonical layout is handled: key/value are [N, Hkv, S, E] and are concatenated along axis 2.
+class SparseAttentionKVCacheFusion : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("SparseAttentionKVCacheFusion");
+ SparseAttentionKVCacheFusion();
+
+private:
+ // Variable ids whose SparseAttention has already been fused; later matches on the same Variable are
+ // reader-only consumers and must be skipped.
+ std::unordered_set<std::string> m_processed_k_variable_ids;
+ std::unordered_set<std::string> m_processed_v_variable_ids;
+};
+
+} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp
index e81a1936d57..2d458804bf2 100644
--- a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp
+++ b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp
@@ -221,6 +221,7 @@
# include "transformations/cpu_opset/x64/pass/convert_to_interaction.hpp"
# include "transformations/cpu_opset/x64/pass/mlp_fusion.hpp"
# include "transformations/cpu_opset/x64/pass/qkv_proj_fusion.hpp"
+# include "transformations/cpu_opset/x64/pass/sparse_attention_kv_cache_fusion.hpp"
# include "transformations/op_conversions/group_normalization_decomposition.hpp"
# include "transformations/op_conversions/hsigmoid_decomposition.hpp"
# include "transformations/op_conversions/reduce_l1_decomposition.hpp"
@@ -595,6 +596,7 @@ void Transformations::PreLpt(const std::vector<ov::element::Type>& defaultPrecis
ov::pass::KeepConstAndDecompression);
CPU_REGISTER_PASS_COMMON(manager, ov::pass::AUGRUCellFusion);
CPU_REGISTER_PASS_COMMON(manager, SDPASubgraphFusion);
+ CPU_REGISTER_PASS_X64(manager, SparseAttentionKVCacheFusion);
CPU_REGISTER_PASS_COMMON(manager, ov::pass::GatedDeltaNetFusion);
CPU_REGISTER_PASS_COMMON(manager, ov::pass::CommonOptimizations);
CPU_REGISTER_PASS_COMMON(manager, ov::pass::KeepConstPrecision, decompression_precisions, false, true);
diff --git a/src/plugins/intel_cpu/tests/functional/CMakeLists.txt b/src/plugins/intel_cpu/tests/functional/CMakeLists.txt
index 43d3c6d52c2..b28aec4809b 100644
--- a/src/plugins/intel_cpu/tests/functional/CMakeLists.txt
+++ b/src/plugins/intel_cpu/tests/functional/CMakeLists.txt
@@ -42,6 +42,10 @@ target_link_libraries(cpuUtils PRIVATE ${CPU_UTILS_LINK_LIBRARIES})
target_include_directories(cpuUtils PRIVATE ${CPU_UTILS_INCLUDE_PATHS})
set(INCLUDES ${CMAKE_CURRENT_SOURCE_DIR} $<TARGET_PROPERTY:openvino_intel_cpu_plugin,SOURCE_DIR>/src)
+if(X86_64)
+ # x64 tests compile CPU-specific op sources (e.g. QSAIndexer) which use transformations/itt.hpp
+ list(APPEND INCLUDES $<TARGET_PROPERTY:openvino::conditional_compilation,INTERFACE_INCLUDE_DIRECTORIES>)
+endif()
set(DEPENDENCIES openvino_intel_cpu_plugin openvino_template_extension)
set(LINK_LIBRARIES funcSharedTests cpuUtils openvino::snippets ov_snippets_models openvino::reference)
diff --git a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/paged_qsa_indexer.cpp b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/paged_qsa_indexer.cpp
new file mode 100644
index 00000000000..64b8451d58b
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/paged_qsa_indexer.cpp
@@ -0,0 +1,567 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "paged_qsa_indexer.hpp"
+
+#include <algorithm>
+#include <array>
+#include <cmath>
+#include <cstdint>
+#include <limits>
+#include <vector>
+
+#include "common_test_utils/ov_tensor_utils.hpp"
+#include "openvino/core/type/bfloat16.hpp"
+#include "openvino/core/type/float16.hpp"
+#include "openvino/op/paged_qsa_indexer.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/runtime/properties.hpp"
+
+namespace {
+
+// Small configuration exercised by this test: up to 2 independent sequences of `new_tokens` tokens each (see
+// PagedQSAIndexerLayerTestParams), each with its own past_len (kPastLens[s]) and its own run of physical cache blocks
+// (enough for its tokens and a spare one), addressed through
+// a non-identity BLOCK_INDICES permutation (see generate_inputs) so a kernel bug that walked
+// physical blocks in logical/sequential order instead of resolving through BLOCK_INDICES would be
+// caught. An odd number of tokens is not a multiple of compress_ratio, so such an instantiation naturally
+// exercises the causal-tail-marker path on its final tokens and the empty-selection path on its
+// first token -- mirroring the dense QSAIndexer test (classes/qsa_indexer.cpp), whose per-token
+// math this test's oracle reuses verbatim: paged and dense kernels share identical per-token/
+// per-block math and process sequences independently, differing only in cache addressing.
+constexpr size_t kDidx = 16;
+constexpr size_t kRotaryDim = 8;
+constexpr size_t kR = 2;
+constexpr size_t kBlockTopk = 2;
+constexpr std::array<int32_t, 2> kPastLens = {0, 2};
+constexpr float kEps = 1e-6F;
+constexpr float kScale = 0.25F;
+
+// Paged-cache layout: the page size (a test parameter) must be a multiple of compress_ratio. The physical blocks of a
+// sequence (m_seq_blocks) hold its past and new tokens plus a spare page, so the last, incomplete block always has
+// room.
+
+void fill_pseudo_random(std::vector<float>& v, uint32_t seed_base) {
+ for (size_t i = 0; i < v.size(); i++) {
+ uint32_t x = seed_base * 2654435761U + static_cast<uint32_t>(i) * 40503U + 1U;
+ x ^= x >> 13;
+ x *= 0x85EBCA6BU;
+ x ^= x >> 16;
+ v[i] = (static_cast<float>(x % 20000U) / 10000.0F) - 1.0F;
+ }
+}
+
+float rms_inv_scale(const float* x, size_t n, float eps) {
+ float sumsq = 0.0F;
+ for (size_t i = 0; i < n; i++) {
+ sumsq += x[i] * x[i];
+ }
+ return 1.0F / std::sqrt(sumsq / static_cast<float>(n) + eps);
+}
+
+void rmsnorm_partial_rope(const float* src,
+ float* dst,
+ const float* weight,
+ size_t dim,
+ size_t rotary_dim,
+ float eps,
+ const float* cos_sin_row) {
+ const float inv_rms = rms_inv_scale(src, dim, eps);
+ for (size_t d = 0; d < dim; d++) {
+ dst[d] = src[d] * inv_rms * weight[d];
+ }
+ const size_t half = rotary_dim / 2;
+ for (size_t j = 0; j < half; j++) {
+ const float cos_lo = cos_sin_row[2 * j];
+ const float sin_lo = cos_sin_row[2 * j + 1];
+ const float cos_hi = cos_sin_row[2 * (j + half)];
+ const float sin_hi = cos_sin_row[2 * (j + half) + 1];
+ const float x0 = dst[j];
+ const float x1 = dst[j + half];
+ dst[j] = x0 * cos_lo - x1 * sin_lo;
+ dst[j + half] = x1 * cos_hi + x0 * sin_hi;
+ }
+}
+
+// Independent (host-vector based) re-implementation of the paged-qsa-indexer.rst per-sequence
+// spec, used purely as a test oracle -- NOT a copy of the CPU node's PlainTensor-based paged
+// addressing. Per-sequence math is bit-for-bit identical to the dense QSAIndexer oracle
+// (classes/qsa_indexer.cpp's run_qsa_indexer_reference): the paged kernel's logical_pos ==
+// past_len + local token index, exactly dense's abs_pos, and sequences never interact.
+struct PagedQSAIndexerOracleOutput {
+ std::vector<int64_t> sel_indices;
+ std::vector<int64_t> sel_count;
+};
+
+PagedQSAIndexerOracleOutput run_paged_qsa_indexer_reference(size_t new_tokens,
+ size_t h_iq,
+ size_t h_ik,
+ size_t h_sel,
+ const std::vector<float>& q_idx,
+ const std::vector<float>& k_idx,
+ const std::vector<float>& rope_cos,
+ const std::vector<float>& rope_sin,
+ const std::vector<float>& q_norm_weight,
+ const std::vector<float>& k_norm_weight,
+ int64_t past_len) {
+ const size_t group = h_iq / h_ik;
+ std::vector<size_t> kv_of_head(h_iq), sel_of_head(h_iq);
+ for (size_t h = 0; h < h_iq; h++) {
+ kv_of_head[h] = h / group;
+ sel_of_head[h] = (kv_of_head[h] * h_sel) / h_ik;
+ }
+
+ const size_t s_cap = new_tokens + static_cast<size_t>(past_len);
+ const size_t summary_len = s_cap / kR;
+ std::vector<float> raw_k_cache(h_ik * s_cap * kDidx, 0.0F);
+ std::vector<float> summary_cache(h_ik * summary_len * kDidx, 0.0F);
+
+ const auto interleave = [&](size_t local_idx, std::array<float, 2 * kRotaryDim>& buf) {
+ for (size_t j = 0; j < kRotaryDim; j++) {
+ buf[2 * j] = rope_cos[local_idx * kRotaryDim + j];
+ buf[2 * j + 1] = rope_sin[local_idx * kRotaryDim + j];
+ }
+ };
+
+ PagedQSAIndexerOracleOutput out;
+ out.sel_indices.assign(h_sel * new_tokens * kBlockTopk, -1);
+ out.sel_count.assign(h_sel * new_tokens, 0);
+
+ for (size_t l = 0; l < new_tokens; l++) {
+ const int64_t abs_pos = past_len + static_cast<int64_t>(l);
+
+ std::vector<float> q_normed(h_iq * kDidx);
+ std::array<float, 2 * kRotaryDim> cos_sin_buf{};
+ interleave(l, cos_sin_buf);
+ const float* cos_sin_row = cos_sin_buf.data();
+ for (size_t h = 0; h < h_iq; h++) {
+ const float* src = &q_idx[(l * h_iq + h) * kDidx];
+ rmsnorm_partial_rope(src, &q_normed[h * kDidx], q_norm_weight.data(), kDidx, kRotaryDim, kEps, cos_sin_row);
+ }
+
+ for (size_t h = 0; h < h_ik; h++) {
+ const float* src = &k_idx[(l * h_ik + h) * kDidx];
+ std::copy_n(src, kDidx, &raw_k_cache[(h * s_cap + static_cast<size_t>(abs_pos)) * kDidx]);
+ }
+
+ const int64_t n_complete = (abs_pos + 1) / static_cast<int64_t>(kR);
+ if ((abs_pos + 1) % static_cast<int64_t>(kR) == 0) {
+ const int64_t block_idx = n_complete - 1;
+ const int64_t block_start = block_idx * static_cast<int64_t>(kR);
+ std::array<float, 2 * kRotaryDim> block_cos_sin_buf{};
+ interleave(static_cast<size_t>(block_start - past_len), block_cos_sin_buf);
+ const float* block_cos_sin = block_cos_sin_buf.data();
+ for (size_t h = 0; h < h_ik; h++) {
+ std::vector<float> pooled(kDidx, 0.0F);
+ for (int64_t p = block_start; p < block_start + static_cast<int64_t>(kR); p++) {
+ const float* raw = &raw_k_cache[(h * s_cap + static_cast<size_t>(p)) * kDidx];
+ for (size_t d = 0; d < kDidx; d++) {
+ pooled[d] += raw[d];
+ }
+ }
+ for (float& v : pooled) {
+ v /= static_cast<float>(kR);
+ }
+ std::vector<float> summary(kDidx);
+ rmsnorm_partial_rope(pooled.data(),
+ summary.data(),
+ k_norm_weight.data(),
+ kDidx,
+ kRotaryDim,
+ kEps,
+ block_cos_sin);
+ std::copy(summary.begin(),
+ summary.end(),
+ &summary_cache[(h * summary_len + static_cast<size_t>(block_idx)) * kDidx]);
+ }
+ }
+
+ for (size_t sh = 0; sh < h_sel; sh++) {
+ size_t k = 0;
+ std::vector<int32_t> chosen;
+ if (n_complete > 0) {
+ std::vector<std::pair<float, int32_t>> scores(static_cast<size_t>(n_complete));
+ for (int64_t bidx = 0; bidx < n_complete; bidx++) {
+ float score = 0.0F;
+ for (size_t h = 0; h < h_iq; h++) {
+ if (sel_of_head[h] != sh) {
+ continue;
+ }
+ const float* summary =
+ &summary_cache[(kv_of_head[h] * summary_len + static_cast<size_t>(bidx)) * kDidx];
+ float dot = 0.0F;
+ for (size_t d = 0; d < kDidx; d++) {
+ dot += q_normed[h * kDidx + d] * summary[d];
+ }
+ score += std::max(0.0F, dot);
+ }
+ scores[static_cast<size_t>(bidx)] = {score * kScale, static_cast<int32_t>(bidx)};
+ }
+ k = std::min(kBlockTopk, static_cast<size_t>(n_complete));
+ std::partial_sort(scores.begin(),
+ scores.begin() + static_cast<ptrdiff_t>(k),
+ scores.end(),
+ [](const auto& a, const auto& b) {
+ if (a.first != b.first) {
+ return a.first > b.first;
+ }
+ return a.second < b.second;
+ });
+ chosen.resize(k);
+ for (size_t i = 0; i < k; i++) {
+ chosen[i] = scores[i].second;
+ }
+ std::sort(chosen.begin(), chosen.end());
+ }
+
+ auto* out_row = &out.sel_indices[(sh * new_tokens + l) * kBlockTopk];
+ for (size_t i = 0; i < k; i++) {
+ out_row[i] = chosen[i];
+ }
+ out.sel_count[sh * new_tokens + l] = static_cast<int64_t>(k);
+ }
+ }
+ return out;
+}
+
+} // namespace
+
+namespace ov {
+namespace test {
+
+std::string PagedQSAIndexerLayerCPUTest::getTestCaseName(
+ const testing::TestParamInfo<PagedQSAIndexerLayerTestParams>& obj) {
+ const auto& [device, data_precision, h_iq, h_ik, h_sel, num_sequences, new_tokens, page_size] = obj.param;
+ return "Target=" + device + "_DataPrecision=" + data_precision.get_type_name() + "_Hiq=" + std::to_string(h_iq) +
+ "_Hik=" + std::to_string(h_ik) + "_Hsel=" + std::to_string(h_sel) +
+ "_NumSeq=" + std::to_string(num_sequences) + "_NewTokens=" + std::to_string(new_tokens) +
+ "_PageSize=" + std::to_string(page_size);
+}
+
+void PagedQSAIndexerLayerCPUTest::SetUp() {
+ const auto& [device, data_precision, h_iq, h_ik, h_sel, num_sequences, new_tokens, page_size] = GetParam();
+ targetDevice = device;
+ m_data_precision = data_precision;
+ m_h_iq = h_iq;
+ m_h_ik = h_ik;
+ m_h_sel = h_sel;
+ m_num_sequences = num_sequences;
+ m_l = new_tokens;
+ m_page_size = page_size;
+ m_slots_per_page = page_size / kR;
+ // the tokens of the longest sequence in whole pages, and one spare page
+ m_seq_blocks = (m_l + static_cast<size_t>(kPastLens.back()) + m_page_size - 1) / m_page_size + 1;
+ rel_threshold = 1e-3F;
+ abs_threshold = 1e-4F;
+ if (data_precision == ov::element::bf16) {
+ rel_threshold = 5e-2F;
+ abs_threshold = 5e-2F;
+ m_mismatch_share = 0.02;
+ configuration.insert(ov::hint::inference_precision(ov::element::bf16));
+ } else if (data_precision == ov::element::f16) {
+ rel_threshold = 5e-3F;
+ abs_threshold = 5e-3F;
+ m_mismatch_share = 0.02;
+ configuration.insert(ov::hint::inference_precision(ov::element::f16));
+ }
+
+ const size_t tokens_total = m_num_sequences * m_l;
+ const size_t n_phys = m_num_sequences * m_seq_blocks;
+
+ auto p_q_idx = std::make_shared<ov::op::v0::Parameter>(data_precision, ov::Shape{tokens_total, m_h_iq * kDidx});
+ auto p_k_idx = std::make_shared<ov::op::v0::Parameter>(data_precision, ov::Shape{tokens_total, m_h_ik * kDidx});
+ auto p_rope_cos = std::make_shared<ov::op::v0::Parameter>(data_precision, ov::Shape{tokens_total, kRotaryDim});
+ auto p_rope_sin = std::make_shared<ov::op::v0::Parameter>(data_precision, ov::Shape{tokens_total, kRotaryDim});
+ auto p_q_norm_weight = std::make_shared<ov::op::v0::Parameter>(data_precision, ov::Shape{kDidx});
+ auto p_k_norm_weight = std::make_shared<ov::op::v0::Parameter>(data_precision, ov::Shape{kDidx});
+ auto p_past_lens = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{m_num_sequences});
+ auto p_subsequence_begins =
+ std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{m_num_sequences + 1});
+ auto p_block_indices = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{n_phys});
+ auto p_block_indices_begins =
+ std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{m_num_sequences + 1});
+ auto p_raw_k_cache =
+ std::make_shared<ov::op::v0::Parameter>(data_precision, ov::Shape{n_phys, m_h_ik, m_page_size, kDidx});
+ auto p_indexer_rope_cache =
+ std::make_shared<ov::op::v0::Parameter>(data_precision, ov::Shape{n_phys, m_slots_per_page, 2 * kRotaryDim});
+ auto p_summary_cache =
+ std::make_shared<ov::op::v0::Parameter>(data_precision, ov::Shape{n_phys, m_h_ik, m_slots_per_page, kDidx});
+
+ const ov::ParameterVector params_in{p_q_idx,
+ p_k_idx,
+ p_rope_cos,
+ p_rope_sin,
+ p_q_norm_weight,
+ p_k_norm_weight,
+ p_past_lens,
+ p_subsequence_begins,
+ p_block_indices,
+ p_block_indices_begins,
+ p_raw_k_cache,
+ p_indexer_rope_cache,
+ p_summary_cache};
+ std::vector<ov::Shape> input_shapes;
+ for (const auto& p : params_in) {
+ input_shapes.push_back(p->get_shape());
+ }
+ init_input_shapes(static_shapes_to_test_representation(input_shapes));
+
+ ov::op::internal::PagedQSAIndexer::Config config;
+ config.key_block_size = kR;
+ config.block_topk = kBlockTopk;
+ config.num_selection_heads = m_h_sel;
+ config.indexer_rotary_dim = kRotaryDim;
+ config.indexer_head_dim = kDidx;
+ config.epsilon = kEps;
+ config.scale = kScale;
+
+ ov::OutputVector args(params_in.begin(), params_in.end());
+ auto paged_qsa_indexer = std::make_shared<ov::op::internal::PagedQSAIndexer>(args, config);
+
+ function = std::make_shared<ov::Model>(
+ ov::ResultVector{std::make_shared<ov::op::v0::Result>(paged_qsa_indexer->output(0)),
+ std::make_shared<ov::op::v0::Result>(paged_qsa_indexer->output(1))},
+ params_in);
+}
+
+void PagedQSAIndexerLayerCPUTest::generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) {
+ inputs.clear();
+ host_inputs.clear();
+
+ const auto assign_precision = [this](ov::Tensor& t, const std::vector<float>& data) {
+ if (m_data_precision == ov::element::bf16) {
+ auto* dst = t.data<ov::bfloat16>();
+ for (size_t i = 0; i < data.size(); i++) {
+ dst[i] = ov::bfloat16(data[i]);
+ }
+ } else if (m_data_precision == ov::element::f16) {
+ auto* dst = t.data<ov::float16>();
+ for (size_t i = 0; i < data.size(); i++) {
+ dst[i] = ov::float16(data[i]);
+ }
+ } else {
+ std::copy(data.begin(), data.end(), t.data<float>());
+ }
+ };
+ // Each sequence gets its own pseudo-random seed (seed_base + s * 97) so sequence 0 and
+ // sequence 1 data are distinguishable -- a kernel bug that mixed up the sequence index (or
+ // its physical cache blocks) would otherwise go undetected since all sequences would look
+ // identical.
+ const auto make_seq_data = [this](size_t h, uint32_t seed_base) {
+ ov::Tensor t(m_data_precision, ov::Shape{m_num_sequences * m_l, h * kDidx});
+ const size_t per_seq = m_l * h * kDidx;
+ std::vector<float> data(t.get_size());
+ for (size_t s = 0; s < m_num_sequences; s++) {
+ std::vector<float> seq_data(per_seq);
+ fill_pseudo_random(seq_data, seed_base + static_cast<uint32_t>(s) * 97U);
+ std::copy(seq_data.begin(), seq_data.end(), data.begin() + static_cast<ptrdiff_t>(s * per_seq));
+ }
+ if (m_data_precision == ov::element::bf16) {
+ auto* dst = t.data<ov::bfloat16>();
+ for (size_t i = 0; i < data.size(); i++) {
+ dst[i] = ov::bfloat16(data[i]);
+ }
+ } else if (m_data_precision == ov::element::f16) {
+ auto* dst = t.data<ov::float16>();
+ for (size_t i = 0; i < data.size(); i++) {
+ dst[i] = ov::float16(data[i]);
+ }
+ } else {
+ std::copy(data.begin(), data.end(), t.data<float>());
+ }
+ return t;
+ };
+ const auto make_zeros = [this](const ov::Shape& shape) {
+ ov::Tensor t(m_data_precision, shape);
+ if (m_data_precision == ov::element::bf16) {
+ std::fill_n(t.data<ov::bfloat16>(), t.get_size(), ov::bfloat16(0.0F));
+ } else if (m_data_precision == ov::element::f16) {
+ std::fill_n(t.data<ov::float16>(), t.get_size(), ov::float16(0.0F));
+ } else {
+ std::fill_n(t.data<float>(), t.get_size(), 0.0F);
+ }
+ return t;
+ };
+ const auto make_i32 = [](const std::vector<int32_t>& values) {
+ ov::Tensor t(ov::element::i32, ov::Shape{values.size()});
+ std::copy(values.begin(), values.end(), t.data<int32_t>());
+ return t;
+ };
+ const auto make_norm_weight = [this, &assign_precision](uint32_t seed) {
+ std::vector<float> data(kDidx);
+ fill_pseudo_random(data, seed);
+ for (auto& v : data) {
+ v = 1.0F + 0.1F * v;
+ }
+ ov::Tensor t(m_data_precision, ov::Shape{kDidx});
+ assign_precision(t, data);
+ return t;
+ };
+
+ const size_t n_phys = m_num_sequences * m_seq_blocks;
+
+ const auto& params = function->get_parameters();
+ std::vector<ov::Tensor> tensors(params.size());
+ using InputIdx = ov::op::internal::PagedQSAIndexer::InputIdx;
+ tensors[InputIdx::INDEX_QUERY] = make_seq_data(m_h_iq, 1);
+ tensors[InputIdx::RAW_INDEX_KEYS] = make_seq_data(m_h_ik, 2);
+ {
+ // theta is a function of each token's own absolute position (kPastLens[s] + local index),
+ // matching the per-token rope_cos/rope_sin ABI -- no shared position-indexed table.
+ // Rows are indexer_rotary_dim wide, one coefficient per rotary channel. The two halves are
+ // deliberately NOT duplicates, so a kernel assuming cos[j] == cos[j + rotary_dim/2] fails.
+ ov::Tensor t_cos(m_data_precision, ov::Shape{m_num_sequences * m_l, kRotaryDim});
+ ov::Tensor t_sin(m_data_precision, ov::Shape{m_num_sequences * m_l, kRotaryDim});
+ std::vector<float> cos_data(m_num_sequences * m_l * kRotaryDim);
+ std::vector<float> sin_data(m_num_sequences * m_l * kRotaryDim);
+ for (size_t s = 0; s < m_num_sequences; s++) {
+ for (size_t l = 0; l < m_l; l++) {
+ const size_t abs_pos = static_cast<size_t>(kPastLens[s]) + l;
+ const size_t row = s * m_l + l;
+ for (size_t j = 0; j < kRotaryDim; j++) {
+ const float theta = static_cast<float>(abs_pos) * 0.1F + static_cast<float>(j) * 0.05F;
+ cos_data[row * kRotaryDim + j] = std::cos(theta);
+ sin_data[row * kRotaryDim + j] = std::sin(theta);
+ }
+ }
+ }
+ assign_precision(t_cos, cos_data);
+ assign_precision(t_sin, sin_data);
+ tensors[InputIdx::ROPE_COS] = t_cos;
+ tensors[InputIdx::ROPE_SIN] = t_sin;
+ }
+ tensors[InputIdx::Q_NORM_WEIGHT] = make_norm_weight(6);
+ tensors[InputIdx::K_NORM_WEIGHT] = make_norm_weight(7);
+ {
+ // Non-identity permutation (simple reversal) across all physical blocks shared by every
+ // sequence, so a kernel bug that walked physical blocks in logical/sequential order
+ // instead of resolving through block_indices would produce numerically wrong results.
+ std::vector<int32_t> block_indices(n_phys);
+ for (size_t i = 0; i < n_phys; i++) {
+ block_indices[i] = static_cast<int32_t>(n_phys - 1 - i);
+ }
+ tensors[InputIdx::BLOCK_INDICES] = make_i32(block_indices);
+ }
+ {
+ std::vector<int32_t> block_indices_begins(m_num_sequences + 1);
+ for (size_t s = 0; s <= m_num_sequences; s++) {
+ block_indices_begins[s] = static_cast<int32_t>(s * m_seq_blocks);
+ }
+ tensors[InputIdx::BLOCK_INDICES_BEGINS] = make_i32(block_indices_begins);
+ }
+ {
+ std::vector<int32_t> subsequence_begins(m_num_sequences + 1);
+ for (size_t s = 0; s <= m_num_sequences; s++) {
+ subsequence_begins[s] = static_cast<int32_t>(s * m_l);
+ }
+ tensors[InputIdx::SUBSEQUENCE_BEGINS] = make_i32(subsequence_begins);
+ }
+ {
+ std::vector<int32_t> past_lens_values(m_num_sequences);
+ for (size_t s = 0; s < m_num_sequences; s++) {
+ past_lens_values[s] = kPastLens[s];
+ }
+ tensors[InputIdx::PAST_LENS] = make_i32(past_lens_values);
+ }
+ tensors[InputIdx::INDEX_KEY_CACHE] = make_zeros(ov::Shape{n_phys, m_h_ik, m_page_size, kDidx});
+ tensors[InputIdx::INDEX_BLOCK_ROPE_CACHE] = make_zeros(ov::Shape{n_phys, m_slots_per_page, 2 * kRotaryDim});
+ tensors[InputIdx::BLOCK_INDEX_KEYS_CACHE] = make_zeros(ov::Shape{n_phys, m_h_ik, m_slots_per_page, kDidx});
+
+ for (size_t i = 0; i < params.size(); i++) {
+ host_inputs[params[i]] = tensors[i];
+ inputs[params[i]] = tensors[i];
+ }
+}
+
+std::vector<ov::Tensor> PagedQSAIndexerLayerCPUTest::calculate_refs() {
+ const auto& params = function->get_parameters();
+ const auto to_f32 = [&](const std::shared_ptr<ov::Node>& p) {
+ const auto& t = host_inputs.at(p);
+ std::vector<float> out(t.get_size());
+ if (t.get_element_type() == ov::element::bf16) {
+ const auto* ptr = t.data<const ov::bfloat16>();
+ std::copy(ptr, ptr + t.get_size(), out.begin());
+ } else if (t.get_element_type() == ov::element::f16) {
+ const auto* ptr = t.data<const ov::float16>();
+ std::copy(ptr, ptr + t.get_size(), out.begin());
+ } else {
+ const auto* ptr = t.data<const float>();
+ std::copy(ptr, ptr + t.get_size(), out.begin());
+ }
+ return out;
+ };
+
+ using InputIdx = ov::op::internal::PagedQSAIndexer::InputIdx;
+ auto q_idx = to_f32(params[InputIdx::INDEX_QUERY]);
+ auto k_idx = to_f32(params[InputIdx::RAW_INDEX_KEYS]);
+ auto rope_cos = to_f32(params[InputIdx::ROPE_COS]);
+ auto rope_sin = to_f32(params[InputIdx::ROPE_SIN]);
+ auto q_norm_weight = to_f32(params[InputIdx::Q_NORM_WEIGHT]);
+ auto k_norm_weight = to_f32(params[InputIdx::K_NORM_WEIGHT]);
+ const auto* past_lens_ptr = host_inputs.at(params[InputIdx::PAST_LENS]).data<const int32_t>();
+
+ const size_t tokens_total = m_num_sequences * m_l;
+ ov::Tensor sel_indices(ov::element::i32, ov::Shape{tokens_total, m_h_sel, kBlockTopk});
+ ov::Tensor sel_count(ov::element::i32, ov::Shape{tokens_total, m_h_sel});
+ auto* sel_indices_data = sel_indices.data<int32_t>();
+ auto* sel_count_data = sel_count.data<int32_t>();
+
+ const size_t q_idx_stride = m_l * m_h_iq * kDidx;
+ const size_t k_idx_stride = m_l * m_h_ik * kDidx;
+ const size_t rope_stride = m_l * kRotaryDim;
+ for (size_t s = 0; s < m_num_sequences; s++) {
+ std::vector<float> q_idx_s(q_idx.begin() + static_cast<ptrdiff_t>(s * q_idx_stride),
+ q_idx.begin() + static_cast<ptrdiff_t>((s + 1) * q_idx_stride));
+ std::vector<float> k_idx_s(k_idx.begin() + static_cast<ptrdiff_t>(s * k_idx_stride),
+ k_idx.begin() + static_cast<ptrdiff_t>((s + 1) * k_idx_stride));
+ std::vector<float> rope_cos_s(rope_cos.begin() + static_cast<ptrdiff_t>(s * rope_stride),
+ rope_cos.begin() + static_cast<ptrdiff_t>((s + 1) * rope_stride));
+ std::vector<float> rope_sin_s(rope_sin.begin() + static_cast<ptrdiff_t>(s * rope_stride),
+ rope_sin.begin() + static_cast<ptrdiff_t>((s + 1) * rope_stride));
+ const int64_t past_len = past_lens_ptr[s];
+
+ auto oracle = run_paged_qsa_indexer_reference(m_l,
+ m_h_iq,
+ m_h_ik,
+ m_h_sel,
+ q_idx_s,
+ k_idx_s,
+ rope_cos_s,
+ rope_sin_s,
+ q_norm_weight,
+ k_norm_weight,
+ past_len);
+
+ // Oracle output is [h_sel, m_l, kBlockTopk]/[h_sel, m_l] (per-sequence, sh-major); the op's
+ // real outputs are token-major ([tokens_total, h_sel, kBlockTopk]/[tokens_total, h_sel]),
+ // so transpose while scattering into the global, token-offset tensor.
+ for (size_t l = 0; l < m_l; l++) {
+ const size_t token = s * m_l + l;
+ for (size_t sh = 0; sh < m_h_sel; sh++) {
+ for (size_t i = 0; i < kBlockTopk; i++) {
+ sel_indices_data[(token * m_h_sel + sh) * kBlockTopk + i] =
+ static_cast<int32_t>(oracle.sel_indices[(sh * m_l + l) * kBlockTopk + i]);
+ }
+ sel_count_data[token * m_h_sel + sh] = static_cast<int32_t>(oracle.sel_count[sh * m_l + l]);
+ }
+ }
+ }
+ return {sel_indices, sel_count};
+}
+
+void PagedQSAIndexerLayerCPUTest::compare(const std::vector<ov::Tensor>& expected,
+ const std::vector<ov::Tensor>& actual) {
+ ASSERT_EQ(expected.size(), actual.size());
+ for (size_t i = 0; i < expected.size(); i++) {
+ ov::test::utils::compare(expected[i], actual[i], abs_threshold, rel_threshold, m_mismatch_share);
+ }
+}
+
+TEST_P(PagedQSAIndexerLayerCPUTest, CompareWithRefs) {
+ run();
+}
+
+} // namespace test
+} // namespace ov
\ No newline at end of file
diff --git a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/paged_qsa_indexer.hpp b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/paged_qsa_indexer.hpp
new file mode 100644
index 00000000000..a80934b8321
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/paged_qsa_indexer.hpp
@@ -0,0 +1,57 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstddef>
+#include <map>
+#include <memory>
+#include <string>
+#include <tuple>
+
+#include "openvino/core/type/element_type.hpp"
+#include "shared_test_classes/base/ov_subgraph.hpp"
+
+namespace ov {
+namespace test {
+
+// target device, data precision (q_idx/k_idx/rotary/caches/norm weights),
+// H_iq (index-query head count), H_ik (index-key head count), h_sel (selection-head count),
+// num_sequences (each sequence gets its own past_len and its own run of physical cache blocks,
+// see classes/paged_qsa_indexer.cpp), new_tokens (the tokens every sequence adds in the call: 1 is a decode step),
+// page_size (tokens of a cache page: a multiple of the compress ratio; 32 blocks of the scoring can lie in one page or
+// run over several)
+using PagedQSAIndexerLayerTestParams =
+ std::tuple<std::string, ov::element::Type, size_t, size_t, size_t, size_t, size_t, size_t>;
+
+class PagedQSAIndexerLayerCPUTest : public testing::WithParamInterface<PagedQSAIndexerLayerTestParams>,
+ virtual public SubgraphBaseTest {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<PagedQSAIndexerLayerTestParams>& obj);
+
+protected:
+ void SetUp() override;
+ void generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) override;
+ std::vector<ov::Tensor> calculate_refs() override;
+ void compare(const std::vector<ov::Tensor>& expected, const std::vector<ov::Tensor>& actual) override;
+
+private:
+ std::map<std::shared_ptr<ov::Node>, ov::Tensor> host_inputs;
+ ov::element::Type m_data_precision = ov::element::f32;
+ size_t m_h_iq = 2;
+ size_t m_h_ik = 2;
+ size_t m_h_sel = 1;
+ size_t m_num_sequences = 1;
+ size_t m_l = 7; // new tokens of every sequence
+ // Share of the elements of an output that may differ: selections of (almost) tied blocks flip with the rounding of
+ // a 16-bit cache, which the f32 oracle does not do. 0 for f32; for the small tests of the 16-bit types the share
+ // of a few elements rounds down to none, so they stay exact.
+ double m_mismatch_share = 0.0;
+ size_t m_page_size = 4;
+ size_t m_slots_per_page = 2; // blocks of a page: page_size / compress_ratio
+ size_t m_seq_blocks = 4; // physical cache blocks of every sequence, enough for its tokens and a spare one
+};
+
+} // namespace test
+} // namespace ov
\ No newline at end of file
diff --git a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/qsa_indexer.cpp b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/qsa_indexer.cpp
new file mode 100644
index 00000000000..052d9d9a7f0
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/qsa_indexer.cpp
@@ -0,0 +1,625 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "qsa_indexer.hpp"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdint>
+#include <cstring>
+#include <unordered_map>
+#include <vector>
+
+#include "common_test_utils/ov_tensor_utils.hpp"
+#include "openvino/core/type/bfloat16.hpp"
+#include "openvino/core/type/float16.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/result.hpp"
+#include "transformations/cpu_opset/common/op/qsa_indexer.hpp"
+
+namespace ov {
+namespace test {
+
+std::vector<float> read_tensor_to_f32(const ov::Tensor& t) {
+ std::vector<float> out(t.get_size());
+ if (t.get_element_type() == ov::element::bf16) {
+ const auto* src = t.data<ov::bfloat16>();
+ std::copy(src, src + out.size(), out.begin());
+ } else if (t.get_element_type() == ov::element::f16) {
+ const auto* src = t.data<ov::float16>();
+ std::copy(src, src + out.size(), out.begin());
+ } else {
+ const auto* src = t.data<float>();
+ std::copy(src, src + out.size(), out.begin());
+ }
+ return out;
+}
+
+void write_f32_to_tensor(ov::Tensor& t, const std::vector<float>& data) {
+ if (t.get_element_type() == ov::element::bf16) {
+ auto* dst = t.data<ov::bfloat16>();
+ for (size_t i = 0; i < data.size(); i++) {
+ dst[i] = ov::bfloat16(data[i]);
+ }
+ } else if (t.get_element_type() == ov::element::f16) {
+ auto* dst = t.data<ov::float16>();
+ for (size_t i = 0; i < data.size(); i++) {
+ dst[i] = ov::float16(data[i]);
+ }
+ } else {
+ std::copy(data.begin(), data.end(), t.data<float>());
+ }
+}
+
+ov::Tensor make_zero_tensor(const ov::element::Type& precision, const ov::Shape& shape) {
+ ov::Tensor t(precision, shape);
+ if (t.get_byte_size() != 0) {
+ std::memset(t.data(), 0, t.get_byte_size());
+ }
+ return t;
+}
+
+namespace {
+
+float rms_inv_scale(const float* x, size_t n, float eps) {
+ float sumsq = 0.0F;
+ for (size_t i = 0; i < n; i++) {
+ sumsq += x[i] * x[i];
+ }
+ return 1.0F / std::sqrt(sumsq / static_cast<float>(n) + eps);
+}
+
+// Independent re-implementation of new_spec/qsa-prepare-17.rst's rotate-half RMSNorm+RoPE, used
+// purely as a test oracle. `cos_row`/`sin_row` each hold `rotary_dim` values.
+void rmsnorm_partial_rope(const float* src,
+ float* dst,
+ const float* weight,
+ size_t dim,
+ size_t rotary_dim,
+ float eps,
+ const float* cos_row,
+ const float* sin_row) {
+ const float inv_rms = rms_inv_scale(src, dim, eps);
+ for (size_t d = 0; d < dim; d++) {
+ dst[d] = src[d] * inv_rms * weight[d];
+ }
+ const size_t half = rotary_dim / 2;
+ for (size_t j = 0; j < half; j++) {
+ const float x0 = dst[j];
+ const float x1 = dst[j + half];
+ dst[j] = x0 * cos_row[j] - x1 * sin_row[j];
+ dst[j + half] = x1 * cos_row[j + half] + x0 * sin_row[j + half];
+ }
+}
+
+// Independent (host-vector based) oracle for one QSAIndexer call, re-implementing
+// new_spec/qsa-prepare-17.rst's padding-aware prepare+selection pseudocode directly -- NOT a copy
+// of the CPU node's PlainTensor-based indexing/control flow. `summary_cache`/`past_raw_k`/
+// `past_rope` are caller-owned state threaded in by reference across sequential calls, mirroring
+// the production op's state (fed back from the op's state outputs).
+} // namespace
+
+QSAIndexerOracle::Output QSAIndexerOracle::run_call(size_t batch,
+ int64_t length,
+ const std::vector<int32_t>& key_length,
+ const std::vector<float>& q_idx,
+ const std::vector<float>& k_idx,
+ const std::vector<float>& rope_cos,
+ const std::vector<float>& rope_sin,
+ const std::vector<float>& q_norm_weight,
+ const std::vector<float>& k_norm_weight) {
+ const size_t group = h_iq / h_ik;
+ std::vector<size_t> kv_of_head(h_iq), sel_of_head(h_iq);
+ for (size_t h = 0; h < h_iq; h++) {
+ kv_of_head[h] = h / group;
+ sel_of_head[h] = (kv_of_head[h] * h_sel) / h_ik;
+ }
+
+ Output out;
+ out.sel_indices.assign(batch * h_sel * static_cast<size_t>(length) * block_topk, -1);
+ out.sel_count.assign(batch * h_sel * static_cast<size_t>(length), 0);
+
+ const size_t L = static_cast<size_t>(length);
+
+ for (size_t b = 0; b < batch; b++) {
+ const int64_t key_len = key_length[b];
+ const int64_t past_n = std::max<int64_t>(0, key_len - length);
+ const int64_t current_n = key_len - past_n;
+ const int64_t num_padding_n = length - current_n;
+ const int64_t c_n = past_n % r;
+ const int64_t num_cached_blocks_n = past_n / r;
+
+ std::vector<float> q_normed(h_iq * d_idx);
+ std::vector<float> rope_cos_buf(rotary_dim);
+ std::vector<float> rope_sin_buf(rotary_dim);
+ std::vector<float> block_ref_cos_sin(2 * rotary_dim, 0.0F);
+ std::vector<float> pooled(d_idx);
+ std::vector<float> summary_buf(d_idx);
+
+ std::vector<float> pending_rows(static_cast<size_t>(r) * h_ik * d_idx, 0.0F);
+ auto pending_ptr = [&](int64_t pos_in_block, size_t h) {
+ return pending_rows.data() + (static_cast<size_t>(pos_in_block) * h_ik + h) * d_idx;
+ };
+ auto past_raw_k_ptr = [&](size_t h, int64_t p) {
+ return past_raw_k.data() + ((b * h_ik + h) * static_cast<size_t>(r - 1) + static_cast<size_t>(p)) * d_idx;
+ };
+ auto summary_ptr = [&](size_t h, int64_t block) {
+ return summary_cache.data() + ((b * h_ik + h) * summary_cap + static_cast<size_t>(block)) * d_idx;
+ };
+
+ for (int64_t p = 0; p < c_n; p++) {
+ for (size_t h = 0; h < h_ik; h++) {
+ std::copy_n(past_raw_k_ptr(h, p), d_idx, pending_ptr(p, h));
+ }
+ }
+ if (c_n > 0) {
+ std::copy_n(past_rope.data() + b * 2 * rotary_dim, 2 * rotary_dim, block_ref_cos_sin.data());
+ }
+
+ int64_t running_block_idx = num_cached_blocks_n;
+
+ for (int64_t l = num_padding_n; l < length; l++) {
+ const int64_t v = l - num_padding_n;
+ const int64_t pending_pos = c_n + v;
+ const int64_t pos_in_block = pending_pos % r;
+ const size_t lu = static_cast<size_t>(l);
+
+ std::copy_n(&rope_cos[(b * L + lu) * rotary_dim], rotary_dim, rope_cos_buf.data());
+ std::copy_n(&rope_sin[(b * L + lu) * rotary_dim], rotary_dim, rope_sin_buf.data());
+ for (size_t h = 0; h < h_iq; h++) {
+ const float* src = &q_idx[((b * L + lu) * h_iq + h) * d_idx];
+ rmsnorm_partial_rope(src,
+ &q_normed[h * d_idx],
+ q_norm_weight.data(),
+ d_idx,
+ rotary_dim,
+ eps,
+ rope_cos_buf.data(),
+ rope_sin_buf.data());
+ }
+
+ if (pos_in_block == 0) {
+ std::copy(rope_cos_buf.begin(), rope_cos_buf.end(), block_ref_cos_sin.begin());
+ std::copy(rope_sin_buf.begin(),
+ rope_sin_buf.end(),
+ block_ref_cos_sin.begin() + static_cast<ptrdiff_t>(rotary_dim));
+ }
+ for (size_t h = 0; h < h_ik; h++) {
+ std::copy_n(&k_idx[((b * L + lu) * h_ik + h) * d_idx], d_idx, pending_ptr(pos_in_block, h));
+ }
+
+ if (pos_in_block + 1 == r) {
+ for (size_t h = 0; h < h_ik; h++) {
+ std::fill(pooled.begin(), pooled.end(), 0.0F);
+ for (int64_t p = 0; p < r; p++) {
+ const float* src = pending_ptr(p, h);
+ for (size_t d = 0; d < d_idx; d++) {
+ pooled[d] += src[d];
+ }
+ }
+ const float inv_r = 1.0F / static_cast<float>(r);
+ for (float& val : pooled) {
+ val *= inv_r;
+ }
+ rmsnorm_partial_rope(pooled.data(),
+ summary_buf.data(),
+ k_norm_weight.data(),
+ d_idx,
+ rotary_dim,
+ eps,
+ block_ref_cos_sin.data(),
+ block_ref_cos_sin.data() + rotary_dim);
+ std::copy(summary_buf.begin(), summary_buf.end(), summary_ptr(h, running_block_idx));
+ }
+ running_block_idx += 1;
+ }
+
+ const int64_t n_complete = running_block_idx;
+ for (size_t sh = 0; sh < h_sel; sh++) {
+ size_t k = 0;
+ std::vector<int32_t> chosen;
+ if (n_complete > 0) {
+ std::vector<std::pair<float, int32_t>> scores(static_cast<size_t>(n_complete));
+ for (int64_t bidx = 0; bidx < n_complete; bidx++) {
+ float score = 0.0F;
+ for (size_t h = 0; h < h_iq; h++) {
+ if (sel_of_head[h] != sh) {
+ continue;
+ }
+ const float* summary = summary_ptr(kv_of_head[h], bidx);
+ float dot = 0.0F;
+ for (size_t d = 0; d < d_idx; d++) {
+ dot += q_normed[h * d_idx + d] * summary[d];
+ }
+ score += std::max(0.0F, dot);
+ }
+ scores[static_cast<size_t>(bidx)] = {score * scale, static_cast<int32_t>(bidx)};
+ }
+ k = std::min(block_topk, static_cast<size_t>(n_complete));
+ std::partial_sort(scores.begin(),
+ scores.begin() + static_cast<ptrdiff_t>(k),
+ scores.end(),
+ [](const auto& a, const auto& bb) {
+ if (a.first != bb.first) {
+ return a.first > bb.first;
+ }
+ return a.second < bb.second;
+ });
+ chosen.resize(k);
+ for (size_t i = 0; i < k; i++) {
+ chosen[i] = scores[i].second;
+ }
+ if (!order_by_score) {
+ std::sort(chosen.begin(), chosen.end()); // else: the order of partial_sort, by score
+ }
+ }
+ auto* out_row = &out.sel_indices[((b * h_sel + sh) * L + lu) * block_topk];
+ for (size_t i = 0; i < k; i++) {
+ out_row[i] = chosen[i];
+ }
+ out.sel_count[(b * h_sel + sh) * L + lu] = static_cast<int32_t>(k);
+ }
+ }
+
+ const int64_t rest = (c_n + current_n) - (running_block_idx - num_cached_blocks_n) * r;
+ for (int64_t p = 0; p < r - 1; p++) {
+ for (size_t h = 0; h < h_ik; h++) {
+ const float* src = p < rest ? pending_ptr(p, h) : nullptr;
+ if (src != nullptr) {
+ std::copy_n(src, d_idx, past_raw_k_ptr(h, p));
+ } else {
+ std::fill_n(past_raw_k_ptr(h, p), d_idx, 0.0F);
+ }
+ }
+ }
+ if (rest == 0) {
+ std::fill(block_ref_cos_sin.begin(), block_ref_cos_sin.end(), 0.0F);
+ }
+ std::copy(block_ref_cos_sin.begin(), block_ref_cos_sin.end(), past_rope.data() + b * 2 * rotary_dim);
+ }
+ return out;
+}
+
+std::string QSAIndexerLayerCPUTest::getTestCaseName(const testing::TestParamInfo<QSAIndexerLayerTestParams>& obj) {
+ const auto& [device, data_precision, h_iq, h_ik, h_sel, batch, scenario, order_by_score] = obj.param;
+ std::string scenario_name;
+ switch (scenario) {
+ case QSAIndexerScenario::kDensePrefill:
+ scenario_name = "DensePrefill";
+ break;
+ case QSAIndexerScenario::kWorkedExample:
+ scenario_name = "WorkedExample";
+ break;
+ case QSAIndexerScenario::kFullyPaddedRow:
+ scenario_name = "FullyPaddedRow";
+ break;
+ case QSAIndexerScenario::kRaggedCalls:
+ scenario_name = "RaggedCalls";
+ break;
+ }
+ return "Target=" + device + "_DataPrecision=" + data_precision.get_type_name() + "_Hiq=" + std::to_string(h_iq) +
+ "_Hik=" + std::to_string(h_ik) + "_Hsel=" + std::to_string(h_sel) + "_Batch=" + std::to_string(batch) +
+ "_Scenario=" + scenario_name + "_OrderByScore=" + std::to_string(order_by_score);
+}
+
+void QSAIndexerLayerCPUTest::SetUp() {
+ const auto& [device, data_precision, h_iq, h_ik, h_sel, batch, scenario, order_by_score] = GetParam();
+ targetDevice = device;
+ m_data_precision = data_precision;
+ m_h_iq = h_iq;
+ m_h_ik = h_ik;
+ m_h_sel = h_sel;
+ m_batch = batch;
+ m_scenario = scenario;
+ m_order_by_score = order_by_score;
+ m_mismatch_share = order_by_score && data_precision != ov::element::f32 ? 0.1 : 0.0;
+ rel_threshold = 1e-3F;
+ abs_threshold = 1e-4F;
+ if (data_precision == ov::element::bf16) {
+ rel_threshold = 5e-2F;
+ abs_threshold = 5e-2F;
+ } else if (data_precision == ov::element::f16) {
+ rel_threshold = 5e-3F;
+ abs_threshold = 5e-3F;
+ }
+
+ m_didx = 16;
+ m_rotary_dim = 8;
+ m_block_topk = 2;
+ m_calls.clear();
+
+ if (m_scenario == QSAIndexerScenario::kWorkedExample) {
+ m_batch = 2;
+ m_compress_ratio = 4;
+ m_summary_cap = 3;
+ m_calls.push_back(CallSpec{10, {10, 7}});
+ m_calls.push_back(CallSpec{1, {11, 8}});
+ } else if (m_scenario == QSAIndexerScenario::kFullyPaddedRow) {
+ m_batch = 2;
+ m_compress_ratio = 4;
+ m_summary_cap = 3;
+ m_calls.push_back(CallSpec{5, {5, 0}});
+ m_calls.push_back(CallSpec{3, {8, 3}});
+ } else if (m_scenario == QSAIndexerScenario::kRaggedCalls) {
+ m_batch = 2;
+ m_compress_ratio = 4;
+ m_summary_cap = 4;
+ m_calls.push_back(CallSpec{7, {7, 5}});
+ m_calls.push_back(CallSpec{3, {10, 8}});
+ m_calls.push_back(CallSpec{5, {15, 13}});
+ } else {
+ m_compress_ratio = 2;
+ m_summary_cap = 4;
+ std::vector<int32_t> key_length(m_batch, 7);
+ m_calls.push_back(CallSpec{7, key_length});
+ }
+
+ auto p_q_idx = std::make_shared<ov::op::v0::Parameter>(m_data_precision,
+ ov::PartialShape{static_cast<int64_t>(m_batch),
+ -1,
+ static_cast<int64_t>(m_h_iq),
+ static_cast<int64_t>(m_didx)});
+ auto p_k_idx = std::make_shared<ov::op::v0::Parameter>(m_data_precision,
+ ov::PartialShape{static_cast<int64_t>(m_batch),
+ -1,
+ static_cast<int64_t>(m_h_ik),
+ static_cast<int64_t>(m_didx)});
+ auto p_rope_cos = std::make_shared<ov::op::v0::Parameter>(
+ m_data_precision,
+ ov::PartialShape{static_cast<int64_t>(m_batch), -1, static_cast<int64_t>(m_rotary_dim)});
+ auto p_rope_sin = std::make_shared<ov::op::v0::Parameter>(
+ m_data_precision,
+ ov::PartialShape{static_cast<int64_t>(m_batch), -1, static_cast<int64_t>(m_rotary_dim)});
+ auto p_key_length = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{m_batch});
+ auto p_q_norm_weight = std::make_shared<ov::op::v0::Parameter>(m_data_precision, ov::Shape{m_didx});
+ auto p_k_norm_weight = std::make_shared<ov::op::v0::Parameter>(m_data_precision, ov::Shape{m_didx});
+ // Only the blocks of the earlier calls: the op returns them grown by the blocks of this call.
+ auto p_summary_cache = std::make_shared<ov::op::v0::Parameter>(m_data_precision,
+ ov::PartialShape{static_cast<int64_t>(m_batch),
+ static_cast<int64_t>(m_h_ik),
+ -1,
+ static_cast<int64_t>(m_didx)});
+ auto p_past_raw_k =
+ std::make_shared<ov::op::v0::Parameter>(m_data_precision,
+ ov::Shape{m_batch, m_h_ik, m_compress_ratio - 1, m_didx});
+ auto p_past_rope = std::make_shared<ov::op::v0::Parameter>(m_data_precision, ov::Shape{m_batch, 2 * m_rotary_dim});
+
+ p_q_idx->set_friendly_name("q_idx");
+ p_k_idx->set_friendly_name("k_idx");
+ p_rope_cos->set_friendly_name("rope_cos");
+ p_rope_sin->set_friendly_name("rope_sin");
+ p_key_length->set_friendly_name("key_length");
+ p_q_norm_weight->set_friendly_name("q_norm_weight");
+ p_k_norm_weight->set_friendly_name("k_norm_weight");
+ p_summary_cache->set_friendly_name("summary_cache");
+ p_past_raw_k->set_friendly_name("past_raw_k");
+ p_past_rope->set_friendly_name("past_rope");
+
+ ov::intel_cpu::QSAIndexerNode::Config config;
+ config.compress_ratio = m_compress_ratio;
+ config.block_topk = m_block_topk;
+ config.h_sel = m_h_sel;
+ config.indexer_rotary_dim = m_rotary_dim;
+ config.indexer_head_dim = m_didx;
+ config.eps = 1e-6F;
+ config.scale = 0.25F;
+ config.order_by_score = m_order_by_score;
+
+ ov::OutputVector args = {p_q_idx,
+ p_k_idx,
+ p_rope_cos,
+ p_rope_sin,
+ p_key_length,
+ p_q_norm_weight,
+ p_k_norm_weight,
+ p_summary_cache,
+ p_past_raw_k,
+ p_past_rope};
+ using OutputIdx = ov::intel_cpu::QSAIndexerNode::OutputIdx;
+ auto qsa_indexer_v2 = std::make_shared<ov::intel_cpu::QSAIndexerNode>(args, config);
+
+ function = std::make_shared<ov::Model>(
+ ov::ResultVector{std::make_shared<ov::op::v0::Result>(qsa_indexer_v2->output(OutputIdx::SEL_INDICES)),
+ std::make_shared<ov::op::v0::Result>(qsa_indexer_v2->output(OutputIdx::SEL_COUNT)),
+ std::make_shared<ov::op::v0::Result>(qsa_indexer_v2->output(OutputIdx::SUMMARY_CACHE)),
+ std::make_shared<ov::op::v0::Result>(qsa_indexer_v2->output(OutputIdx::PAST_INCOMPLETE_RAW_K)),
+ std::make_shared<ov::op::v0::Result>(qsa_indexer_v2->output(OutputIdx::PAST_INCOMPLETE_ROPE))},
+ ov::ParameterVector{p_q_idx,
+ p_k_idx,
+ p_rope_cos,
+ p_rope_sin,
+ p_key_length,
+ p_q_norm_weight,
+ p_k_norm_weight,
+ p_summary_cache,
+ p_past_raw_k,
+ p_past_rope});
+}
+
+void QSAIndexerLayerCPUTest::compare(const std::vector<ov::Tensor>& expected, const std::vector<ov::Tensor>& actual) {
+ ASSERT_EQ(expected.size(), actual.size());
+ for (size_t i = 0; i < expected.size(); i++) {
+ ov::test::utils::compare(expected[i], actual[i], abs_threshold, rel_threshold, m_mismatch_share);
+ }
+}
+
+std::vector<ov::Tensor> QSAIndexerLayerCPUTest::run_call(const CallSpec& call, size_t call_idx) {
+ const size_t L = static_cast<size_t>(call.length);
+
+ ov::Tensor t_q_idx = ov::test::utils::create_and_fill_tensor(
+ m_data_precision,
+ ov::Shape{m_batch, L, m_h_iq, m_didx},
+ ov::test::utils::InputGenerateData(-1.0, 2000, 1000, static_cast<int32_t>(10 + call_idx * 4 + 1)));
+ ov::Tensor t_k_idx = ov::test::utils::create_and_fill_tensor(
+ m_data_precision,
+ ov::Shape{m_batch, L, m_h_ik, m_didx},
+ ov::test::utils::InputGenerateData(-1.0, 2000, 1000, static_cast<int32_t>(10 + call_idx * 4 + 2)));
+
+ // rope_cos/rope_sin can't be arbitrary random data: they must be genuine (cos, sin) pairs,
+ // pre-duplicated across both halves of rotary_dim (per new_spec's rotate-half convention), so
+ // they're synthesized directly rather than through create_and_fill_tensor.
+ std::vector<float> rope_cos_data(m_batch * L * m_rotary_dim);
+ std::vector<float> rope_sin_data(m_batch * L * m_rotary_dim);
+ const size_t half = m_rotary_dim / 2;
+ for (size_t b = 0; b < m_batch; b++) {
+ for (size_t l = 0; l < L; l++) {
+ const int64_t abs_pos = call.key_length[b] - call.length + static_cast<int64_t>(l);
+ for (size_t j = 0; j < m_rotary_dim; j++) {
+ const size_t jj = j % half;
+ const float theta = static_cast<float>(abs_pos) * 0.1F + static_cast<float>(jj) * 0.05F;
+ rope_cos_data[(b * L + l) * m_rotary_dim + j] = std::cos(theta);
+ rope_sin_data[(b * L + l) * m_rotary_dim + j] = std::sin(theta);
+ }
+ }
+ }
+ ov::Tensor t_rope_cos(m_data_precision, ov::Shape{m_batch, L, m_rotary_dim});
+ ov::Tensor t_rope_sin(m_data_precision, ov::Shape{m_batch, L, m_rotary_dim});
+ write_f32_to_tensor(t_rope_cos, rope_cos_data);
+ write_f32_to_tensor(t_rope_sin, rope_sin_data);
+
+ ov::Tensor t_key_length(ov::element::i32, ov::Shape{m_batch});
+ std::copy(call.key_length.begin(), call.key_length.end(), t_key_length.data<int32_t>());
+
+ const std::unordered_map<std::string, ov::Tensor> name_to_tensor = {
+ {"q_idx", t_q_idx},
+ {"k_idx", t_k_idx},
+ {"rope_cos", t_rope_cos},
+ {"rope_sin", t_rope_sin},
+ {"key_length", t_key_length},
+ {"q_norm_weight", m_q_norm_weight_tensor},
+ {"k_norm_weight", m_k_norm_weight_tensor},
+ {"summary_cache", m_summary_cache_tensor},
+ {"past_raw_k", m_past_raw_k_tensor},
+ {"past_rope", m_past_rope_tensor},
+ };
+ for (const auto& port : compiledModel.inputs()) {
+ const auto it = name_to_tensor.find(port.get_node()->get_friendly_name());
+ if (it != name_to_tensor.end()) {
+ m_infer_request.set_tensor(port, it->second);
+ }
+ }
+
+ // The op must not update its state inputs in place: snapshot them to check afterwards.
+ std::vector<ov::Tensor> state_in_snapshot;
+ for (const auto* state : {&m_summary_cache_tensor, &m_past_raw_k_tensor, &m_past_rope_tensor}) {
+ ov::Tensor snapshot{state->get_element_type(), state->get_shape()};
+ state->copy_to(snapshot);
+ state_in_snapshot.push_back(std::move(snapshot));
+ }
+
+ m_infer_request.infer();
+
+ std::vector<ov::Tensor> outs;
+ for (const auto& port : compiledModel.outputs()) {
+ const auto& src = m_infer_request.get_tensor(port);
+ ov::Tensor c{src.get_element_type(), src.get_shape()};
+ src.copy_to(c);
+ outs.push_back(std::move(c));
+ }
+
+ QSAIndexerOracle oracle;
+ oracle.h_iq = m_h_iq;
+ oracle.h_ik = m_h_ik;
+ oracle.h_sel = m_h_sel;
+ oracle.d_idx = m_didx;
+ oracle.rotary_dim = m_rotary_dim;
+ oracle.r = static_cast<int64_t>(m_compress_ratio);
+ oracle.block_topk = m_block_topk;
+ oracle.eps = 1e-6F;
+ oracle.scale = 0.25F;
+ oracle.order_by_score = m_order_by_score;
+ oracle.summary_cap = m_summary_cap;
+ oracle.summary_cache = std::move(m_oracle_summary_cache);
+ oracle.past_raw_k = std::move(m_oracle_past_raw_k);
+ oracle.past_rope = std::move(m_oracle_past_rope);
+
+ auto expected = oracle.run_call(m_batch,
+ call.length,
+ call.key_length,
+ read_tensor_to_f32(t_q_idx),
+ read_tensor_to_f32(t_k_idx),
+ read_tensor_to_f32(t_rope_cos),
+ read_tensor_to_f32(t_rope_sin),
+ read_tensor_to_f32(m_q_norm_weight_tensor),
+ read_tensor_to_f32(m_k_norm_weight_tensor));
+ m_oracle_summary_cache = std::move(oracle.summary_cache);
+ m_oracle_past_raw_k = std::move(oracle.past_raw_k);
+ m_oracle_past_rope = std::move(oracle.past_rope);
+
+ ov::Tensor expected_sel_indices(ov::element::i32, ov::Shape{m_batch, m_h_sel, L, m_block_topk});
+ ov::Tensor expected_sel_count(ov::element::i32, ov::Shape{m_batch, m_h_sel, L});
+ std::copy(expected.sel_indices.begin(), expected.sel_indices.end(), expected_sel_indices.data<int32_t>());
+ std::copy(expected.sel_count.begin(), expected.sel_count.end(), expected_sel_count.data<int32_t>());
+
+ // The output holds the blocks of the longest row: max(key_length) / compress_ratio.
+ const size_t num_blocks = static_cast<size_t>(*std::max_element(call.key_length.begin(), call.key_length.end()) /
+ static_cast<int64_t>(m_compress_ratio));
+ ov::Tensor expected_summary_cache(m_data_precision, ov::Shape{m_batch, m_h_ik, num_blocks, m_didx});
+ std::vector<float> expected_summary(m_batch * m_h_ik * num_blocks * m_didx);
+ for (size_t bh = 0; bh < m_batch * m_h_ik; bh++) {
+ std::copy_n(m_oracle_summary_cache.begin() + bh * m_summary_cap * m_didx,
+ num_blocks * m_didx,
+ expected_summary.begin() + bh * num_blocks * m_didx);
+ }
+ ov::Tensor expected_past_raw_k(m_data_precision, m_past_raw_k_tensor.get_shape());
+ ov::Tensor expected_past_rope(m_data_precision, m_past_rope_tensor.get_shape());
+ write_f32_to_tensor(expected_summary_cache, expected_summary);
+ write_f32_to_tensor(expected_past_raw_k, m_oracle_past_raw_k);
+ write_f32_to_tensor(expected_past_rope, m_oracle_past_rope);
+
+ compare({expected_sel_indices, expected_sel_count, expected_summary_cache, expected_past_raw_k, expected_past_rope},
+ outs);
+
+ // State inputs are untouched (bitwise)...
+ const std::vector<const ov::Tensor*> state_in = {&m_summary_cache_tensor,
+ &m_past_raw_k_tensor,
+ &m_past_rope_tensor};
+ for (size_t i = 0; i < state_in.size(); i++) {
+ if (state_in_snapshot[i].get_byte_size() == 0) {
+ continue;
+ }
+ EXPECT_EQ(0,
+ std::memcmp(state_in[i]->data(), state_in_snapshot[i].data(), state_in_snapshot[i].get_byte_size()))
+ << "state input " << i << " was modified in place";
+ }
+ // ...and the state outputs are what the outside Assign feeds into the next call.
+ m_summary_cache_tensor = outs[ov::intel_cpu::QSAIndexerNode::OutputIdx::SUMMARY_CACHE];
+ m_past_raw_k_tensor = outs[ov::intel_cpu::QSAIndexerNode::OutputIdx::PAST_INCOMPLETE_RAW_K];
+ m_past_rope_tensor = outs[ov::intel_cpu::QSAIndexerNode::OutputIdx::PAST_INCOMPLETE_ROPE];
+ return outs;
+}
+
+void QSAIndexerLayerCPUTest::run() {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+ compiledModel = core->compile_model(function, targetDevice, configuration);
+ m_infer_request = compiledModel.create_infer_request();
+
+ m_summary_cache_tensor = make_zero_tensor(m_data_precision, ov::Shape{m_batch, m_h_ik, 0, m_didx});
+ m_past_raw_k_tensor = make_zero_tensor(m_data_precision, ov::Shape{m_batch, m_h_ik, m_compress_ratio - 1, m_didx});
+ m_past_rope_tensor = make_zero_tensor(m_data_precision, ov::Shape{m_batch, 2 * m_rotary_dim});
+
+ m_q_norm_weight_tensor =
+ ov::test::utils::create_and_fill_tensor(m_data_precision,
+ ov::Shape{m_didx},
+ ov::test::utils::InputGenerateData(0.5, 1000, 1000, 6));
+ m_k_norm_weight_tensor =
+ ov::test::utils::create_and_fill_tensor(m_data_precision,
+ ov::Shape{m_didx},
+ ov::test::utils::InputGenerateData(0.5, 1000, 1000, 7));
+
+ m_oracle_summary_cache.assign(m_batch * m_h_ik * m_summary_cap * m_didx, 0.0F);
+ m_oracle_past_raw_k.assign(m_batch * m_h_ik * (m_compress_ratio - 1) * m_didx, 0.0F);
+ m_oracle_past_rope.assign(m_batch * 2 * m_rotary_dim, 0.0F);
+
+ for (size_t i = 0; i < m_calls.size(); i++) {
+ run_call(m_calls[i], i);
+ }
+}
+
+TEST_P(QSAIndexerLayerCPUTest, CompareWithRefs) {
+ run();
+}
+
+} // namespace test
+} // namespace ov
diff --git a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/qsa_indexer.hpp b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/qsa_indexer.hpp
new file mode 100644
index 00000000000..0817ca5a422
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/qsa_indexer.hpp
@@ -0,0 +1,137 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+#include <string>
+#include <tuple>
+#include <vector>
+
+#include "openvino/core/type/element_type.hpp"
+#include "openvino/runtime/tensor.hpp"
+#include "shared_test_classes/base/ov_subgraph.hpp"
+
+namespace ov {
+namespace test {
+
+// Host-vector helpers of the reference below (float <-> f32/f16/bf16 tensors).
+std::vector<float> read_tensor_to_f32(const ov::Tensor& t);
+void write_f32_to_tensor(ov::Tensor& t, const std::vector<float>& data);
+ov::Tensor make_zero_tensor(const ov::element::Type& precision, const ov::Shape& shape);
+
+// Independent (host-vector based) reference of one QSAIndexer call, re-implementing
+// new_spec/qsa-prepare-17.rst's padding-aware prepare+selection pseudocode directly -- NOT a copy
+// of the CPU node's PlainTensor-based indexing/control flow. `summary_cache`/`past_raw_k`/
+// `past_rope` are caller-owned state threaded in by reference across sequential calls, mirroring
+// the production op's state.
+struct QSAIndexerOracle {
+ size_t h_iq = 0;
+ size_t h_ik = 0;
+ size_t h_sel = 0;
+ size_t d_idx = 0;
+ size_t rotary_dim = 0;
+ int64_t r = 0;
+ size_t block_topk = 0;
+ float eps = 1e-6F;
+ float scale = 0.25F;
+ size_t summary_cap = 0;
+ // the chosen blocks of a row by descending score, equal scores by ascending block id (the order of
+ // SparseAttentionIndexer-17), instead of ascending block ids
+ bool order_by_score = false;
+
+ std::vector<float> summary_cache; // [B, h_ik, summary_cap, d_idx]
+ std::vector<float> past_raw_k; // [B, h_ik, r - 1, d_idx]
+ std::vector<float> past_rope; // [B, 2 * rotary_dim]
+
+ struct Output {
+ std::vector<int32_t> sel_indices;
+ std::vector<int32_t> sel_count;
+ };
+
+ Output run_call(size_t batch,
+ int64_t length,
+ const std::vector<int32_t>& key_length,
+ const std::vector<float>& q_idx,
+ const std::vector<float>& k_idx,
+ const std::vector<float>& rope_cos,
+ const std::vector<float>& rope_sin,
+ const std::vector<float>& q_norm_weight,
+ const std::vector<float>& k_norm_weight);
+};
+
+// Which fixed per-call (L, key_length) schedule SetUp() builds. kDensePrefill is a single call
+// with key_length[b] == L for every row (no past, no padding) -- basic correctness coverage.
+// kWorkedExample reproduces new_spec/qsa-prepare-17.rst's worked example verbatim: compress_ratio
+// 4, a prefill call (L=10, key_length=[10,7], row 1 left-padded by 3) followed by a decode call
+// (L=1, key_length=[11,8]) that completes row 1's second block. Forces batch to 2.
+// kFullyPaddedRow: compress_ratio 4, a prefill call (L=5, key_length=[5,0]) whose row 1 is entirely padding
+// (no token, no block, all-zero state), then a call (L=3, key_length=[8,3]) in which that row starts from scratch.
+// kRaggedCalls: compress_ratio 4, three calls with L > 1 and different past lengths per row (key_length=[7,5],
+// [10,8], [15,13]): the incomplete-block tail is 3/1, 2/0 and 3/1 rows long at the start of the calls and a block
+// is completed exactly at the end of a call (row 1 of the second one). Forces batch to 2.
+enum class QSAIndexerScenario { kDensePrefill, kWorkedExample, kFullyPaddedRow, kRaggedCalls };
+
+// target device, data precision (q_idx/k_idx/rotary/caches/norm weights),
+// H_iq (index-query head count), H_ik (index-key head count), h_sel (selection-head count),
+// batch (ignored by all scenarios but kDensePrefill, which force batch == 2), scenario,
+// order_by_score (the chosen blocks of a row by descending score instead of ascending block ids)
+using QSAIndexerLayerTestParams =
+ std::tuple<std::string, ov::element::Type, size_t, size_t, size_t, size_t, QSAIndexerScenario, bool>;
+
+class QSAIndexerLayerCPUTest : public testing::WithParamInterface<QSAIndexerLayerTestParams>,
+ virtual public SubgraphBaseTest {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<QSAIndexerLayerTestParams>& obj);
+
+protected:
+ void SetUp() override;
+ void run() override;
+ void compare(const std::vector<ov::Tensor>& expected, const std::vector<ov::Tensor>& actual) override;
+
+private:
+ struct CallSpec {
+ int64_t length = 0;
+ std::vector<int32_t> key_length;
+ };
+
+ std::vector<ov::Tensor> run_call(const CallSpec& call, size_t call_idx);
+
+ ov::element::Type m_data_precision = ov::element::f32;
+ size_t m_h_iq = 2;
+ size_t m_h_ik = 2;
+ size_t m_h_sel = 1;
+ size_t m_batch = 1;
+ bool m_order_by_score = false;
+ // Share of the elements of an output that may differ. The order of the chosen blocks by score flips for blocks
+ // whose scores are within the rounding of a 16-bit type (the f32 oracle does not round), so the 16-bit types allow
+ // a few such indices when the blocks are ordered by score; the share of a handful of elements rounds down to none.
+ double m_mismatch_share = 0.0;
+ QSAIndexerScenario m_scenario = QSAIndexerScenario::kDensePrefill;
+
+ size_t m_compress_ratio = 2;
+ size_t m_block_topk = 2;
+ size_t m_rotary_dim = 8;
+ size_t m_didx = 16;
+ size_t m_summary_cap = 0; // block capacity of the host oracle's summary cache only
+ std::vector<CallSpec> m_calls;
+
+ ov::InferRequest m_infer_request;
+ ov::Tensor m_summary_cache_tensor;
+ ov::Tensor m_past_raw_k_tensor;
+ ov::Tensor m_past_rope_tensor;
+ ov::Tensor m_q_norm_weight_tensor;
+ ov::Tensor m_k_norm_weight_tensor;
+
+ // Independent (host-vector based) oracle state, persisted across the calls in m_calls --
+ // mirrors the production op's three state tensors (fed back from its state outputs), but is never read from the
+ // compiled model's own tensors.
+ std::vector<float> m_oracle_summary_cache;
+ std::vector<float> m_oracle_past_raw_k;
+ std::vector<float> m_oracle_past_rope;
+};
+
+} // namespace test
+} // namespace ov
diff --git a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/sparse_pa.cpp b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/sparse_pa.cpp
new file mode 100644
index 00000000000..ec619c4bb66
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/sparse_pa.cpp
@@ -0,0 +1,751 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "sparse_pa.hpp"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdint>
+#include <cstring>
+#include <limits>
+#include <numeric>
+#include <sstream>
+#include <vector>
+
+#include "common_test_utils/ov_tensor_utils.hpp"
+#include "common_test_utils/test_constants.hpp"
+#include "openvino/core/type/bfloat16.hpp"
+#include "openvino/core/type/float16.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/paged_sparse_attention.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/runtime/internal_properties.hpp"
+#include "openvino/runtime/properties.hpp"
+#include "openvino/runtime/system_conf.hpp"
+#include "utils/quantization_utils.hpp"
+
+namespace {
+
+void fill_pseudo_random(std::vector<float>& v, uint32_t seed_base) {
+ for (size_t i = 0; i < v.size(); i++) {
+ uint32_t x = seed_base * 2654435761U + static_cast<uint32_t>(i) * 40503U + 1U;
+ x ^= x >> 13;
+ x *= 0x85EBCA6BU;
+ x ^= x >> 16;
+ v[i] = (static_cast<float>(x % 20000U) / 10000.0F) - 1.0F;
+ }
+}
+
+uint32_t next_random(uint32_t& state) {
+ state = state * 1664525U + 1013904223U;
+ return state >> 8;
+}
+
+// Synthetic indexer output for one (token, selection head): `num_complete` = (position + 1) / key_block_size blocks
+// are complete at the token, so any of them may be selected -- including the one that ends exactly at the token, which
+// leaves the causal tail empty. Entries after the count are -1.
+void make_selection(ov::test::SparsePASelection mode,
+ bool shuffle,
+ size_t max_blocks,
+ size_t num_complete,
+ uint32_t& rng,
+ int32_t* indices,
+ int32_t& count) {
+ std::fill(indices, indices + max_blocks, -1);
+ count = 0;
+ if (mode == ov::test::SparsePASelection::kEmpty || num_complete == 0) {
+ return;
+ }
+ const size_t limit = std::min(num_complete, max_blocks);
+ size_t n = limit;
+ if (mode == ov::test::SparsePASelection::kRecent) {
+ for (size_t k = 0; k < n; k++) {
+ indices[k] = static_cast<int32_t>(num_complete - n + k);
+ }
+ } else {
+ n = next_random(rng) % (limit + 1);
+ std::vector<int32_t> pool(num_complete);
+ std::iota(pool.begin(), pool.end(), 0);
+ for (size_t k = 0; k < n; k++) {
+ const size_t j = k + next_random(rng) % (num_complete - k);
+ std::swap(pool[k], pool[j]);
+ }
+ std::sort(pool.begin(), pool.begin() + static_cast<ptrdiff_t>(n));
+ std::copy_n(pool.begin(), n, indices);
+ }
+ // the order of the blocks of a row is up to the producer: ascending, like the CPU indexer returns them, or random
+ for (size_t k = shuffle ? n : 0; k > 1; k--) {
+ std::swap(indices[k - 1], indices[next_random(rng) % k]);
+ }
+ count = static_cast<int32_t>(n);
+}
+
+// Quantize + dequantize one by-token group with the plugin's formulas (attn_quant_kernel.hpp): min/max affine
+// quantization, evaluated like its vector code as fma(x, 1 / scale, zp) rounded to nearest even. Evaluating x / scale +
+// zp with std::round instead differs by one level on values within an ulp of a rounding tie.
+void fake_quant_group(bool u4, const float* src, float* dst, size_t n) {
+ float max_val = -std::numeric_limits<float>::max();
+ float min_val = std::numeric_limits<float>::max();
+ for (size_t i = 0; i < n; i++) {
+ max_val = std::max(max_val, src[i]);
+ min_val = std::min(min_val, src[i]);
+ }
+ const float levels = u4 ? 15.0F : 255.0F;
+ float scale = (max_val - min_val) / levels;
+ if (scale == 0.0F) {
+ scale = 0.0001F;
+ }
+ const float zp = -min_val / scale;
+ const float inv_scale = 1.0F / scale;
+ for (size_t i = 0; i < n; i++) {
+ const float q = std::min(levels, std::max(0.0F, std::nearbyint(std::fma(src[i], inv_scale, zp))));
+ dst[i] = (q - zp) * scale;
+ }
+}
+
+void fake_quant_by_token(ov::element::Type prec, size_t group_size, const float* src, float* dst, size_t head) {
+ const size_t group = group_size ? group_size : head;
+ for (size_t g = 0; g < head; g += group) {
+ fake_quant_group(prec == ov::element::u4, src + g, dst + g, group);
+ }
+}
+
+// One scale and zero point per channel over `rows` rows of a key page, evaluated like the plugin's
+// quantize_by_channel() (attn_quant_kernel.hpp): scale = (max - min) * (1 / levels), zp = -min / scale, x quantized as
+// fma(x, 1 / scale, zp) rounded to nearest even.
+void fake_quant_by_channel(ov::element::Type prec, const float* src, float* dst, size_t rows, size_t hidden) {
+ const float levels = prec == ov::element::u4 ? 15.0F : 255.0F;
+ for (size_t j = 0; j < hidden; j++) {
+ float max_val = -std::numeric_limits<float>::max();
+ float min_val = std::numeric_limits<float>::max();
+ for (size_t i = 0; i < rows; i++) {
+ max_val = std::max(max_val, src[i * hidden + j]);
+ min_val = std::min(min_val, src[i * hidden + j]);
+ }
+ float scale = (max_val - min_val) * (1.0F / levels);
+ if (scale == 0.0F) {
+ scale = 0.0001F;
+ }
+ const float zp = -min_val / scale;
+ const float inv_scale = 1.0F / scale;
+ for (size_t i = 0; i < rows; i++) {
+ const float q =
+ std::min(levels, std::max(0.0F, std::nearbyint(std::fma(src[i * hidden + j], inv_scale, zp))));
+ dst[i * hidden + j] = (q - zp) * scale;
+ }
+ }
+}
+
+struct ReferenceDims {
+ size_t num_heads;
+ size_t num_kv_heads;
+ size_t num_selection_heads;
+ size_t k_head_size;
+ size_t v_head_size;
+ size_t key_block_size;
+ size_t max_selected_blocks;
+};
+
+// Independent (host-vector based) re-implementation of the PagedSparseAttention spec for one sequence, used purely as
+// a test oracle. `key`/`value` are the FULL logical history of the sequence, [kv, past_len + chunk_len, S], i.e. the
+// rows the caches hold once the new tokens are written; `query` covers only the chunk's rows. `sel_indices` /
+// `sel_count` are [chunk_len, num_selection_heads, max_selected_blocks] / [chunk_len, num_selection_heads].
+std::vector<float> run_sparse_pa_reference(const ReferenceDims& d,
+ size_t chunk_len,
+ float scale,
+ int64_t past_len,
+ const std::vector<float>& query,
+ const std::vector<float>& key,
+ const std::vector<float>& value,
+ const std::vector<int32_t>& sel_indices,
+ const std::vector<int32_t>& sel_count) {
+ const int64_t history_len = past_len + static_cast<int64_t>(chunk_len);
+ auto key_at = [&](size_t head, int64_t pos) {
+ return &key[(head * static_cast<size_t>(history_len) + static_cast<size_t>(pos)) * d.k_head_size];
+ };
+ auto value_at = [&](size_t head, int64_t pos) {
+ return &value[(head * static_cast<size_t>(history_len) + static_cast<size_t>(pos)) * d.v_head_size];
+ };
+
+ std::vector<float> output(chunk_len * d.num_heads * d.v_head_size, 0.0F);
+ const size_t group = d.num_heads / d.num_kv_heads;
+ const size_t q_per_sel = d.num_heads / d.num_selection_heads;
+ const auto Bk = static_cast<int64_t>(d.key_block_size);
+ for (size_t l = 0; l < chunk_len; l++) {
+ const int64_t token_pos = past_len + static_cast<int64_t>(l);
+ for (size_t h = 0; h < d.num_heads; h++) {
+ const size_t kv_head = h / group;
+ const size_t sh = h / q_per_sel;
+ const float* q = &query[(l * d.num_heads + h) * d.k_head_size];
+ std::vector<float> acc(d.v_head_size, 0.0F);
+ float running_max = -std::numeric_limits<float>::infinity();
+ float running_sum = 0.0F;
+ // One online-softmax step for key/value position `kpos`: score = (q . K) * scale, rescale the running
+ // max/sum by corr, then acc = acc * corr + p * V. Positions outside the valid history are skipped.
+ auto attend_token = [&](int64_t kpos) {
+ if (kpos < 0 || kpos >= history_len || kpos > token_pos) {
+ return;
+ }
+ const float* k = key_at(kv_head, kpos);
+ const float* v = value_at(kv_head, kpos);
+ float dot = 0.0F;
+ for (size_t i = 0; i < d.k_head_size; i++) {
+ dot += q[i] * k[i];
+ }
+ const float score = dot * scale;
+ const float new_max = std::max(running_max, score);
+ const float corr = std::exp(running_max - new_max);
+ const float p = std::exp(score - new_max);
+ running_sum = running_sum * corr + p;
+ for (size_t i = 0; i < d.v_head_size; i++) {
+ acc[i] = acc[i] * corr + p * v[i];
+ }
+ running_max = new_max;
+ };
+
+ const size_t row = l * d.num_selection_heads + sh;
+ const auto nblocks = static_cast<size_t>(sel_count[row]);
+ for (size_t i = 0; i < nblocks; i++) {
+ const int64_t block_start = static_cast<int64_t>(sel_indices[row * d.max_selected_blocks + i]) * Bk;
+ for (int64_t p = block_start; p < block_start + Bk; p++) {
+ attend_token(p);
+ }
+ }
+
+ // sel_indices/sel_count only ever carry *complete* blocks. The consumer derives and attends the
+ // incomplete block of the query itself, which is empty when the position ends a block.
+ for (int64_t p = ((token_pos + 1) / Bk) * Bk; p <= token_pos; p++) {
+ attend_token(p);
+ }
+
+ const float inv_sum = running_sum > 0.0F ? 1.0F / running_sum : 0.0F;
+ for (size_t i = 0; i < d.v_head_size; i++) {
+ output[(l * d.num_heads + h) * d.v_head_size + i] = acc[i] * inv_sum;
+ }
+ }
+ }
+ return output;
+}
+
+const char* selection_name(ov::test::SparsePASelection selection) {
+ switch (selection) {
+ case ov::test::SparsePASelection::kRecent:
+ return "Recent";
+ case ov::test::SparsePASelection::kRandom:
+ return "Random";
+ default:
+ return "Empty";
+ }
+}
+
+} // namespace
+
+namespace ov {
+namespace test {
+
+std::string SparsePALayerCPUTest::getTestCaseName(const testing::TestParamInfo<SparsePALayerTestParams>& obj) {
+ const auto& [data_precision, shapes, cfg] = obj.param;
+ std::ostringstream result;
+ result << "Prc=" << data_precision << "_Steps=";
+ for (const auto& step : shapes.at(0).second) {
+ result << step[0] << "_";
+ }
+ const auto& first = shapes.at(0).second.at(0);
+ result << "B=" << first[1] << "_Hq=" << first[2] << "_Dh=" << first[3] << "_Hkv=" << cfg.num_kv_heads
+ << "_Hsel=" << cfg.num_selection_heads << "_Dv=" << cfg.v_head_size << "_Bk=" << cfg.key_block_size
+ << "_Page=" << cfg.page_size << "_Kmax=" << cfg.max_selected_blocks
+ << "_Sel=" << selection_name(cfg.selection) << (cfg.shuffle_blocks ? "_Shuffled" : "")
+ << "_Cache=" << (cfg.cache_precision == ov::element::dynamic ? "plain" : cfg.cache_precision.get_type_name())
+ << "_KeyByChannel=" << cfg.key_bychannel << "_Group=" << cfg.group_size << "_Mixed=" << cfg.mixed_lengths;
+ return result.str();
+}
+
+float SparsePALayerCPUTest::through_cache(float value) const {
+ if (cache_type() == ov::element::f16) {
+ return static_cast<float>(ov::float16(value));
+ }
+ return value;
+}
+
+size_t SparsePALayerCPUTest::sequence_len(size_t step_len, size_t sequence) const {
+ if (!m_cfg.mixed_lengths) {
+ return step_len;
+ }
+ switch (sequence % 3) {
+ case 0:
+ return step_len; // (chunked) prefill
+ case 1:
+ return 1; // decode
+ default:
+ return (step_len + 1) / 2; // a shorter chunk
+ }
+}
+
+ov::Shape SparsePALayerCPUTest::cache_shape(bool is_key) const {
+ const size_t head = is_key ? m_k_head_size : m_cfg.v_head_size;
+ const size_t n_phys = m_num_sequences * m_pages_per_sequence;
+ if (!quantized()) {
+ return {n_phys, m_cfg.num_kv_heads, m_cfg.page_size, head};
+ }
+ // Scale and zero point are f32; u4 counts them in half-byte elements.
+ const size_t params = m_cfg.cache_precision == ov::element::u4 ? 16 : 8;
+ const size_t group = m_cfg.group_size ? m_cfg.group_size : head;
+ if (is_key && m_cfg.key_bychannel) {
+ return {n_phys, m_cfg.num_kv_heads, m_cfg.page_size + params, head};
+ }
+ return {n_phys, m_cfg.num_kv_heads, m_cfg.page_size, head + params * (head / group)};
+}
+
+void SparsePALayerCPUTest::SetUp() {
+ const auto& [data_precision, shapes, cfg] = GetParam();
+ targetDevice = ov::test::utils::DEVICE_CPU;
+ m_data_precision = data_precision;
+ m_cfg = cfg;
+ m_steps = shapes.at(0).second;
+ ASSERT_FALSE(m_steps.empty());
+ m_num_sequences = m_steps[0][1];
+ m_num_heads = m_steps[0][2];
+ m_k_head_size = m_steps[0][3];
+ // Tokens every sequence holds after all the steps; the caches have room for the longest one.
+ std::vector<size_t> sequence_tokens(m_num_sequences, 0);
+ for (const auto& step : m_steps) {
+ ASSERT_EQ(step.size(), 4U) << "SparsePA test expects [L, B, H, S] step shapes";
+ ASSERT_EQ(step[1], m_num_sequences) << "the number of sequences is fixed across the steps";
+ ASSERT_EQ(step[2], m_num_heads);
+ ASSERT_EQ(step[3], m_k_head_size);
+ for (size_t s = 0; s < m_num_sequences; s++) {
+ sequence_tokens[s] += sequence_len(step[0], s);
+ }
+ }
+ const size_t max_tokens = *std::max_element(sequence_tokens.begin(), sequence_tokens.end());
+ m_pages_per_sequence = (max_tokens + m_cfg.page_size - 1) / m_cfg.page_size;
+ m_total_len.assign(m_num_sequences, 0);
+ m_scale = 1.0F / std::sqrt(static_cast<float>(m_k_head_size));
+
+ rel_threshold = 1e-3F;
+ abs_threshold = 1e-4F;
+ // Every floating-point input follows the data precision, which is also the inference precision.
+ configuration.insert(ov::hint::inference_precision(data_precision));
+ // A prefill (several new tokens in a sequence) runs as AMX matrix products over the query heads of a K head
+ // whatever the thread count. A decode packs the query heads only with at least 2 work items per worker thread: one
+ // thread packs it (the SIMD pack paths), two threads give a decode of one sequence fewer items than that, so it
+ // runs one head per item next to the prefill items of a mixed call (the layout on many cores). Single-sequence
+ // cases take the first, mixed batches the second.
+ configuration[ov::inference_num_threads.name()] = m_cfg.mixed_lengths ? 2 : 1;
+ if (data_precision == ov::element::bf16) {
+ rel_threshold = 5e-2F;
+ abs_threshold = 5e-2F;
+ } else if (data_precision == ov::element::f16) {
+ rel_threshold = 5e-3F;
+ abs_threshold = 5e-3F;
+ }
+ // ConvertPagedAttnInputs applies the KV cache precision (u8 by default) to the cache inputs: pin it to the data
+ // precision for plain caches, or to the quantized precision, quantization mode and group size under test.
+ if (quantized()) {
+ configuration[ov::key_cache_precision.name()] = m_cfg.cache_precision;
+ configuration[ov::value_cache_precision.name()] = m_cfg.cache_precision;
+ configuration[ov::key_cache_group_size.name()] = static_cast<uint64_t>(m_cfg.group_size);
+ configuration[ov::value_cache_group_size.name()] = static_cast<uint64_t>(m_cfg.group_size);
+ configuration[ov::internal::key_cache_quant_mode.name()] =
+ m_cfg.key_bychannel ? ov::internal::CacheQuantMode::BY_CHANNEL : ov::internal::CacheQuantMode::BY_TOKEN;
+ configuration[ov::internal::value_cache_quant_mode.name()] = ov::internal::CacheQuantMode::BY_TOKEN;
+ } else {
+ // The cache inputs are declared at the data precision; ConvertPagedAttnInputs gives them the cache type.
+ configuration.insert(ov::hint::kv_cache_precision(cache_type()));
+ }
+
+ const size_t Hkv = m_cfg.num_kv_heads;
+ const size_t Dv = m_cfg.v_head_size;
+ const size_t Hs = m_cfg.num_selection_heads;
+ const size_t K = m_cfg.max_selected_blocks;
+ const size_t n_phys = m_num_sequences * m_pages_per_sequence;
+ const auto dyn = ov::Dimension::dynamic();
+ const auto dim = [](size_t value) {
+ return static_cast<int64_t>(value);
+ };
+
+ auto p_query = std::make_shared<ov::op::v0::Parameter>(data_precision,
+ ov::PartialShape{dyn, dim(m_num_heads * m_k_head_size)});
+ auto p_key =
+ std::make_shared<ov::op::v0::Parameter>(data_precision, ov::PartialShape{dyn, dim(Hkv * m_k_head_size)});
+ auto p_value = std::make_shared<ov::op::v0::Parameter>(data_precision, ov::PartialShape{dyn, dim(Hkv * Dv)});
+ // Quantized caches get their final element type and padded shape from ConvertPagedAttnInputs (driven by the head
+ // runtime info set on the op below), so they start out unspecified.
+ auto p_key_cache = quantized()
+ ? std::make_shared<ov::op::v0::Parameter>(ov::element::dynamic, ov::PartialShape::dynamic(4))
+ : std::make_shared<ov::op::v0::Parameter>(data_precision, cache_shape(true));
+ auto p_value_cache =
+ quantized() ? std::make_shared<ov::op::v0::Parameter>(ov::element::dynamic, ov::PartialShape::dynamic(4))
+ : std::make_shared<ov::op::v0::Parameter>(data_precision, cache_shape(false));
+ auto p_past_lens = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{m_num_sequences});
+ auto p_subsequence_begins =
+ std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{m_num_sequences + 1});
+ auto p_block_indices = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{n_phys});
+ auto p_block_indices_begins =
+ std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{m_num_sequences + 1});
+ auto p_sel_indices =
+ std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{dyn, dim(Hs), dim(K)});
+ auto p_sel_count = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{dyn, dim(Hs)});
+
+ // Input order follows ov::op::internal::PagedSparseAttention; SCALE and SINKS are constants
+ // (SINKS is an empty tensor: sinks are not supported yet).
+ ov::ParameterVector parameters{p_query,
+ p_key,
+ p_value,
+ p_key_cache,
+ p_value_cache,
+ p_past_lens,
+ p_subsequence_begins,
+ p_block_indices,
+ p_block_indices_begins,
+ p_sel_indices,
+ p_sel_count};
+
+ // Static target shapes of every step, in parameter order.
+ std::vector<InputShape> input_shapes;
+ for (const auto& parameter : parameters) {
+ input_shapes.emplace_back(parameter->get_partial_shape(), std::vector<ov::Shape>{});
+ }
+ for (const auto& step : m_steps) {
+ size_t tokens = 0;
+ for (size_t s = 0; s < m_num_sequences; s++) {
+ tokens += sequence_len(step[0], s);
+ }
+ const std::vector<ov::Shape> step_shapes = {{tokens, m_num_heads * m_k_head_size},
+ {tokens, Hkv * m_k_head_size},
+ {tokens, Hkv * Dv},
+ cache_shape(true),
+ cache_shape(false),
+ {m_num_sequences},
+ {m_num_sequences + 1},
+ {n_phys},
+ {m_num_sequences + 1},
+ {tokens, Hs, K},
+ {tokens, Hs}};
+ for (size_t i = 0; i < step_shapes.size(); i++) {
+ input_shapes[i].second.push_back(step_shapes[i]);
+ }
+ }
+ init_input_shapes(input_shapes);
+
+ auto scale = ov::op::v0::Constant::create(data_precision, ov::Shape{}, {m_scale});
+ auto sinks = ov::op::v0::Constant::create(data_precision, ov::Shape{0}, std::vector<float>{});
+ ov::OutputVector args = {p_query,
+ p_key,
+ p_value,
+ p_key_cache,
+ p_value_cache,
+ p_past_lens,
+ p_subsequence_begins,
+ p_block_indices,
+ p_block_indices_begins,
+ p_sel_indices,
+ p_sel_count,
+ scale,
+ sinks};
+ auto sparse_pa = std::make_shared<ov::op::internal::PagedSparseAttention>(args, m_cfg.key_block_size);
+ if (quantized()) {
+ // Head metadata for ConvertPagedAttnInputs, which builds the padded quantized cache shapes from it.
+ sparse_pa->get_rt_info()["num_k_heads"] = Hkv;
+ sparse_pa->get_rt_info()["k_head_size"] = m_k_head_size;
+ sparse_pa->get_rt_info()["num_v_heads"] = Hkv;
+ sparse_pa->get_rt_info()["v_head_size"] = Dv;
+ }
+
+ function =
+ std::make_shared<ov::Model>(ov::ResultVector{std::make_shared<ov::op::v0::Result>(sparse_pa)}, parameters);
+}
+
+void SparsePALayerCPUTest::generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) {
+ inputs.clear();
+ host_inputs.clear();
+
+ const size_t step = m_step++;
+ const size_t B = m_num_sequences;
+ const size_t Hq = m_num_heads;
+ const size_t Dh = m_k_head_size;
+ const size_t Hkv = m_cfg.num_kv_heads;
+ const size_t Dv = m_cfg.v_head_size;
+ const size_t Hs = m_cfg.num_selection_heads;
+ const size_t K = m_cfg.max_selected_blocks;
+ const size_t Bk = m_cfg.key_block_size;
+ const size_t n_phys = B * m_pages_per_sequence;
+ // New tokens of every sequence in this step and the first global token of each: sequences of a mixed batch differ.
+ std::vector<size_t> begins(B + 1, 0);
+ m_cur_past = m_total_len;
+ m_cur_len.resize(B);
+ for (size_t s = 0; s < B; s++) {
+ m_cur_len[s] = sequence_len(m_steps.at(step)[0], s);
+ begins[s + 1] = begins[s] + m_cur_len[s];
+ m_total_len[s] += m_cur_len[s];
+ }
+ const size_t tokens = begins[B];
+
+ const auto assign_precision = [this](ov::Tensor& t, const std::vector<float>& data) {
+ if (m_data_precision == ov::element::bf16) {
+ auto* dst = t.data<ov::bfloat16>();
+ for (size_t i = 0; i < data.size(); i++) {
+ dst[i] = ov::bfloat16(data[i]);
+ }
+ } else if (m_data_precision == ov::element::f16) {
+ auto* dst = t.data<ov::float16>();
+ for (size_t i = 0; i < data.size(); i++) {
+ dst[i] = ov::float16(data[i]);
+ }
+ } else {
+ std::copy(data.begin(), data.end(), t.data<float>());
+ }
+ };
+ const auto make_i32 = [](const std::vector<int32_t>& values) {
+ ov::Tensor t(ov::element::i32, ov::Shape{values.size()});
+ std::copy(values.begin(), values.end(), t.data<int32_t>());
+ return t;
+ };
+
+ // The caches start out empty and are written by the op itself in every step, like a real multi-call sequence.
+ if (step == 0) {
+ m_key_cache = ov::Tensor(cache_type(), cache_shape(true));
+ m_value_cache = ov::Tensor(cache_type(), cache_shape(false));
+ std::memset(m_key_cache.data(), 0, m_key_cache.get_byte_size());
+ std::memset(m_value_cache.data(), 0, m_value_cache.get_byte_size());
+ }
+
+ ov::Tensor query(m_data_precision, ov::Shape{tokens, Hq * Dh});
+ ov::Tensor key(m_data_precision, ov::Shape{tokens, Hkv * Dh});
+ ov::Tensor value(m_data_precision, ov::Shape{tokens, Hkv * Dv});
+ {
+ std::vector<float> query_data(query.get_size());
+ std::vector<float> key_data(key.get_size());
+ std::vector<float> value_data(value.get_size());
+ for (size_t s = 0; s < B; s++) {
+ const uint32_t seed = static_cast<uint32_t>(step) * 101U + static_cast<uint32_t>(s) * 11U;
+ const size_t L = m_cur_len[s];
+ std::vector<float> q_slot(L * Hq * Dh);
+ std::vector<float> k_slot(L * Hkv * Dh);
+ std::vector<float> v_slot(L * Hkv * Dv);
+ fill_pseudo_random(q_slot, 1 + seed);
+ fill_pseudo_random(k_slot, 2 + seed);
+ fill_pseudo_random(v_slot, 3 + seed);
+ std::copy(q_slot.begin(), q_slot.end(), query_data.begin() + static_cast<ptrdiff_t>(begins[s] * Hq * Dh));
+ std::copy(k_slot.begin(), k_slot.end(), key_data.begin() + static_cast<ptrdiff_t>(begins[s] * Hkv * Dh));
+ std::copy(v_slot.begin(), v_slot.end(), value_data.begin() + static_cast<ptrdiff_t>(begins[s] * Hkv * Dv));
+ }
+ assign_precision(query, query_data);
+ assign_precision(key, key_data);
+ assign_precision(value, value_data);
+ }
+
+ // Non-identity permutation (simple reversal) across all physical blocks shared by every sequence, so a kernel bug
+ // that walked physical blocks in logical order instead of resolving through block_indices would give wrong results.
+ std::vector<int32_t> block_indices(n_phys);
+ for (size_t i = 0; i < n_phys; i++) {
+ block_indices[i] = static_cast<int32_t>(n_phys - 1 - i);
+ }
+
+ // Synthetic selection of the complete blocks every token attends to, see make_selection().
+ std::vector<int32_t> sel_indices_flat(tokens * Hs * K, -1);
+ std::vector<int32_t> sel_count_flat(tokens * Hs, 0);
+ uint32_t rng = 12345U + static_cast<uint32_t>(step);
+ for (size_t s = 0; s < B; s++) {
+ for (size_t l = 0; l < m_cur_len[s]; l++) {
+ const size_t token = begins[s] + l;
+ const size_t num_complete = (m_cur_past[s] + l + 1) / Bk;
+ for (size_t sh = 0; sh < Hs; sh++) {
+ const size_t row = token * Hs + sh;
+ make_selection(m_cfg.selection,
+ m_cfg.shuffle_blocks,
+ K,
+ num_complete,
+ rng,
+ &sel_indices_flat[row * K],
+ sel_count_flat[row]);
+ }
+ }
+ }
+
+ const auto& params = function->get_parameters();
+ OPENVINO_ASSERT(targetInputStaticShapes.size() == params.size());
+ std::vector<ov::Tensor> tensors(params.size());
+ tensors[0] = query;
+ tensors[1] = key;
+ tensors[2] = value;
+ tensors[3] = m_key_cache;
+ tensors[4] = m_value_cache;
+ tensors[5] = make_i32(std::vector<int32_t>(m_cur_past.begin(), m_cur_past.end()));
+ std::vector<int32_t> subsequence_begins(B + 1);
+ std::vector<int32_t> block_indices_begins(B + 1);
+ for (size_t s = 0; s <= B; s++) {
+ subsequence_begins[s] = static_cast<int32_t>(begins[s]);
+ block_indices_begins[s] = static_cast<int32_t>(s * m_pages_per_sequence);
+ }
+ tensors[6] = make_i32(subsequence_begins);
+ tensors[7] = make_i32(block_indices);
+ tensors[8] = make_i32(block_indices_begins);
+ {
+ ov::Tensor t(ov::element::i32, ov::Shape{tokens, Hs, K});
+ std::copy(sel_indices_flat.begin(), sel_indices_flat.end(), t.data<int32_t>());
+ tensors[9] = t;
+ }
+ {
+ ov::Tensor t(ov::element::i32, ov::Shape{tokens, Hs});
+ std::copy(sel_count_flat.begin(), sel_count_flat.end(), t.data<int32_t>());
+ tensors[10] = t;
+ }
+
+ for (size_t i = 0; i < params.size(); i++) {
+ host_inputs[params[i]] = tensors[i];
+ inputs[params[i]] = tensors[i];
+ }
+}
+
+std::vector<ov::Tensor> SparsePALayerCPUTest::calculate_refs() {
+ const auto& params = function->get_parameters();
+ const auto to_f32 = [&](const std::shared_ptr<ov::Node>& p) {
+ const auto& t = host_inputs.at(p);
+ std::vector<float> out(t.get_size());
+ if (t.get_element_type() == ov::element::bf16) {
+ const auto* ptr = t.data<const ov::bfloat16>();
+ std::copy(ptr, ptr + t.get_size(), out.begin());
+ } else if (t.get_element_type() == ov::element::f16) {
+ const auto* ptr = t.data<const ov::float16>();
+ std::copy(ptr, ptr + t.get_size(), out.begin());
+ } else {
+ const auto* ptr = t.data<const float>();
+ std::copy(ptr, ptr + t.get_size(), out.begin());
+ }
+ return out;
+ };
+ const auto to_i32 = [&](const std::shared_ptr<ov::Node>& p) {
+ const auto& t = host_inputs.at(p);
+ const auto* ptr = t.data<const int32_t>();
+ return std::vector<int32_t>(ptr, ptr + t.get_size());
+ };
+
+ const size_t B = m_num_sequences;
+ std::vector<size_t> begins(B + 1, 0);
+ for (size_t s = 0; s < B; s++) {
+ begins[s + 1] = begins[s] + m_cur_len[s];
+ }
+ const size_t Hq = m_num_heads;
+ const size_t Dh = m_k_head_size;
+ const size_t Hkv = m_cfg.num_kv_heads;
+ const size_t Dv = m_cfg.v_head_size;
+ const size_t Hs = m_cfg.num_selection_heads;
+ const size_t K = m_cfg.max_selected_blocks;
+ const size_t page = m_cfg.page_size;
+ const auto prec = m_cfg.cache_precision;
+ const ReferenceDims dims{Hq, Hkv, Hs, Dh, Dv, m_cfg.key_block_size, K};
+
+ const auto query = to_f32(params[0]);
+ const auto key = to_f32(params[1]);
+ const auto value = to_f32(params[2]);
+ const auto sel_indices = to_i32(params[9]);
+ const auto sel_count = to_i32(params[10]);
+
+ if (m_eff_key.empty()) {
+ m_eff_key.assign(B, std::vector<std::vector<float>>(Hkv));
+ m_eff_value.assign(B, std::vector<std::vector<float>>(Hkv));
+ }
+
+ // Oracle for the caches. The effective rows are what the op reads back: plain caches hold the rows as given;
+ // quantized by-token rows are quantized once when written; a by-channel key page is requantized as a whole (its
+ // dequantized earlier rows plus the new ones) every time new rows land in it, so the rows chain across the steps.
+ for (size_t s = 0; s < B; s++) {
+ const size_t L = m_cur_len[s];
+ const size_t past = m_cur_past[s];
+ const size_t total = past + L;
+ for (size_t kv = 0; kv < Hkv; kv++) {
+ auto& eff_key = m_eff_key[s][kv];
+ auto& eff_value = m_eff_value[s][kv];
+ eff_key.resize(total * Dh);
+ eff_value.resize(total * Dv);
+ for (size_t l = 0; l < L; l++) {
+ const size_t token = begins[s] + l;
+ const float* k_src = &key[(token * Hkv + kv) * Dh];
+ const float* v_src = &value[(token * Hkv + kv) * Dv];
+ float* k_dst = &eff_key[(past + l) * Dh];
+ float* v_dst = &eff_value[(past + l) * Dv];
+ if (quantized()) {
+ fake_quant_by_token(prec, m_cfg.group_size, v_src, v_dst, Dv);
+ if (m_cfg.key_bychannel) {
+ std::copy_n(k_src, Dh, k_dst); // requantized with its page below
+ } else {
+ fake_quant_by_token(prec, m_cfg.group_size, k_src, k_dst, Dh);
+ }
+ } else {
+ for (size_t d = 0; d < Dh; d++) {
+ k_dst[d] = through_cache(k_src[d]);
+ }
+ for (size_t d = 0; d < Dv; d++) {
+ v_dst[d] = through_cache(v_src[d]);
+ }
+ }
+ }
+ if (quantized() && m_cfg.key_bychannel) {
+ for (size_t page_start = (past / page) * page; page_start < total; page_start += page) {
+ const size_t rows = std::min(page, total - page_start);
+ const std::vector<float> page_rows(
+ eff_key.begin() + static_cast<ptrdiff_t>(page_start * Dh),
+ eff_key.begin() + static_cast<ptrdiff_t>((page_start + rows) * Dh));
+ fake_quant_by_channel(prec, page_rows.data(), &eff_key[page_start * Dh], rows, Dh);
+ }
+ }
+ }
+ }
+
+ ov::Tensor output(ov::element::f32, ov::Shape{begins[B], Hq * Dv});
+ auto* output_data = output.data<float>();
+ for (size_t s = 0; s < B; s++) {
+ const size_t L = m_cur_len[s];
+ const size_t past = m_cur_past[s];
+ // Full logical history of the sequence as [kv, total, S].
+ std::vector<float> history_key;
+ std::vector<float> history_value;
+ for (size_t kv = 0; kv < Hkv; kv++) {
+ history_key.insert(history_key.end(), m_eff_key[s][kv].begin(), m_eff_key[s][kv].end());
+ history_value.insert(history_value.end(), m_eff_value[s][kv].begin(), m_eff_value[s][kv].end());
+ }
+ const auto first = static_cast<ptrdiff_t>(begins[s]);
+ const auto last = first + static_cast<ptrdiff_t>(L);
+ const std::vector<float> query_s(query.begin() + first * static_cast<ptrdiff_t>(Hq * Dh),
+ query.begin() + last * static_cast<ptrdiff_t>(Hq * Dh));
+ const std::vector<int32_t> sel_indices_s(sel_indices.begin() + first * static_cast<ptrdiff_t>(Hs * K),
+ sel_indices.begin() + last * static_cast<ptrdiff_t>(Hs * K));
+ const std::vector<int32_t> sel_count_s(sel_count.begin() + first * static_cast<ptrdiff_t>(Hs),
+ sel_count.begin() + last * static_cast<ptrdiff_t>(Hs));
+ const auto out_s = run_sparse_pa_reference(dims,
+ L,
+ m_scale,
+ static_cast<int64_t>(past),
+ query_s,
+ history_key,
+ history_value,
+ sel_indices_s,
+ sel_count_s);
+ std::copy(out_s.begin(), out_s.end(), output_data + begins[s] * Hq * Dv);
+ }
+ return {output};
+}
+
+void SparsePALayerCPUTest::compare(const std::vector<ov::Tensor>& expected, const std::vector<ov::Tensor>& actual) {
+ ASSERT_EQ(expected.size(), actual.size());
+ for (size_t i = 0; i < expected.size(); i++) {
+ ov::test::utils::compare(expected[i], actual[i], abs_threshold, rel_threshold);
+ }
+}
+
+TEST_P(SparsePALayerCPUTest, CompareWithRefs) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+ // Without f16 instructions the plugin runs f16 models in f32 and converts their parameters, so the node writes the
+ // new keys and values into a converted copy of the caches this test feeds from step to step, not into the caches.
+ if (std::get<0>(GetParam()) == ov::element::f16 &&
+ !(ov::with_cpu_x86_avx512_core_fp16() || ov::with_cpu_x86_avx2_vnni_2())) {
+ GTEST_SKIP() << "f16 is not supported on this CPU";
+ }
+ run();
+}
+
+} // namespace test
+} // namespace ov
diff --git a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/sparse_pa.hpp b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/sparse_pa.hpp
new file mode 100644
index 00000000000..f9e5468865c
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/sparse_pa.hpp
@@ -0,0 +1,107 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstddef>
+#include <map>
+#include <memory>
+#include <string>
+#include <tuple>
+#include <vector>
+
+#include "openvino/core/type/element_type.hpp"
+#include "shared_test_classes/base/ov_subgraph.hpp"
+
+namespace ov {
+namespace test {
+
+// How the synthetic indexer picks the complete blocks every new token attends to.
+enum class SparsePASelection {
+ kRecent, // the most recent complete blocks, up to max_selected_blocks
+ kRandom, // a random number (zero included) of random distinct complete blocks, in ascending order
+ kEmpty, // none: only the causal tail is attended
+};
+
+// Everything about the op that is not carried by the step shapes.
+struct SparsePAConfig {
+ size_t num_kv_heads = 2;
+ size_t num_selection_heads = 1; // 1, num_kv_heads, or the number of query heads
+ size_t v_head_size = 16;
+ size_t key_block_size = 2;
+ size_t page_size = 4; // tokens per physical cache block; a multiple of key_block_size
+ size_t max_selected_blocks = 4;
+ // u8/u4: quantized KV caches, laid out as PagedAttention does. f16 with f32 data: f16 plain caches. dynamic: plain
+ // caches at the data precision.
+ ov::element::Type cache_precision = ov::element::dynamic;
+ bool key_bychannel = false; // quantized key cache by channel, else by token (the value cache is always by token)
+ size_t group_size = 0; // by-token quantization group, 0: the whole row
+ SparsePASelection selection = SparsePASelection::kRecent;
+ // the selected blocks of a row in random order instead of ascending: the order does not matter to SparseAttention
+ bool shuffle_blocks = false;
+ // false: every sequence of a step has the step's L new tokens. true: a mixed batch of decode and (chunked) prefill
+ // sequences in one call -- sequence s gets L tokens if s % 3 == 0, a single decode token if s % 3 == 1 and
+ // (L + 1) / 2 tokens if s % 3 == 2, so the sequences also have different past lengths.
+ bool mixed_lengths = false;
+};
+
+// Data precision (query, key, value, scale, sinks, plain caches and the inference precision), the steps and the config.
+// The steps follow the PagedAttention tests: one InputShape whose target shapes are consecutive calls of the same
+// sequences, each [L, B, H, S] = L new tokens in each of B sequences, H query heads, S key head size. The caches
+// persist across the calls, so every call continues the history written by the previous ones: L > 1 is a (chunked)
+// prefill, L == 1 a decode step.
+using SparsePALayerTestParams = std::tuple<ov::element::Type, std::vector<InputShape>, SparsePAConfig>;
+
+class SparsePALayerCPUTest : public testing::WithParamInterface<SparsePALayerTestParams>,
+ virtual public SubgraphBaseTest {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<SparsePALayerTestParams>& obj);
+
+protected:
+ void SetUp() override;
+ void generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) override;
+ std::vector<ov::Tensor> calculate_refs() override;
+ void compare(const std::vector<ov::Tensor>& expected, const std::vector<ov::Tensor>& actual) override;
+
+private:
+ [[nodiscard]] bool quantized() const {
+ return m_cfg.cache_precision == ov::element::u8 || m_cfg.cache_precision == ov::element::u4;
+ }
+ // Element type of the cache tensors handed to the op.
+ [[nodiscard]] ov::element::Type cache_type() const {
+ return m_cfg.cache_precision == ov::element::dynamic ? m_data_precision : m_cfg.cache_precision;
+ }
+ // A value as the op reads it back from a plain cache of cache_type().
+ [[nodiscard]] float through_cache(float value) const;
+ // New tokens of `sequence` in a step whose shape says `step_len`.
+ [[nodiscard]] size_t sequence_len(size_t step_len, size_t sequence) const;
+ // Final key/value cache shapes: quantization parameters live inside the cache tensor (see SparsePAQuant).
+ [[nodiscard]] ov::Shape cache_shape(bool is_key) const;
+
+ ov::element::Type m_data_precision = ov::element::f32;
+ SparsePAConfig m_cfg;
+ // Step shapes [L, B, H, S]
+ std::vector<ov::Shape> m_steps;
+ size_t m_num_sequences = 1;
+ size_t m_num_heads = 4;
+ size_t m_k_head_size = 16;
+ size_t m_pages_per_sequence = 1;
+ float m_scale = 0.25F;
+
+ // Step bookkeeping. The caches are created by the first step and reused by the next ones.
+ size_t m_step = 0;
+ std::vector<size_t> m_total_len; // per sequence: tokens written by the steps generated so far
+ std::vector<size_t> m_cur_past; // per sequence: tokens before the current step
+ std::vector<size_t> m_cur_len; // per sequence: new tokens in the current step
+ ov::Tensor m_key_cache;
+ ov::Tensor m_value_cache;
+ std::map<std::shared_ptr<ov::Node>, ov::Tensor> host_inputs;
+
+ // Oracle state: effective (dequantized) key/value rows of every sequence and kv head, [sequence][kv] -> [pos, S].
+ std::vector<std::vector<std::vector<float>>> m_eff_key;
+ std::vector<std::vector<std::vector<float>>> m_eff_value;
+};
+
+} // namespace test
+} // namespace ov
diff --git a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/sparse_sdpa.cpp b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/sparse_sdpa.cpp
new file mode 100644
index 00000000000..773c2566bf4
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/sparse_sdpa.cpp
@@ -0,0 +1,410 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "sparse_sdpa.hpp"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdint>
+#include <limits>
+#include <random>
+#include <vector>
+
+#include "common_test_utils/ov_tensor_utils.hpp"
+#include "openvino/core/type/bfloat16.hpp"
+#include "openvino/core/type/float16.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/sparse_attention.hpp"
+
+namespace {
+
+// Fixed configuration of this test: B independent batch items, each with its own dense [Hkv, S, D] K/V history and L
+// query positions. S == L (see SparseSDPAShape), so the bottom-right-aligned logical position q_abs = S - L + l reduces
+// to q_abs == l, matching a straightforward causal prefill over the whole history. k_head_size / sel_block_size are
+// parameterized (see SparseSDPALayerTestParams) so the AMX paths -- which require k_head_size % 32 == 0, merging
+// adjacent selected blocks up to a 16-row multiple when sel_block_size itself isn't one (see m_amx_unit_blocks in
+// sparse_sdpa.cpp)
+// -- can be exercised by dedicated instantiations. The synthetic selection below selects up to max_blocks complete
+// blocks before the query's own block, block_step apart (ascending by default, duplicate-free, matching what the CPU
+// indexer returns; SparseAttention does not depend on the order: see SparseSDPAShape::shuffle): with step 1 the query
+// rows near the end of the sequence build up a long run of physically-adjacent selected blocks (L = 40 and K_max = 10
+// give the sel_block_size == 4 AMX instantiation a run of up to 9 adjacent blocks), with step 2 there are none.
+constexpr size_t kHq = 4;
+constexpr size_t kHkv = 2;
+constexpr size_t kDv = 16;
+
+void fill_pseudo_random(std::vector<float>& v, uint32_t seed_base) {
+ for (size_t i = 0; i < v.size(); i++) {
+ uint32_t x = seed_base * 2654435761U + static_cast<uint32_t>(i) * 40503U + 1U;
+ x ^= x >> 13;
+ x *= 0x85EBCA6BU;
+ x ^= x >> 16;
+ v[i] = (static_cast<float>(x % 20000U) / 10000.0F) - 1.0F;
+ }
+}
+
+// Independent (host-vector based) re-implementation of the sparse-pa.rst non-paged consumer
+// spec, used purely as a test oracle -- NOT a copy of the CPU node's PlainTensor-based indexing.
+// `query`/`key`/`value` are plain batched [B, H, {L|S}, D]; `sel_indices`/`sel_count` are
+// [B, h_sel, L, Kmax] / [B, h_sel, L]. Since S == L, the bottom-right-aligned logical
+// position q_abs = S - L + l reduces to q_abs == l. When causal, the current (possibly
+// incomplete) block is never in sel_indices/sel_count -- this oracle derives and attends it
+// itself, matching the CPU node's own automatic tail derivation.
+std::vector<float> run_sparse_sdpa_reference(size_t len,
+ size_t kmax,
+ size_t batch,
+ size_t h_sel,
+ bool causal,
+ size_t k_head_size,
+ size_t sel_block_size,
+ float scale,
+ const std::vector<float>& query,
+ const std::vector<float>& key,
+ const std::vector<float>& value,
+ const std::vector<int32_t>& sel_indices,
+ const std::vector<int32_t>& sel_count,
+ const std::vector<size_t>& key_length) {
+ auto key_at = [&](size_t b, size_t head, size_t pos) {
+ return &key[((b * kHkv + head) * len + pos) * k_head_size];
+ };
+ auto value_at = [&](size_t b, size_t head, size_t pos) {
+ return &value[((b * kHkv + head) * len + pos) * kDv];
+ };
+
+ std::vector<float> output(batch * kHq * len * kDv, 0.0F);
+ const size_t group = kHq / kHkv;
+ const size_t q_per_sel = kHq / h_sel;
+ for (size_t b = 0; b < batch; b++) {
+ // pad = physically-empty rows at the front of batch b's dense [Hkv, S, D] K/V history;
+ // key_length empty means no padding (pad == 0 for every batch), matching today's behavior.
+ const int64_t pad = key_length.empty() ? 0 : static_cast<int64_t>(len) - static_cast<int64_t>(key_length[b]);
+ for (size_t l = 0; l < len; l++) {
+ const int64_t token_pos = static_cast<int64_t>(l);
+ for (size_t h = 0; h < kHq; h++) {
+ const size_t kv_head = h / group;
+ const size_t sh = h / q_per_sel;
+ const float* q = &query[((b * kHq + h) * len + l) * k_head_size];
+ std::vector<float> acc(kDv, 0.0F);
+ float running_max = -std::numeric_limits<float>::infinity();
+ float running_sum = 0.0F;
+ // One online-softmax step for key/value position `kpos`: score = (q . K) * scale, rescale the running
+ // max/sum by corr, then acc = acc * corr + p * V. Positions outside the valid history are skipped.
+ auto attend_token = [&](int64_t kpos) {
+ if (kpos < pad || kpos >= static_cast<int64_t>(len)) {
+ return;
+ }
+ if (causal && kpos > token_pos) {
+ return;
+ }
+ const float* k = key_at(b, kv_head, static_cast<size_t>(kpos));
+ const float* v = value_at(b, kv_head, static_cast<size_t>(kpos));
+ float dot = 0.0F;
+ for (size_t d = 0; d < k_head_size; d++) {
+ dot += q[d] * k[d];
+ }
+ const float score = dot * scale;
+ const float new_max = std::max(running_max, score);
+ const float corr = std::exp(running_max - new_max);
+ const float p = std::exp(score - new_max);
+ running_sum = running_sum * corr + p;
+ for (size_t d = 0; d < kDv; d++) {
+ acc[d] = acc[d] * corr + p * v[d];
+ }
+ running_max = new_max;
+ };
+
+ const size_t nblocks = static_cast<size_t>(sel_count[(b * h_sel + sh) * len + l]);
+ for (size_t i = 0; i < nblocks; i++) {
+ const int64_t block_id = sel_indices[((b * h_sel + sh) * len + l) * kmax + i];
+ const int64_t block_start = pad + block_id * static_cast<int64_t>(sel_block_size);
+ for (int64_t p = block_start; p < block_start + static_cast<int64_t>(sel_block_size); p++) {
+ attend_token(p);
+ }
+ }
+
+ // sel_indices/sel_count only ever carry *complete* selected blocks -- the current
+ // (possibly incomplete) block is never in them. When causal, the consumer derives
+ // and attends that tail itself from the query's own logical position.
+ if (causal) {
+ const int64_t tail_start = pad + (((token_pos - pad + 1) / static_cast<int64_t>(sel_block_size)) *
+ static_cast<int64_t>(sel_block_size));
+ for (int64_t p = tail_start; p <= token_pos; p++) {
+ attend_token(p);
+ }
+ }
+
+ const float inv_sum = running_sum > 0.0F ? 1.0F / running_sum : 0.0F;
+ for (size_t d = 0; d < kDv; d++) {
+ output[((b * kHq + h) * len + l) * kDv + d] = acc[d] * inv_sum;
+ }
+ }
+ }
+ }
+ return output;
+}
+
+} // namespace
+
+namespace ov {
+namespace test {
+
+std::string SparseSDPALayerCPUTest::getTestCaseName(const testing::TestParamInfo<SparseSDPALayerTestParams>& obj) {
+ const auto& [device, data_precision, h_sel, causal, batch, k_head_size, sel_block_size, key_length, shape] =
+ obj.param;
+ std::string name = "Target=" + device + "_DataPrecision=" + data_precision.get_type_name() +
+ "_Hsel=" + std::to_string(h_sel) + "_Causal=" + std::to_string(causal) +
+ "_Batch=" + std::to_string(batch) + "_Dh=" + std::to_string(k_head_size) +
+ "_Bk=" + std::to_string(sel_block_size) + "_Len=" + std::to_string(shape.seq_len) +
+ "_Kmax=" + std::to_string(shape.max_blocks) + "_Step=" + std::to_string(shape.block_step);
+ if (shape.shuffle) {
+ name += "_Shuffled";
+ }
+ if (!key_length.empty()) {
+ name += "_KeyLength";
+ for (auto len : key_length) {
+ name += "_" + std::to_string(len);
+ }
+ }
+ return name;
+}
+
+void SparseSDPALayerCPUTest::SetUp() {
+ const auto& [device, data_precision, h_sel, causal, batch, k_head_size, sel_block_size, key_length, shape] =
+ GetParam();
+ targetDevice = device;
+ m_data_precision = data_precision;
+ m_h_sel = h_sel;
+ m_causal = causal;
+ m_batch = batch;
+ m_k_head_size = k_head_size;
+ m_sel_block_size = sel_block_size;
+ m_key_length = key_length;
+ m_shape = shape;
+ m_scale = 1.0F / std::sqrt(static_cast<float>(m_k_head_size));
+ rel_threshold = 1e-3F;
+ abs_threshold = 1e-4F;
+ if (data_precision == ov::element::bf16) {
+ rel_threshold = 1e-2F;
+ abs_threshold = 1e-2F;
+ } else if (data_precision == ov::element::f16) {
+ rel_threshold = 1e-3F;
+ abs_threshold = 1e-3F;
+ }
+
+ auto p_query = std::make_shared<ov::op::v0::Parameter>(data_precision,
+ ov::Shape{m_batch, kHq, m_shape.seq_len, m_k_head_size});
+ auto p_key = std::make_shared<ov::op::v0::Parameter>(data_precision,
+ ov::Shape{m_batch, kHkv, m_shape.seq_len, m_k_head_size});
+ auto p_value =
+ std::make_shared<ov::op::v0::Parameter>(data_precision, ov::Shape{m_batch, kHkv, m_shape.seq_len, kDv});
+ auto p_sel_indices =
+ std::make_shared<ov::op::v0::Parameter>(ov::element::i32,
+ ov::Shape{m_batch, m_h_sel, m_shape.seq_len, m_shape.max_blocks});
+ auto p_sel_count =
+ std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{m_batch, m_h_sel, m_shape.seq_len});
+
+ std::vector<ov::Shape> input_shapes = {p_query->get_shape(),
+ p_key->get_shape(),
+ p_value->get_shape(),
+ p_sel_indices->get_shape(),
+ p_sel_count->get_shape()};
+ ov::ParameterVector params = {p_query, p_key, p_value, p_sel_indices, p_sel_count};
+ ov::OutputVector args = {p_query, p_key, p_value, p_sel_indices, p_sel_count};
+
+ std::shared_ptr<ov::op::v0::Parameter> p_key_length;
+ if (!m_key_length.empty()) {
+ p_key_length = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{m_batch});
+ input_shapes.push_back(p_key_length->get_shape());
+ params.push_back(p_key_length);
+ args.push_back(p_key_length);
+ }
+
+ init_input_shapes(static_shapes_to_test_representation(input_shapes));
+
+ auto sparse_sdpa = std::make_shared<ov::op::v17::SparseAttention>(args,
+ static_cast<int64_t>(m_sel_block_size),
+ /*query_block_size=*/1,
+ m_causal);
+
+ function = std::make_shared<ov::Model>(ov::ResultVector{std::make_shared<ov::op::v0::Result>(sparse_sdpa)}, params);
+}
+
+void SparseSDPALayerCPUTest::generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) {
+ inputs.clear();
+ host_inputs.clear();
+
+ const auto assign_precision = [this](ov::Tensor& t, const std::vector<float>& data) {
+ if (m_data_precision == ov::element::bf16) {
+ auto* dst = t.data<ov::bfloat16>();
+ for (size_t i = 0; i < data.size(); i++) {
+ dst[i] = ov::bfloat16(data[i]);
+ }
+ } else if (m_data_precision == ov::element::f16) {
+ auto* dst = t.data<ov::float16>();
+ for (size_t i = 0; i < data.size(); i++) {
+ dst[i] = ov::float16(data[i]);
+ }
+ } else {
+ std::copy(data.begin(), data.end(), t.data<float>());
+ }
+ };
+ const auto make_data = [this, &assign_precision](const ov::Shape& shape, uint32_t seed) {
+ ov::Tensor t(m_data_precision, shape);
+ std::vector<float> data(t.get_size());
+ fill_pseudo_random(data, seed);
+ assign_precision(t, data);
+ return t;
+ };
+ const auto make_index = [](const std::vector<int32_t>& values, const ov::Shape& shape) {
+ ov::Tensor t(ov::element::i32, shape);
+ std::copy(values.begin(), values.end(), t.data<int32_t>());
+ return t;
+ };
+
+ const auto& params = function->get_parameters();
+ std::vector<ov::Tensor> tensors(params.size());
+ tensors[0] = make_data(ov::Shape{m_batch, kHq, m_shape.seq_len, m_k_head_size}, 1);
+ {
+ // Each batch slot gets a distinct seed so a kernel bug that reused batch 0's cache slot
+ // for batch 1 produces numerically different (and thus detectable) output.
+ ov::Tensor key(m_data_precision, ov::Shape{m_batch, kHkv, m_shape.seq_len, m_k_head_size});
+ ov::Tensor value(m_data_precision, ov::Shape{m_batch, kHkv, m_shape.seq_len, kDv});
+ const size_t key_per_batch = kHkv * m_shape.seq_len * m_k_head_size;
+ const size_t value_per_batch = kHkv * m_shape.seq_len * kDv;
+ std::vector<float> key_data(key.get_size());
+ std::vector<float> value_data(value.get_size());
+ for (size_t b = 0; b < m_batch; b++) {
+ std::vector<float> key_slot(key_per_batch);
+ std::vector<float> value_slot(value_per_batch);
+ fill_pseudo_random(key_slot, 2 + static_cast<uint32_t>(b) * 11U);
+ fill_pseudo_random(value_slot, 3 + static_cast<uint32_t>(b) * 11U);
+ std::copy(key_slot.begin(), key_slot.end(), key_data.begin() + static_cast<ptrdiff_t>(b * key_per_batch));
+ std::copy(value_slot.begin(),
+ value_slot.end(),
+ value_data.begin() + static_cast<ptrdiff_t>(b * value_per_batch));
+ }
+ assign_precision(key, key_data);
+ assign_precision(value, value_data);
+ tensors[1] = key;
+ tensors[2] = value;
+ }
+
+ // Synthetic selection: the up-to-m_shape.max_blocks *complete* blocks immediately strictly before the
+ // query's own block, in ascending order (or shuffled, see below) -- per the documented producer contract, the
+ // current (possibly incomplete) block must never appear in sel_indices/sel_count, and the blocks of a row are
+ // duplicate-free; the consumer derives and attends the current block automatically instead. Picking a run of
+ // consecutive preceding blocks (rather than just one) exercises the CPU node's AMX adjacent-block-merging path.
+ // Shared across batch items (only the underlying K/V differs), so a bug that mixed up batch indices for the K/V
+ // cache still gets caught via numerically different output. Block ids are counted from the start of each batch
+ // item's *real* (non-padded) history -- physical row `pad + block_id * sel_block_size`, per the producer contract
+ // -- so with padding the query's own logical block is (l - pad) / sel_block_size rather than l / sel_block_size.
+ // pad == 0 for every batch when m_key_length is empty, reducing to the original formula exactly.
+ // The order of the selected blocks of a row is up to the producer (SparseAttention does not depend on it):
+ // ascending like the CPU indexer returns them, or, with m_shape.shuffle, random.
+ std::mt19937 shuffle_gen(2026);
+ std::vector<int32_t> sel_indices_flat(m_batch * m_h_sel * m_shape.seq_len * m_shape.max_blocks, -1);
+ std::vector<int32_t> sel_count_flat(m_batch * m_h_sel * m_shape.seq_len, 0);
+ for (size_t b = 0; b < m_batch; b++) {
+ const int64_t pad =
+ m_key_length.empty() ? 0 : static_cast<int64_t>(m_shape.seq_len) - static_cast<int64_t>(m_key_length[b]);
+ for (size_t l = 0; l < m_shape.seq_len; l++) {
+ const int64_t rel_pos = static_cast<int64_t>(l) - pad;
+ const int32_t cur_block =
+ rel_pos >= 0 ? static_cast<int32_t>(rel_pos / static_cast<int64_t>(m_sel_block_size)) : 0;
+ const size_t num_sel =
+ rel_pos >= 0 ? std::min(static_cast<size_t>(cur_block) / m_shape.block_step, m_shape.max_blocks) : 0;
+ for (size_t sh = 0; sh < m_h_sel; sh++) {
+ const size_t base = (b * m_h_sel + sh) * m_shape.seq_len + l;
+ for (size_t k = 0; k < num_sel; k++) {
+ sel_indices_flat[base * m_shape.max_blocks + k] =
+ cur_block - static_cast<int32_t>(m_shape.block_step * (num_sel - k));
+ }
+ if (m_shape.shuffle) {
+ auto* row = sel_indices_flat.data() + base * m_shape.max_blocks;
+ std::shuffle(row, row + num_sel, shuffle_gen);
+ }
+ sel_count_flat[base] = static_cast<int32_t>(num_sel);
+ }
+ }
+ }
+ tensors[3] = make_index(sel_indices_flat, ov::Shape{m_batch, m_h_sel, m_shape.seq_len, m_shape.max_blocks});
+ tensors[4] = make_index(sel_count_flat, ov::Shape{m_batch, m_h_sel, m_shape.seq_len});
+
+ if (!m_key_length.empty()) {
+ std::vector<int32_t> key_length_flat(m_key_length.size());
+ std::transform(m_key_length.begin(), m_key_length.end(), key_length_flat.begin(), [](size_t v) {
+ return static_cast<int32_t>(v);
+ });
+ tensors[5] = make_index(key_length_flat, ov::Shape{m_batch});
+ }
+
+ for (size_t i = 0; i < params.size(); i++) {
+ host_inputs[params[i]] = tensors[i];
+ inputs[params[i]] = tensors[i];
+ }
+}
+
+std::vector<ov::Tensor> SparseSDPALayerCPUTest::calculate_refs() {
+ const auto& params = function->get_parameters();
+ const auto to_f32 = [&](const std::shared_ptr<ov::Node>& p) {
+ const auto& t = host_inputs.at(p);
+ std::vector<float> out(t.get_size());
+ if (t.get_element_type() == ov::element::bf16) {
+ const auto* ptr = t.data<const ov::bfloat16>();
+ std::copy(ptr, ptr + t.get_size(), out.begin());
+ } else if (t.get_element_type() == ov::element::f16) {
+ const auto* ptr = t.data<const ov::float16>();
+ std::copy(ptr, ptr + t.get_size(), out.begin());
+ } else {
+ const auto* ptr = t.data<const float>();
+ std::copy(ptr, ptr + t.get_size(), out.begin());
+ }
+ return out;
+ };
+ const auto to_i32 = [&](const std::shared_ptr<ov::Node>& p) {
+ const auto& t = host_inputs.at(p);
+ const auto* ptr = t.data<const int32_t>();
+ return std::vector<int32_t>(ptr, ptr + t.get_size());
+ };
+
+ auto query = to_f32(params[0]);
+ auto key = to_f32(params[1]);
+ auto value = to_f32(params[2]);
+ auto sel_indices = to_i32(params[3]);
+ auto sel_count = to_i32(params[4]);
+
+ auto output = run_sparse_sdpa_reference(m_shape.seq_len,
+ m_shape.max_blocks,
+ m_batch,
+ m_h_sel,
+ m_causal,
+ m_k_head_size,
+ m_sel_block_size,
+ m_scale,
+ query,
+ key,
+ value,
+ sel_indices,
+ sel_count,
+ m_key_length);
+
+ ov::Tensor output_tensor(ov::element::f32, ov::Shape{m_batch, kHq, m_shape.seq_len, kDv});
+ std::copy(output.begin(), output.end(), output_tensor.data<float>());
+ return {output_tensor};
+}
+
+void SparseSDPALayerCPUTest::compare(const std::vector<ov::Tensor>& expected, const std::vector<ov::Tensor>& actual) {
+ ASSERT_EQ(expected.size(), actual.size());
+ for (size_t i = 0; i < expected.size(); i++) {
+ ov::test::utils::compare(expected[i], actual[i], abs_threshold, rel_threshold);
+ }
+}
+
+TEST_P(SparseSDPALayerCPUTest, CompareWithRefs) {
+ run();
+}
+
+} // namespace test
+} // namespace ov
diff --git a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/sparse_sdpa.hpp b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/sparse_sdpa.hpp
new file mode 100644
index 00000000000..62eabc54188
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/sparse_sdpa.hpp
@@ -0,0 +1,63 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+#include <map>
+#include <memory>
+#include <string>
+#include <tuple>
+#include <vector>
+
+#include "openvino/core/type/element_type.hpp"
+#include "shared_test_classes/base/ov_subgraph.hpp"
+
+namespace ov {
+namespace test {
+
+// Shape knobs that are not part of the op; the defaults are the small shape of the smoke tests (S == L,
+// so the query at index l attends positions up to l).
+struct SparseSDPAShape {
+ size_t seq_len = 40; // L == S
+ size_t max_blocks = 10; // K_max: the width of block_indices
+ size_t block_step = 1; // distance between the selected blocks: 2 selects every second block (no adjacent runs)
+ bool shuffle =
+ false; // the selected blocks of a row in random order instead of ascending (the order does not matter)
+};
+
+// target device, data precision (query/key/value), h_sel, causal, batch (B; plain batched dense
+// K/V history, see classes/sparse_sdpa.cpp), k_head_size, sel_block_size, per-batch key_length
+// (empty = no padding / 5-input op, matching today's behavior exactly; otherwise one entry per
+// batch item in [1, seq_len], builds the 6-input op with KEY_LENGTH), shape knobs
+using SparseSDPALayerTestParams = std::
+ tuple<std::string, ov::element::Type, size_t, bool, size_t, size_t, size_t, std::vector<size_t>, SparseSDPAShape>;
+
+class SparseSDPALayerCPUTest : public testing::WithParamInterface<SparseSDPALayerTestParams>,
+ virtual public SubgraphBaseTest {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<SparseSDPALayerTestParams>& obj);
+
+protected:
+ void SetUp() override;
+ void generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) override;
+ std::vector<ov::Tensor> calculate_refs() override;
+ void compare(const std::vector<ov::Tensor>& expected, const std::vector<ov::Tensor>& actual) override;
+
+private:
+ std::map<std::shared_ptr<ov::Node>, ov::Tensor> host_inputs;
+ ov::element::Type m_data_precision = ov::element::f32;
+ size_t m_h_sel = 1;
+ bool m_causal = true;
+ size_t m_batch = 1;
+ size_t m_k_head_size = 16;
+ size_t m_sel_block_size = 2;
+ float m_scale = 0.25F;
+ std::vector<size_t> m_key_length;
+ SparseSDPAShape m_shape;
+};
+
+} // namespace test
+} // namespace ov
diff --git a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/paged_qsa_indexer.cpp b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/paged_qsa_indexer.cpp
new file mode 100644
index 00000000000..5d092ad6b91
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/paged_qsa_indexer.cpp
@@ -0,0 +1,73 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "custom/single_layer_tests/classes/paged_qsa_indexer.hpp"
+
+#include "utils/cpu_test_utils.hpp"
+
+namespace ov {
+namespace test {
+
+// H_iq == H_ik, h_sel == 1: every index-query head contributes to the single selection head.
+INSTANTIATE_TEST_SUITE_P(smoke_PagedQSAIndexer_CPU_Hsel1,
+ PagedQSAIndexerLayerCPUTest,
+ testing::Combine(testing::Values(ov::test::utils::DEVICE_CPU),
+ testing::Values(ov::element::f32, ov::element::f16, ov::element::bf16),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(1)),
+ testing::Values(static_cast<size_t>(1), static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(7)),
+ testing::Values(static_cast<size_t>(4))),
+ PagedQSAIndexerLayerCPUTest::getTestCaseName);
+
+// H_iq = 2 * H_ik, h_sel == H_ik: exercises the grouped per-selection-head scoring path.
+INSTANTIATE_TEST_SUITE_P(smoke_PagedQSAIndexer_CPU_HselEqualsHik,
+ PagedQSAIndexerLayerCPUTest,
+ testing::Combine(testing::Values(ov::test::utils::DEVICE_CPU),
+ testing::Values(ov::element::f32, ov::element::f16, ov::element::bf16),
+ testing::Values(static_cast<size_t>(4)),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(1), static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(7)),
+ testing::Values(static_cast<size_t>(4))),
+ PagedQSAIndexerLayerCPUTest::getTestCaseName);
+
+// Other query lengths: a decode step (1 token: a block completes or not, nothing or the past blocks to score) and a
+// chunk of 20 tokens (more blocks than block_topk, several pages, a sequence with enough tokens to spread over
+// threads), one and two sequences.
+INSTANTIATE_TEST_SUITE_P(smoke_PagedQSAIndexer_CPU_Lengths,
+ PagedQSAIndexerLayerCPUTest,
+ testing::Combine(testing::Values(ov::test::utils::DEVICE_CPU),
+ testing::Values(ov::element::f32, ov::element::bf16),
+ testing::Values(static_cast<size_t>(4)),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(1), static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(1), static_cast<size_t>(20)),
+ testing::Values(static_cast<size_t>(4))),
+ PagedQSAIndexerLayerCPUTest::getTestCaseName);
+
+// Pages of the size of a real cache, long sequences: the scoring takes 32 blocks at a time, which lie in one page
+// (128 tokens = 64 blocks per page, used in place), run over two (96 tokens = 48 blocks per page, gathered), or are
+// the blocks of many tiny pages; several tiles of tokens, a decode step over a long cache, a group of heads.
+// The oracle keeps the block keys in f32 while the kernel stores them in the cache precision, so with 150 blocks to
+// choose the best 2 from, a 16-bit cache flips a few near-tied selections (the reference scalar kernel does the same):
+// the test allows a small fraction of the indices to differ for the 16-bit precisions (see compare()).
+INSTANTIATE_TEST_SUITE_P(
+ smoke_PagedQSAIndexer_CPU_LongSequences,
+ PagedQSAIndexerLayerCPUTest,
+ testing::Combine(testing::Values(ov::test::utils::DEVICE_CPU),
+ testing::Values(ov::element::f32, ov::element::bf16),
+ testing::Values(static_cast<size_t>(4)),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(1), static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(1), static_cast<size_t>(300)),
+ testing::Values(static_cast<size_t>(8), static_cast<size_t>(96), static_cast<size_t>(128))),
+ PagedQSAIndexerLayerCPUTest::getTestCaseName);
+
+} // namespace test
+} // namespace ov
\ No newline at end of file
diff --git a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/qsa_indexer.cpp b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/qsa_indexer.cpp
new file mode 100644
index 00000000000..3b6a35e617b
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/qsa_indexer.cpp
@@ -0,0 +1,99 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "custom/single_layer_tests/classes/qsa_indexer.hpp"
+
+#include "utils/cpu_test_utils.hpp"
+
+namespace ov {
+namespace test {
+
+// Dense (no padding) single-call prefill: H_iq == H_ik, h_sel == 1.
+INSTANTIATE_TEST_SUITE_P(smoke_QSAIndexer_CPU_DensePrefill_Hsel1,
+ QSAIndexerLayerCPUTest,
+ testing::Combine(testing::Values(ov::test::utils::DEVICE_CPU),
+ testing::Values(ov::element::f32, ov::element::f16, ov::element::bf16),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(1)),
+ testing::Values(static_cast<size_t>(1), static_cast<size_t>(2)),
+ testing::Values(QSAIndexerScenario::kDensePrefill),
+ testing::Values(false)),
+ QSAIndexerLayerCPUTest::getTestCaseName);
+
+// Dense (no padding) single-call prefill: H_iq = 2 * H_ik, h_sel == H_ik.
+INSTANTIATE_TEST_SUITE_P(smoke_QSAIndexer_CPU_DensePrefill_HselEqualsHik,
+ QSAIndexerLayerCPUTest,
+ testing::Combine(testing::Values(ov::test::utils::DEVICE_CPU),
+ testing::Values(ov::element::f32, ov::element::f16, ov::element::bf16),
+ testing::Values(static_cast<size_t>(4)),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(1), static_cast<size_t>(2)),
+ testing::Values(QSAIndexerScenario::kDensePrefill),
+ testing::Values(false)),
+ QSAIndexerLayerCPUTest::getTestCaseName);
+
+// new_spec/qsa-prepare-17.rst's worked example verbatim: left-padded prefill followed by a decode
+// call that completes an incomplete tail block. Scenario forces batch == 2; the batch axis here is
+// a don't-care placeholder.
+INSTANTIATE_TEST_SUITE_P(smoke_QSAIndexer_CPU_WorkedExample,
+ QSAIndexerLayerCPUTest,
+ testing::Combine(testing::Values(ov::test::utils::DEVICE_CPU),
+ testing::Values(ov::element::f32, ov::element::f16, ov::element::bf16),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(1)),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(QSAIndexerScenario::kWorkedExample),
+ testing::Values(false)),
+ QSAIndexerLayerCPUTest::getTestCaseName);
+
+// A row without any real token (key_length == 0) next to a regular one, then that row starting from scratch.
+// H_iq in {2, 4} x h_sel in {1, 2} with H_ik == 2.
+INSTANTIATE_TEST_SUITE_P(smoke_QSAIndexer_CPU_FullyPaddedRow,
+ QSAIndexerLayerCPUTest,
+ testing::Combine(testing::Values(ov::test::utils::DEVICE_CPU),
+ testing::Values(ov::element::f32, ov::element::f16, ov::element::bf16),
+ testing::Values(static_cast<size_t>(2), static_cast<size_t>(4)),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(1), static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(QSAIndexerScenario::kFullyPaddedRow),
+ testing::Values(false)),
+ QSAIndexerLayerCPUTest::getTestCaseName);
+
+// Several calls with L > 1 and different past lengths per row (non-empty incomplete-block tails, blocks completed
+// mid-call and exactly at the end of a call).
+INSTANTIATE_TEST_SUITE_P(smoke_QSAIndexer_CPU_RaggedCalls,
+ QSAIndexerLayerCPUTest,
+ testing::Combine(testing::Values(ov::test::utils::DEVICE_CPU),
+ testing::Values(ov::element::f32, ov::element::f16, ov::element::bf16),
+ testing::Values(static_cast<size_t>(2), static_cast<size_t>(4)),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(1), static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(QSAIndexerScenario::kRaggedCalls),
+ testing::Values(false)),
+ QSAIndexerLayerCPUTest::getTestCaseName);
+
+// The chosen blocks of a row by descending score (equal scores: ascending block id), the order of
+// SparseAttentionIndexer-17, instead of ascending block ids: dense prefill with one and with several selection heads,
+// the worked example and calls with ragged lengths (which also cover the tokens that take all their blocks).
+INSTANTIATE_TEST_SUITE_P(smoke_QSAIndexer_CPU_OrderByScore,
+ QSAIndexerLayerCPUTest,
+ testing::Combine(testing::Values(ov::test::utils::DEVICE_CPU),
+ testing::Values(ov::element::f32, ov::element::f16, ov::element::bf16),
+ testing::Values(static_cast<size_t>(2), static_cast<size_t>(4)),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(1), static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(QSAIndexerScenario::kDensePrefill,
+ QSAIndexerScenario::kWorkedExample,
+ QSAIndexerScenario::kRaggedCalls),
+ testing::Values(true)),
+ QSAIndexerLayerCPUTest::getTestCaseName);
+
+} // namespace test
+} // namespace ov
diff --git a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/sparse_pa.cpp b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/sparse_pa.cpp
new file mode 100644
index 00000000000..9e7d7dc0236
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/sparse_pa.cpp
@@ -0,0 +1,400 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "custom/single_layer_tests/classes/sparse_pa.hpp"
+
+#include "utils/cpu_test_utils.hpp"
+
+namespace ov {
+namespace test {
+
+namespace {
+
+constexpr size_t kNumHeads = 4;
+
+// Decode steps at the positions 3, 4, 5, ... after a 3-token prefill: the causal boundaries around key_block_size 2 and
+// 4 (the position ends a block, starts one, and is the second token of one), where the incomplete tail block of the
+// query is empty or not and a block becomes selectable.
+const std::vector<size_t> kBoundarySteps = {3, 1, 1, 1, 1, 1, 1, 5, 1};
+// A prefill that stops in the middle of a page, a chunked prefill that crosses a page boundary (29 + 8 > 32), decode
+// steps on the partially filled pages and another chunk: every call continues the caches the previous ones wrote.
+const std::vector<size_t> kChunkedSteps = {29, 8, 1, 1, 32, 1};
+// Prefill lengths around the 32 rows of a brgemm chunk (31, 32) and the 128 rows of a tile (the 254-token chunk after
+// 64 tokens of history: the selection of a token grows from 65 to 318 rows, so it crosses one tile boundary at 128 rows
+// and ends exactly on the next one at 256), then a chunk after a long history. 128 selectable blocks of 4 tokens,
+// kRecent.
+const std::vector<size_t> kLongSteps = {31, 1, 32, 254, 2};
+
+enum class Batch {
+ kSingle, // one sequence
+ kMixed, // three sequences: a prefill, a decode and a shorter chunk in the same call (see SparsePAConfig)
+ kLong, // one sequence, long steps
+};
+
+// One test: the steps follow the PagedAttention tests' [L, B, H, S] form (consecutive calls of the same B sequences).
+SparsePALayerTestParams make_case(ov::element::Type data_precision, size_t head_size, Batch batch, SparsePAConfig cfg) {
+ const bool mixed = batch == Batch::kMixed;
+ const size_t sequences = mixed ? 3 : 1;
+ std::vector<ov::Shape> targets;
+ for (const auto len : batch == Batch::kLong ? kLongSteps : mixed ? kChunkedSteps : kBoundarySteps) {
+ targets.push_back({len, sequences, kNumHeads, head_size});
+ }
+ cfg.mixed_lengths = mixed;
+ const std::vector<InputShape> steps = {{ov::PartialShape{-1,
+ static_cast<int64_t>(sequences),
+ static_cast<int64_t>(kNumHeads),
+ static_cast<int64_t>(head_size)},
+ targets}};
+ return {data_precision, steps, cfg};
+}
+
+SparsePAConfig plain_config(size_t sel_head_num,
+ size_t key_block_size,
+ size_t page_size,
+ size_t max_selected_blocks,
+ SparsePASelection selection,
+ size_t v_head_size = 16) {
+ SparsePAConfig cfg;
+ cfg.num_selection_heads = sel_head_num;
+ cfg.v_head_size = v_head_size;
+ cfg.key_block_size = key_block_size;
+ cfg.page_size = page_size;
+ cfg.max_selected_blocks = max_selected_blocks;
+ cfg.selection = selection;
+ return cfg;
+}
+
+// Quantized caches as ConvertPagedAttnInputs produces them: 32-token pages, key_block_size 4.
+SparsePAConfig quantized_config(ov::element::Type cache_precision,
+ bool key_bychannel,
+ size_t group_size,
+ size_t sel_head_num,
+ SparsePASelection selection,
+ size_t v_head_size = 16,
+ size_t max_selected_blocks = 8) {
+ auto cfg = plain_config(sel_head_num, 4, 32, max_selected_blocks, selection, v_head_size);
+ cfg.cache_precision = cache_precision;
+ cfg.key_bychannel = key_bychannel;
+ cfg.group_size = group_size;
+ return cfg;
+}
+
+constexpr auto kRecent = SparsePASelection::kRecent;
+constexpr auto kRandom = SparsePASelection::kRandom;
+constexpr auto kEmpty = SparsePASelection::kEmpty;
+
+// Plain caches on the vector kernels: every data precision, selection head counts of 1 / K heads / query heads, tiny
+// pages (selected blocks straddle pages) and every selection mode. The worker threads follow from the steps (see the
+// test's SetUp): the multi-token calls pack the query heads of a K head, the decode steps do not.
+std::vector<SparsePALayerTestParams> plain_cases() {
+ const auto f32 = ov::element::f32;
+ const auto f16 = ov::element::f16;
+ const auto bf16 = ov::element::bf16;
+ return {make_case(f32,
+ /*head_size=*/16,
+ Batch::kSingle,
+ plain_config(/*sel_heads=*/1,
+ /*key_block_size=*/2,
+ /*page_size=*/4,
+ /*max_blocks=*/4,
+ /*selection=*/kRecent)),
+ make_case(f16,
+ /*head_size=*/16,
+ Batch::kSingle,
+ plain_config(/*sel_heads=*/2,
+ /*key_block_size=*/2,
+ /*page_size=*/8,
+ /*max_blocks=*/4,
+ /*selection=*/kRandom)),
+ make_case(bf16,
+ /*head_size=*/16,
+ Batch::kMixed,
+ plain_config(/*sel_heads=*/kNumHeads,
+ /*key_block_size=*/2,
+ /*page_size=*/8,
+ /*max_blocks=*/4,
+ /*selection=*/kRandom)),
+ make_case(f32,
+ /*head_size=*/16,
+ Batch::kMixed,
+ plain_config(/*sel_heads=*/1,
+ /*key_block_size=*/2,
+ /*page_size=*/4,
+ /*max_blocks=*/4,
+ /*selection=*/kEmpty)),
+ make_case(bf16,
+ /*head_size=*/16,
+ Batch::kMixed,
+ plain_config(/*sel_heads=*/2,
+ /*key_block_size=*/2,
+ /*page_size=*/8,
+ /*max_blocks=*/4,
+ /*selection=*/kRecent)),
+ make_case(f16,
+ /*head_size=*/16,
+ Batch::kMixed,
+ plain_config(/*sel_heads=*/1,
+ /*key_block_size=*/2,
+ /*page_size=*/4,
+ /*max_blocks=*/4,
+ /*selection=*/kRandom))};
+}
+
+// AMX brgemm path (see sparse_brgemm_kernel.hpp), bf16 end to end (AMX f16 needs amx_fp16): key_block_size 4 with pages
+// that fit several blocks or only one, so adjacent selected blocks of a page are attended as one run. Head sizes 32,
+// 128 and 256 (the Qwen head size). v_head_size differs from the key head size to catch any coupling of the two. A
+// selection head per query head (no pack) keeps the prefill on the per-head AMX path.
+std::vector<SparsePALayerTestParams> amx_cases() {
+ const auto bf16 = ov::element::bf16;
+ return {make_case(bf16,
+ /*head_size=*/32,
+ Batch::kMixed,
+ plain_config(/*sel_heads=*/1,
+ /*key_block_size=*/4,
+ /*page_size=*/16,
+ /*max_blocks=*/4,
+ /*selection=*/kRecent)),
+ make_case(bf16,
+ /*head_size=*/32,
+ Batch::kMixed,
+ plain_config(/*sel_heads=*/1,
+ /*key_block_size=*/4,
+ /*page_size=*/64,
+ /*max_blocks=*/16,
+ /*selection=*/kRandom)),
+ make_case(bf16,
+ /*head_size=*/32,
+ Batch::kMixed,
+ plain_config(/*sel_heads=*/kNumHeads,
+ /*key_block_size=*/4,
+ /*page_size=*/32,
+ /*max_blocks=*/8,
+ /*selection=*/kRandom)),
+ // one sequence: the decode steps pack the query heads (the mixed batches run one head per decode item)
+ make_case(bf16,
+ /*head_size=*/32,
+ Batch::kSingle,
+ plain_config(/*sel_heads=*/1,
+ /*key_block_size=*/4,
+ /*page_size=*/32,
+ /*max_blocks=*/8,
+ /*selection=*/kRandom)),
+ make_case(bf16,
+ /*head_size=*/32,
+ Batch::kMixed,
+ plain_config(/*sel_heads=*/2,
+ /*key_block_size=*/4,
+ /*page_size=*/64,
+ /*max_blocks=*/16,
+ /*selection=*/kRecent)),
+ make_case(bf16,
+ /*head_size=*/128,
+ Batch::kMixed,
+ plain_config(/*sel_heads=*/1,
+ /*key_block_size=*/4,
+ /*page_size=*/32,
+ /*max_blocks=*/8,
+ /*selection=*/kRandom,
+ /*v_head_size=*/64)),
+ make_case(bf16,
+ /*head_size=*/256,
+ Batch::kMixed,
+ plain_config(/*sel_heads=*/1,
+ /*key_block_size=*/4,
+ /*page_size=*/16,
+ /*max_blocks=*/8,
+ /*selection=*/kRecent,
+ /*v_head_size=*/256)),
+ make_case(bf16,
+ /*head_size=*/256,
+ Batch::kMixed,
+ plain_config(/*sel_heads=*/1,
+ /*key_block_size=*/4,
+ /*page_size=*/64,
+ /*max_blocks=*/8,
+ /*selection=*/kRandom,
+ /*v_head_size=*/128)),
+ make_case(bf16,
+ /*head_size=*/256,
+ Batch::kMixed,
+ plain_config(/*sel_heads=*/2,
+ /*key_block_size=*/4,
+ /*page_size=*/32,
+ /*max_blocks=*/8,
+ /*selection=*/kRandom,
+ /*v_head_size=*/256)),
+ // selections of up to 3 tiles of rows, tails of every length
+ make_case(bf16,
+ /*head_size=*/256,
+ Batch::kLong,
+ plain_config(/*sel_heads=*/1,
+ /*key_block_size=*/4,
+ /*page_size=*/32,
+ /*max_blocks=*/128,
+ /*selection=*/kRecent,
+ /*v_head_size=*/256))};
+}
+
+// Quantized (u8 / u4) caches: by-token and by-channel keys, one group per row or several, one or several selection
+// heads (a selection head per query head keeps the prefill unpacked). Quantized chunks are dequantized to the AMX type,
+// so with bf16 data and a head size that fits the AMX kernel the prefill steps run on it (quantized decode uses the
+// fused direct-quantized kernels).
+std::vector<SparsePALayerTestParams> quantized_cases() {
+ const auto f32 = ov::element::f32;
+ const auto bf16 = ov::element::bf16;
+ const auto u8 = ov::element::u8;
+ const auto u4 = ov::element::u4;
+ return {make_case(f32,
+ /*head_size=*/32,
+ Batch::kMixed,
+ quantized_config(/*cache=*/u8,
+ /*key_bychannel=*/false,
+ /*group_size=*/0,
+ /*sel_heads=*/1,
+ /*selection=*/kRecent)),
+ make_case(f32,
+ /*head_size=*/32,
+ Batch::kMixed,
+ quantized_config(/*cache=*/u4,
+ /*key_bychannel=*/true,
+ /*group_size=*/0,
+ /*sel_heads=*/2,
+ /*selection=*/kRandom)),
+ make_case(bf16,
+ /*head_size=*/32,
+ Batch::kMixed,
+ quantized_config(/*cache=*/u8,
+ /*key_bychannel=*/true,
+ /*group_size=*/16,
+ /*sel_heads=*/1,
+ /*selection=*/kRandom)),
+ make_case(bf16,
+ /*head_size=*/32,
+ Batch::kMixed,
+ quantized_config(/*cache=*/u8,
+ /*key_bychannel=*/false,
+ /*group_size=*/0,
+ /*sel_heads=*/kNumHeads,
+ /*selection=*/kRecent)),
+ make_case(bf16,
+ /*head_size=*/32,
+ Batch::kSingle,
+ quantized_config(/*cache=*/u4,
+ /*key_bychannel=*/false,
+ /*group_size=*/16,
+ /*sel_heads=*/1,
+ /*selection=*/kRandom)),
+ make_case(bf16,
+ /*head_size=*/32,
+ Batch::kMixed,
+ quantized_config(/*cache=*/u4,
+ /*key_bychannel=*/false,
+ /*group_size=*/16,
+ /*sel_heads=*/1,
+ /*selection=*/kRecent)),
+ make_case(bf16,
+ /*head_size=*/32,
+ Batch::kMixed,
+ quantized_config(/*cache=*/u8,
+ /*key_bychannel=*/true,
+ /*group_size=*/0,
+ /*sel_heads=*/2,
+ /*selection=*/kRandom)),
+ // 16 selected blocks span two 32-token pages, so runs of four adjacent blocks inside one page occur.
+ make_case(bf16,
+ /*head_size=*/256,
+ Batch::kMixed,
+ quantized_config(/*cache=*/u8,
+ /*key_bychannel=*/true,
+ /*group_size=*/0,
+ /*sel_heads=*/1,
+ /*selection=*/kRecent,
+ /*v_head_size=*/128,
+ /*max_blocks=*/16)),
+ make_case(bf16,
+ /*head_size=*/256,
+ Batch::kMixed,
+ quantized_config(/*cache=*/u4,
+ /*key_bychannel=*/false,
+ /*group_size=*/16,
+ /*sel_heads=*/1,
+ /*selection=*/kRandom,
+ /*v_head_size=*/256,
+ /*max_blocks=*/16)),
+ make_case(bf16,
+ /*head_size=*/256,
+ Batch::kLong,
+ quantized_config(/*cache=*/u8,
+ /*key_bychannel=*/false,
+ /*group_size=*/0,
+ /*sel_heads=*/1,
+ /*selection=*/kRecent,
+ /*v_head_size=*/256,
+ /*max_blocks=*/128))};
+}
+
+// f16 caches next to f32 data, the one plain cache type that differs from the data type (as in PagedAttention): the
+// inference precision follows the data precision and ConvertPagedAttnInputs gives the caches their type. The SIMD heads
+// read the f16 rows in place.
+std::vector<SparsePALayerTestParams> f16_cache_cases() {
+ const auto f32 = ov::element::f32;
+ const auto with_f16_cache = [](SparsePAConfig cfg) {
+ cfg.cache_precision = ov::element::f16;
+ return cfg;
+ };
+ const auto small = plain_config(/*sel_heads=*/2, /*key_block_size=*/2, /*page_size=*/8, /*max_blocks=*/4, kRandom);
+ const auto tile = plain_config(/*sel_heads=*/1, /*key_block_size=*/4, /*page_size=*/32, /*max_blocks=*/8, kRecent);
+ return {make_case(f32, /*head_size=*/16, Batch::kSingle, with_f16_cache(small)),
+ make_case(f32, /*head_size=*/16, Batch::kMixed, with_f16_cache(small)),
+ make_case(f32, /*head_size=*/32, Batch::kMixed, with_f16_cache(tile))};
+}
+
+// The same cases with the selected blocks of a row in random order instead of ascending (SparseAttention does not
+// depend on the order): no adjacent runs remain.
+std::vector<SparsePALayerTestParams> shuffled(std::vector<SparsePALayerTestParams> cases) {
+ for (auto& test_case : cases) {
+ std::get<2>(test_case).shuffle_blocks = true;
+ }
+ return cases;
+}
+
+} // namespace
+
+INSTANTIATE_TEST_SUITE_P(smoke_SparsePA_CPU_Plain,
+ SparsePALayerCPUTest,
+ testing::ValuesIn(plain_cases()),
+ SparsePALayerCPUTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(smoke_SparsePA_CPU_AMX,
+ SparsePALayerCPUTest,
+ testing::ValuesIn(amx_cases()),
+ SparsePALayerCPUTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(smoke_SparsePA_CPU_QuantizedCache,
+ SparsePALayerCPUTest,
+ testing::ValuesIn(quantized_cases()),
+ SparsePALayerCPUTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(smoke_SparsePA_CPU_F16Cache,
+ SparsePALayerCPUTest,
+ testing::ValuesIn(f16_cache_cases()),
+ SparsePALayerCPUTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(smoke_SparsePA_CPU_Plain_Shuffled,
+ SparsePALayerCPUTest,
+ testing::ValuesIn(shuffled(plain_cases())),
+ SparsePALayerCPUTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(smoke_SparsePA_CPU_AMX_Shuffled,
+ SparsePALayerCPUTest,
+ testing::ValuesIn(shuffled(amx_cases())),
+ SparsePALayerCPUTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(smoke_SparsePA_CPU_QuantizedCache_Shuffled,
+ SparsePALayerCPUTest,
+ testing::ValuesIn(shuffled(quantized_cases())),
+ SparsePALayerCPUTest::getTestCaseName);
+
+} // namespace test
+} // namespace ov
diff --git a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/sparse_sdpa.cpp b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/sparse_sdpa.cpp
new file mode 100644
index 00000000000..bb5a4d30e36
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/sparse_sdpa.cpp
@@ -0,0 +1,202 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "custom/single_layer_tests/classes/sparse_sdpa.hpp"
+
+#include "utils/cpu_test_utils.hpp"
+
+namespace ov {
+namespace test {
+
+// h_sel == 1: a single selection head shared by every query head.
+INSTANTIATE_TEST_SUITE_P(smoke_SparseSDPA_CPU_Hsel1,
+ SparseSDPALayerCPUTest,
+ testing::Combine(testing::Values(ov::test::utils::DEVICE_CPU),
+ testing::Values(ov::element::f32, ov::element::f16, ov::element::bf16),
+ testing::Values(static_cast<size_t>(1)),
+ testing::Values(true, false),
+ testing::Values(static_cast<size_t>(1), static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(16)),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(std::vector<size_t>{}),
+ testing::Values(SparseSDPAShape{})),
+ SparseSDPALayerCPUTest::getTestCaseName);
+
+// h_sel == Hkv: one selection head per kv head, exercises the sh = h / (Hq/h_sel) grouping path.
+INSTANTIATE_TEST_SUITE_P(smoke_SparseSDPA_CPU_HselEqualsHkv,
+ SparseSDPALayerCPUTest,
+ testing::Combine(testing::Values(ov::test::utils::DEVICE_CPU),
+ testing::Values(ov::element::f32, ov::element::f16, ov::element::bf16),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(true, false),
+ testing::Values(static_cast<size_t>(1), static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(16)),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(std::vector<size_t>{}),
+ testing::Values(SparseSDPAShape{})),
+ SparseSDPALayerCPUTest::getTestCaseName);
+
+// AMX paths: bf16 end-to-end, k_head_size % 32 == 0, sel_block_size == 4 (the real Qwen4 production shape). Falls back
+// to the SIMD kernels on non-AMX hardware, with the same pass/fail bar.
+INSTANTIATE_TEST_SUITE_P(smoke_SparseSDPA_CPU_AMX,
+ SparseSDPALayerCPUTest,
+ testing::Combine(testing::Values(ov::test::utils::DEVICE_CPU),
+ testing::Values(ov::element::bf16),
+ testing::Values(static_cast<size_t>(1)),
+ testing::Values(true, false),
+ testing::Values(static_cast<size_t>(1)),
+ // 256 (the Qwen head size) is above the 192 that fit the six B tiles of the
+ // AMX kernel and takes its K-chunk loop.
+ testing::Values(static_cast<size_t>(32), static_cast<size_t>(256)),
+ testing::Values(static_cast<size_t>(4)),
+ testing::Values(std::vector<size_t>{}),
+ testing::Values(SparseSDPAShape{})),
+ SparseSDPALayerCPUTest::getTestCaseName);
+
+// Left-padded batches: KEY_LENGTH input present, one entry per batch item (kCacheLen == kL == 40,
+// see classes/sparse_sdpa.cpp). Covers a batch item with no padding at all (40), one padded short
+// of a sel_block_size boundary (37 -- exercises the pad-not-block-aligned causal-tail path), one
+// padded to exactly a sel_block_size boundary (32), and one so short that some leading queries have
+// no valid history whatsoever (4 -- query rows l < pad must produce all-zero output).
+INSTANTIATE_TEST_SUITE_P(smoke_SparseSDPA_CPU_Padded,
+ SparseSDPALayerCPUTest,
+ testing::Combine(testing::Values(ov::test::utils::DEVICE_CPU),
+ testing::Values(ov::element::f32, ov::element::bf16),
+ testing::Values(static_cast<size_t>(1)),
+ testing::Values(true, false),
+ testing::Values(static_cast<size_t>(4)),
+ testing::Values(static_cast<size_t>(16)),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(std::vector<size_t>{40, 37, 32, 4}),
+ testing::Values(SparseSDPAShape{})),
+ SparseSDPALayerCPUTest::getTestCaseName);
+
+// The left-padded batches of smoke_SparseSDPA_CPU_Padded with an AMX-eligible shape (k_head_size % 32 == 0, see the AMX
+// gate in sparse_sdpa.cpp), so the padded AMX path (attend_amx_chunks()) runs on AMX hardware; elsewhere the scalar
+// kernel runs, with the same pass bar.
+INSTANTIATE_TEST_SUITE_P(smoke_SparseSDPA_CPU_AMX_Padded,
+ SparseSDPALayerCPUTest,
+ testing::Combine(testing::Values(ov::test::utils::DEVICE_CPU),
+ testing::Values(ov::element::bf16),
+ testing::Values(static_cast<size_t>(1)),
+ testing::Values(true, false),
+ testing::Values(static_cast<size_t>(4)),
+ testing::Values(static_cast<size_t>(32)),
+ testing::Values(static_cast<size_t>(4)),
+ testing::Values(std::vector<size_t>{40, 37, 32, 4}),
+ testing::Values(SparseSDPAShape{})),
+ SparseSDPALayerCPUTest::getTestCaseName);
+
+namespace {
+
+SparseSDPALayerTestParams packed_case(size_t h_sel,
+ size_t batch,
+ size_t k_head_size,
+ std::vector<size_t> key_length,
+ SparseSDPAShape shape) {
+ return {ov::test::utils::DEVICE_CPU,
+ ov::element::bf16,
+ h_sel,
+ true,
+ batch,
+ k_head_size,
+ 4,
+ std::move(key_length),
+ shape};
+}
+
+// AMX prefill over packs of query heads: bf16, sel_block_size 4, causal. The shapes are {seq_len, max_blocks,
+// block_step}. The suites above already run the prefill over the 2 query heads of a K head as brgemm products (a
+// prefill takes that path whatever the thread count); these add
+// - a selection of every second block (no adjacent runs) and a selection head per query head (no pack: the per-head
+// AMX
+// path);
+// - prefill lengths around the 32 rows of a brgemm chunk (31, 32) and the 128 rows of a tile (254, 256 tokens: with
+// adjacent blocks the selection of the token at position p has p + 1 rows, so every row count up to the length
+// occurs, the tails of every length, a tile that is exactly full and a partial last tile).
+std::vector<SparseSDPALayerTestParams> packed_cases() {
+ return {packed_case(/*h_sel=*/1,
+ /*batch=*/1,
+ /*head_size=*/256,
+ /*key_length=*/{},
+ {/*seq_len=*/40, /*max_blocks=*/10, /*block_step=*/2}),
+ packed_case(/*h_sel=*/4,
+ /*batch=*/1,
+ /*head_size=*/32,
+ /*key_length=*/{},
+ {/*seq_len=*/40, /*max_blocks=*/10, /*block_step=*/1}),
+ packed_case(/*h_sel=*/1,
+ /*batch=*/1,
+ /*head_size=*/32,
+ /*key_length=*/{},
+ {/*seq_len=*/31, /*max_blocks=*/128, /*block_step=*/1}),
+ packed_case(/*h_sel=*/1,
+ /*batch=*/1,
+ /*head_size=*/32,
+ /*key_length=*/{},
+ {/*seq_len=*/32, /*max_blocks=*/128, /*block_step=*/1}),
+ packed_case(/*h_sel=*/1,
+ /*batch=*/1,
+ /*head_size=*/32,
+ /*key_length=*/{},
+ {/*seq_len=*/254, /*max_blocks=*/128, /*block_step=*/1}),
+ packed_case(/*h_sel=*/1,
+ /*batch=*/1,
+ /*head_size=*/256,
+ /*key_length=*/{},
+ {/*seq_len=*/256, /*max_blocks=*/128, /*block_step=*/1})};
+}
+
+} // namespace
+
+INSTANTIATE_TEST_SUITE_P(smoke_SparseSDPA_CPU_AMX_Packed,
+ SparseSDPALayerCPUTest,
+ testing::ValuesIn(packed_cases()),
+ SparseSDPALayerCPUTest::getTestCaseName);
+
+// The selected blocks in random order instead of ascending (SparseAttention does not depend on the order, no adjacent
+// runs remain): bf16 with the AMX head sizes, the non-AMX precisions, the non-adjacent step and padded batches.
+INSTANTIATE_TEST_SUITE_P(smoke_SparseSDPA_CPU_Shuffled,
+ SparseSDPALayerCPUTest,
+ testing::Combine(testing::Values(ov::test::utils::DEVICE_CPU),
+ testing::Values(ov::element::bf16),
+ testing::Values(static_cast<size_t>(1), static_cast<size_t>(2)),
+ testing::Values(true, false),
+ testing::Values(static_cast<size_t>(1), static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(32), static_cast<size_t>(256)),
+ testing::Values(static_cast<size_t>(4)),
+ testing::Values(std::vector<size_t>{}),
+ testing::Values(SparseSDPAShape{40, 10, 1, true},
+ SparseSDPAShape{40, 10, 2, true},
+ SparseSDPAShape{96, 20, 1, true})),
+ SparseSDPALayerCPUTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(smoke_SparseSDPA_CPU_Shuffled_NoAMX,
+ SparseSDPALayerCPUTest,
+ testing::Combine(testing::Values(ov::test::utils::DEVICE_CPU),
+ testing::Values(ov::element::f32, ov::element::f16),
+ testing::Values(static_cast<size_t>(1)),
+ testing::Values(true, false),
+ testing::Values(static_cast<size_t>(1), static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(32)),
+ testing::Values(static_cast<size_t>(4)),
+ testing::Values(std::vector<size_t>{}),
+ testing::Values(SparseSDPAShape{96, 20, 1, true})),
+ SparseSDPALayerCPUTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(smoke_SparseSDPA_CPU_Shuffled_Padded,
+ SparseSDPALayerCPUTest,
+ testing::Combine(testing::Values(ov::test::utils::DEVICE_CPU),
+ testing::Values(ov::element::bf16),
+ testing::Values(static_cast<size_t>(1)),
+ testing::Values(true, false),
+ testing::Values(static_cast<size_t>(2)),
+ testing::Values(static_cast<size_t>(32)),
+ testing::Values(static_cast<size_t>(4)),
+ testing::Values(std::vector<size_t>{96, 70}),
+ testing::Values(SparseSDPAShape{96, 20, 1, true})),
+ SparseSDPALayerCPUTest::getTestCaseName);
+
+} // namespace test
+} // namespace ov
diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/stateful_sparse_attention.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/stateful_sparse_attention.cpp
new file mode 100644
index 00000000000..4628bf9d508
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/stateful_sparse_attention.cpp
@@ -0,0 +1,468 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+// Stateful SparseAttention: ReadValue -> Gather(beam_idx) -> Concat -> SparseAttention (+ Assign) is fused into
+// SparseAttentionWithKVCache by the CPU plugin, which keeps the K/V cache in its KV cache states. The test runs the
+// stateful model step by step and compares each step with a stateless SparseAttention model fed with the K/V history
+// accumulated on the host.
+
+#include <gtest/gtest.h>
+
+#include <algorithm>
+#include <cmath>
+#include <cstddef>
+#include <cstdint>
+#include <memory>
+#include <numeric>
+#include <random>
+#include <sstream>
+#include <string>
+#include <tuple>
+#include <vector>
+
+#include "common_test_utils/ov_plugin_cache.hpp"
+#include "common_test_utils/ov_tensor_utils.hpp"
+#include "common_test_utils/test_constants.hpp"
+#include "openvino/core/model.hpp"
+#include "openvino/core/type/bfloat16.hpp"
+#include "openvino/op/assign.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/read_value.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/sparse_attention.hpp"
+#include "openvino/op/util/variable.hpp"
+#include "openvino/runtime/core.hpp"
+#include "openvino/runtime/exec_model_info.hpp"
+#include "openvino/runtime/internal_properties.hpp"
+#include "openvino/runtime/properties.hpp"
+#include "openvino/runtime/system_conf.hpp"
+
+namespace ov {
+namespace test {
+
+namespace {
+
+constexpr size_t kHeads = 4;
+constexpr size_t kKvHeads = 2;
+constexpr size_t kTopK = 3;
+
+struct Step {
+ size_t len; // L of the step
+ bool reorder_beam; // gather the cache rows with the reversed batch order before appending
+};
+
+// {inference precision, kv cache precision, key cache quantized by channel, batch, head size, key block size,
+// number of selection heads}
+using StatefulSparseAttentionParams =
+ std::tuple<ov::element::Type, ov::element::Type, bool, size_t, size_t, size_t, size_t>;
+
+// values in [-1, 1] with a step of 0.01, exactly representable in bf16 after the rounding done by the helper
+ov::Tensor random_tensor(ov::element::Type prec, const ov::Shape& shape, int seed) {
+ return ov::test::utils::create_and_fill_tensor(prec, shape, ov::test::utils::InputGenerateData(-1, 2, 100, seed));
+}
+
+void set_name(const std::shared_ptr<ov::op::v0::Parameter>& param, const std::string& name) {
+ param->set_friendly_name(name);
+ param->output(0).set_names({name});
+}
+
+// a tensor of the given floating point precision (f32 / bf16) with the given values
+ov::Tensor to_tensor(const std::vector<float>& data,
+ const ov::Shape& shape,
+ ov::element::Type prec = ov::element::f32) {
+ ov::Tensor t(prec, shape);
+ if (prec == ov::element::bf16) {
+ std::transform(data.begin(), data.end(), t.data<ov::bfloat16>(), [](float x) {
+ return ov::bfloat16(x);
+ });
+ } else {
+ std::copy(data.begin(), data.end(), t.data<float>());
+ }
+ return t;
+}
+
+std::vector<float> to_f32(const ov::Tensor& t) {
+ std::vector<float> out(t.get_size());
+ if (t.get_element_type() == ov::element::bf16) {
+ std::transform(t.data<const ov::bfloat16>(),
+ t.data<const ov::bfloat16>() + t.get_size(),
+ out.begin(),
+ [](ov::bfloat16 x) {
+ return static_cast<float>(x);
+ });
+ } else {
+ std::copy_n(t.data<const float>(), t.get_size(), out.begin());
+ }
+ return out;
+}
+
+ov::Tensor to_tensor(const std::vector<int32_t>& data, const ov::Shape& shape) {
+ ov::Tensor t(ov::element::i32, shape);
+ std::copy(data.begin(), data.end(), t.data<int32_t>());
+ return t;
+}
+
+// Host-side [N, Hkv, S, E] cache.
+struct HostCache {
+ size_t N = 0;
+ size_t E = 0;
+ size_t S = 0;
+ std::vector<float> data; // [N, Hkv, S, E]
+
+ HostCache(size_t n, size_t e) : N(n), E(e) {}
+
+ void reorder(const std::vector<int32_t>& beam) {
+ std::vector<float> out(data.size());
+ const size_t per_batch = kKvHeads * S * E;
+ for (size_t b = 0; b < N; b++) {
+ std::copy_n(data.begin() + beam[b] * per_batch, per_batch, out.begin() + b * per_batch);
+ }
+ data = std::move(out);
+ }
+
+ // append cur [N, Hkv, L, E]
+ void append(const std::vector<float>& cur, size_t L) {
+ std::vector<float> out(N * kKvHeads * (S + L) * E);
+ for (size_t b = 0; b < N; b++) {
+ for (size_t h = 0; h < kKvHeads; h++) {
+ auto* dst = out.data() + ((b * kKvHeads + h) * (S + L)) * E;
+ std::copy_n(data.data() + ((b * kKvHeads + h) * S) * E, S * E, dst);
+ std::copy_n(cur.data() + ((b * kKvHeads + h) * L) * E, L * E, dst + S * E);
+ }
+ }
+ data = std::move(out);
+ S += L;
+ }
+
+ [[nodiscard]] ov::Tensor tensor(ov::element::Type prec) const {
+ return to_tensor(data, ov::Shape{N, kKvHeads, S, E}, prec);
+ }
+};
+
+} // namespace
+
+class StatefulSparseAttentionTest : public ::testing::TestWithParam<StatefulSparseAttentionParams> {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<StatefulSparseAttentionParams>& obj) {
+ const auto& [prec, cache_prec, by_channel, batch, head_size, block_size, sel_heads] = obj.param;
+ std::ostringstream result;
+ result << "Prec=" << prec.get_type_name() << "_Cache=" << cache_prec.get_type_name()
+ << (by_channel ? "_KeyByChannel" : "") << "_N=" << batch << "_E=" << head_size << "_Bk=" << block_size
+ << "_Hs=" << sel_heads;
+ return result.str();
+ }
+
+protected:
+ static std::shared_ptr<ov::Model> make_stateful_model(ov::element::Type data_prec,
+ size_t head_size,
+ size_t block_size,
+ size_t sel_heads) {
+ // PartialShape takes signed dimensions: convert the runtime sizes explicitly (-Werror=narrowing)
+ const auto head_dim = static_cast<int64_t>(head_size);
+ const auto sel_dim = static_cast<int64_t>(sel_heads);
+ auto q = std::make_shared<ov::op::v0::Parameter>(data_prec, ov::PartialShape{-1, kHeads, -1, head_dim});
+ auto k = std::make_shared<ov::op::v0::Parameter>(data_prec, ov::PartialShape{-1, kKvHeads, -1, head_dim});
+ auto v = std::make_shared<ov::op::v0::Parameter>(data_prec, ov::PartialShape{-1, kKvHeads, -1, head_dim});
+ auto sel_idx =
+ std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1, sel_dim, -1, kTopK});
+ auto sel_cnt = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1, sel_dim, -1});
+ auto beam_idx = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1});
+ auto past_init =
+ std::make_shared<ov::op::v0::Parameter>(data_prec, ov::PartialShape{-1, kKvHeads, -1, head_dim});
+ set_name(q, "q");
+ set_name(k, "k");
+ set_name(v, "v");
+ set_name(sel_idx, "block_indices");
+ set_name(sel_cnt, "block_count");
+ set_name(beam_idx, "beam_idx");
+ set_name(past_init, "past_init");
+
+ auto variable_k = std::make_shared<ov::op::util::Variable>(
+ ov::op::util::VariableInfo{ov::PartialShape{-1, kKvHeads, -1, head_dim}, data_prec, "pastk"});
+ auto variable_v = std::make_shared<ov::op::util::Variable>(
+ ov::op::util::VariableInfo{ov::PartialShape{-1, kKvHeads, -1, head_dim}, data_prec, "pastv"});
+ auto past_k = std::make_shared<ov::op::v6::ReadValue>(past_init, variable_k);
+ auto past_v = std::make_shared<ov::op::v6::ReadValue>(past_init, variable_v);
+
+ auto axis = ov::op::v0::Constant::create(ov::element::i32, {1}, {0});
+ auto gather_k = std::make_shared<ov::op::v8::Gather>(past_k, beam_idx, axis);
+ auto gather_v = std::make_shared<ov::op::v8::Gather>(past_v, beam_idx, axis);
+ auto concat_k = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{gather_k, k}, 2);
+ auto concat_v = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{gather_v, v}, 2);
+
+ auto sparse = std::make_shared<ov::op::v17::SparseAttention>(q,
+ concat_k,
+ concat_v,
+ sel_idx,
+ sel_cnt,
+ static_cast<int64_t>(block_size),
+ /*query_block_size=*/1,
+ /*causal=*/true);
+ auto assign_k = std::make_shared<ov::op::v6::Assign>(concat_k, variable_k);
+ auto assign_v = std::make_shared<ov::op::v6::Assign>(concat_v, variable_v);
+ return std::make_shared<ov::Model>(ov::ResultVector{std::make_shared<ov::op::v0::Result>(sparse)},
+ ov::SinkVector{assign_k, assign_v},
+ ov::ParameterVector{q, k, v, sel_idx, sel_cnt, beam_idx, past_init},
+ "StatefulSparseAttention");
+ }
+
+ static std::shared_ptr<ov::Model> make_reference_model(ov::element::Type data_prec,
+ size_t head_size,
+ size_t block_size,
+ size_t sel_heads) {
+ // PartialShape takes signed dimensions: convert the runtime sizes explicitly (-Werror=narrowing)
+ const auto head_dim = static_cast<int64_t>(head_size);
+ const auto sel_dim = static_cast<int64_t>(sel_heads);
+ auto q = std::make_shared<ov::op::v0::Parameter>(data_prec, ov::PartialShape{-1, kHeads, -1, head_dim});
+ auto k = std::make_shared<ov::op::v0::Parameter>(data_prec, ov::PartialShape{-1, kKvHeads, -1, head_dim});
+ auto v = std::make_shared<ov::op::v0::Parameter>(data_prec, ov::PartialShape{-1, kKvHeads, -1, head_dim});
+ auto sel_idx =
+ std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1, sel_dim, -1, kTopK});
+ auto sel_cnt = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1, sel_dim, -1});
+ set_name(q, "q");
+ set_name(k, "k");
+ set_name(v, "v");
+ set_name(sel_idx, "block_indices");
+ set_name(sel_cnt, "block_count");
+ auto sparse = std::make_shared<ov::op::v17::SparseAttention>(q,
+ k,
+ v,
+ sel_idx,
+ sel_cnt,
+ static_cast<int64_t>(block_size),
+ /*query_block_size=*/1,
+ /*causal=*/true);
+ return std::make_shared<ov::Model>(ov::ResultVector{std::make_shared<ov::op::v0::Result>(sparse)},
+ ov::ParameterVector{q, k, v, sel_idx, sel_cnt},
+ "SparseAttentionReference");
+ }
+
+ // sel_indices / sel_count for queries at the absolute positions [S - L, S): complete blocks only, ascending
+ static void make_selection(std::mt19937& gen,
+ size_t N,
+ size_t sel_heads,
+ size_t L,
+ size_t S,
+ size_t block_size,
+ std::vector<int32_t>& indices,
+ std::vector<int32_t>& count) {
+ indices.assign(N * sel_heads * L * kTopK, 0);
+ count.assign(N * sel_heads * L, 0);
+ for (size_t n = 0; n < N; n++) {
+ for (size_t hs = 0; hs < sel_heads; hs++) {
+ for (size_t l = 0; l < L; l++) {
+ const size_t token_pos = S - L + l;
+ const size_t complete = (token_pos + 1) / block_size;
+ std::vector<int32_t> ids(complete);
+ std::iota(ids.begin(), ids.end(), 0);
+ std::shuffle(ids.begin(), ids.end(), gen);
+ const size_t cnt = std::min(kTopK, complete);
+ ids.resize(cnt);
+ std::sort(ids.begin(), ids.end());
+ const size_t row = (n * sel_heads + hs) * L + l;
+ count[row] = static_cast<int32_t>(cnt);
+ std::copy(ids.begin(), ids.end(), indices.begin() + row * kTopK);
+ }
+ }
+ }
+ }
+
+ static void compare(const ov::Tensor& expected,
+ const ov::Tensor& actual,
+ float threshold,
+ const std::string& tag,
+ float min_diff = 0.F) {
+ ASSERT_EQ(expected.get_shape(), actual.get_shape()) << tag;
+ const auto e = to_f32(expected);
+ const auto a = to_f32(actual);
+ float max_diff = 0.F;
+ for (size_t i = 0; i < e.size(); i++) {
+ max_diff = std::max(max_diff, std::abs(e[i] - a[i]));
+ }
+ EXPECT_LE(max_diff, threshold) << tag << ": max abs diff " << max_diff;
+ EXPECT_GE(max_diff, min_diff) << tag << ": max abs diff " << max_diff << " is suspiciously small";
+ }
+
+ static void check_fused(const ov::CompiledModel& compiled) {
+ bool has_sparse = false;
+ for (const auto& op : compiled.get_runtime_model()->get_ops()) {
+ const auto& info = op->get_rt_info();
+ const auto it = info.find(ov::exec_model_info::LAYER_TYPE);
+ if (it == info.end()) {
+ continue;
+ }
+ const auto type = it->second.as<std::string>();
+ has_sparse |= type == "SparseSDPA";
+ EXPECT_NE(type, "Concat") << "the KV cache Concat must be fused into the sparse attention node";
+ }
+ EXPECT_TRUE(has_sparse) << "SparseSDPA node is expected in the runtime model";
+ }
+};
+
+TEST_P(StatefulSparseAttentionTest, CompareWithStatelessReference) {
+ // plain variables: the lambda below captures them, which clang rejects for structured bindings before C++20
+ const auto& param = GetParam();
+ const auto prec = std::get<0>(param);
+ const auto cache_prec = std::get<1>(param);
+ const auto key_by_channel = std::get<2>(param);
+ const auto N = std::get<3>(param);
+ const auto E = std::get<4>(param);
+ const auto Bk = std::get<5>(param);
+ const auto Hs = std::get<6>(param);
+ if (prec == ov::element::bf16 && !ov::with_cpu_x86_bfloat16()) {
+ GTEST_SKIP() << "bf16 is not supported on this machine";
+ }
+ auto core = ov::test::utils::PluginCache::get().core();
+ // the reference keeps a plain (not compressed) cache: the stateful model is compared against it, a compressed cache
+ // is only expected to be close (the groups of 32 elements are quantized with a {scale, zero point} each)
+ ov::AnyMap ref_config{{ov::hint::inference_precision.name(), prec}};
+ ov::AnyMap config = ref_config;
+ config[ov::hint::kv_cache_precision.name()] = cache_prec;
+ config[ov::key_cache_group_size.name()] = static_cast<uint64_t>(32);
+ config[ov::value_cache_group_size.name()] = static_cast<uint64_t>(32);
+ if (key_by_channel) {
+ // the key groups are 32 tokens long: the prefill ends in a partial group that the decodes keep filling
+ config[ov::internal::key_cache_quant_mode.name()] = ov::internal::CacheQuantMode::BY_CHANNEL;
+ }
+ // the random selection of blocks below; the K/V/Q values come from the common tensor helper
+ std::mt19937 gen(1234);
+ int seed = 1;
+ // the prefill is not a multiple of the block size; the decode steps outgrow the capacity of the buffers twice
+ std::vector<Step> steps{{19, false}, {1, false}, {1, false}, {5, false}};
+ for (size_t i = 0; i < 24; i++) {
+ steps.push_back({1, false});
+ }
+ if (N > 1) {
+ steps.push_back({1, true});
+ steps.push_back({1, false});
+ }
+ steps.push_back({3, false});
+
+ auto compiled = core->compile_model(make_stateful_model(prec, E, Bk, Hs), ov::test::utils::DEVICE_CPU, config);
+ auto compiled_ref =
+ core->compile_model(make_reference_model(prec, E, Bk, Hs), ov::test::utils::DEVICE_CPU, ref_config);
+ check_fused(compiled);
+
+ // bf16 inference rounds the cache once, in both models
+ float threshold = prec == ov::element::bf16 ? 2e-2F : 1e-4F;
+ if (cache_prec == ov::element::u8) {
+ threshold = 3e-2F;
+ } else if (cache_prec == ov::element::u4) {
+ threshold = 0.15F;
+ }
+
+ auto request = compiled.create_infer_request();
+ auto request_ref = compiled_ref.create_infer_request();
+
+ // runs one sequence of steps from the current (reset) state of the request
+ auto run_sequence = [&](HostCache& k_cache, HostCache& v_cache, const std::vector<Step>& seq) {
+ for (size_t step = 0; step < seq.size(); step++) {
+ const auto L = seq[step].len;
+ std::vector<int32_t> beam(N);
+ std::iota(beam.begin(), beam.end(), 0);
+ if (seq[step].reorder_beam) {
+ std::reverse(beam.begin(), beam.end());
+ k_cache.reorder(beam);
+ v_cache.reorder(beam);
+ }
+
+ const auto q_t = random_tensor(prec, ov::Shape{N, kHeads, L, E}, seed++);
+ const auto k_t = random_tensor(prec, ov::Shape{N, kKvHeads, L, E}, seed++);
+ const auto v_t = random_tensor(prec, ov::Shape{N, kKvHeads, L, E}, seed++);
+ k_cache.append(to_f32(k_t), L);
+ v_cache.append(to_f32(v_t), L);
+ std::vector<int32_t> indices;
+ std::vector<int32_t> count;
+ make_selection(gen, N, Hs, L, k_cache.S, Bk, indices, count);
+
+ const auto idx_t = to_tensor(indices, ov::Shape{N, Hs, L, kTopK});
+ const auto cnt_t = to_tensor(count, ov::Shape{N, Hs, L});
+
+ request.set_tensor("q", q_t);
+ request.set_tensor("k", k_t);
+ request.set_tensor("v", v_t);
+ request.set_tensor("block_indices", idx_t);
+ request.set_tensor("block_count", cnt_t);
+ request.set_tensor("beam_idx", to_tensor(beam, ov::Shape{N}));
+ request.set_tensor("past_init", ov::Tensor(prec, ov::Shape{N, kKvHeads, 0, E}));
+ request.infer();
+
+ request_ref.set_tensor("q", q_t);
+ request_ref.set_tensor("k", k_cache.tensor(prec));
+ request_ref.set_tensor("v", v_cache.tensor(prec));
+ request_ref.set_tensor("block_indices", idx_t);
+ request_ref.set_tensor("block_count", cnt_t);
+ request_ref.infer();
+
+ compare(
+ request_ref.get_output_tensor(0),
+ request.get_output_tensor(0),
+ threshold,
+ "step " + std::to_string(step) + " (L=" + std::to_string(L) + ", S=" + std::to_string(k_cache.S) + ")");
+ if (::testing::Test::HasFailure()) {
+ return;
+ }
+ }
+ };
+
+ HostCache k_cache(N, E);
+ HostCache v_cache(N, E);
+ ASSERT_NO_FATAL_FAILURE(run_sequence(k_cache, v_cache, steps));
+
+ // the state exposes the accumulated cache in the model layout and precision
+ for (auto&& state : request.query_state()) {
+ const auto& expected = state.get_name() == "pastk" ? k_cache : v_cache;
+ // a compressed cache must not be exact: that proves the cache is really quantized
+ const float min_diff = cache_prec == ov::element::f32 ? 0.F : 1e-4F;
+ compare(expected.tensor(prec), state.get_state(), threshold, "get_state " + state.get_name(), min_diff);
+ }
+
+ // reset: a new sequence starts from the empty cache and reuses the buffers
+ request.reset_state();
+ HostCache k_cache2(N, E);
+ HostCache v_cache2(N, E);
+ ASSERT_NO_FATAL_FAILURE(run_sequence(k_cache2, v_cache2, {{9, false}, {1, false}, {1, false}}));
+
+ // set_state: continue from a cache written from the outside
+ {
+ const size_t L_init = 11;
+ HostCache k_init(N, E);
+ HostCache v_init(N, E);
+ k_init.append(to_f32(random_tensor(prec, ov::Shape{N, kKvHeads, L_init, E}, seed++)), L_init);
+ v_init.append(to_f32(random_tensor(prec, ov::Shape{N, kKvHeads, L_init, E}, seed++)), L_init);
+ for (auto&& state : request.query_state()) {
+ state.set_state(state.get_name() == "pastk" ? k_init.tensor(prec) : v_init.tensor(prec));
+ }
+ ASSERT_NO_FATAL_FAILURE(run_sequence(k_init, v_init, {{1, false}, {1, false}, {2, false}}));
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(smoke_StatefulSparseAttention,
+ StatefulSparseAttentionTest,
+ ::testing::Combine(::testing::Values(ov::element::f32, ov::element::bf16),
+ ::testing::Values(ov::element::f32, ov::element::u8, ov::element::u4),
+ ::testing::Values(false),
+ ::testing::Values(1, 2),
+ ::testing::Values(32, 64),
+ ::testing::Values(4, 16),
+ ::testing::Values(1, 2)),
+ StatefulSparseAttentionTest::getTestCaseName);
+
+// keys quantized by channel (u8 only); the values are quantized by token
+INSTANTIATE_TEST_SUITE_P(smoke_StatefulSparseAttention_KeyByChannel,
+ StatefulSparseAttentionTest,
+ ::testing::Combine(::testing::Values(ov::element::f32, ov::element::bf16),
+ ::testing::Values(ov::element::u8),
+ ::testing::Values(true),
+ ::testing::Values(1, 2),
+ ::testing::Values(32, 64),
+ ::testing::Values(4, 16),
+ ::testing::Values(1, 2)),
+ StatefulSparseAttentionTest::getTestCaseName);
+
+} // namespace test
+} // namespace ov
diff --git a/src/plugins/intel_cpu/tests/functional/shared_tests_instances/skip_tests_config.cpp b/src/plugins/intel_cpu/tests/functional/shared_tests_instances/skip_tests_config.cpp
index bc3418a7b0f..ad6e0cb71bb 100644
--- a/src/plugins/intel_cpu/tests/functional/shared_tests_instances/skip_tests_config.cpp
+++ b/src/plugins/intel_cpu/tests/functional/shared_tests_instances/skip_tests_config.cpp
@@ -600,6 +600,10 @@ const std::vector<std::regex>& disabled_test_patterns() {
// on platforms which do not support AMX, we are disabling I8 input tests
patterns.emplace_back(std::regex(R"(smoke_LPT/FakeQuantizeWithNotOptimalTransformation.CompareWithRefImpl.*CPU.*i8.*)"));
}
+ if (!ov::with_cpu_x86_avx512_core_amx_bf16()) {
+ // the AMX QK^T fast path of SparseSDPA requires AMX bf16
+ patterns.emplace_back(std::regex(R"(.*smoke_SparseSDPA_CPU_AMX.*)"));
+ }
// RNN/LSTM/GRU/AUGRU BF16 tests on avx512 core ISA
if (ov::with_cpu_x86_avx512_core() && !ov::with_cpu_x86_avx512_core_amx_bf16()) {
patterns.emplace_back(std::regex(R"(smoke.*(AUGRUCellCPUTest|GRUCellCPUTest|RNNCellCPUTest|LSTMCellLayerCPUTest).CompareWithRefs.*INFERENCE_PRECISION_HINT=bf16.*)"));
diff --git a/src/plugins/intel_cpu/tests/functional/sources.cmake b/src/plugins/intel_cpu/tests/functional/sources.cmake
index e6b0a61e703..183fa4dce27 100644
--- a/src/plugins/intel_cpu/tests/functional/sources.cmake
+++ b/src/plugins/intel_cpu/tests/functional/sources.cmake
@@ -279,6 +279,16 @@ set(CPU_FUNC_TESTS_CUSTOM_SRCS
set(CPU_FUNC_TESTS_X64_SRCS
${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/divide_pythondiv.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/classes/qsa_indexer.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/classes/qsa_indexer.hpp
+ ${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/classes/paged_qsa_indexer.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/classes/paged_qsa_indexer.hpp
+ ${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/classes/sparse_sdpa.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/classes/sparse_sdpa.hpp
+ ${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/classes/sparse_pa.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/classes/sparse_pa.hpp
+ ${CMAKE_CURRENT_LIST_DIR}/../../src/transformations/cpu_opset/common/op/qsa_indexer.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/../../src/transformations/cpu_opset/common/op/qsa_indexer.hpp
${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/x64/selective_ssm_jit.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/instances/x64/activation.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/instances/x64/col2im.cpp
@@ -293,12 +303,16 @@ set(CPU_FUNC_TESTS_X64_SRCS
${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/instances/x64/matmul.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/instances/x64/mlas/matmul.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/instances/x64/mvn.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/instances/x64/paged_qsa_indexer.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/instances/x64/pooling.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/instances/x64/qsa_indexer.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/instances/x64/quantized/convolution.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/instances/x64/random_uniform.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/instances/x64/reduce.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/instances/x64/rms_norm.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/instances/x64/softmax.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/instances/x64/sparse_pa.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/instances/x64/sparse_sdpa.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/single_layer_tests/instances/x64/transpose.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/x64/bf16_attention_mask.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/x64/bf16_convert_saturation.cpp
@@ -339,6 +353,7 @@ set(CPU_FUNC_TESTS_X64_SRCS
${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/x64/qkv_proj_fusion.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/x64/rms_norm_no_gamma.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/x64/rope_table_precision.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/x64/stateful_sparse_attention.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/x64/sdpa_sink_input.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/x64/stateful_sdpa_bool_mask.cpp
${CMAKE_CURRENT_LIST_DIR}/custom/subgraph_tests/src/x64/strided_slice_reshape_concat_fusion.cpp
diff --git a/src/plugins/intel_cpu/tests/unit/brgemm_executor_test.cpp b/src/plugins/intel_cpu/tests/unit/brgemm_executor_test.cpp
index 4ed219395c1..80e9c589759 100644
--- a/src/plugins/intel_cpu/tests/unit/brgemm_executor_test.cpp
+++ b/src/plugins/intel_cpu/tests/unit/brgemm_executor_test.cpp
@@ -242,6 +242,235 @@ TEST_P(BrgemmKernelTest, simpleGemmTest) {
}
}
+// AmxTileState: back-to-back executeGemm() calls that share a state skip the AMX tile configuration when the palette is
+// the one configured last. The result must not depend on it, also when kernels with different palettes (other shapes,
+// the M tail) alternate under one state.
+class PreparedBf16Gemm {
+public:
+ PreparedBf16Gemm(size_t M, size_t N, size_t K)
+ : M(M),
+ N(N),
+ K(K),
+ gemm(M, N, K, K, N, N, false, ov::element::bf16),
+ a_data(M * K),
+ b_data(K * N),
+ b_scratch(gemm.get_scratch_b_size(), 0),
+ wsp(ov::intel_cpu::BrgemmKernel::get_wsp_size(), 0),
+ a_scratch(gemm.get_scratch_a_size(), 0) {
+ for (size_t i = 0; i < a_data.size(); i++) {
+ a_data[i] = static_cast<float>(static_cast<int>(i % 13) - 6) * 0.125F;
+ }
+ for (size_t i = 0; i < b_data.size(); i++) {
+ b_data[i] = static_cast<float>(static_cast<int>(i % 7) - 3) * 0.25F;
+ }
+ gemm.copy_buffer_b(b_data.data(), b_scratch.data());
+ }
+
+ [[nodiscard]] size_t blocks() const {
+ return (M + gemm.get_mblk_size() - 1) / gemm.get_mblk_size();
+ }
+
+ // one M block into c (M x N, f32); the overload without a state when tiles is null
+ void run_block(size_t blk, std::vector<float>& c, ov::intel_cpu::AmxTileState* tiles) {
+ const size_t m_start = blk * gemm.get_mblk_size();
+ const size_t m_cnt = std::min(gemm.get_mblk_size(), M - m_start);
+ void* a = a_data.data() + m_start * K;
+ void* out = c.data() + m_start * N;
+ if (tiles != nullptr) {
+ gemm.executeGemm(m_cnt < gemm.get_mblk_size(),
+ a,
+ b_scratch.data(),
+ out,
+ nullptr,
+ nullptr,
+ wsp.data(),
+ a_scratch.data(),
+ *tiles);
+ } else {
+ gemm.executeGemm(m_cnt < gemm.get_mblk_size(),
+ a,
+ b_scratch.data(),
+ out,
+ nullptr,
+ nullptr,
+ wsp.data(),
+ a_scratch.data());
+ }
+ }
+
+ size_t M, N, K;
+ ov::intel_cpu::BrgemmKernel gemm;
+ std::vector<ov::bfloat16> a_data;
+ std::vector<ov::bfloat16> b_data;
+ std::vector<uint8_t> b_scratch;
+ std::vector<uint8_t> wsp;
+ std::vector<uint8_t> a_scratch;
+};
+
+static bool has_nonzero(const std::vector<float>& v) {
+ return std::any_of(v.begin(), v.end(), [](float x) {
+ return x != 0.0F;
+ });
+}
+
+TEST(BrgemmKernelTileStateTest, sharedStateOverMBlocksMatchesPlainOverload) {
+ if (!ov::with_cpu_x86_bfloat16()) {
+ GTEST_SKIP() << "bf16 brgemm is not supported";
+ }
+ // 33 rows: a body block and a tail block (two palettes)
+ PreparedBf16Gemm prepared(33, 32, 64);
+ std::vector<float> expected(33 * 32, 0.0F);
+ std::vector<float> actual(33 * 32, 0.0F);
+ for (size_t blk = 0; blk < prepared.blocks(); blk++) {
+ prepared.run_block(blk, expected, nullptr);
+ }
+ ov::intel_cpu::AmxTileState tiles;
+ for (size_t repeat = 0; repeat < 3; repeat++) {
+ std::fill(actual.begin(), actual.end(), 0.0F);
+ for (size_t blk = 0; blk < prepared.blocks(); blk++) {
+ prepared.run_block(blk, actual, &tiles);
+ }
+ ASSERT_TRUE(has_nonzero(expected));
+ ASSERT_EQ(expected, actual);
+ }
+}
+
+TEST(BrgemmKernelTileStateTest, sharedStateAcrossKernelsWithDifferentPalettes) {
+ if (!ov::with_cpu_x86_bfloat16()) {
+ GTEST_SKIP() << "bf16 brgemm is not supported";
+ }
+ // different K and N give different palettes (and K / N tails with K = 96, N = 48)
+ PreparedBf16Gemm first(33, 32, 64);
+ PreparedBf16Gemm second(40, 48, 96);
+ PreparedBf16Gemm third(8, 16, 32);
+ std::vector<float> expected_first(33 * 32, 0.0F);
+ std::vector<float> expected_second(40 * 48, 0.0F);
+ std::vector<float> expected_third(8 * 16, 0.0F);
+ for (size_t blk = 0; blk < first.blocks(); blk++) {
+ first.run_block(blk, expected_first, nullptr);
+ }
+ for (size_t blk = 0; blk < second.blocks(); blk++) {
+ second.run_block(blk, expected_second, nullptr);
+ }
+ third.run_block(0, expected_third, nullptr);
+
+ std::vector<float> actual_first(33 * 32, 0.0F);
+ std::vector<float> actual_second(40 * 48, 0.0F);
+ std::vector<float> actual_third(8 * 16, 0.0F);
+ ov::intel_cpu::AmxTileState tiles;
+ // interleave the kernels so that every call may find the palette of another kernel configured
+ for (size_t blk = 0; blk < std::max(first.blocks(), second.blocks()); blk++) {
+ if (blk < first.blocks()) {
+ first.run_block(blk, actual_first, &tiles);
+ }
+ third.run_block(0, actual_third, &tiles);
+ if (blk < second.blocks()) {
+ second.run_block(blk, actual_second, &tiles);
+ }
+ }
+ ASSERT_TRUE(has_nonzero(expected_first) && has_nonzero(expected_second) && has_nonzero(expected_third));
+ EXPECT_EQ(expected_first, actual_first);
+ EXPECT_EQ(expected_second, actual_second);
+ EXPECT_EQ(expected_third, actual_third);
+}
+
+TEST(BrgemmKernelTileStateTest, freshStateAfterOtherAmxCode) {
+ if (!ov::with_cpu_x86_bfloat16()) {
+ GTEST_SKIP() << "bf16 brgemm is not supported";
+ }
+ // a new state is "unknown": it must configure even though the tiles hold another palette
+ PreparedBf16Gemm first(32, 32, 64);
+ PreparedBf16Gemm second(32, 48, 96);
+ std::vector<float> expected(32 * 48, 0.0F);
+ second.run_block(0, expected, nullptr);
+ std::vector<float> scratch(32 * 32, 0.0F);
+ std::vector<float> actual(32 * 48, 0.0F);
+ {
+ ov::intel_cpu::AmxTileState tiles;
+ first.run_block(0, scratch, &tiles);
+ }
+ {
+ ov::intel_cpu::AmxTileState tiles;
+ second.run_block(0, actual, &tiles);
+ }
+ ASSERT_TRUE(has_nonzero(expected));
+ EXPECT_EQ(expected, actual);
+}
+
+TEST(BrgemmKernelTileStateTest, quantizedKernelWithScalesSharesState) {
+ if (!(ov::with_cpu_x86_avx512_core_amx_int8() ||
+ dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::cpu_isa_t::avx2_vnni_2))) {
+ GTEST_SKIP() << "int8 brgemm is not supported";
+ }
+ const size_t M = 65;
+ const size_t N = 32;
+ const size_t K = 64;
+ ov::intel_cpu::BrgemmKernelQuantized gemm(M,
+ N,
+ K,
+ K + 4,
+ K + 4,
+ N,
+ N,
+ true,
+ ov::element::i8,
+ ov::element::f32,
+ ov::intel_cpu::BrgemmKernel::ScaleType::PER_CHANNEL,
+ false);
+ std::vector<int8_t> a_data(M * (K + 4));
+ std::vector<int8_t> b_data(N * (K + 4), 0);
+ std::vector<float> b_scale(N);
+ for (size_t n = 0; n < N; n++) {
+ b_scale[n] = static_cast<float>(n % 4 + 1) * 0.25F;
+ }
+ fill_int8_matrices(M, N, K, a_data, b_data);
+ std::vector<uint8_t> b_scratch(gemm.get_scratch_b_size(), 0);
+ gemm.copy_buffer_b(b_data.data() + 4, b_scratch.data());
+ std::vector<uint8_t> wsp(ov::intel_cpu::BrgemmKernel::get_wsp_size(), 0);
+ std::vector<uint8_t> a_scratch(gemm.get_scratch_a_size(), 0);
+ const size_t m_block = gemm.get_mblk_size();
+ const size_t m_blocks = (M + m_block - 1) / m_block;
+
+ // the scaled path (d / scale_b given) and the path without scales (scale_b == nullptr)
+ for (const bool with_scale : {true, false}) {
+ std::vector<int32_t> c_plain(M * N, 0);
+ std::vector<float> d_plain(M * N, 0.0F);
+ std::vector<int32_t> c_state(M * N, 0);
+ std::vector<float> d_state(M * N, 0.0F);
+ ov::intel_cpu::AmxTileState tiles;
+ for (size_t blk = 0; blk < m_blocks; blk++) {
+ const size_t m_start = blk * m_block;
+ const bool is_tail = std::min(m_block, M - m_start) < m_block;
+ auto run = [&](std::vector<int32_t>& c, std::vector<float>& d, ov::intel_cpu::AmxTileState* state) {
+ void* a = a_data.data() + 4 + m_start * (K + 4);
+ void* c_ptr = c.data() + m_start * N;
+ void* d_ptr = d.data() + m_start * N;
+ float* scale = with_scale ? b_scale.data() : nullptr;
+ if (state != nullptr) {
+ gemm.executeGemm(is_tail,
+ a,
+ b_scratch.data(),
+ c_ptr,
+ d_ptr,
+ scale,
+ wsp.data(),
+ a_scratch.data(),
+ *state);
+ } else {
+ gemm.executeGemm(is_tail, a, b_scratch.data(), c_ptr, d_ptr, scale, wsp.data(), a_scratch.data());
+ }
+ };
+ run(c_plain, d_plain, nullptr);
+ run(c_state, d_state, &tiles);
+ }
+ EXPECT_EQ(c_plain, c_state);
+ EXPECT_EQ(d_plain, d_state);
+ EXPECT_TRUE(with_scale ? has_nonzero(d_plain) : std::any_of(c_plain.begin(), c_plain.end(), [](int32_t x) {
+ return x != 0;
+ }));
+ }
+}
+
const std::vector<BrgemmKernelParams> params = {{ov::element::f32, 33, 32, 33, false},
{ov::element::bf16, 33, 32, 33, false},
{ov::element::f16, 33, 32, 33, false},
diff --git a/src/plugins/intel_cpu/tests/unit/graph/x64/enforce_inference_precision_sparse_test.cpp b/src/plugins/intel_cpu/tests/unit/graph/x64/enforce_inference_precision_sparse_test.cpp
new file mode 100644
index 00000000000..7fa8eeca116
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/unit/graph/x64/enforce_inference_precision_sparse_test.cpp
@@ -0,0 +1,148 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <gtest/gtest.h>
+
+#include <memory>
+#include <vector>
+
+#include "graph.h"
+#include "openvino/core/model.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/paged_qsa_indexer.hpp"
+#include "openvino/op/paged_sparse_attention.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/result.hpp"
+
+using namespace ov::intel_cpu;
+
+namespace {
+
+// A Convert to bf16 before every Result makes the outputs already match the inference precision, so the node under test
+// is not part of the graph tail and EnforceInferencePrecision treats it like a node in the middle of a model.
+std::shared_ptr<const ov::Model> make_model_with_bf16_results(const std::shared_ptr<ov::Node>& node,
+ const ov::ParameterVector& params) {
+ ov::ResultVector results;
+ for (const auto& output : node->outputs()) {
+ results.push_back(
+ std::make_shared<ov::op::v0::Result>(std::make_shared<ov::op::v0::Convert>(output, ov::element::bf16)));
+ }
+ return std::make_shared<const ov::Model>(results, params);
+}
+
+void expect_inputs_keep_precision(const Graph& graph, Type type, const std::vector<ov::element::Type>& expected) {
+ NodePtr found;
+ for (const auto& node : graph.GetNodes()) {
+ if (node->getType() == type) {
+ found = node;
+ }
+ }
+ ASSERT_NE(found, nullptr);
+ ASSERT_EQ(found->getOriginalInputsNumber(), expected.size());
+ for (size_t i = 0; i < expected.size(); i++) {
+ EXPECT_EQ(found->getOriginalInputPrecisionAtPort(i), expected[i]) << "input " << i;
+ }
+}
+
+Graph init_graph_with_bf16_inference(const std::shared_ptr<const ov::Model>& model) {
+ Config config;
+ config.inferencePrecision = ov::element::bf16;
+ config.inferencePrecisionSetExplicitly = true;
+ auto context = std::make_shared<GraphContext>(config, nullptr, false);
+ Graph graph;
+ graph.Init(model, context);
+ return graph;
+}
+
+// PagedSparseAttention with u8 caches (the default KV cache precision): f32 query, key, value and scale.
+std::shared_ptr<ov::op::internal::PagedSparseAttention> make_sparse_pa(ov::ParameterVector& params) {
+ const auto f32 = ov::element::f32;
+ const auto i32 = ov::element::i32;
+ const size_t tokens = 4;
+ const size_t blocks = 2;
+ auto p = [](ov::element::Type type, const ov::Shape& shape) {
+ return std::make_shared<ov::op::v0::Parameter>(type, shape);
+ };
+ // u8 caches keep a scale and a zero point (2 f32 = 8 bytes): the key cache is quantized by channel (8 extra rows),
+ // the value cache by token (8 extra elements per row)
+ const ov::Shape key_cache{blocks, 2, 4 + 8, 16};
+ const ov::Shape value_cache{blocks, 2, 4, 16 + 8};
+ params = {p(f32, {tokens, 64}),
+ p(f32, {tokens, 32}),
+ p(f32, {tokens, 32}),
+ p(ov::element::u8, key_cache),
+ p(ov::element::u8, value_cache),
+ p(i32, {1}),
+ p(i32, {2}),
+ p(i32, {blocks}),
+ p(i32, {2}),
+ p(i32, {tokens, 1, 4}),
+ p(i32, {tokens, 1})};
+ ov::OutputVector args(params.begin(), params.end());
+ args.push_back(ov::op::v0::Constant::create(f32, ov::Shape{}, {0.25F}));
+ args.push_back(ov::op::v0::Constant::create(f32, ov::Shape{0}, std::vector<float>{}));
+ return std::make_shared<ov::op::internal::PagedSparseAttention>(args, 2);
+}
+
+} // namespace
+
+// The caches are written in place, so their ports are never converted. With a quantized cache (the default KV cache
+// precision) query, key, value and the constant scale follow the inference precision, as the op needs them to share
+// one type.
+TEST(EnforceInferencePrecisionBF16Test, SparsePAFollowsInferencePrecisionWithQuantizedCache) {
+ const auto f32 = ov::element::f32;
+ const auto bf16 = ov::element::bf16;
+ const auto u8 = ov::element::u8;
+ const auto i32 = ov::element::i32;
+ ov::ParameterVector params;
+ auto sparse_pa = make_sparse_pa(params);
+
+ auto graph = init_graph_with_bf16_inference(make_model_with_bf16_results(sparse_pa, params));
+ expect_inputs_keep_precision(graph,
+ Type::SparsePA,
+ {bf16, bf16, bf16, u8, u8, i32, i32, i32, i32, i32, i32, bf16, f32});
+}
+
+// The op needs one element type on all float inputs, so with f32 caches the whole node stays f32.
+TEST(EnforceInferencePrecisionBF16Test, KeepsPagedQSAIndexerInputsInOriginalPrecision) {
+ const auto f32 = ov::element::f32;
+ const auto i32 = ov::element::i32;
+ const size_t tokens = 4;
+ const size_t blocks = 2;
+ const size_t page = 4;
+ const size_t head_dim = 16;
+ const size_t rotary_dim = 8;
+ auto p = [](ov::element::Type type, const ov::Shape& shape) {
+ return std::make_shared<ov::op::v0::Parameter>(type, shape);
+ };
+ const ov::ParameterVector params{p(f32, {tokens, 2 * head_dim}),
+ p(f32, {tokens, 2 * head_dim}),
+ p(f32, {tokens, rotary_dim}),
+ p(f32, {tokens, rotary_dim}),
+ p(f32, {head_dim}),
+ p(f32, {head_dim}),
+ p(i32, {1}),
+ p(i32, {2}),
+ p(i32, {blocks}),
+ p(i32, {2}),
+ p(f32, {blocks, 2, page, head_dim}),
+ p(f32, {blocks, page / 2, 2 * rotary_dim}),
+ p(f32, {blocks, 2, page / 2, head_dim})};
+ ov::op::internal::PagedQSAIndexer::Config config;
+ config.key_block_size = 2;
+ config.block_topk = 2;
+ config.num_selection_heads = 1;
+ config.indexer_rotary_dim = rotary_dim;
+ config.indexer_head_dim = head_dim;
+ config.epsilon = 1e-6F;
+ config.scale = 0.25F;
+ ov::OutputVector args(params.begin(), params.end());
+ auto qsa = std::make_shared<ov::op::internal::PagedQSAIndexer>(args, config);
+
+ auto graph = init_graph_with_bf16_inference(make_model_with_bf16_results(qsa, params));
+ expect_inputs_keep_precision(graph,
+ Type::PagedQSAIndexer,
+ {f32, f32, f32, f32, f32, f32, i32, i32, i32, i32, f32, f32, f32});
+}
diff --git a/src/plugins/intel_cpu/tests/unit/sources.cmake b/src/plugins/intel_cpu/tests/unit/sources.cmake
index 0d5b0ab21cc..b46e18470c2 100644
--- a/src/plugins/intel_cpu/tests/unit/sources.cmake
+++ b/src/plugins/intel_cpu/tests/unit/sources.cmake
@@ -188,6 +188,7 @@ set(CPU_UNIT_TESTS_X64_SRCS
${CMAKE_CURRENT_LIST_DIR}/softmax_kernel_test.cpp
${CMAKE_CURRENT_LIST_DIR}/xattention_test.cpp
${CMAKE_CURRENT_LIST_DIR}/nodes/eltwise_node_test.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/graph/x64/enforce_inference_precision_sparse_test.cpp
${CMAKE_CURRENT_LIST_DIR}/nodes/kernels/x64/selective_ssm_jit_kernel_test.cpp
${CMAKE_CURRENT_LIST_DIR}/snippets_transformations/x64/brgemm_supported_precisions.cpp
${CMAKE_CURRENT_LIST_DIR}/snippets_transformations/x64/fake_quantize_tokenization_test.cpp