Skip to content

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

Add XAttention reference operation (#31864)

Vasily Shamporov175e5d7c5284
diff --git a/src/core/reference/include/openvino/reference/xattention.hpp b/src/core/reference/include/openvino/reference/xattention.hpp
new file mode 100644
index 00000000000..6e847d57053
--- /dev/null
+++ b/src/core/reference/include/openvino/reference/xattention.hpp
@@ -0,0 +1,346 @@
+// Copyright (C) 2018-2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cmath>
+#include <cstddef>
+#include <memory>
+#include <queue>
+
+#include "openvino/reference/divide.hpp"
+#include "openvino/reference/matmul.hpp"
+#include "openvino/reference/softmax.hpp"
+#include "openvino/reference/transpose.hpp"
+#include "openvino/runtime/tensor.hpp"
+
+namespace ov::reference {
+
+using XAttentionBlockIndex =
+ std::pair<size_t, size_t>; // .first is the *query* dimension block index, .second is *key*
+using XAttentionRetainedBlockIndices = std::set<XAttentionBlockIndex>;
+using XAttentionRetainedBlockIndicesForAllHeads = std::vector<XAttentionRetainedBlockIndices>;
+
+/** @brief Reference implementation of the XAttention sparse attention prefill mechanism
+ * (https://arxiv.org/abs/2503.16428) */
+template <typename T>
+class XAttentionBlockSelector {
+public:
+ /** @param threshold Defines a threshold for introduced block sparsity - XAttention attempts to preserve the
+ * smallest subset of attention score matrix blocks so that the ratio of the attention score sum to the total sum of
+ * attention score matrix elements is no less than `threshold`. In other words, `threshold` defines a fraction of
+ * the attention score mass which is to be preserved by most "important" blocks. Valid range is 0.0-1.0, with 0.0
+ * corresponding to 0% of the blocks retained, and 1.0 corresponding to 100% of the blocks retained.
+ * @param block_size The size of blocks into which the attention score matrix [num_heads, query_token_dimension,
+ * key_token_dimension] will be subdivided for purposes of determining the subset of the most important blocks
+ * according to `threshold`. This subdivision occurs on query and key dimensions of the attention score matrix with
+ * the same granularity, i.e. the resulting blocks have equal size on both dimensions. Essentially `block_size`
+ * defines the granularity of the eventual sparse attention computations. Must be a multiple of `stride`.
+ * @param stride The stride at which the full attention matrix is subsampled in a block-antidiagonal fashion to
+ * estimate the block importance. Note that the full attention matrix is not computed, instead the original query
+ * and key matrices are reshaped appropriately so that only the necessary elements are computed. Ideally, the
+ * computational complexity of the entire block estimation operation is `stride` times lower than the full attention
+ * matrix computation.
+ * */
+ XAttentionBlockSelector(double threshold, size_t block_size, size_t stride)
+ : m_threshold(threshold),
+ m_block_size(block_size),
+ m_stride(stride) {
+ OPENVINO_ASSERT(m_block_size % m_stride == 0);
+ }
+
+ /** Assuming the input tensor is either a query tensor or key tensor, reshapes it in a diagonal or antidiagonal
+ * fashion as appropriate so that the resulting matrices could be used to compute the block-antidiagonal subset of
+ * the attention matrix in further operations. For the query tensor, the antidiagonal reshaping should be applied,
+ * and diagonal - for the key tensor. Note that for the diagonal reshaping the data layout is effectively unchanged
+ * and only the shape can be adjusted in the efficient implementation of the same operation in HW.
+ * @param input_data Pointer to the input tensor data (query or key)
+ * @param input_shape Shape of the input tensor data (query or key). Expected shape is [num_heads, num_tokens,
+ * head_size], where `num_tokens` must be a multiple of `stride`.
+ * @param output_data Pointer to the output tensor data (reshaped query or key storage)
+ * @param out_shape Shape of the output tensor data. Expected shape is [num_heads, num_tokens / stride, head_size *
+ * stride]
+ * @param is_antidiagonal Whether to reshape antidiagonally (true) or diagonally (false). Use `true` for query
+ * tensor and `false` for key tensor.
+ */
+ void diagonal_reshape(const T* input_data,
+ const Shape& input_shape,
+ T* output_data,
+ const Shape& out_shape,
+ bool is_antidiagonal) {
+ OPENVINO_ASSERT(input_shape.size() == 3); // [num_heads, num_tokens, head_size]
+ OPENVINO_ASSERT(out_shape.size() == 3);
+ OPENVINO_ASSERT(input_shape[0] == out_shape[0]);
+ OPENVINO_ASSERT(input_shape[1] % m_stride == 0);
+ OPENVINO_ASSERT(input_shape[1] / m_stride == out_shape[1]);
+ OPENVINO_ASSERT(input_shape[2] * m_stride == out_shape[2]);
+
+ size_t num_stride_steps = input_shape[1] / m_stride;
+ for (size_t head_idx = 0; head_idx < input_shape[0]; head_idx++) {
+ size_t head_offset = head_idx * input_shape[1] * input_shape[2];
+ for (size_t slice_idx = 0; slice_idx < m_stride; slice_idx++) {
+ for (size_t stride_idx = 0; stride_idx < num_stride_steps; stride_idx++) {
+ size_t input_offset = head_offset;
+ size_t output_offset = head_offset + stride_idx * out_shape[2] + slice_idx * input_shape[2];
+ if (is_antidiagonal) {
+ input_offset += (input_shape[1] - 1 - slice_idx - stride_idx * m_stride) * input_shape[2];
+ } else {
+ input_offset += (slice_idx + stride_idx * m_stride) * input_shape[2];
+ }
+ std::memcpy(output_data + output_offset, input_data + input_offset, input_shape[2] * sizeof(T));
+ }
+ }
+ }
+ }
+
+ /** Performs a matrix multiplication on the input tensors Q and K and scales the result in a typical attention op
+ * fashion, i.e. Q @ K^T / (sqrt(D) * S). Additionally rescales by the stride value, as compared to the regular
+ * attention.
+ * @param reshaped_query_data Pointer to the reshaped query input.
+ * @param reshaped_key_data Pointer to the reshaped key input.
+ * @param reshaped_query_shape Shape of the reshaped query input data. Expected shape is [num_heads,
+ * num_query_tokens / stride, head_size * stride].
+ * @param reshaped_key_shape Shape of the reshaped key input data. Expected shape is [num_heads, num_key_tokens /
+ * stride, head_size * stride].
+ * @param out Pointer to the output tensor data (attention logit scores)
+ * @param out_shape Shape of the output tensor data. Expected shape is [num_heads, num_query_tokens / stride,
+ * num_key_tokens / stride]
+ */
+ void transpose_matmul_scale(const T* reshaped_query_data,
+ const T* reshaped_key_data,
+ const Shape& reshaped_query_shape,
+ const Shape& reshaped_key_shape,
+ T* out,
+ const Shape& out_shape) {
+ OPENVINO_ASSERT(reshaped_key_shape.size() == 3);
+ OPENVINO_ASSERT(reshaped_query_shape.size() == 3);
+ OPENVINO_ASSERT(reshaped_query_shape[0] == reshaped_key_shape[0]);
+ OPENVINO_ASSERT(reshaped_query_shape[2] == reshaped_key_shape[2]);
+
+ OPENVINO_ASSERT(out_shape.size() == 3);
+ OPENVINO_ASSERT(out_shape[0] == reshaped_query_shape[0]);
+ OPENVINO_ASSERT(out_shape[1] == reshaped_query_shape[1]);
+ OPENVINO_ASSERT(out_shape[2] == reshaped_key_shape[1]);
+
+ ov::reference::matmul(reshaped_query_data,
+ reshaped_key_data,
+ out,
+ reshaped_query_shape,
+ reshaped_key_shape,
+ out_shape,
+ /* transpose_arg0 = */ false,
+ /* transpose_arg1 = */ true);
+
+ size_t out_size = out_shape[0] * out_shape[1] * out_shape[2];
+
+ for (size_t i = 0; i < out_size; i++) {
+ // The D in the formula above refers to the original head dimension, while
+ // reshaped_query_shape[2] had been scaled in the process of reshaping, therefore
+ // the formula is also adjusted:
+ out[i] = out[i] / std::sqrt(reshaped_query_shape[2] * m_stride);
+ }
+ }
+
+ /** Performs a softmax operation on the last dimension of the rank-3 input tensor.
+ * @param reshaped_qk_product_data Pointer to the reshaped query-key product input (attention logits pre-softmax).
+ * @param reshaped_qk_product_shape Shape of the input tensor. Expected shape is [num_heads, num_query_tokens /
+ * stride, num_key_tokens / stride].
+ * @param out Pointer to the output tensor data (attention scores)
+ * @param out_shape Shape of the output tensor data. Expected shape is strictly equal to
+ * `reshaped_qk_product_shape`.
+ */
+ void softmax(const T* reshaped_qk_product_data,
+ const Shape& reshaped_qk_product_shape,
+ T* out,
+ const Shape& out_shape) {
+ OPENVINO_ASSERT(reshaped_qk_product_shape.size() == 3);
+ OPENVINO_ASSERT(reshaped_qk_product_shape == out_shape);
+ ov::reference::softmax(reshaped_qk_product_data, out, reshaped_qk_product_shape, {2});
+ }
+
+ /** Divides the input rank-3 tensor into blocks along last two dimensions, performs the addition of the values
+ * inside each block and outputs each block sum into corresponding positions in the output tensor downsampled along
+ * the same dimensions. The output tensor dimensions are such that the query and key token dimensions are
+ * downsampled by `block_size` when compared to the *original* query and key tensors.
+ * @param attention_scores_data Pointer to the attention score input.
+ * @param attention_score_shape Shape of the attention score input tensor. Expected shape is [num_heads,
+ * num_query_tokens / stride, num_key_tokens / stride], where `num_query_tokens` and `num_key_tokens` must be
+ * multiples of `block_size`.
+ * @param out Pointer to the output tensor data (block sums)
+ * @param out_shape Shape of the output tensor data. Expected shape is [num_heads, num_query_tokens / block_size,
+ * num_key_tokens / block_size].
+ */
+ void block_sum_attention_scores(const T* attention_scores_data,
+ const Shape& attention_scores_shape,
+ T* out,
+ const Shape& out_shape) {
+ OPENVINO_ASSERT(attention_scores_shape.size() == 3); // [num_heads, query_antidiagonals, key_antidiagonals]
+ size_t antidiagonals_per_xattention_block = m_block_size / m_stride;
+ OPENVINO_ASSERT(attention_scores_shape[1] % antidiagonals_per_xattention_block == 0);
+ OPENVINO_ASSERT(attention_scores_shape[2] % antidiagonals_per_xattention_block == 0);
+
+ OPENVINO_ASSERT(out_shape[0] == attention_scores_shape[0]);
+ OPENVINO_ASSERT(out_shape[1] ==
+ attention_scores_shape[1] / antidiagonals_per_xattention_block); // query length, blocked
+ OPENVINO_ASSERT(out_shape[2] ==
+ attention_scores_shape[2] / antidiagonals_per_xattention_block); // key length, blocked
+
+ std::memset(out, 0, out_shape[0] * out_shape[1] * out_shape[2] * sizeof(T));
+
+ for (size_t head_idx = 0; head_idx < attention_scores_shape[0]; head_idx++) {
+ size_t in_head_offset = head_idx * attention_scores_shape[1] * attention_scores_shape[2];
+ size_t out_head_offset = head_idx * out_shape[1] * out_shape[2];
+ for (size_t query_len_idx = 0; query_len_idx < attention_scores_shape[1]; query_len_idx++) {
+ for (size_t key_len_idx = 0; key_len_idx < attention_scores_shape[2]; key_len_idx++) {
+ size_t query_block_idx = query_len_idx / antidiagonals_per_xattention_block;
+ size_t key_block_idx = key_len_idx / antidiagonals_per_xattention_block;
+ auto target_block_sum_ptr = out + out_head_offset + query_block_idx * out_shape[2] + key_block_idx;
+ *target_block_sum_ptr += *(attention_scores_data + in_head_offset +
+ query_len_idx * attention_scores_shape[2] + key_len_idx);
+ }
+ }
+ }
+ }
+
+ /** Selects the elements of the input tensor along the last two dimensions, independently along the first dimension,
+ * so that the elements constitute a smallest subset constituting a sum portion no less than `threshold` of the
+ * total element sum.
+ * @param blocked_scores_data Pointer to the blocked score input.
+ * @param blocked_attention_scores_shape Shape of the blocked score input tensor. Expected shape is [num_heads,
+ * num_query_tokens / block_size, num_key_tokens / block_size]
+ * @return A vector of size `num_heads` of sets, each set containing pairs of block indices (.first is the block
+ * index along the query dimension, .second - along the key). Each set is the head-specific subset of blocks
+ * corresponding to the property described above.
+ */
+ XAttentionRetainedBlockIndicesForAllHeads get_block_indices_to_keep(const T* blocked_attention_scores_data,
+ const Shape& blocked_attention_scores_shape) {
+ OPENVINO_ASSERT(blocked_attention_scores_shape.size() ==
+ 3); // [num_heads, num_blocks_in_query, num_blocks_in_key]
+
+ auto retval = XAttentionRetainedBlockIndicesForAllHeads(blocked_attention_scores_shape[0]);
+
+ struct IndexAndScore {
+ XAttentionBlockIndex idx;
+ T score;
+ bool operator<(const IndexAndScore& rhs) const {
+ return score < rhs.score;
+ }
+ };
+
+ for (size_t head_idx = 0; head_idx < blocked_attention_scores_shape[0]; head_idx++) {
+ size_t head_offset = head_idx * blocked_attention_scores_shape[1] * blocked_attention_scores_shape[2];
+ std::priority_queue<IndexAndScore> indices_and_scores_queue;
+ double total_sum = 0.0;
+ for (size_t q_block_idx = 0; q_block_idx < blocked_attention_scores_shape[1]; q_block_idx++) {
+ for (size_t k_block_idx = 0; k_block_idx < blocked_attention_scores_shape[2]; k_block_idx++) {
+ size_t target_offset = head_offset + blocked_attention_scores_shape[2] * q_block_idx + k_block_idx;
+ T current_score = *(blocked_attention_scores_data + target_offset);
+ indices_and_scores_queue.push({{q_block_idx, k_block_idx}, current_score});
+ total_sum += current_score;
+ }
+ }
+ double cumsum = 0.0;
+ double required_sum = m_threshold * total_sum;
+ while (cumsum < required_sum && !indices_and_scores_queue.empty()) {
+ auto index_and_largest_score = indices_and_scores_queue.top();
+ indices_and_scores_queue.pop();
+ cumsum += index_and_largest_score.score;
+ retval[head_idx].insert(index_and_largest_score.idx);
+ }
+ }
+ return retval;
+ }
+
+ /** Applies XAttention to the provided query and key matrices, returning the subset of the most important blocks for
+ * each attention head, according to the configured block size and threshold, which are to be preserved in the
+ * subsequent sparse attention computation.
+ * @param query_data Pointer to the query input tensor data
+ * @param query_shape Shape of the query input tensor data. Expected shape is [num_heads, num_query_tokens,
+ * head_size], where `num_query_tokens` must be a multiple of both `block_size` and `stride`, padded with zeroes if
+ * necessary to do so in the real-world scenario.
+ * @param key_data Pointer to the key input tensor data
+ * @param key_shape Shape of the key input tensor data. Expected shape is [num_heads, num_key_tokens, head_size],
+ * where `num_key_tokens` must be a multiple of both `block_size` and `stride`, padded with zeroes if necessary to
+ * do so in the real-world scenario.
+ * @return A vector of size `num_heads` of sets, each set containing pairs of block indices (.first is the block
+ * index along the query dimension, .second - along the key). Each set is the head-specific subset of blocks that
+ * must be preserved in the sparse attention computation. Indices are given in units of XAttention-specific
+ * `block_size` (as configured), which may differ from the block size in the paged attention implementation.
+ */
+ XAttentionRetainedBlockIndicesForAllHeads select_blocks(const T* query_data,
+ const Shape& query_shape,
+ const T* key_data,
+ const Shape& key_shape) {
+ OPENVINO_ASSERT(query_shape.size() == 3); // [num_heads, query_token_len, head_dim]
+ OPENVINO_ASSERT(key_shape.size() == 3); // [num_heads, key_token_len, head_dim]
+
+ OPENVINO_ASSERT(key_shape[0] == query_shape[0]);
+ OPENVINO_ASSERT(key_shape[2] == query_shape[2]);
+
+ OPENVINO_ASSERT(query_shape[1] % m_stride == 0);
+ OPENVINO_ASSERT(key_shape[1] % m_stride == 0);
+
+ OPENVINO_ASSERT(query_shape[1] % m_block_size == 0);
+ OPENVINO_ASSERT(key_shape[1] % m_block_size == 0);
+
+ Shape reshaped_query_shape = {query_shape[0], query_shape[1] / m_stride, query_shape[2] * m_stride};
+ auto q_buf = allocate_buf(reshaped_query_shape);
+ diagonal_reshape(query_data, query_shape, q_buf.get(), reshaped_query_shape, /* is_antidiagonal = */ true);
+
+ Shape reshaped_key_shape = {key_shape[0], key_shape[1] / m_stride, key_shape[2] * m_stride};
+ auto k_buf = allocate_buf(reshaped_key_shape);
+ diagonal_reshape(key_data, key_shape, k_buf.get(), reshaped_key_shape, /* is_antidiagonal = */ false);
+
+ Shape transpose_matmul_scaled_shape = {key_shape[0], query_shape[1] / m_stride, key_shape[1] / m_stride};
+ auto qk_buf = allocate_buf(transpose_matmul_scaled_shape);
+ transpose_matmul_scale(q_buf.get(),
+ k_buf.get(),
+ reshaped_query_shape,
+ reshaped_key_shape,
+ qk_buf.get(),
+ transpose_matmul_scaled_shape);
+ q_buf.reset();
+ k_buf.reset();
+
+ Shape attention_scores_shape = transpose_matmul_scaled_shape;
+ auto attn_score_buf = allocate_buf(attention_scores_shape);
+ softmax(qk_buf.get(), transpose_matmul_scaled_shape, attn_score_buf.get(), attention_scores_shape);
+ qk_buf.reset();
+
+ size_t antidiagonals_per_xattention_block = m_block_size / m_stride;
+ Shape block_sum_shape = {attention_scores_shape[0],
+ attention_scores_shape[1] / antidiagonals_per_xattention_block,
+ attention_scores_shape[2] / antidiagonals_per_xattention_block};
+ auto block_sum_buf = allocate_buf(block_sum_shape);
+ block_sum_attention_scores(attn_score_buf.get(), attention_scores_shape, block_sum_buf.get(), block_sum_shape);
+ attn_score_buf.reset();
+
+ auto selected_block_indices = get_block_indices_to_keep(block_sum_buf.get(), block_sum_shape);
+ block_sum_buf.reset();
+
+ return selected_block_indices;
+ }
+
+ /**
+ * @param shape Shape of a tensor
+ * @return A shared_ptr owning a buffer that can be used to store tensor data for the given shape.
+ * */
+ std::shared_ptr<T[]> allocate_buf(const Shape& shape) {
+ return std::shared_ptr<T[]>(new T[ov::shape_size(shape)]);
+ }
+
+ /**
+ * @param token_length An integer value
+ * @return The closest multiple of `block_size` to `token_length`, rounding up.
+ * */
+ size_t pad_to_block(size_t token_length) {
+ return (token_length + m_block_size - 1) / m_block_size * m_block_size;
+ }
+
+ double m_threshold;
+ size_t m_block_size;
+ size_t m_stride;
+};
+
+} // namespace ov::reference
diff --git a/src/core/tests/reference/xattention.cpp b/src/core/tests/reference/xattention.cpp
new file mode 100644
index 00000000000..281a4b781c5
--- /dev/null
+++ b/src/core/tests/reference/xattention.cpp
@@ -0,0 +1,550 @@
+// Copyright (C) 2018-2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+#include <openvino/reference/xattention.hpp>
+
+double DEFAULT_THRESHOLD = 0.8;
+size_t DEFAULT_BLOCK_SIZE = 32;
+size_t DEFAULT_STRIDE = 8;
+
+struct E2EBlockSelectTestData {
+ ov::Shape q_shape;
+ std::vector<double> q_data;
+ ov::Shape k_shape;
+ std::vector<double> k_data;
+ double threshold;
+ size_t block_size;
+ size_t stride;
+};
+
+using XAttentionE2EBlockSelectTest = ::testing::TestWithParam<E2EBlockSelectTestData>;
+
+std::vector<E2EBlockSelectTestData> E2E_BLOCK_SELECT_TEST_CASES = {{
+ {2, 4, 4},
+ // clang-format off
+ {
+ 3.144, 8.512, 8.518, -8.386,
+ 7.889, -5.721, 5.507, 4.295,
+ -6.624, -8.463, 7.474, 9.879,
+ 4.534, -5.908, -9.388, 2.356,
+
+ 7.497, 8.186, -8.658, -4.796,
+ -8.248, -9.797, -7.907, -4.513,
+ 3.469, 7.633, 7.244, -6.844,
+ -7.173, 4.450, 6.705, -7.035
+ },
+ // clang-format on
+ {2, 4, 4},
+ // clang-format off
+ {
+ 3.144, 8.512, 8.518, -8.386,
+ 7.889, -5.721, 5.507, 4.295,
+ -6.624, -8.463, 7.474, 9.879,
+ 4.534, -5.908, -9.388, 2.356,
+
+ 7.497, 8.186, -8.658, -4.796,
+ -8.248, -9.797, -7.907, -4.513,
+ 3.469, 7.633, 7.244, -6.844,
+ -7.173, 4.450, 6.705, -7.035
+ },
+ // clang-format on
+
+ /* threshold = */ 0.8,
+ /* block_size = */ 2,
+ /* stride = */ 2,
+}};
+
+TEST_P(XAttentionE2EBlockSelectTest, SelectsBlocksWithoutThrowing) {
+ auto test_struct = GetParam();
+ ov::reference::XAttentionBlockSelector<double> selector(test_struct.threshold,
+ test_struct.block_size,
+ test_struct.stride);
+
+ EXPECT_NO_THROW(selector.select_blocks(test_struct.q_data.data(),
+ test_struct.q_shape,
+ test_struct.k_data.data(),
+ test_struct.k_shape));
+};
+
+INSTANTIATE_TEST_SUITE_P(VariousInputs, XAttentionE2EBlockSelectTest, ::testing::ValuesIn(E2E_BLOCK_SELECT_TEST_CASES));
+
+struct DiagonalReshapeTestData {
+ ov::Shape in_shape;
+ std::vector<double> in_data;
+ bool is_antidiagonal;
+ size_t block_size;
+ size_t stride;
+ ov::Shape out_shape;
+ std::vector<double> ref_out_data;
+};
+
+using XAttentionDiagonalReshapeTest = ::testing::TestWithParam<DiagonalReshapeTestData>;
+
+std::vector<DiagonalReshapeTestData> DIAGONAL_RESHAPE_TEST_CASES = {
+ {
+ {2, 4, 4},
+ // clang-format off
+ {
+ 3.144, 8.512, 8.518, -8.386,
+ 7.889, -5.721, 5.507, 4.295,
+ -6.624, -8.463, 7.474, 9.879,
+ 4.534, -5.908, -9.388, 2.356,
+
+ 7.497, 8.186, -8.658, -4.796,
+ -8.248, -9.797, -7.907, -4.513,
+ 3.469, 7.633, 7.244, -6.844,
+ -7.173, 4.450, 6.705, -7.035
+ },
+ // clang-format on
+
+ /* is_antidiagonal = */ true,
+ /* block_size = */ 2,
+ /* stride = */ 2,
+ {2, 2, 8},
+
+ // clang-format off
+ {
+ 4.534, -5.908, -9.388, 2.356, -6.624, -8.463, 7.474, 9.879,
+ 7.889, -5.721, 5.507, 4.295, 3.144, 8.512, 8.518, -8.386,
+
+ -7.173, 4.450, 6.705, -7.035, 3.469, 7.633, 7.244, -6.844,
+ -8.248, -9.797, -7.907, -4.513, 7.497, 8.186, -8.658, -4.796,
+ },
+ // clang-format on
+ },
+ {
+ {2, 4, 4},
+ // clang-format off
+ {
+ 3.144, 8.512, 8.518, -8.386,
+ 7.889, -5.721, 5.507, 4.295,
+ -6.624, -8.463, 7.474, 9.879,
+ 4.534, -5.908, -9.388, 2.356,
+
+ 7.497, 8.186, -8.658, -4.796,
+ -8.248, -9.797, -7.907, -4.513,
+ 3.469, 7.633, 7.244, -6.844,
+ -7.173, 4.450, 6.705, -7.035
+ },
+ // clang-format on
+
+ /* is_antidiagonal = */ false,
+ /* block_size = */ 2,
+ /* stride = */ 2,
+ {2, 2, 8},
+
+ // clang-format off
+ {
+ 3.144, 8.512, 8.518, -8.386, 7.889, -5.721, 5.507, 4.295,
+ -6.624, -8.463, 7.474, 9.879, 4.534, -5.908, -9.388, 2.356,
+
+ 7.497, 8.186, -8.658, -4.796, -8.248, -9.797, -7.907, -4.513,
+ 3.469, 7.633, 7.244, -6.844, -7.173, 4.450, 6.705, -7.035
+ },
+ // clang-format on
+ },
+ {
+ {2, 9, 2},
+ // clang-format off
+ {
+ 1.110, -4.244,
+ 3.530, -1.083,
+ 3.664, -2.459,
+ 3.930, -2.122,
+ -4.142, 2.837,
+ -7.413, 5.855,
+ 1.354, -7.748,
+ 0.264, 7.095,
+ -8.410, 6.247,
+
+ -7.832, 9.163,
+ -7.414, -3.682,
+ -5.429, 7.854,
+ 1.767, 5.950,
+ -0.841, 1.935,
+ 3.568, 8.530,
+ 9.438, -2.421,
+ -5.892, 7.820,
+ -9.869, -7.636
+ },
+ // clang-format on
+
+ /* is_antidiagonal = */ true,
+ /* block_size = */ 9,
+ /* stride = */ 3,
+ {2, 3, 6},
+
+ // clang-format off
+ {
+ -8.410, 6.247, 0.264, 7.095, 1.354, -7.748,
+ -7.413, 5.855, -4.142, 2.837, 3.930, -2.122,
+ 3.664, -2.459, 3.530, -1.083, 1.110, -4.244,
+
+ -9.869, -7.636, -5.892, 7.820, 9.438, -2.421,
+ 3.568, 8.530, -0.841, 1.935, 1.767, 5.950,
+ -5.429, 7.854, -7.414, -3.682, -7.832, 9.163,
+ },
+ // clang-format on
+ },
+ {
+ {2, 9, 2},
+ // clang-format off
+ {
+ 1.110, -4.244,
+ 3.530, -1.083,
+ 3.664, -2.459,
+ 3.930, -2.122,
+ -4.142, 2.837,
+ -7.413, 5.855,
+ 1.354, -7.748,
+ 0.264, 7.095,
+ -8.410, 6.247,
+
+ -7.832, 9.163,
+ -7.414, -3.682,
+ -5.429, 7.854,
+ 1.767, 5.950,
+ -0.841, 1.935,
+ 3.568, 8.530,
+ 9.438, -2.421,
+ -5.892, 7.820,
+ -9.869, -7.636
+ },
+ // clang-format on
+
+ /* is_antidiagonal = */ false,
+ /* block_size = */ 9,
+ /* stride = */ 3,
+ {2, 3, 6},
+
+ // clang-format off
+ {
+ 1.110, -4.244, 3.530, -1.083, 3.664, -2.459,
+ 3.930, -2.122, -4.142, 2.837, -7.413, 5.855,
+ 1.354, -7.748, 0.264, 7.095, -8.410, 6.247,
+
+ -7.832, 9.163, -7.414, -3.682, -5.429, 7.854,
+ 1.767, 5.950, -0.841, 1.935, 3.568, 8.530,
+ 9.438, -2.421, -5.892, 7.820, -9.869, -7.636
+ },
+ // clang-format on
+ },
+};
+
+TEST_P(XAttentionDiagonalReshapeTest, ReshapesDiagonally) {
+ auto test_struct = GetParam();
+ ASSERT_EQ(test_struct.in_data.size(), ov::shape_size(test_struct.in_shape));
+ ASSERT_EQ(test_struct.ref_out_data.size(), ov::shape_size(test_struct.out_shape));
+
+ ov::reference::XAttentionBlockSelector<double> selector(DEFAULT_THRESHOLD,
+ test_struct.block_size,
+ test_struct.stride);
+ std::vector<double> test_out_data(test_struct.ref_out_data.size());
+ selector.diagonal_reshape(test_struct.in_data.data(),
+ test_struct.in_shape,
+ test_out_data.data(),
+ test_struct.out_shape,
+ test_struct.is_antidiagonal);
+ EXPECT_EQ(test_out_data, test_struct.ref_out_data);
+}
+
+INSTANTIATE_TEST_SUITE_P(VariousInputs,
+ XAttentionDiagonalReshapeTest,
+ ::testing::ValuesIn(DIAGONAL_RESHAPE_TEST_CASES));
+
+struct TransposeMatmulScaleTestData {
+ ov::Shape reshaped_query_shape;
+ std::vector<double> reshaped_query_data;
+ ov::Shape reshaped_key_shape;
+ std::vector<double> reshaped_key_data;
+ size_t block_size;
+ size_t stride;
+ ov::Shape out_shape;
+ std::vector<double> ref_out_data;
+};
+
+using XAttentionTransposeMatmulScaleTest = ::testing::TestWithParam<TransposeMatmulScaleTestData>;
+
+std::vector<TransposeMatmulScaleTestData> TRANSPOSE_MATMUL_SCALE_TEST_CASES = {
+ {
+ {2, 2, 8},
+ // clang-format off
+ {
+ 4.534, -5.908, -9.388, 2.356, -6.624, -8.463, 7.474, 9.879,
+ 7.889, -5.721, 5.507, 4.295, 3.144, 8.512, 8.518, -8.386,
+
+ -7.173, 4.450, 6.705, -7.035, 3.469, 7.633, 7.244, -6.844,
+ -8.248, -9.797, -7.907, -4.513, 7.497, 8.186, -8.658, -4.796,
+ },
+ // clang-format on
+
+ {2, 3, 8},
+
+ // clang-format off
+ {
+ -2.731, -0.545, 6.128, -6.175, -2.198, -1.275, -8.617, -0.683,
+ 3.085, 7.929, -1.127, 5.369, -6.891, 9.582, -6.954, 1.189,
+ -0.610, -6.310, -9.216, -1.196, 9.509, -8.119, 4.652, -4.435,
+
+ -0.026, -9.294, 7.862, 9.318, -6.012, 8.252, -3.224, -0.710,
+ -2.915, -7.362, -5.553, 0.097, -4.509, 6.993, 2.021, 2.870,
+ -3.682, 8.637, -9.922, -6.336, -2.949, 4.339, -2.807, -9.192
+ },
+
+ /* block_size = */ 2,
+ /* stride = */ 2,
+ {2, 2, 3},
+
+ // clang-format off
+ {
+ -31.760349, -21.32551225, 28.723734,
+ -24.15923075, -3.369805999, 3.2507255,
+
+ -7.593187497, -4.258293245, 27.08950801,
+ 10.21206450, 32.95415775, 33.649577
+ },
+ // clang-format on
+ },
+};
+
+TEST_P(XAttentionTransposeMatmulScaleTest, TransposesMatmulsAndScales) {
+ auto test_struct = GetParam();
+ ASSERT_EQ(test_struct.reshaped_key_data.size(), ov::shape_size(test_struct.reshaped_key_shape));
+ ASSERT_EQ(test_struct.reshaped_query_data.size(), ov::shape_size(test_struct.reshaped_query_shape));
+ ASSERT_EQ(test_struct.ref_out_data.size(), ov::shape_size(test_struct.out_shape));
+
+ ov::reference::XAttentionBlockSelector<double> selector(DEFAULT_THRESHOLD,
+ test_struct.block_size,
+ test_struct.stride);
+ std::vector<double> test_out_data(test_struct.ref_out_data.size());
+ selector.transpose_matmul_scale(test_struct.reshaped_query_data.data(),
+ test_struct.reshaped_key_data.data(),
+ test_struct.reshaped_query_shape,
+ test_struct.reshaped_key_shape,
+ test_out_data.data(),
+ test_struct.out_shape);
+
+ EXPECT_THAT(test_out_data, ::testing::Pointwise(::testing::DoubleNear(1e-8), test_struct.ref_out_data));
+}
+
+INSTANTIATE_TEST_SUITE_P(VariousInputs,
+ XAttentionTransposeMatmulScaleTest,
+ ::testing::ValuesIn(TRANSPOSE_MATMUL_SCALE_TEST_CASES));
+
+struct SoftmaxTestData {
+ ov::Shape in_shape;
+ std::vector<double> in_data;
+ ov::Shape out_shape;
+ std::vector<double> ref_out_data;
+};
+
+using XAttentionSoftmaxTest = ::testing::TestWithParam<SoftmaxTestData>;
+
+std::vector<SoftmaxTestData> SOFTMAX_TEST_CASES = {
+ {
+ {2, 2, 4},
+ // clang-format off
+ {
+ 4.534, -5.908, -9.388, 2.356,
+ 7.889, -5.721, 5.507, 4.295,
+
+ -7.173, 4.450, 6.705, -7.035,
+ -8.248, -9.797, -7.907, -4.513
+ },
+ // clang-format on
+
+ {2, 2, 4},
+
+ // clang-format off
+ {
+ 0.898232, 2.62111e-05, 8.07497e-07, 0.101741,
+ 0.892973, 1.09671e-06, 0.08248, 0.0245462,
+
+ 8.50252e-07, 0.0949189, 0.905079, 9.76069e-07,
+ 0.0224685, 0.00477366, 0.0315986, 0.941159
+ },
+ },
+};
+
+TEST_P(XAttentionSoftmaxTest, SoftmaxIsCorrect) {
+ auto test_struct = GetParam();
+ ASSERT_EQ(test_struct.in_data.size(), ov::shape_size(test_struct.in_shape));
+ ASSERT_EQ(test_struct.ref_out_data.size(), ov::shape_size(test_struct.out_shape));
+
+ ov::reference::XAttentionBlockSelector<double> selector(DEFAULT_THRESHOLD,
+ DEFAULT_BLOCK_SIZE,
+ DEFAULT_STRIDE);
+ std::vector<double> test_out_data(test_struct.ref_out_data.size());
+ selector.softmax(test_struct.in_data.data(), test_struct.in_shape, test_out_data.data(), test_struct.out_shape);
+
+ EXPECT_THAT(test_out_data, ::testing::Pointwise(::testing::DoubleNear(1e-5), test_struct.ref_out_data));
+}
+
+INSTANTIATE_TEST_SUITE_P(VariousInputs,
+ XAttentionSoftmaxTest,
+ ::testing::ValuesIn(SOFTMAX_TEST_CASES));
+
+struct BlockSumTestData {
+ ov::Shape in_shape;
+ std::vector<double> in_data;
+ size_t block_size;
+ size_t stride;
+ ov::Shape out_shape;
+ std::vector<double> ref_out_data;
+};
+
+using XAttentionBlockSumTest = ::testing::TestWithParam<BlockSumTestData>;
+
+std::vector<BlockSumTestData> BLOCK_SUM_TEST_CASES = {
+ {
+ {2, 4, 8},
+ // clang-format off
+ {
+ 0.1117, 0.0780, 0.1347, 0.0885, 0.1942, 0.0922, 0.1184, 0.1824,
+ 0.1488, 0.1766, 0.0852, 0.1239, 0.0930, 0.1220, 0.1367, 0.1138,
+ 0.1410, 0.0861, 0.0774, 0.1325, 0.1478, 0.1689, 0.0885, 0.1579,
+ 0.1248, 0.1038, 0.1842, 0.0935, 0.1813, 0.0890, 0.0897, 0.1336,
+
+ 0.0905, 0.1049, 0.1263, 0.0953, 0.1018, 0.1297, 0.1659, 0.1855,
+ 0.1373, 0.1791, 0.1005, 0.1286, 0.1492, 0.1373, 0.0820, 0.0860,
+ 0.0997, 0.1285, 0.0786, 0.1366, 0.1963, 0.0904, 0.1488, 0.1211,
+ 0.1859, 0.1174, 0.1364, 0.0930, 0.1028, 0.1034, 0.1699, 0.0912
+ },
+ // clang-format on
+
+ /* block_size = */ 8,
+ /* stride = */ 4,
+ {2, 2, 4},
+
+ // clang-format off
+ {
+ 0.5151, 0.4323, 0.5014, 0.5513,
+ 0.4557, 0.4876, 0.5870, 0.4697,
+
+ 0.5118, 0.4507, 0.5180, 0.5194,
+ 0.5315, 0.4446, 0.4929, 0.5310
+ },
+ },
+};
+TEST_P(XAttentionBlockSumTest, BlockSumIsCorrect) {
+ auto test_struct = GetParam();
+ ASSERT_EQ(test_struct.in_data.size(), ov::shape_size(test_struct.in_shape));
+ ASSERT_EQ(test_struct.ref_out_data.size(), ov::shape_size(test_struct.out_shape));
+
+ ov::reference::XAttentionBlockSelector<double> selector(DEFAULT_THRESHOLD,
+ test_struct.block_size,
+ test_struct.stride);
+ std::vector<double> test_out_data(test_struct.ref_out_data.size());
+ selector.block_sum_attention_scores(test_struct.in_data.data(), test_struct.in_shape, test_out_data.data(), test_struct.out_shape);
+
+ EXPECT_THAT(test_out_data, ::testing::Pointwise(::testing::DoubleNear(1e-5), test_struct.ref_out_data));
+}
+
+INSTANTIATE_TEST_SUITE_P(VariousInputs,
+ XAttentionBlockSumTest,
+ ::testing::ValuesIn(BLOCK_SUM_TEST_CASES));
+
+struct BlockSelectTestData {
+ ov::Shape in_shape;
+ std::vector<double> in_data;
+ double threshold;
+ ov::reference::XAttentionRetainedBlockIndicesForAllHeads ref_retained_block_indices;
+};
+
+using XAttentionBlockSelectTest = ::testing::TestWithParam<BlockSelectTestData>;
+
+std::vector<BlockSelectTestData> BLOCK_SELECT_TEST_CASES = {
+ {
+ {2, 2, 4},
+ // clang-format off
+ {
+ 0.5151, 0.4323, 0.5014, 0.5513,
+ 0.4557, 0.4876, 0.5870, 0.4697,
+
+ 0.5118, 0.4507, 0.5180, 0.5194,
+ 0.5315, 0.4446, 0.4929, 0.5310
+ },
+ // clang-format on
+ /* threshold = */ 0.25,
+ {
+ {{1, 2}, {0, 3}},
+ {{1, 0}, {1, 3}},
+ }},
+
+ {{2, 2, 4},
+ // clang-format off
+ {
+ 0.5151, 0.4323, 0.5014, 0.5513,
+ 0.4557, 0.4876, 0.5870, 0.4697,
+
+ 0.5118, 0.4507, 0.5180, 0.5194,
+ 0.5315, 0.4446, 0.4929, 0.5310
+ },
+ // clang-format on
+ /* threshold = */ 0.35,
+ {
+ {{1, 2}, {0, 3}, {0, 0}},
+ {{1, 0}, {1, 3}, {0, 3}},
+ }},
+ {{2, 2, 4},
+ // clang-format off
+ {
+ 0.5151, 0.4323, 0.5014, 0.5513,
+ 0.4557, 0.4876, 0.5870, 0.4697,
+
+ 0.5118, 0.4507, 0.5180, 0.5194,
+ 0.5315, 0.4446, 0.4929, 0.5310
+ },
+ // clang-format on
+ /* threshold = */ 0.1,
+ {
+ {{1, 2}},
+ {{1, 0}},
+ }},
+ {{2, 2, 4},
+ // clang-format off
+ {
+ 0.5151, 0.4323, 0.5014, 0.5513,
+ 0.4557, 0.4876, 0.5870, 0.4697,
+
+ 0.5118, 0.4507, 0.5180, 0.5194,
+ 0.5315, 0.4446, 0.4929, 0.5310
+ },
+ // clang-format on
+ /* threshold = */ 0.0,
+ {
+ {},
+ {},
+ }},
+ {{2, 2, 4},
+ // clang-format off
+ {
+ 0.5151, 0.4323, 0.5014, 0.5513,
+ 0.4557, 0.4876, 0.5870, 0.4697,
+
+ 0.5118, 0.4507, 0.5180, 0.5194,
+ 0.5315, 0.4446, 0.4929, 0.5310
+ },
+ // clang-format on
+ /* threshold = */ 1.0,
+ {
+ {{1, 2}, {0, 3}, {0, 0}, {0, 2}, {1, 1}, {1, 3}, {1, 0}, {0, 1}},
+ {{1, 0}, {1, 3}, {0, 3}, {0, 2}, {0, 0}, {1, 2}, {0, 1}, {1, 1}},
+ }},
+};
+
+TEST_P(XAttentionBlockSelectTest, BlockSelectionIsCorrect) {
+ auto test_struct = GetParam();
+ ASSERT_EQ(test_struct.in_data.size(), ov::shape_size(test_struct.in_shape));
+
+ ov::reference::XAttentionBlockSelector<double> selector(test_struct.threshold, DEFAULT_BLOCK_SIZE, DEFAULT_STRIDE);
+ auto test_result = selector.get_block_indices_to_keep(test_struct.in_data.data(), test_struct.in_shape);
+
+ EXPECT_EQ(test_result, test_struct.ref_retained_block_indices);
+}
+
+INSTANTIATE_TEST_SUITE_P(VariousInputs, XAttentionBlockSelectTest, ::testing::ValuesIn(BLOCK_SELECT_TEST_CASES));