Skip to content

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

[CPU] Implement X-Attention for intel CPU (#32086)

Mang Guo3ac45ad5a4b5
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cpp
index e678260d838..4b542f8df3f 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cpp
@@ -37,6 +37,7 @@
#include "transpose_kernel.hpp"
#include "utils/general_utils.h"
#include "utils/plain_tensor.hpp"
+#include "xattention.hpp"
#if defined(OPENVINO_ARCH_X86_64)
# include "nodes/kernels/x64/brgemm_kernel.hpp"
#elif defined(OPENVINO_ARCH_ARM64) && defined(HAVE_SVE)
@@ -583,6 +584,9 @@ struct MHAHelper {
std::vector<ScoreAggregationInfo> _score_infos;
PlainTensor _block_rotation_coefficient_scratch;
+ // Block size used when generating sparse_attention_mask (0 means unspecified/equal to _block_size)
+ size_t _sparse_mask_block_size = 0;
+ bool _use_softmax_sparse_mask = false;
MHAHelper() {
_weight.resize<float>({size_t{1}, size_t{1}, size_t{1}, size_t{1}});
@@ -829,13 +833,32 @@ struct MHAHelper {
const PlainTensor& alibi_slopes,
float* score_output,
size_t q_start_idx_score,
- const ScoreAggregationInfo* score_info_ptr) {
+ const ScoreAggregationInfo* score_info_ptr,
+ size_t batch_in_seq = 0,
+ const std::vector<PlainTensor>& sparse_attention_mask = {}) {
auto q_start = q_blk * _block_size;
auto q_end = std::min(q_start + _block_size, q_len);
auto q_cnt = q_end - q_start;
constexpr bool q_is_xf16 = any_of(precision_of<DATA_TYPE>::value, ov::element::bf16, ov::element::f16);
constexpr bool q_cache_is_same = precision_of<DATA_TYPE>::value == VALUE_PREC;
auto cur_kv_len_blocks = div_up(cur_kv_len, _block_size);
+ [[maybe_unused]] size_t sparse_scale = 1;
+ [[maybe_unused]] std::function<std::pair<size_t, size_t>(size_t, size_t)> map_to_mask_idx =
+ [](size_t q_blk_rt, size_t k_blk_rt) {
+ return std::pair<size_t, size_t>{q_blk_rt, k_blk_rt};
+ };
+ // Sparse attention mask pointer for current softmax kernel processing
+ uint8_t* xattn_mask = nullptr;
+ if (!sparse_attention_mask.empty()) {
+ if (!(_sparse_mask_block_size == 0 || _sparse_mask_block_size == _block_size)) {
+ sparse_scale = _sparse_mask_block_size / _block_size;
+ map_to_mask_idx = [sparse_scale](size_t q_blk_rt, size_t k_blk_rt) {
+ size_t q_mask = q_blk_rt / sparse_scale;
+ size_t k_mask = k_blk_rt / sparse_scale;
+ return std::pair<size_t, size_t>{q_mask, k_mask};
+ };
+ }
+ }
for (size_t h = hq_beg; h < hq_end; h++) {
auto* q_ptr = query.ptr<DATA_TYPE>(h, q_start, 0);
if (_params.is_sage_attn) {
@@ -850,7 +873,16 @@ struct MHAHelper {
// 1 1 0 0 ...
// 1 1 1 0 ...
// just computing the positions of 1 should be enough
+ // map runtime (block_size) indices to mask (xt_block_size) indices
for (size_t k_blk = 0; k_blk < cur_kv_len_blocks; k_blk++) {
+ // sparse attention mask filtering
+ if (!sparse_attention_mask.empty() && sparse_attention_mask[batch_in_seq].ptr_v() != nullptr) {
+ auto [q_m, k_m] = map_to_mask_idx(q_blk, k_blk);
+ if (!sparse_attention_mask[batch_in_seq].ptr<bool>(h, q_m, k_m)[0]) {
+ // Skip GEMM for this block if mask is false
+ continue;
+ }
+ }
if (_params.is_sage_attn) {
# if defined(OPENVINO_ARCH_X86_64)
auto* q_ptr = _quantized_q.ptr<int8_t>(ithr);
@@ -897,6 +929,17 @@ struct MHAHelper {
start_idx = ncausal - _sliding_window;
new_causal = _sliding_window;
}
+
+ // Handle sparse attention mask for sliding window
+ if (!sparse_attention_mask.empty() && sparse_attention_mask[batch_in_seq].ptr_v() != nullptr &&
+ _use_softmax_sparse_mask) {
+ // Get the original xattn_mask and calculate offset
+ auto* original_mask = reinterpret_cast<uint8_t*>(
+ sparse_attention_mask[batch_in_seq].ptr<bool>(h, q_blk / sparse_scale));
+ size_t mask_start_offset = start_idx / _sparse_mask_block_size;
+ xattn_mask = original_mask + mask_start_offset;
+ }
+
attn_softmax_kernel<float>(score + start_idx,
reinterpret_cast<DATA_TYPE*>(score) + start_idx,
revised_d_scale,
@@ -908,7 +951,10 @@ struct MHAHelper {
rnd_up(cur_kv_len, _block_size) - start_idx,
precision_of<DATA_TYPE>::value,
precision_of<DATA_TYPE>::value,
- nullptr);
+ nullptr,
+ 0.f,
+ xattn_mask,
+ _sparse_mask_block_size);
memset(score, 0, sizeof(DATA_TYPE) * start_idx);
} else {
@@ -919,6 +965,11 @@ struct MHAHelper {
alibi_slope = alibi_slopes.ptr<float>()[h];
alibi_lookup = _alibi_lookup.ptr<float>() + _alibi_lookup.m_dims[0] - ncausal;
}
+ if (!sparse_attention_mask.empty() && sparse_attention_mask[batch_in_seq].ptr_v() != nullptr &&
+ _use_softmax_sparse_mask) {
+ xattn_mask = reinterpret_cast<uint8_t*>(
+ sparse_attention_mask[batch_in_seq].ptr<bool>(h, q_blk / sparse_scale));
+ }
attn_softmax_kernel<float>(score,
reinterpret_cast<DATA_TYPE*>(score),
revised_d_scale,
@@ -931,7 +982,9 @@ struct MHAHelper {
precision_of<DATA_TYPE>::value,
precision_of<DATA_TYPE>::value,
nullptr,
- alibi_slope);
+ alibi_slope,
+ xattn_mask,
+ _sparse_mask_block_size);
}
if (score_output && m >= q_start_idx_score) {
auto* score_block_ptr =
@@ -954,6 +1007,13 @@ struct MHAHelper {
// for each weight block, loop through all value block
for (size_t v_blk = 0; v_blk < cur_kv_len_blocks; v_blk++) {
+ // sparse attention mask filtering for value blocks
+ if (!sparse_attention_mask.empty() && sparse_attention_mask[batch_in_seq].ptr_v() != nullptr) {
+ auto [q_m, v_m] = map_to_mask_idx(q_blk, v_blk);
+ if (!sparse_attention_mask[batch_in_seq].ptr<bool>(h, q_m, v_m)[0]) {
+ continue;
+ }
+ }
DATA_TYPE* v_ptr = nullptr;
if (q_is_xf16 || !q_cache_is_same) {
v_ptr = wv_scratch_b.ptr<DATA_TYPE>(v_blk, hk);
@@ -1512,7 +1572,8 @@ struct MHA {
const PlainTensor& block_indices,
const PlainTensor& block_indices_begins,
const PlainTensor& alibi_slopes,
- const PlainTensor& score_aggregation_window) {
+ const PlainTensor& score_aggregation_window,
+ const std::vector<PlainTensor>& sparse_attention_mask) {
auto Hk = v_cache.m_dims[1];
constexpr bool q_is_xf16 = any_of(precision_of<DATA_TYPE>::value, ov::element::bf16, ov::element::f16);
@@ -1659,7 +1720,7 @@ struct MHA {
score_output = _helper._score_output.template ptr<float>() + score_offset * _helper.H;
}
}
-
+ // TODO: support second token sparse attention execution
_helper.exec_kernel_one_bh(
q.slice(0, batch_in_token, batch_in_token),
k_cache,
@@ -1766,7 +1827,9 @@ struct MHA {
alibi_slopes,
score_output,
q_start_idx_score,
- score_info_ptr);
+ score_info_ptr,
+ batch_in_seq,
+ sparse_attention_mask);
# endif
}
});
@@ -1803,7 +1866,8 @@ struct MHA {
const PlainTensor& block_indices,
const PlainTensor& block_indices_begins,
const PlainTensor& alibi_slopes,
- const PlainTensor& score_aggregation_window) {
+ const PlainTensor& score_aggregation_window,
+ const std::vector<PlainTensor>& sparse_attention_mask) {
_workitems
.reset(query, past_lens, subsequence_begins, block_indices, block_indices_begins, _helper._block_size);
if (output_score) {
@@ -1824,8 +1888,10 @@ struct MHA {
block_indices,
block_indices_begins,
alibi_slopes,
- score_aggregation_window);
+ score_aggregation_window,
+ sparse_attention_mask);
} else {
+ // TODO: support second token sparse attention execution
_helper.exec_loop_bhl(query,
present_key,
present_value,
@@ -1847,6 +1913,9 @@ struct AttentionExecutor : public PagedAttentionExecutor {
MHAHelper<DATA_TYPE, KEY_PREC, VALUE_PREC> _helper;
MHA<DATA_TYPE, KEY_PREC, VALUE_PREC> _kernel;
PlainTensor _slot_mapping;
+# if defined(OPENVINO_ARCH_X86_64)
+ Xattn _xatt;
+# endif
AttentionExecutor() : _kernel(_helper) {}
@@ -1878,7 +1947,8 @@ struct AttentionExecutor : public PagedAttentionExecutor {
int32_t& xattention_stride,
PlainTensor& sinks,
PlainTensor& output_emb,
- PlainTensor& output_score) {
+ PlainTensor& output_score,
+ std::vector<PlainTensor>& sparse_attention_mask) {
q.reset(inputs[ID_Q]); // [B_token, H * S]
k.reset(inputs[ID_K]);
v.reset(inputs[ID_V]);
@@ -2057,10 +2127,9 @@ struct AttentionExecutor : public PagedAttentionExecutor {
}
if (xattention_threshold) {
xattention_threshold.assert_dims({B_seq});
- OPENVINO_ASSERT(xattention_block_size > 0);
+ OPENVINO_ASSERT(static_cast<size_t>(xattention_block_size) >= block_size &&
+ static_cast<size_t>(xattention_block_size) % block_size == 0);
OPENVINO_ASSERT(xattention_stride > 0);
- // TODO: add assertions on the block size and stride limitations as defined by the
- // block sparse operation and importance score computation impls
}
if (sinks) {
@@ -2073,6 +2142,37 @@ struct AttentionExecutor : public PagedAttentionExecutor {
// TODO: enable block_size to be multiple of 32
OPENVINO_ASSERT(block_size == 32, "CPU: block size must be 32, current: ", block_size);
+# if defined(OPENVINO_ARCH_X86_64)
+ // TODO: Support multiple batches. Currently only support B_seq is 1.
+ if (xattention_threshold && q.size(0) > 1 && B_seq == 1) {
+ sparse_attention_mask.resize(B_seq);
+ _xatt.init(B_token, H, 1, S, Hk, xattention_stride, xattention_block_size, q.m_dt);
+ size_t seq_idx = 0;
+ _xatt.estimate(q,
+ k,
+ xattention_block_size,
+ xattention_stride,
+ xattention_threshold.ptr<float>()[seq_idx],
+ sparse_attention_mask[seq_idx]);
+
+ // keep original mask granularity; remember its block size for on-the-fly mapping
+ _helper._sparse_mask_block_size = xattention_block_size;
+ // Check sparse_mask_block_size is a multiple of vector length for correct sparse_mask indexing
+# if defined(HAVE_AVX512F)
+ constexpr size_t vec_len = vec_len_f32_avx512;
+# elif defined(HAVE_AVX2)
+ constexpr size_t vec_len = vec_len_f32_avx2;
+# elif defined(OPENVINO_ARCH_ARM64)
+ constexpr size_t vec_len = vec_len_f32_neon;
+# else
+ constexpr size_t vec_len = 1;
+# endif
+ if (xattention_block_size % vec_len == 0) {
+ _helper._use_softmax_sparse_mask = true;
+ }
+ }
+# endif
+
_helper.init(H,
S,
SV,
@@ -2167,6 +2267,10 @@ struct AttentionExecutor : public PagedAttentionExecutor {
PlainTensor output_emb;
PlainTensor output_score;
+ std::vector<PlainTensor>
+ sparse_attention_mask; // Each vector element corresponds to a batch, and each PlainTensor corresponds to a
+ // batch, with shape: [H, q_blocks, k_blocks], type: bool
+
init(inputs,
outputs,
q,
@@ -2191,7 +2295,8 @@ struct AttentionExecutor : public PagedAttentionExecutor {
xattention_stride,
sinks,
output_emb,
- output_score);
+ output_score,
+ sparse_attention_mask);
if (rotated_block_indices) {
// Rotate kv cache currently doesn't support quantized cache.
@@ -2217,7 +2322,8 @@ struct AttentionExecutor : public PagedAttentionExecutor {
block_indices,
block_indices_begins,
alibi_slopes,
- score_aggregation_window);
+ score_aggregation_window,
+ sparse_attention_mask);
}
};
#endif
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/softmax_kernel.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/softmax_kernel.hpp
index 1c8757969cc..c2049ba0da1 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/softmax_kernel.hpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/softmax_kernel.hpp
@@ -183,7 +183,7 @@ inline void scale_add_reduce_max(float* a, const float scale, const float* b, co
#endif
}
-template <bool has_alibi, bool has_attn_mask, bool has_causal_mask, typename T>
+template <bool has_alibi, bool has_attn_mask, bool has_causal_mask, bool has_sparse_mask, typename T>
inline void scale_add2_reduce_max(float* a,
float scale,
const float* alibi_lookup,
@@ -192,7 +192,24 @@ inline void scale_add2_reduce_max(float* a,
bool select_nfltmax_at_0, // true: 0 in mask set -FLT_MAX
size_t size,
float alibi_slope,
- float& max) {
+ float& max,
+ const uint8_t* sparse_mask,
+ size_t sparse_block_size) {
+ // Check sparse_block_size is a multiple of vector length for correct sparse_mask indexing
+#if defined(HAVE_AVX512F)
+ constexpr size_t vec_len = vec_len_f32_avx512;
+#elif defined(HAVE_AVX2)
+ constexpr size_t vec_len = vec_len_f32_avx2;
+#elif defined(OPENVINO_ARCH_ARM64)
+ constexpr size_t vec_len = vec_len_f32_neon;
+#else
+ constexpr size_t vec_len = 1;
+#endif
+ if (has_sparse_mask && (sparse_block_size % vec_len != 0)) {
+ OPENVINO_THROW("sparse_block_size must be a multiple of vector length (",
+ vec_len,
+ ") for correct sparse_mask indexing");
+ }
OPENVINO_ASSERT(ov::intel_cpu::implication(has_alibi, alibi_lookup), "CPU: alibi_lookup should not be nullptr.");
OPENVINO_ASSERT(ov::intel_cpu::implication(has_attn_mask, attn_mask), "CPU: attn_mask should not be nullptr.");
OPENVINO_ASSERT(ov::intel_cpu::implication(has_causal_mask, causal_mask),
@@ -223,6 +240,12 @@ inline void scale_add2_reduce_max(float* a,
auto v_mask = mm512_uni_loadu_ps(attn_mask + i + n * vec_len_f32_avx512); \
v_a = _mm512_add_ps(v_a, v_mask); \
} \
+ if (has_sparse_mask) { \
+ size_t mask_idx = (i + n * vec_len_f32_avx512) / sparse_block_size; \
+ uint8_t mask_val = sparse_mask[mask_idx]; \
+ __m512 v_mask_block = _mm512_set1_ps(mask_val ? 0.f : -FLT_MAX); \
+ v_a = _mm512_add_ps(v_a, v_mask_block); \
+ } \
if (has_causal_mask) { \
auto v_maski8 = \
_mm_loadu_si128(reinterpret_cast<__m128i const*>(causal_mask + i + n * vec_len_f32_avx512)); \
@@ -254,6 +277,13 @@ inline void scale_add2_reduce_max(float* a,
v_a = _mm512_add_ps(v_a, v_mask);
}
+ if (has_sparse_mask) {
+ size_t mask_idx = i / sparse_block_size;
+ uint8_t mask_val = sparse_mask[mask_idx];
+ __m512 v_mask_block = _mm512_set1_ps(mask_val ? 0.f : -FLT_MAX);
+ v_a = _mm512_add_ps(v_a, v_mask_block);
+ }
+
if (has_causal_mask) {
auto v_maski8 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(causal_mask + i));
auto v_maski32 = _mm512_cvtepi8_epi32(v_maski8);
@@ -282,6 +312,13 @@ inline void scale_add2_reduce_max(float* a,
v_a = _mm512_add_ps(v_a, v_mask);
}
+ if (has_sparse_mask) {
+ size_t mask_idx = i / sparse_block_size;
+ uint8_t mask_val = sparse_mask[mask_idx];
+ __m512 v_mask_block = _mm512_set1_ps(mask_val ? 0.f : -FLT_MAX);
+ v_a = _mm512_add_ps(v_a, v_mask_block);
+ }
+
if (has_causal_mask) {
auto v_maski8 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(causal_mask + i));
auto v_maski32 = _mm512_cvtepi8_epi32(v_maski8);
@@ -324,6 +361,12 @@ inline void scale_add2_reduce_max(float* a,
auto v_mask = mm256_uni_loadu_ps(attn_mask + i + n * vec_len_f32_avx2); \
v_a = _mm256_add_ps(v_a, v_mask); \
} \
+ if (has_sparse_mask) { \
+ size_t mask_idx = (i + n * vec_len_f32_avx2) / sparse_block_size; \
+ uint8_t mask_val = sparse_mask[mask_idx]; \
+ __m256 v_mask_block = _mm256_set1_ps(mask_val ? 0.f : -FLT_MAX); \
+ v_a = _mm256_add_ps(v_a, v_mask_block); \
+ } \
if (has_causal_mask) { \
auto v_maski8 = _mm_loadu_si128(reinterpret_cast<__m128i const*>(causal_mask + i + n * vec_len_f32_avx2)); \
auto v_maski32 = _mm256_cvtepi8_epi32(v_maski8); \
@@ -355,6 +398,13 @@ inline void scale_add2_reduce_max(float* a,
v_a = _mm256_add_ps(v_a, v_mask);
}
+ if (has_sparse_mask) {
+ size_t mask_idx = i / sparse_block_size;
+ uint8_t mask_val = sparse_mask[mask_idx];
+ __m256 v_mask_block = _mm256_set1_ps(mask_val ? 0.f : -FLT_MAX);
+ v_a = _mm256_add_ps(v_a, v_mask_block);
+ }
+
if (has_causal_mask) {
auto v_maski8 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(causal_mask + i));
auto v_maski32 = _mm256_cvtepi8_epi32(v_maski8);
@@ -384,6 +434,13 @@ inline void scale_add2_reduce_max(float* a,
v_a = _mm256_add_ps(v_a, v_mask);
}
+ if (has_sparse_mask) {
+ size_t mask_idx = i / sparse_block_size;
+ uint8_t mask_val = sparse_mask[mask_idx];
+ __m256 v_mask_block = _mm256_set1_ps(mask_val ? 0.f : -FLT_MAX);
+ v_a = _mm256_add_ps(v_a, v_mask_block);
+ }
+
if (has_causal_mask) {
auto v_maski8 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(causal_mask + i));
auto v_maski32 = _mm256_cvtepi8_epi32(v_maski8);
@@ -425,6 +482,13 @@ inline void scale_add2_reduce_max(float* a,
v_a = vaddq_f32(v_a, v_mask);
}
+ if (has_sparse_mask) {
+ size_t mask_idx = i / sparse_block_size;
+ uint8_t mask_val = sparse_mask[mask_idx];
+ float32x4_t v_mask_block = vdupq_n_f32(mask_val ? 0.f : -FLT_MAX);
+ v_a = vaddq_f32(v_a, v_mask_block);
+ }
+
if (has_causal_mask) {
uint8x16_t v_maski8 = vld1q_u8(causal_mask + i);
uint16x8_t v_maski16 = vmovl_u8(vget_low_u8(v_maski8));
@@ -454,6 +518,12 @@ inline void scale_add2_reduce_max(float* a,
a[i] += attn_mask[i];
}
+ if (has_sparse_mask) {
+ size_t mask_idx = i / sparse_block_size;
+ uint8_t mask_val = sparse_mask[mask_idx];
+ a[i] += (mask_val ? 0.f : -FLT_MAX);
+ }
+
if (has_causal_mask) {
if (select_nfltmax_at_0) {
if (causal_mask[i] == 0) {
@@ -1074,8 +1144,9 @@ inline void attn_softmax_kernel(T* a,
ov::element::Type attn_mask_prec,
ov::element::Type dst_precision,
const float* sink,
- float alibi_slope = 0);
-
+ float alibi_slope = 0,
+ uint8_t* sparse_mask = nullptr,
+ size_t sparse_block_size = 1);
template <>
inline void attn_softmax_kernel<float>(float* a,
void* a_dst,
@@ -1089,38 +1160,92 @@ inline void attn_softmax_kernel<float>(float* a,
ov::element::Type attn_mask_prec,
ov::element::Type dst_precision,
const float* sink,
- float alibi_slope) {
- using func_fp32_type =
- void (*)(float*, float, const float*, const float*, const uint8_t*, bool, size_t, float, float&);
- using func_bf16_type =
- void (*)(float*, float, const float*, const ov::bfloat16*, const uint8_t*, bool, size_t, float, float&);
- using func_f16_type =
- void (*)(float*, float, const float*, const ov::float16*, const uint8_t*, bool, size_t, float, float&);
- static constexpr func_fp32_type funcs_fp32[] = {scale_add2_reduce_max<false, false, false>,
- scale_add2_reduce_max<false, false, true>,
- scale_add2_reduce_max<false, true, false>,
- scale_add2_reduce_max<false, true, true>,
- scale_add2_reduce_max<true, false, false>,
- scale_add2_reduce_max<true, false, true>,
- scale_add2_reduce_max<true, true, false>,
- scale_add2_reduce_max<true, true, true>};
- static constexpr func_bf16_type funcs_bf16[] = {scale_add2_reduce_max<false, false, false>,
- scale_add2_reduce_max<false, false, true>,
- scale_add2_reduce_max<false, true, false>,
- scale_add2_reduce_max<false, true, true>,
- scale_add2_reduce_max<true, false, false>,
- scale_add2_reduce_max<true, false, true>,
- scale_add2_reduce_max<true, true, false>,
- scale_add2_reduce_max<true, true, true>};
- static constexpr func_f16_type funcs_f16[] = {scale_add2_reduce_max<false, false, false>,
- scale_add2_reduce_max<false, false, true>,
- scale_add2_reduce_max<false, true, false>,
- scale_add2_reduce_max<false, true, true>,
- scale_add2_reduce_max<true, false, false>,
- scale_add2_reduce_max<true, false, true>,
- scale_add2_reduce_max<true, true, false>,
- scale_add2_reduce_max<true, true, true>};
- int dispatch = (alibi ? 0b100 : 0) | (attn_mask ? 0b010 : 0) | (causal_mask ? 0b001 : 0);
+ float alibi_slope,
+ uint8_t* sparse_mask,
+ size_t sparse_block_size) {
+ using func_fp32_type = void (*)(float*,
+ float,
+ const float*,
+ const float*,
+ const uint8_t*,
+ bool,
+ size_t,
+ float,
+ float&,
+ const uint8_t*,
+ size_t);
+ using func_bf16_type = void (*)(float*,
+ float,
+ const float*,
+ const ov::bfloat16*,
+ const uint8_t*,
+ bool,
+ size_t,
+ float,
+ float&,
+ const uint8_t*,
+ size_t);
+ using func_f16_type = void (*)(float*,
+ float,
+ const float*,
+ const ov::float16*,
+ const uint8_t*,
+ bool,
+ size_t,
+ float,
+ float&,
+ const uint8_t*,
+ size_t);
+ static constexpr func_fp32_type funcs_fp32[] = {scale_add2_reduce_max<false, false, false, false>,
+ scale_add2_reduce_max<false, false, true, false>,
+ scale_add2_reduce_max<false, true, false, false>,
+ scale_add2_reduce_max<false, true, true, false>,
+ scale_add2_reduce_max<true, false, false, false>,
+ scale_add2_reduce_max<true, false, true, false>,
+ scale_add2_reduce_max<true, true, false, false>,
+ scale_add2_reduce_max<true, true, true, false>,
+ scale_add2_reduce_max<false, false, false, true>,
+ scale_add2_reduce_max<false, false, true, true>,
+ scale_add2_reduce_max<false, true, false, true>,
+ scale_add2_reduce_max<false, true, true, true>,
+ scale_add2_reduce_max<true, false, false, true>,
+ scale_add2_reduce_max<true, false, true, true>,
+ scale_add2_reduce_max<true, true, false, true>,
+ scale_add2_reduce_max<true, true, true, true>};
+ static constexpr func_bf16_type funcs_bf16[] = {scale_add2_reduce_max<false, false, false, false>,
+ scale_add2_reduce_max<false, false, true, false>,
+ scale_add2_reduce_max<false, true, false, false>,
+ scale_add2_reduce_max<false, true, true, false>,
+ scale_add2_reduce_max<true, false, false, false>,
+ scale_add2_reduce_max<true, false, true, false>,
+ scale_add2_reduce_max<true, true, false, false>,
+ scale_add2_reduce_max<true, true, true, false>,
+ scale_add2_reduce_max<false, false, false, true>,
+ scale_add2_reduce_max<false, false, true, true>,
+ scale_add2_reduce_max<false, true, false, true>,
+ scale_add2_reduce_max<false, true, true, true>,
+ scale_add2_reduce_max<true, false, false, true>,
+ scale_add2_reduce_max<true, false, true, true>,
+ scale_add2_reduce_max<true, true, false, true>,
+ scale_add2_reduce_max<true, true, true, true>};
+ static constexpr func_f16_type funcs_f16[] = {scale_add2_reduce_max<false, false, false, false>,
+ scale_add2_reduce_max<false, false, true, false>,
+ scale_add2_reduce_max<false, true, false, false>,
+ scale_add2_reduce_max<false, true, true, false>,
+ scale_add2_reduce_max<true, false, false, false>,
+ scale_add2_reduce_max<true, false, true, false>,
+ scale_add2_reduce_max<true, true, false, false>,
+ scale_add2_reduce_max<true, true, true, false>,
+ scale_add2_reduce_max<false, false, false, true>,
+ scale_add2_reduce_max<false, false, true, true>,
+ scale_add2_reduce_max<false, true, false, true>,
+ scale_add2_reduce_max<false, true, true, true>,
+ scale_add2_reduce_max<true, false, false, true>,
+ scale_add2_reduce_max<true, false, true, true>,
+ scale_add2_reduce_max<true, true, false, true>,
+ scale_add2_reduce_max<true, true, true, true>};
+ int dispatch =
+ (alibi ? 0b100 : 0) | (attn_mask ? 0b010 : 0) | (causal_mask ? 0b001 : 0) | (sparse_mask ? 0b1000 : 0);
float max = std::numeric_limits<float>::lowest();
if (attn_mask_prec == ov::element::f32) {
funcs_fp32[dispatch](a,
@@ -1131,7 +1256,9 @@ inline void attn_softmax_kernel<float>(float* a,
select_nfltmax_at_0,
len,
alibi_slope,
- max);
+ max,
+ sparse_mask,
+ sparse_block_size);
} else if (attn_mask_prec == ov::element::bf16) {
funcs_bf16[dispatch](a,
scale,
@@ -1141,7 +1268,9 @@ inline void attn_softmax_kernel<float>(float* a,
select_nfltmax_at_0,
len,
alibi_slope,
- max);
+ max,
+ sparse_mask,
+ sparse_block_size);
} else {
funcs_f16[dispatch](a,
scale,
@@ -1151,7 +1280,9 @@ inline void attn_softmax_kernel<float>(float* a,
select_nfltmax_at_0,
len,
alibi_slope,
- max);
+ max,
+ sparse_mask,
+ sparse_block_size);
}
float sum = 0.0f;
@@ -1199,7 +1330,9 @@ inline void attn_softmax_kernel<ov::float16>(ov::float16* a,
ov::element::Type attn_mask_prec,
ov::element::Type dst_precision,
const float* sink,
- float alibi_slope) {
+ float alibi_slope,
+ [[maybe_unused]] uint8_t* sparse_mask,
+ [[maybe_unused]] size_t sparse_block_size) {
using func_fp32_type = void (*)(ov::float16*,
float,
const ov::float16*,
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/transpose.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/transpose.hpp
new file mode 100644
index 00000000000..3375741cb43
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/transpose.hpp
@@ -0,0 +1,86 @@
+#pragma once
+
+#include <type_traits>
+
+#include "openvino/core/type/element_type.hpp"
+#include "transpose_kernel.hpp"
+#include "utils/general_utils.h"
+
+namespace ov::Extensions::Cpu::XARCH {
+using namespace ov::intel_cpu;
+
+template <typename TDST, typename TSRC>
+inline void transpose_tailx16_kernel(TDST* dst,
+ TSRC* src,
+ size_t n_cnt,
+ size_t k_cnt,
+ size_t dst_stride,
+ size_t src_stride) {
+ for (size_t i = 0; i < n_cnt; i++) {
+ for (size_t j = 0; j < k_cnt; j++) {
+ dst[j * dst_stride + i] = static_cast<TDST>(src[j + i * src_stride]);
+ }
+ }
+}
+
+template <typename TDST,
+ ov::element::Type_t SRC_PREC,
+ std::enable_if_t<(none_of(SRC_PREC, ov::element::i8, ov::element::u8, ov::element::u4)), bool> = true>
+void transpose_16NxK(TDST* dst,
+ void* src,
+ const size_t N,
+ const size_t K,
+ const size_t block_size,
+ const size_t dst_stride,
+ const size_t src_stride) {
+ size_t k = 0;
+ auto* src_ptr = reinterpret_cast<typename ov::element_type_traits<SRC_PREC>::value_type*>(src);
+ for (size_t k = 0; k < K; k++) {
+ memset(dst + k * dst_stride + N, 0, (block_size - N) * sizeof(TDST));
+ }
+
+ for (; k + 16 <= K; k += 16) {
+ size_t n = 0;
+ for (; n + 16 <= N; n += 16) {
+ transpose_16x16_kernel(dst + n, src_ptr + n * src_stride, dst_stride, src_stride);
+ }
+
+ if (n < block_size) {
+ transpose_tailx16_kernel(dst + n, src_ptr + n * src_stride, N - n, 16, dst_stride, src_stride);
+ }
+
+ dst += 16 * dst_stride;
+ src_ptr += 16;
+ }
+ if (k < K) {
+ size_t n = 0;
+ for (; n + 16 <= N; n += 16) {
+ transpose_16xK_kernel(dst + n, src_ptr + n * src_stride, K - k, dst_stride, src_stride);
+ }
+
+ if (n < block_size) {
+ transpose_tailx16_kernel(dst + n, src_ptr + n * src_stride, N - n, K - k, dst_stride, src_stride);
+ }
+ }
+}
+
+#if defined(HAVE_AVX512F)
+template <typename T,
+ ov::element::Type_t SRC_PREC,
+ typename std::enable_if<(SRC_PREC == ov::element::bf16 || SRC_PREC == ov::element::f16) &&
+ (SRC_PREC == precision_of<T>::value),
+ bool>::type = true>
+static void transpose_16NxK(T* dst,
+ T* src,
+ const size_t N,
+ const size_t K,
+ const size_t block_size,
+ const size_t dst_stride,
+ const size_t src_stride) {
+ // will treat as uint32_t transpose
+ auto s = reinterpret_cast<uint32_t*>(src);
+ auto d = reinterpret_cast<uint32_t*>(dst);
+ transpose_16NxK<uint32_t, ov::element::u32>(d, s, N, K >> 1, block_size, dst_stride, src_stride >> 1);
+}
+#endif
+} // namespace ov::Extensions::Cpu::XARCH
\ No newline at end of file
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/xattention.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/xattention.hpp
new file mode 100644
index 00000000000..cdedbb0aab6
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/xattention.hpp
@@ -0,0 +1,362 @@
+// Copyright (C) 2018-2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#pragma once
+
+#include <fstream>
+#include <utility>
+
+#if defined(OPENVINO_ARCH_X86_64)
+# include "nodes/kernels/x64/brgemm_kernel.hpp"
+#elif defined(OPENVINO_ARCH_ARM64)
+# include "nodes/kernels/aarch64/brgemm_kernel.hpp"
+#endif
+#include "openvino/core/parallel.hpp"
+#include "openvino/core/shape.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "utils/plain_tensor.hpp"
+
+#if defined(HAVE_AVX2) || defined(HAVE_AVX512F)
+# include <immintrin.h>
+
+# include "common.hpp"
+#endif
+#include "softmax_kernel.hpp"
+#include "transpose.hpp"
+
+using namespace ov::intel_cpu;
+namespace ov::Extensions::Cpu::XARCH {
+
+#if defined(OPENVINO_ARCH_X86_64) || defined(OPENVINO_ARCH_ARM64)
+struct Xattn {
+ std::vector<uint8_t> _scratch_a;
+ std::vector<uint8_t> _wsp;
+ std::vector<std::shared_ptr<BrgemmKernel>> _xattn_gemm;
+ PlainTensor _attn_sum_temp;
+ PlainTensor _attn_sum;
+ PlainTensor _key_repack;
+ size_t _k_num_to_pad = 0;
+ size_t _k_num_strided = 0;
+ size_t _q_num_strided = 0;
+ size_t _q_num_blocks = 0;
+ size_t _k_num_blocks = 0;
+ size_t _num_per_block = 0;
+ const size_t _n_block_size = 32;
+ size_t _kv_head_groups = 0;
+ const size_t _m_block_size = 32;
+
+ void sum_blocks_ref(const float* a,
+ const size_t M,
+ const size_t N,
+ const size_t a_stride,
+ float* dst,
+ const size_t out_stride,
+ const size_t num_per_block) {
+ size_t row_block_num = div_up(M, num_per_block);
+ size_t col_block_num = div_up(N, num_per_block);
+ for (size_t row = 0; row < row_block_num; row++) {
+ for (size_t col = 0; col < col_block_num; col++) {
+ float value = 0.0f;
+ for (size_t i = 0; i < num_per_block; i++) {
+ for (size_t j = 0; j < num_per_block; j++) {
+ auto r_idx = row * num_per_block + i;
+ auto c_idx = col * num_per_block + j;
+ if (r_idx < M && c_idx < N) {
+ auto in = a[r_idx * a_stride + c_idx];
+ value += in;
+ }
+ }
+ }
+ dst[row * out_stride + col] = value;
+ }
+ }
+ }
+
+# if defined(HAVE_AVX512F) || defined(HAVE_AVX2)
+ void sum_blocks8x8(const float* a,
+ const size_t M,
+ const size_t N,
+ const size_t a_stride,
+ float* out,
+ const size_t out_stride) {
+ size_t col_num = rnd_up(N, 8); // The src in the column direction must be aligned to 8.
+ size_t i = 0;
+ for (; i + 8 <= M; i += 8) {
+ for (size_t j = 0; j + 8 <= col_num; j += 8) {
+ __m256 r0 = _mm256_loadu_ps(a + (i + 0) * a_stride + j);
+ __m256 r1 = _mm256_loadu_ps(a + (i + 1) * a_stride + j);
+ __m256 r2 = _mm256_loadu_ps(a + (i + 2) * a_stride + j);
+ __m256 r3 = _mm256_loadu_ps(a + (i + 3) * a_stride + j);
+ __m256 r4 = _mm256_loadu_ps(a + (i + 4) * a_stride + j);
+ __m256 r5 = _mm256_loadu_ps(a + (i + 5) * a_stride + j);
+ __m256 r6 = _mm256_loadu_ps(a + (i + 6) * a_stride + j);
+ __m256 r7 = _mm256_loadu_ps(a + (i + 7) * a_stride + j);
+
+ __m256 sum = _mm256_add_ps(r0, r1);
+ sum = _mm256_add_ps(sum, r2);
+ sum = _mm256_add_ps(sum, r3);
+ sum = _mm256_add_ps(sum, r4);
+ sum = _mm256_add_ps(sum, r5);
+ sum = _mm256_add_ps(sum, r6);
+ sum = _mm256_add_ps(sum, r7);
+ hsum(sum);
+
+ const int ib = i >> 3;
+ const int jb = j >> 3;
+ const float block_sum = _mm256_cvtss_f32(sum);
+ out[ib * out_stride + jb] = block_sum;
+ }
+ }
+
+ auto tails = M - i;
+ if (tails) {
+ for (size_t j = 0; j + 8 <= col_num; j += 8) {
+ __m256 sum = _mm256_setzero_ps();
+ for (size_t row = i; row < M; row++) {
+ __m256 r = _mm256_loadu_ps(a + row * a_stride + j);
+ sum = _mm256_add_ps(sum, r);
+ }
+ hsum(sum);
+ const float block_sum = _mm256_cvtss_f32(sum);
+ const int jb = j >> 3;
+ out[(M / 8) * out_stride + jb] = block_sum;
+ }
+ }
+ }
+# endif
+
+ void init(const size_t B,
+ const size_t H,
+ const size_t L,
+ const size_t S,
+ const size_t K_H,
+ const size_t xattn_stride,
+ const size_t xattn_block_size,
+ const ov::element::Type in_type) {
+ _kv_head_groups = H / K_H;
+ // The k length should first divided by stride, and the result should be divisible by 32 since block
+ // size in brgemm computation is 32. Therefore align k to multiple of xattn_stride * 32.
+ auto k_padded = rnd_up(B, xattn_stride * 32);
+ _k_num_to_pad = k_padded - B;
+ _k_num_strided = div_up(k_padded, xattn_stride);
+
+ _q_num_strided = div_up(B, xattn_stride);
+ _q_num_blocks = div_up(B, xattn_block_size);
+ _k_num_blocks = div_up(B, xattn_block_size);
+ _num_per_block = xattn_block_size / xattn_stride;
+ size_t n_num_blocks = _k_num_strided / _n_block_size;
+
+ if (_q_num_blocks <= 1 || _k_num_blocks <= 1) {
+ return;
+ }
+
+ if (_xattn_gemm.empty()) {
+ _xattn_gemm.resize(_m_block_size);
+ for (size_t i = 1; i < _m_block_size + 1; i++) {
+ _xattn_gemm[i - 1] = std::make_shared<BrgemmKernel>(i, // M
+ _n_block_size, // N
+ S, // K
+ S * xattn_stride * H * L, // lda
+ _n_block_size, // ldb
+ _k_num_strided, // ldc
+ false,
+ in_type,
+ true);
+ }
+ auto max_threads_num = parallel_get_max_threads();
+ auto scratch_a_size = _xattn_gemm.back()->get_scratch_a_size();
+ auto wsp_size = _xattn_gemm.back()->get_wsp_size();
+
+ _scratch_a.assign(scratch_a_size * max_threads_num, 0.0f);
+ _wsp.assign(wsp_size * max_threads_num, 0.0f);
+
+ _attn_sum_temp.resize({H, L, _q_num_strided, _k_num_strided}, sizeof(float), ov::element::Type_t::f32);
+ _attn_sum.resize({H, L, _q_num_blocks, _k_num_blocks}, _attn_sum_temp.m_element_size, _attn_sum_temp.m_dt);
+ _key_repack.resize({K_H, L, S * n_num_blocks, _n_block_size}, sizeof(float), ov::element::Type_t::f32);
+ }
+
+ // Set brgemm output buffer each time before use.
+ ov::parallel_for3d(_q_num_strided, H, L, [&](size_t b, size_t h, size_t l) {
+ memset(_attn_sum_temp.ptr<float>(h, l, b, 0), 0, _k_num_strided * sizeof(float));
+ });
+ }
+
+ void estimate(const PlainTensor& query,
+ const PlainTensor& key,
+ const size_t block_size,
+ const size_t stride,
+ const float threshold,
+ PlainTensor& mask) {
+ const auto B = query.size(0);
+ const auto H = query.size(1);
+ const auto L = query.size(2);
+ const auto S = query.size(3);
+ const auto K_H = key.size(1);
+ OPENVINO_ASSERT(query.size(0) == key.size(0));
+ if (_q_num_blocks <= 1 || _k_num_blocks <= 1) {
+ return;
+ }
+
+ const auto m_num_blocks = div_up(_q_num_strided, _m_block_size);
+ auto in_type = query.m_dt;
+ auto scratch_a_size = _xattn_gemm.back()->get_scratch_a_size();
+ auto wsp_size = _xattn_gemm.back()->get_wsp_size();
+ const auto n_num_blocks = _k_num_strided / _n_block_size;
+
+ for (size_t i = 0; i < stride; i++) {
+ // repack key buffer
+ ov::parallel_for2d(K_H, n_num_blocks, [&](size_t h, size_t n_blk) {
+ auto n_start = n_blk * _n_block_size;
+ size_t need_to_pad = (_k_num_to_pad + i) / stride;
+ size_t N = (n_blk == n_num_blocks - 1) ? _n_block_size - need_to_pad : 32;
+
+ if (N) {
+ void* src = key.ptr_v(n_start * stride + i, h, 0, 0);
+ void* dst = _key_repack.ptr_v(h, 0, S * n_blk, 0);
+ if (in_type == ov::element::bf16) {
+# if defined(HAVE_AVX512F)
+ transpose_16NxK<bfloat16, ov::element::bf16>(reinterpret_cast<bfloat16*>(dst), // dst
+ reinterpret_cast<bfloat16*>(src), // src
+ N, // N
+ S, // K
+ _n_block_size, // block size
+ _n_block_size, // dst stride
+ (S * stride * K_H) // src stride
+ );
+# else
+ OPENVINO_THROW("xattention: bf16 needs avx512+ hardware");
+# endif
+ } else if (in_type == ov::element::f32) {
+ transpose_16NxK<float, ov::element::f32>(reinterpret_cast<float*>(dst), // dst
+ src, // src
+ N, // N
+ S, // K
+ _n_block_size, // block size
+ _n_block_size, // dst stride
+ (S * stride * K_H) // src stride
+ );
+ } else {
+ OPENVINO_THROW("xattention: unsupported precision: ", in_type);
+ }
+
+ } else {
+ for (size_t k = 0; k < S; k++) {
+ auto* dst = _key_repack.ptr_v(h, 0, S * n_blk + k, 0);
+ memset(dst, 0, _n_block_size * _key_repack.m_element_size);
+ }
+ }
+ });
+
+ ov::parallel_for2d(H, m_num_blocks, [&](size_t h, size_t m_blk) {
+ auto ithr = parallel_get_thread_num();
+ auto m_start = m_blk * _m_block_size;
+ auto m_end = std::min(m_start + _m_block_size, _q_num_strided);
+ auto m_cnt = m_end - m_start;
+
+ auto q_index = m_start * stride + stride - i - 1;
+ auto q_end = q_index + stride * (m_cnt - 1);
+
+ // q_end may extend the seq length since it was aligned to multiple of stride
+ if (q_end >= B) {
+ m_cnt--;
+ }
+
+ if (m_cnt > 0) {
+ auto* q_ptr = query.ptr_v(stride - 1 - i + m_start * stride, h, 0, 0);
+ auto cur_k_block_num = m_blk + 1;
+ for (size_t n_blk = 0; n_blk < cur_k_block_num; n_blk++) {
+ auto n_start = n_blk * S;
+ auto* k_ptr = _key_repack.ptr_v(h / _kv_head_groups, 0, n_start, 0);
+ auto* c_ptr = &_attn_sum_temp.at<float>({h, 0, m_start, n_blk * _n_block_size});
+ _xattn_gemm[m_cnt - 1]->executeGemm(m_cnt < _m_block_size,
+ q_ptr,
+ k_ptr,
+ c_ptr,
+ nullptr,
+ nullptr,
+ _wsp.data() + wsp_size * ithr,
+ _scratch_a.data() + scratch_a_size * ithr);
+ }
+ }
+ });
+ }
+
+ parallel_for3d(_q_num_strided, H, L, [&](size_t b, size_t h, size_t l) {
+ auto* data = _attn_sum_temp.ptr<float>(h, l, b, 0);
+ auto ncausal = b + 1;
+ auto scale = 1.0 / sqrt(S) / stride;
+ attn_softmax_kernel<float>(data,
+ reinterpret_cast<float*>(data),
+ scale,
+ nullptr,
+ nullptr,
+ nullptr,
+ false,
+ ncausal,
+ _k_num_strided,
+ ov::element::f32,
+ ov::element::f32,
+ 0);
+ });
+
+ const size_t src_stride = _attn_sum_temp.size(3);
+ const size_t dst_stride = _attn_sum.size(3);
+ size_t row_num = _q_num_strided;
+ size_t col_num = div_up(key.size(0), stride);
+ parallel_for2d(H, L, [&](size_t h, size_t l) {
+ auto* src = _attn_sum_temp.ptr<float>(h, l, 0, 0);
+ auto* dst = _attn_sum.ptr<float>(h, l, 0, 0);
+# if defined(HAVE_AVX512F) || defined(HAVE_AVX2)
+ if (_num_per_block == 8) {
+ sum_blocks8x8(src, row_num, col_num, src_stride, dst, dst_stride);
+ } else {
+ sum_blocks_ref(src, row_num, col_num, src_stride, dst, dst_stride, _num_per_block);
+ }
+# else
+ sum_blocks_ref(src, row_num, col_num, src_stride, dst, dst_stride, _num_per_block);
+# endif
+ });
+
+ // Find blocks
+ mask.resize({H, _q_num_blocks, _k_num_blocks}, sizeof(bool), ov::element::Type_t::boolean);
+ parallel_for3d(_q_num_blocks, H, L, [&](size_t q_n, size_t h, size_t l) {
+ auto* row = _attn_sum.ptr<float>(h, l, q_n, 0);
+ float required_sum = std::accumulate(row, row + _k_num_blocks, 0.0f, std::plus<>()) * threshold;
+
+ std::vector<std::pair<float, int>> values_with_index(_k_num_blocks);
+ for (size_t k = 0; k < _k_num_blocks; k++) {
+ values_with_index[k] = std::make_pair(row[k], k);
+ }
+
+ // The blocks in the first column and along the main diagonal should always be selected thus excluded from
+ // the sorting process.
+ if (q_n > 1) {
+ std::swap(values_with_index[1], values_with_index[q_n]);
+ }
+ std::sort(values_with_index.begin() + 2,
+ values_with_index.end(),
+ [](const std::pair<float, int>& a, const std::pair<float, int>& b) {
+ return a.first > b.first;
+ });
+
+ // Compute the cumulative sum. Set the values in the first and second columns to zero to ensures that the
+ // blocks in the first column and along the main diagonal are always selected.
+ std::vector<float> cumsum_without_self(_k_num_blocks, 0.0f);
+ for (size_t i = 1; i < _k_num_blocks; i++) {
+ cumsum_without_self[i] = values_with_index[i - 1].first + cumsum_without_self[i - 1];
+ }
+ cumsum_without_self[1] = 0.0f;
+
+ for (size_t i = 0; i < _k_num_blocks; i++) {
+ bool value = (cumsum_without_self[i] < required_sum);
+ if (i > q_n) {
+ value = false;
+ }
+ *(mask.ptr<bool>(h, q_n, values_with_index[i].second)) = value;
+ }
+ });
+ }
+};
+#endif
+
+} // namespace ov::Extensions::Cpu::XARCH
diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn.cpp
index 68b048ebb96..2122a65477e 100644
--- a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn.cpp
+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn.cpp
@@ -37,14 +37,14 @@ using namespace ov::op;
namespace ov {
namespace test {
using InputShapes = std::vector<InputShape>;
-using PagedAttnTestParams = std::tuple<ElementType, InputShapes, bool, ov::AnyMap>;
+using PagedAttnTestParams = std::tuple<ElementType, InputShapes, bool, bool, ov::AnyMap>;
class PagedAttnTestBase : public testing::WithParamInterface<PagedAttnTestParams>,
virtual public ov::test::SubgraphBaseTest,
public CPUTestsBase {
public:
static std::string getTestCaseName(const testing::TestParamInfo<PagedAttnTestParams>& obj) {
- const auto& [inType, inputShapes, extendBlockIndices, additional_config] = obj.param;
+ const auto& [inType, inputShapes, extendBlockIndices, enableXattn, additional_config] = obj.param;
std::ostringstream result;
result << "IS=";
for (const auto& shape : inputShapes) {
@@ -61,7 +61,8 @@ public:
result << ")_";
}
result << "Prc=" << inType << "_";
- result << "ExtendBlockIndices=" << extendBlockIndices;
+ result << "ExtendBlockIndices=" << extendBlockIndices << "_";
+ result << "EnableXattn=" << enableXattn << "_";
result << "config=(";
for (const auto& configEntry : additional_config) {
result << configEntry.first << ", " << configEntry.second.as<std::string>() << "_";
@@ -80,6 +81,7 @@ public:
}
std::shared_ptr<ov::Model> get_model(ov::element::Type data_type,
+ bool enable_xattn,
ov::Dimension::value_type head_size = 64,
ov::Dimension::value_type head_num = 8) {
// q [batch_in_tokens, head_num * head_size]
@@ -107,7 +109,7 @@ public:
std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{0});
auto alibi_slopes = std::make_shared<ov::op::v0::Constant>(ov::element::f32, Shape{0}, std::vector<float>{});
auto max_context_len =
- std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{}, std::vector<float>{128});
+ std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{}, std::vector<float>{1024});
auto score_aggregation_window =
std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{0});
auto rotated_block_indices =
@@ -118,12 +120,15 @@ public:
std::make_shared<ov::op::v0::Constant>(ov::element::f32, Shape{0}, std::vector<float>{0});
auto xattention_threshold =
std::make_shared<ov::op::v0::Constant>(ov::element::f32, Shape{0}, std::vector<float>{0});
+ if (enable_xattn) {
+ xattention_threshold =
+ std::make_shared<ov::op::v0::Constant>(ov::element::f32, Shape{1}, std::vector<float>{0.9f});
+ }
auto xattention_block_size =
- std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{0});
+ std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{64});
auto xattention_stride =
- std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{0});
- auto sinks =
- std::make_shared<ov::op::v0::Constant>(data_type, Shape{0, 0, 0, 0}, std::vector<float>{});
+ std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{8});
+ auto sinks = std::make_shared<ov::op::v0::Constant>(data_type, Shape{0, 0, 0, 0}, std::vector<float>{});
ParameterVector params =
{q, k, v, key_cache, value_cache, past_lens, subsequence_begins, block_indices, block_indices_begins};
auto paged_attn = std::make_shared<op::PagedAttentionExtension>(OutputVector{q,
@@ -232,7 +237,7 @@ public:
}
void SetUp() override {
- const auto& [inType, inputShapes, extendBlockIndices, additional_config] = this->GetParam();
+ const auto& [inType, inputShapes, extendBlockIndices, enableXattn, additional_config] = this->GetParam();
targetDevice = ov::test::utils::DEVICE_CPU;
rel_threshold = 1e-2f;
configuration[ov::hint::inference_precision.name()] = ov::element::f32;
@@ -245,7 +250,7 @@ public:
init_input_shapes(inputShapes);
ov::ParameterVector inputParams;
- function = get_model(inType, 64, 8);
+ function = get_model(inType, enableXattn, 64, 8);
targetDevice = ov::test::utils::DEVICE_CPU;
functionRefs = get_ref_model(inType, 64, 8);
@@ -311,7 +316,7 @@ public:
size_t batch_size_in_sequences = 1;
// The test here simulates pagedAttn calcuation with 1 subsequence
// idx = 0 means 1st token calculation, idx > 0 means 2nd token calculation
- int32_t total_blocks = intel_cpu::div_up(past_len_count, 32);
+ int32_t total_blocks = intel_cpu::div_up(qkv_shape[0] * qkv_shape[1] + past_len_count, 32);
ov::Tensor past_lens(ov::element::i32, {batch_size_in_sequences}),
subsequence_begins(ov::element::i32, {batch_size_in_sequences + 1}),
block_indices_begins(ov::element::i32, {batch_size_in_sequences + 1}),
@@ -332,8 +337,10 @@ public:
if (extendBlockIndices)
block_indices_begins_data[1] = 2;
else
- block_indices_begins_data[1] = 1;
- block_indices_data[0] = 0;
+ block_indices_begins_data[1] = total_blocks;
+ for (int32_t i = 0; i < total_blocks; i++) {
+ block_indices_data[i] = i;
+ }
} else {
past_lens_data[0] = past_len_count;
subsequence_begins_data[0] = 0;
@@ -387,7 +394,7 @@ public:
for (const auto& input : compiledModel.inputs()) {
for (auto& name : input.get_names()) {
auto cache_precision = input.get_element_type();
- const size_t block_nums = 4;
+ const size_t block_nums = 1024 / 32;
ov::PartialShape pshape;
if (name.find("key_cache.") == 0) {
pshape = input.get_partial_shape();
@@ -440,8 +447,9 @@ public:
TEST_P(PagedAttnVSSDPATest, CompareWithRefs) {
SKIP_IF_CURRENT_TEST_IS_DISABLED();
- const auto& [inType, inputShapes, extendBlockIndices, additional_config] = this->GetParam();
- const bool isSageAttn = intel_cpu::contains_key_value(additional_config, {ov::intel_cpu::enable_sage_attn.name(), true});
+ const auto& [inType, inputShapes, extendBlockIndices, enableXattn, additional_config] = this->GetParam();
+ const bool isSageAttn =
+ intel_cpu::contains_key_value(additional_config, {ov::intel_cpu::enable_sage_attn.name(), true});
if (inType == ElementType::bf16 && !ov::with_cpu_x86_bfloat16())
GTEST_SKIP();
if (isSageAttn && !(ov::with_cpu_x86_avx512_core_amx_int8() || CPUTestUtils::with_cpu_x86_avx2_vnni_2()))
@@ -464,9 +472,9 @@ const std::vector<ov::AnyMap> additional_configs = {{{ov::intel_cpu::enable_sage
const std::vector<InputShapes> inputShapeAndReorders = { // greedy search
{
// L1, B, H, S
- {{-1, 1, 8, 64}, {{10, 1, 8, 64}, {1, 1, 8, 64}, {1, 1, 8, 64}}},
+ {{-1, 1, 8, 64}, {{256, 1, 8, 64}, {1, 1, 8, 64}}},
// B, L0, H, S
- {{-1, 1, 8, 64}, {{0, 1, 8, 64}, {10, 1, 8, 64}, {11, 1, 8, 64}}},
+ {{-1, 1, 8, 64}, {{0, 1, 8, 64}, {256, 1, 8, 64}}},
}};
INSTANTIATE_TEST_SUITE_P(smoke_PagedAttnVSSDPATest,
@@ -474,6 +482,7 @@ INSTANTIATE_TEST_SUITE_P(smoke_PagedAttnVSSDPATest,
::testing::Combine(::testing::Values(ElementType::f32, ElementType::bf16),
::testing::ValuesIn(inputShapeAndReorders),
::testing::Values(true, false),
+ ::testing::Values(true, false),
::testing::ValuesIn(additional_configs)),
PagedAttnTestBase::getTestCaseName);
} // namespace
@@ -665,8 +674,9 @@ public:
TEST_P(PagedAttnVSMatmulTest, CompareWithRefs) {
SKIP_IF_CURRENT_TEST_IS_DISABLED();
- const auto& [inType, inputShapes, extendBlockIndices, additional_config] = this->GetParam();
- const bool isSageAttn = intel_cpu::contains_key_value(additional_config, {ov::intel_cpu::enable_sage_attn.name(), true});
+ const auto& [inType, inputShapes, extendBlockIndices, enableXattn, additional_config] = this->GetParam();
+ const bool isSageAttn =
+ intel_cpu::contains_key_value(additional_config, {ov::intel_cpu::enable_sage_attn.name(), true});
if (inType == ElementType::bf16 && !ov::with_cpu_x86_bfloat16())
GTEST_SKIP();
if (isSageAttn && !(ov::with_cpu_x86_avx512_core_amx_int8() || CPUTestUtils::with_cpu_x86_avx2_vnni_2()))
@@ -698,6 +708,7 @@ INSTANTIATE_TEST_SUITE_P(smoke_PagedAttnVSMatmulTest,
::testing::Combine(::testing::Values(ElementType::f32, ElementType::f16),
::testing::ValuesIn(inputShapes),
::testing::Values(true, false),
+ ::testing::Values(true, false),
::testing::ValuesIn(additional_configs)),
PagedAttnTestBase::getTestCaseName);
} // namespace
diff --git a/src/plugins/intel_cpu/tests/unit/CMakeLists.txt b/src/plugins/intel_cpu/tests/unit/CMakeLists.txt
index 52400133d99..7ea953d6418 100644
--- a/src/plugins/intel_cpu/tests/unit/CMakeLists.txt
+++ b/src/plugins/intel_cpu/tests/unit/CMakeLists.txt
@@ -31,7 +31,8 @@ if(NOT X86_64)
${CMAKE_CURRENT_SOURCE_DIR}/transformations/x64
${CMAKE_CURRENT_SOURCE_DIR}/snippets_transformations/x64
${CMAKE_CURRENT_SOURCE_DIR}/nodes/eltwise_node_test.cpp
- ${CMAKE_CURRENT_SOURCE_DIR}/brgemm_executor_test.cpp)
+ ${CMAKE_CURRENT_SOURCE_DIR}/brgemm_executor_test.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/xattention_test.cpp)
endif()
if (NOT ENABLE_MLAS_FOR_CPU)
@@ -58,6 +59,7 @@ ov_add_test_target(
$<TARGET_PROPERTY:openvino_intel_cpu_plugin,SOURCE_DIR>/thirdparty/onednn
$<TARGET_PROPERTY:openvino_intel_cpu_plugin,SOURCE_DIR>/thirdparty/onednn/src
$<TARGET_PROPERTY:openvino::conditional_compilation,INTERFACE_INCLUDE_DIRECTORIES>
+ $<TARGET_PROPERTY:openvino::reference,SOURCE_DIR>/include
PRIVATE
$<TARGET_PROPERTY:openvino::snippets,SOURCE_DIR>/include
EXCLUDED_SOURCE_PATHS
diff --git a/src/plugins/intel_cpu/tests/unit/xattention_test.cpp b/src/plugins/intel_cpu/tests/unit/xattention_test.cpp
new file mode 100644
index 00000000000..22489220c93
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/unit/xattention_test.cpp
@@ -0,0 +1,128 @@
+// Copyright (C) 2018-2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#define OPENVINO_ARCH_X86_64
+
+#include "nodes/kernels/scaled_attn/xattention.hpp"
+
+#include <gtest/gtest.h>
+
+#include "common_test_utils/data_utils.hpp"
+#include "common_test_utils/test_common.hpp"
+#include "nodes/kernels/scaled_attn/transpose_kernel.hpp"
+#include "openvino/core/parallel.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "openvino/reference/xattention.hpp"
+#include "utils/plain_tensor.hpp"
+
+using namespace ov::intel_cpu;
+using namespace ov::Extensions::Cpu::XARCH;
+
+namespace XAttentionUnitTest {
+struct XAttr {
+ size_t block_size;
+ size_t stride;
+ float threshold;
+};
+
+using XAttentionParams =
+ std::tuple<ov::element::Type, std::vector<size_t>, std::vector<size_t>, XAttr>;
+
+template <class T>
+void inline fill_data_random(T* pointer, std::size_t size, const float min, const float max, const int seed) {
+ std::mt19937 gen(seed);
+ std::uniform_real_distribution<double> dist(min, max);
+ for (std::size_t i = 0; i < size; i++) {
+ pointer[i] = static_cast<T>(dist(gen));
+ }
+}
+
+class XAttentionTest : public ov::test::TestsCommon, public testing::WithParamInterface<XAttentionParams> {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<XAttentionParams>& obj) {
+ auto shape_to_str = [](const std::vector<size_t>& shape) {
+ std::string msg;
+ for (size_t i = 0; i < shape.size(); i++) {
+ if (i != 0)
+ msg += "x";
+ msg += std::to_string(shape[i]);
+ }
+ return msg;
+ };
+ const auto& [data_type, query_shape, key_shape, xattr] = obj.param;
+ std::ostringstream result;
+ result << "DT=" << data_type.to_string();
+ result << ",Q=" << shape_to_str(query_shape);
+ result << ",K=" << shape_to_str(key_shape);
+ result << ",block_size=" << xattr.block_size;
+ result << ",stride=" << xattr.stride;
+ result << ",threshold=" << xattr.threshold;
+ return result.str();
+ }
+
+public:
+ template <typename T>
+ void compareWithRef() {
+ const auto& [data_type, query_shape, key_shape, xattr] = this->GetParam();
+ auto element_size = ov::element::Type(data_type).size();
+
+ PlainTensor query;
+ PlainTensor key;
+ query.resize(query_shape, element_size, data_type);
+ key.resize(key_shape, element_size, data_type);
+
+ fill_data_random<T>(query.ptr<T>(), ov::shape_size(query_shape.begin(), query_shape.end()), 0, 2, 0);
+ fill_data_random<T>(key.ptr<T>(), ov::shape_size(key_shape.begin(), key_shape.end()), 0, 1, 0);
+
+ Xattn xattn;
+ xattn.init(query.size(0),
+ query.size(1),
+ query.size(2),
+ query.size(3),
+ key.size(1),
+ xattr.stride,
+ xattr.block_size,
+ ov::element::f32);
+ PlainTensor mask;
+ xattn.estimate(query, key, xattr.block_size, xattr.stride, xattr.threshold, mask);
+
+ ov::reference::XAttentionBlockSelector<T> selector(xattr.threshold, xattr.block_size, xattr.stride);
+ ov::Shape query_shape_ref = {query_shape[1], query_shape[0], query_shape[3]};
+ ov::Shape key_shape_ref = {key_shape[1], key_shape[0], key_shape[3]};
+ auto ref_result = selector.select_blocks(query.ptr<T>(), query_shape_ref, key.ptr<T>(), key_shape_ref);
+
+ for (size_t h = 0; h < query.size(1); h++) {
+ for (const auto& idx : ref_result[h]) {
+ auto row = idx.first;
+ auto col = idx.second;
+ EXPECT_EQ(*mask.ptr<bool>(h, row, col), true);
+ }
+ }
+ }
+};
+
+TEST_P(XAttentionTest, testWithRef) {
+ compareWithRef<float>();
+}
+
+const std::vector<XAttentionParams> params = {
+ {ov::element::f32,
+ {8, 1, 1, 8}, // {B, H, L, S}
+ {8, 1, 1, 8},
+ {4, 2, 0.8f}},
+ {ov::element::f32,
+ {16, 1, 1, 32},
+ {16, 1, 1, 32},
+ {4, 2, 0.3f}},
+ {ov::element::f32,
+ {16, 2, 1, 32},
+ {16, 2, 1, 32},
+ {4, 2, 0.7f}}};
+
+INSTANTIATE_TEST_SUITE_P(XAttentionUnitTest,
+ XAttentionTest,
+ ::testing::ValuesIn(params),
+ XAttentionTest::getTestCaseName);
+
+} // namespace XAttentionUnitTest