Skip to content

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

[GPU] Add Adaptive RKV Diversity Calculation Support to PagedAttention (#33568)

Andrew Kwangwoong Park083dcb639be7
diff --git a/src/core/reference/include/openvino/reference/adaptive_rkv_diversity.hpp b/src/core/reference/include/openvino/reference/adaptive_rkv_diversity.hpp
index 6b2921c2e5e..10b9495c957 100644
--- a/src/core/reference/include/openvino/reference/adaptive_rkv_diversity.hpp
+++ b/src/core/reference/include/openvino/reference/adaptive_rkv_diversity.hpp
@@ -79,7 +79,7 @@ public:
for (size_t reduced_dim_idx = 0; reduced_dim_idx < in_out_shape[2]; reduced_dim_idx++) {
size_t target_offset = in_head_offset + token_offset + reduced_dim_idx;
T filled_val = in_out[target_offset];
- in_out[target_offset] = filled_val >= mean_val ? filled_val : 0.0;
+ in_out[target_offset] = filled_val >= mean_val ? filled_val : T{0};
}
}
}
diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/paged_attention.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/paged_attention.hpp
index c01687203db..ba320e21af7 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/primitives/paged_attention.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/paged_attention.hpp
@@ -70,6 +70,7 @@ struct paged_attention : public primitive_base<paged_attention> {
seed = hash_combine(seed, has_score_aggregation);
seed = hash_combine(seed, has_xattention);
seed = hash_combine(seed, has_sink_input);
+ seed = hash_combine(seed, has_adaptive_rkv);
if (scale_val.has_value()) {
seed = hash_combine(seed, scale_val.value());
}
@@ -88,11 +89,15 @@ struct paged_attention : public primitive_base<paged_attention> {
v_head_size == rhs_casted.v_head_size &&
heads_num == rhs_casted.heads_num &&
kv_heads_num == rhs_casted.kv_heads_num &&
- sliding_window == rhs_casted.sliding_window &&
has_alibi == rhs_casted.has_alibi &&
- has_score_aggregation == rhs_casted.has_score_aggregation &&
has_rotated_blocks == rhs_casted.has_rotated_blocks &&
- scale_val.value_or(1.0f) == rhs_casted.scale_val.value_or(1.0f);
+ sliding_window == rhs_casted.sliding_window &&
+ has_score_aggregation == rhs_casted.has_score_aggregation &&
+ has_xattention == rhs_casted.has_xattention &&
+ has_sink_input == rhs_casted.has_sink_input &&
+ has_adaptive_rkv == rhs_casted.has_adaptive_rkv &&
+ scale_val.value_or(1.0f) == rhs_casted.scale_val.value_or(1.0f) &&
+ is_key_by_channel == rhs_casted.is_key_by_channel;
}
void save(BinaryOutputBuffer& ob) const override {
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_adaptive_rkv_diversity_ref.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_adaptive_rkv_diversity_ref.cl
new file mode 100644
index 00000000000..c25918c0f92
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_adaptive_rkv_diversity_ref.cl
@@ -0,0 +1,323 @@
+// Copyright (C) 2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "include/batch_headers/common.cl"
+
+// Key cache offset macros (all offsets in bytes: int8=1, half=2)
+#if KV_CACHE_COMPRESSED
+ #if KEY_CACHE_QUANT_MODE == 1 // BY_CHANNEL: per-dimension scale/zp
+ // Layout: [num_blocks, KV_HEADS_NUM, K_HEAD_SIZE, BLOCK_SIZE+4]
+ #define KEY_CACHE_OFFSET(physical_block, token_offset, d) \
+ ((physical_block) * KV_HEADS_NUM * K_HEAD_SIZE * \
+ (PAGED_ATTENTION_BLOCK_SIZE + COMPRESSED_EXTRA_DIMS) + \
+ head_idx * K_HEAD_SIZE * (PAGED_ATTENTION_BLOCK_SIZE + COMPRESSED_EXTRA_DIMS) + \
+ (d) * (PAGED_ATTENTION_BLOCK_SIZE + COMPRESSED_EXTRA_DIMS) + (token_offset))
+ #define KEY_CACHE_SCALE_OFFSET(physical_block, d) \
+ ((physical_block) * KV_HEADS_NUM * K_HEAD_SIZE * \
+ (PAGED_ATTENTION_BLOCK_SIZE + COMPRESSED_EXTRA_DIMS) + \
+ head_idx * K_HEAD_SIZE * (PAGED_ATTENTION_BLOCK_SIZE + COMPRESSED_EXTRA_DIMS) + \
+ (d) * (PAGED_ATTENTION_BLOCK_SIZE + COMPRESSED_EXTRA_DIMS) + \
+ PAGED_ATTENTION_BLOCK_SIZE)
+ #define KEY_CACHE_ZP_OFFSET(physical_block, d) \
+ (KEY_CACHE_SCALE_OFFSET(physical_block, d) + SIZEOF_HALF)
+ #elif KEY_CACHE_QUANT_MODE == 2 // BY_TOKEN: per-token scale/zp
+ // Layout: [num_blocks, KV_HEADS_NUM, K_HEAD_SIZE+4, BLOCK_SIZE]
+ // Scale at [K_HEAD_SIZE], ZP at [K_HEAD_SIZE+2] (token_offset * 2 for half)
+ #define KEY_CACHE_OFFSET(physical_block, token_offset, d) \
+ ((physical_block) * KV_HEADS_NUM * (K_HEAD_SIZE + COMPRESSED_EXTRA_DIMS) * \
+ PAGED_ATTENTION_BLOCK_SIZE + \
+ head_idx * (K_HEAD_SIZE + COMPRESSED_EXTRA_DIMS) * PAGED_ATTENTION_BLOCK_SIZE + \
+ (d) * PAGED_ATTENTION_BLOCK_SIZE + (token_offset))
+ #define KEY_CACHE_SCALE_OFFSET(physical_block, token_offset) \
+ ((physical_block) * KV_HEADS_NUM * (K_HEAD_SIZE + COMPRESSED_EXTRA_DIMS) * \
+ PAGED_ATTENTION_BLOCK_SIZE + \
+ head_idx * (K_HEAD_SIZE + COMPRESSED_EXTRA_DIMS) * PAGED_ATTENTION_BLOCK_SIZE + \
+ K_HEAD_SIZE * PAGED_ATTENTION_BLOCK_SIZE + (token_offset) * SIZEOF_HALF)
+ #define KEY_CACHE_ZP_OFFSET(physical_block, token_offset) \
+ (KEY_CACHE_SCALE_OFFSET(physical_block, token_offset) + SIZEOF_HALF * PAGED_ATTENTION_BLOCK_SIZE)
+ #endif
+#else
+ // Uncompressed layout: [num_blocks, KV_HEADS_NUM, K_HEAD_SIZE, PAGED_ATTENTION_BLOCK_SIZE]
+ #define KEY_CACHE_OFFSET(physical_block, token_offset, d) \
+ ((physical_block) * KV_HEADS_NUM * K_HEAD_SIZE * PAGED_ATTENTION_BLOCK_SIZE + \
+ head_idx * K_HEAD_SIZE * PAGED_ATTENTION_BLOCK_SIZE + \
+ (d) * PAGED_ATTENTION_BLOCK_SIZE + (token_offset))
+#endif
+
+// Helper macro for normalizing a buffer in-place
+#define NORMALIZE_BUFFER(buffer, size) \
+ do { \
+ barrier(CLK_LOCAL_MEM_FENCE); \
+ ACCUMULATOR_TYPE norm_sq_temp = 0.0f; \
+ for (uint d = sglid; d < size; d += SUBGROUP_SIZE) { \
+ norm_sq_temp += buffer[d] * buffer[d]; \
+ } \
+ norm_sq_temp = sub_group_reduce_add(norm_sq_temp); \
+ ACCUMULATOR_TYPE norm_temp = native_sqrt(norm_sq_temp + EPSILON); \
+ for (uint d = sglid; d < size; d += SUBGROUP_SIZE) { \
+ buffer[d] /= norm_temp; \
+ } \
+ barrier(CLK_LOCAL_MEM_FENCE); \
+ } while(0)
+
+#if KV_CACHE_COMPRESSED
+ #define LOAD_SCALE_ZP_BY_CHANNEL(physical_block, d, scale_var, zp_var) \
+ do { \
+ __global const half* scale_ptr = \
+ (__global const half*)&key_cache[KEY_CACHE_SCALE_OFFSET(physical_block, d)]; \
+ __global const half* zp_ptr = \
+ (__global const half*)&key_cache[KEY_CACHE_ZP_OFFSET(physical_block, d)]; \
+ scale_var = (ACCUMULATOR_TYPE)(*scale_ptr); \
+ zp_var = (ACCUMULATOR_TYPE)(*zp_ptr); \
+ } while(0)
+
+ #define LOAD_SCALE_ZP_BY_TOKEN(physical_block, token_offset, scale_var, zp_var) \
+ do { \
+ __global const half* scale_ptr = \
+ (__global const half*)&key_cache[KEY_CACHE_SCALE_OFFSET(physical_block, token_offset)]; \
+ __global const half* zp_ptr = \
+ (__global const half*)&key_cache[KEY_CACHE_ZP_OFFSET(physical_block, token_offset)]; \
+ scale_var = (ACCUMULATOR_TYPE)(*scale_ptr); \
+ zp_var = (ACCUMULATOR_TYPE)(*zp_ptr); \
+ } while(0)
+#endif
+
+// Load and normalize key vectors (with dequantization if compressed)
+#if KV_CACHE_COMPRESSED
+#define LOAD_AND_NORMALIZE_KEY(buffer, physical_block, token_offset) \
+ do { \
+ for (int d = sglid; d < K_HEAD_SIZE; d += SUBGROUP_SIZE) { \
+ INPUT0_TYPE raw_value = key_cache[KEY_CACHE_OFFSET(physical_block, token_offset, d)]; \
+ ACCUMULATOR_TYPE value; \
+ if (KEY_CACHE_QUANT_MODE == 1) { \
+ ACCUMULATOR_TYPE scale, zp; \
+ LOAD_SCALE_ZP_BY_CHANNEL(physical_block, d, scale, zp); \
+ value = ((ACCUMULATOR_TYPE)raw_value - zp) * scale; \
+ } else if (KEY_CACHE_QUANT_MODE == 2) { \
+ ACCUMULATOR_TYPE scale, zp; \
+ LOAD_SCALE_ZP_BY_TOKEN(physical_block, token_offset, scale, zp); \
+ value = ((ACCUMULATOR_TYPE)raw_value - zp) * scale; \
+ } \
+ buffer[d] = value; \
+ } \
+ NORMALIZE_BUFFER(buffer, K_HEAD_SIZE); \
+ } while(0)
+#else
+#define LOAD_AND_NORMALIZE_KEY(buffer, physical_block, token_offset) \
+ do { \
+ for (int d = sglid; d < K_HEAD_SIZE; d += SUBGROUP_SIZE) { \
+ buffer[d] = (ACCUMULATOR_TYPE)key_cache[KEY_CACHE_OFFSET(physical_block, token_offset, d)]; \
+ } \
+ NORMALIZE_BUFFER(buffer, K_HEAD_SIZE); \
+ } while(0)
+#endif
+
+REQD_SUB_GROUP_SIZE(SUBGROUP_SIZE)
+__attribute__((reqd_work_group_size(SUBGROUP_SIZE, 1, 1)))
+KERNEL(pa_adaptive_rkv_diversity)(
+ OPTIONAL_SHAPE_INFO_ARG
+ __global const INPUT0_TYPE* key_cache,
+ __global const INPUT1_TYPE* evictable_sizes,
+ __global const INPUT2_TYPE* block_indices,
+ __global const INPUT3_TYPE* block_indices_begins,
+ __global OUTPUT_TYPE* diversity_output,
+ __global ACCUMULATOR_TYPE* similarity_matrix,
+ __global ACCUMULATOR_TYPE* aggregated_similarities,
+ __global ACCUMULATOR_TYPE* row_means,
+ __global ACCUMULATOR_TYPE* block_sums,
+ const int start_size
+) {
+ const uint batch_idx = get_group_id(0);
+ const uint sglid = get_sub_group_local_id();
+ const int evictable_size = evictable_sizes[batch_idx];
+ const int num_evictable_blocks = evictable_size / PAGED_ATTENTION_BLOCK_SIZE;
+
+ if (num_evictable_blocks == 0)
+ return;
+
+ // Calculate diversity output offset for this batch
+ int diversity_output_offset = 0;
+ for (int b = 0; b < batch_idx; b++) {
+ int prev_evictable_size = evictable_sizes[b];
+ int prev_num_blocks = prev_evictable_size / PAGED_ATTENTION_BLOCK_SIZE;
+ diversity_output_offset += prev_num_blocks * prev_evictable_size;
+ }
+
+ // Get block indices range for this batch
+ const int block_begin_idx = block_indices_begins[batch_idx];
+ const int block_end_idx = block_indices_begins[batch_idx + 1];
+ const int num_evictable_blocks_for_batch = block_end_idx - block_begin_idx;
+
+ if (num_evictable_blocks_for_batch != num_evictable_blocks)
+ return;
+
+ // Calculate batch buffer offsets
+ int batch_matrix_offset = 0;
+ int batch_vector_offset = 0;
+ // Accumulate offsets from all previous batches
+ for (int b = 0; b < batch_idx; b++) {
+ int prev_evictable_size = evictable_sizes[b];
+ batch_matrix_offset += prev_evictable_size * prev_evictable_size;
+ batch_vector_offset += prev_evictable_size;
+ }
+
+ // Offset pointers to this batch's region
+ __global ACCUMULATOR_TYPE* similarity_matrix_batch = similarity_matrix + batch_matrix_offset;
+ __global ACCUMULATOR_TYPE* aggregated_similarities_batch = aggregated_similarities + batch_matrix_offset;
+ __global ACCUMULATOR_TYPE* row_means_batch = row_means + batch_vector_offset;
+ __global ACCUMULATOR_TYPE* block_sums_batch = block_sums + batch_vector_offset;
+
+ // Keep normalized_key_i in local memory (small, frequently reused)
+ __local ACCUMULATOR_TYPE normalized_key_i[K_HEAD_SIZE];
+
+ // Memory fence for both global and local memory
+ const cl_mem_fence_flags mem_fence = CLK_GLOBAL_MEM_FENCE | CLK_LOCAL_MEM_FENCE;
+
+ // Initialize aggregated similarities (full matrix)
+ for (int i = sglid; i < evictable_size * evictable_size; i += SUBGROUP_SIZE) {
+ aggregated_similarities_batch[i] = 0.0f;
+ }
+ barrier(mem_fence);
+ for (uint head_idx = 0; head_idx < KV_HEADS_NUM; head_idx++) {
+ // Initialize similarity matrix for this head
+ for (int i = sglid; i < evictable_size * evictable_size; i += SUBGROUP_SIZE) {
+ similarity_matrix_batch[i] = 0.0f;
+ }
+ barrier(mem_fence);
+
+ // Compute cosine similarity (upper triangle only for symmetry)
+ for (int token_i = 0; token_i < evictable_size; token_i++) {
+ const int abs_token_i = start_size + token_i;
+ const int block_idx_i = abs_token_i / PAGED_ATTENTION_BLOCK_SIZE;
+ const int token_offset_i = abs_token_i % PAGED_ATTENTION_BLOCK_SIZE;
+ const int evictable_block_idx_i = block_idx_i - start_size / PAGED_ATTENTION_BLOCK_SIZE;
+ const int physical_block_i = block_indices[block_begin_idx + evictable_block_idx_i];
+
+ // Load and normalize key for token_i (reused across all token_j in this row)
+ LOAD_AND_NORMALIZE_KEY(normalized_key_i, physical_block_i, token_offset_i);
+
+ // Compute similarities only with token_j >= token_i (upper triangle)
+ for (int token_j = token_i; token_j < evictable_size; token_j++) {
+ const int abs_token_j = start_size + token_j;
+ const int block_idx_j = abs_token_j / PAGED_ATTENTION_BLOCK_SIZE;
+ const int token_offset_j = abs_token_j % PAGED_ATTENTION_BLOCK_SIZE;
+ const int evictable_block_idx_j = block_idx_j - start_size / PAGED_ATTENTION_BLOCK_SIZE;
+ const int physical_block_j = block_indices[block_begin_idx + evictable_block_idx_j];
+
+ ACCUMULATOR_TYPE similarity;
+ if (token_i == token_j) {
+ similarity = 1.0f;
+ } else {
+ // Compute cosine similarity: dot(normalized_i, j) / norm(j)
+ ACCUMULATOR_TYPE dot_product = 0.0f;
+ ACCUMULATOR_TYPE norm_sq_j = 0.0f;
+
+#if KV_CACHE_COMPRESSED
+ // Compressed: dequantize during loading
+ for (int d = sglid; d < K_HEAD_SIZE; d += SUBGROUP_SIZE) {
+ INPUT0_TYPE raw_value = key_cache[KEY_CACHE_OFFSET(physical_block_j, token_offset_j, d)];
+ ACCUMULATOR_TYPE key_j_val;
+ if (KEY_CACHE_QUANT_MODE == 1) {
+ // BY_CHANNEL: Each dimension [d] has its own scale/zp
+ ACCUMULATOR_TYPE scale, zp;
+ LOAD_SCALE_ZP_BY_CHANNEL(physical_block_j, d, scale, zp);
+ key_j_val = ((ACCUMULATOR_TYPE)raw_value - zp) * scale;
+ } else if (KEY_CACHE_QUANT_MODE == 2) {
+ // BY_TOKEN: All dimensions of token_j share the same scale/zp
+ ACCUMULATOR_TYPE scale, zp;
+ LOAD_SCALE_ZP_BY_TOKEN(physical_block_j, token_offset_j, scale, zp);
+ key_j_val = ((ACCUMULATOR_TYPE)raw_value - zp) * scale;
+ }
+ dot_product += normalized_key_i[d] * key_j_val;
+ norm_sq_j += key_j_val * key_j_val;
+ }
+#else
+ // Uncompressed: direct loading
+ for (int d = sglid; d < K_HEAD_SIZE; d += SUBGROUP_SIZE) {
+ ACCUMULATOR_TYPE key_j_val = (ACCUMULATOR_TYPE)key_cache[KEY_CACHE_OFFSET(physical_block_j, token_offset_j, d)];
+ dot_product += normalized_key_i[d] * key_j_val;
+ norm_sq_j += key_j_val * key_j_val;
+ }
+#endif
+
+ // Subgroup reductions
+ dot_product = sub_group_reduce_add(dot_product);
+ norm_sq_j = sub_group_reduce_add(norm_sq_j);
+ ACCUMULATOR_TYPE norm_j = native_sqrt(norm_sq_j + EPSILON);
+
+ similarity = dot_product / norm_j;
+ }
+
+ // Write to both upper and lower triangle (exploiting symmetry)
+ if (sglid == 0) {
+ similarity_matrix_batch[token_i * evictable_size + token_j] = similarity;
+ similarity_matrix_batch[token_j * evictable_size + token_i] = similarity;
+ }
+ }
+ }
+
+ // Fill diagonal with 0 for this head
+ for (int i = sglid; i < evictable_size; i += SUBGROUP_SIZE) {
+ similarity_matrix_batch[i * evictable_size + i] = 0.0f;
+ }
+ barrier(mem_fence);
+
+ // Compute row-wise mean for this head
+ for (int row = sglid; row < evictable_size; row += SUBGROUP_SIZE) {
+ ACCUMULATOR_TYPE row_sum = 0.0f;
+ for (int col = 0; col < evictable_size; col++) {
+ row_sum += similarity_matrix_batch[row * evictable_size + col];
+ }
+ row_means_batch[row] = row_sum / (ACCUMULATOR_TYPE)evictable_size;
+ }
+ barrier(mem_fence);
+
+ // Apply threshold for this head: set values below mean to 0
+ for (int idx = sglid; idx < evictable_size * evictable_size; idx += SUBGROUP_SIZE) {
+ int row = idx / evictable_size;
+ ACCUMULATOR_TYPE val = similarity_matrix_batch[idx];
+ if (val < row_means_batch[row]) {
+ similarity_matrix_batch[idx] = 0.0f;
+ }
+ }
+ barrier(mem_fence);
+
+ // Accumulate thresholded values across heads
+ for (int idx = sglid; idx < evictable_size * evictable_size; idx += SUBGROUP_SIZE) {
+ aggregated_similarities_batch[idx] += similarity_matrix_batch[idx];
+ }
+ barrier(mem_fence);
+ }
+
+ // Reduce mean across heads
+ for (int idx = sglid; idx < evictable_size * evictable_size; idx += SUBGROUP_SIZE) {
+ aggregated_similarities_batch[idx] /= (ACCUMULATOR_TYPE)KV_HEADS_NUM;
+ }
+ barrier(mem_fence);
+
+ // Block sum (negative): [num_evictable_blocks, evictable_size]
+ for (int block_idx = 0; block_idx < num_evictable_blocks; block_idx++) {
+ // Initialize block sums for this block (all work items participate)
+ for (int col = sglid; col < evictable_size; col += SUBGROUP_SIZE) {
+ ACCUMULATOR_TYPE sum = 0.0f;
+ int row_start = block_idx * PAGED_ATTENTION_BLOCK_SIZE;
+ for (int row_offset = 0; row_offset < PAGED_ATTENTION_BLOCK_SIZE; row_offset++) {
+ int row = row_start + row_offset;
+ if (row < evictable_size) {
+ // Negative sum (as in reference)
+ sum -= aggregated_similarities_batch[row * evictable_size + col];
+ }
+ }
+ block_sums_batch[col] = sum;
+ }
+ barrier(mem_fence);
+
+ // Write block sums to output
+ for (int col = sglid; col < evictable_size; col += SUBGROUP_SIZE) {
+ const int output_offset = diversity_output_offset + block_idx * evictable_size + col;
+ diversity_output[output_offset] = (OUTPUT_TYPE)block_sums_batch[col];
+ }
+ barrier(mem_fence);
+ }
+}
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.cpp
index 1fce2a74581..b63c4ddf465 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.cpp
@@ -94,11 +94,11 @@ inline size_t get_generate_stage_block_size(size_t head_size) {
inline bool can_use_gqa_kernel(const kernel_impl_params& params, const PagedAttentionStage& stage, size_t paged_attention_max_len) {
// Apply GQA only if there is a single subsequence in the request,
// as multiple subsequences might have significantly different lengths
+ const auto desc = params.typed_desc<paged_attention>();
const auto max_subsequences_num = 1;
- const auto has_scores_output = params.output_layouts.size() > 1;
+ const auto has_scores_output = desc->has_scores_output();
const auto scores_calc_only = (stage == PagedAttentionStage::PREFILL) && has_scores_output;
const auto multi_tokens_mode = stage == PagedAttentionStage::MIXED;
- const auto desc = params.typed_desc<paged_attention>();
const size_t kv_group_size = desc->heads_num / desc->kv_heads_num;
const auto& past_lens = params.input_layouts[PagedAttentionInputIdx::PAST_LENS];
const auto subsequences_num = past_lens.get_partial_shape()[0].get_length();
@@ -297,7 +297,7 @@ public:
jit.make("SINK_DATA_T", to_ocl_type(sink_layout.data_type));
jit.make("HAS_SINK_INPUT", 1);
}
- if (params.output_layouts.size() > 1) {
+ if (desc->has_scores_output()) {
jit.make("PAGED_ATTENTION_SCORES_OUTPUT", 1);
if (desc->has_score_aggregation) {
jit.make("HAS_SCORE_AGGREGATION", 1);
@@ -384,7 +384,7 @@ public:
const auto desc = params.typed_desc<paged_attention>();
const auto has_alibi = params.get_input_layout(PagedAttentionInputIdx::ALIBI).count() > 0;
const auto has_scale_input = !desc->scale_val.has_value();
- const auto has_scores_output = params.output_layouts.size() > 1;
+ const auto has_scores_output = desc->has_scores_output();
const auto has_sink_input = desc->has_sink_input;
if (params.is_dynamic()) {
args.push_back({ArgumentDescriptor::Types::SHAPE_INFO, 0});
@@ -498,7 +498,7 @@ public:
args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::PAST_LENS}); // past_lens
args.push_back({ArgumentDescriptor::Types::OUTPUT, 0});
- const auto has_scores_output = params.output_layouts.size() > 1;
+ const auto has_scores_output = desc->has_scores_output();
add_intermediate_inputs(args, has_scores_output, false, desc->has_score_aggregation);
args.push_back({ArgumentDescriptor::Types::SCALAR, 0}); // total_partitions_num
@@ -576,7 +576,7 @@ public:
const auto desc = params.typed_desc<paged_attention>();
const auto has_alibi = params.get_input_layout(PagedAttentionInputIdx::ALIBI).count() > 0;
const auto has_scale_input = !desc->scale_val.has_value();
- const auto has_scores_output = params.output_layouts.size() > 1;
+ const auto has_scores_output = desc->has_scores_output();
if (params.is_dynamic()) {
args.push_back({ArgumentDescriptor::Types::SHAPE_INFO, 0});
@@ -648,7 +648,7 @@ public:
args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::SUBSEQUENCE_BEGINS}); // subsequence_begins
args.push_back({ArgumentDescriptor::Types::OUTPUT, 0});
- const auto has_scores_output = params.output_layouts.size() > 1;
+ const auto has_scores_output = desc->has_scores_output();
add_intermediate_inputs(args, has_scores_output, true, desc->has_score_aggregation);
args.push_back({ArgumentDescriptor::Types::SCALAR, 0}); // total_partitions_num
@@ -701,12 +701,13 @@ public:
[[nodiscard]] Arguments get_arguments_desc(const kernel_impl_params& params) const override {
Arguments args;
+ const auto desc = params.typed_desc<paged_attention>();
+
args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::PAST_LENS}); // past_lens
args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::SUBSEQUENCE_BEGINS}); // subsequence_begins
args.push_back({ArgumentDescriptor::Types::OUTPUT, 1}); // out scores
- const auto has_scores_output = params.output_layouts.size() > 1;
- const auto desc = params.typed_desc<paged_attention>();
+ const auto has_scores_output = desc->has_scores_output();
add_intermediate_inputs(args, has_scores_output, false, desc->has_score_aggregation);
args.push_back({ArgumentDescriptor::Types::SCALAR, 0}); // total_partitions_num
@@ -736,6 +737,113 @@ public:
}
};
+class AdaptiveRKVDiversityGenerator : public KernelGenerator {
+public:
+ AdaptiveRKVDiversityGenerator() : KernelGenerator("pa_adaptive_rkv_diversity_ref") {}
+
+protected:
+ [[nodiscard]] JitConstants get_jit_constants(const kernel_impl_params& params) const override {
+ auto jit = make_base_jit_constants(params);
+
+ const auto& in_offsets_map = params.in_port_to_shape_info_offset;
+ const auto& out_offsets_map = params.out_port_to_shape_info_offset;
+
+ constexpr static std::array input_ids = {PagedAttentionInputIdx::KEY_CACHE,
+ PagedAttentionInputIdx::ADAPTIVE_RKV_EVICTABLE_SIZES,
+ PagedAttentionInputIdx::ADAPTIVE_RKV_DIVERSITY_BLOCK_SET_INDICES,
+ PagedAttentionInputIdx::ADAPTIVE_RKV_DIVERSITY_BLOCK_SET_INDICES_BEGINS};
+
+ for (size_t i = 0; i < input_ids.size(); i++) {
+ const size_t tensor_id = input_ids.at(i);
+ jit.add(make_layout_jit_constants("INPUT" + to_code_string(i), params.input_layouts[tensor_id], in_offsets_map.at(tensor_id)));
+ }
+
+ constexpr size_t diversity_output_id = 2;
+ jit.add(make_layout_jit_constants("OUTPUT", params.output_layouts[diversity_output_id], out_offsets_map.at(diversity_output_id)));
+
+ const auto desc = params.typed_desc<paged_attention>();
+ jit.make("K_HEAD_SIZE", desc->k_head_size);
+ jit.make("HEADS_NUM", desc->heads_num);
+ jit.make("KV_HEADS_NUM", desc->kv_heads_num);
+ jit.make("PAGED_ATTENTION_BLOCK_SIZE", paged_attention_block_size);
+ jit.make("SUBGROUP_SIZE", subgroup_size);
+ jit.make("EPSILON", std::numeric_limits<float>::epsilon());
+ jit.make("SIZEOF_HALF", 2);
+ jit.make("COMPRESSED_EXTRA_DIMS", 4);
+
+ // KV cache compression support
+ const bool kv_cache_compressed = get_kv_compressed(params);
+ jit.make("KV_CACHE_COMPRESSED", kv_cache_compressed);
+
+ // Always define KEY_CACHE_QUANT_MODE for macro expansion (even if not used in uncompressed mode)
+ int key_cache_quant_mode = 0; // Default
+ if (kv_cache_compressed) {
+ const auto quant_mode = params.get_program().get_config().get_key_cache_quant_mode();
+ if (quant_mode == ov::internal::CacheQuantMode::BY_CHANNEL) {
+ key_cache_quant_mode = 1;
+ } else if (quant_mode == ov::internal::CacheQuantMode::BY_TOKEN) {
+ key_cache_quant_mode = 2;
+ }
+ }
+ jit.make("KEY_CACHE_QUANT_MODE", key_cache_quant_mode);
+
+ jit.add(make_type_jit_constants("ACCUMULATOR", softmax_accumulator_type));
+ return jit;
+ }
+
+ [[nodiscard]] Arguments get_arguments_desc(const kernel_impl_params& params) const override {
+ Arguments args;
+
+ if (params.is_dynamic()) {
+ args.push_back({ArgumentDescriptor::Types::SHAPE_INFO, 0});
+ }
+
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::KEY_CACHE});
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::ADAPTIVE_RKV_EVICTABLE_SIZES});
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::ADAPTIVE_RKV_DIVERSITY_BLOCK_SET_INDICES});
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::ADAPTIVE_RKV_DIVERSITY_BLOCK_SET_INDICES_BEGINS});
+ args.push_back({ArgumentDescriptor::Types::OUTPUT, 2});
+
+ // Adaptive RKV diversity buffers (only with scores output)
+ // Allocated after all scores buffers: base index 8 (no aggregation) or 9 (with aggregation)
+ const auto desc = params.typed_desc<paged_attention>();
+ if (desc->has_adaptive_rkv) {
+ const uint32_t diversity_base_idx = desc->has_score_aggregation ? 9 : 8;
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, diversity_base_idx + 0}); // similarity_matrix
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, diversity_base_idx + 1}); // aggregated_similarities
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, diversity_base_idx + 2}); // row_means
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, diversity_base_idx + 3}); // block_sums
+ }
+
+ args.push_back({ArgumentDescriptor::Types::SCALAR, 0}); // start_size scalar
+
+ return args;
+ }
+
+ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {
+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {
+ assert(!params.is_dynamic());
+ auto& wgs = kd.params.workGroups;
+ auto& scalars = kd.params.scalars;
+ scalars.resize(1);
+
+ const auto& evictable_sizes = params.input_layouts[PagedAttentionInputIdx::ADAPTIVE_RKV_EVICTABLE_SIZES];
+ const size_t batch_size = static_cast<size_t>(evictable_sizes.get_partial_shape()[0].get_length());
+
+ wgs.global = {batch_size * subgroup_size, 1, 1};
+ wgs.local = {subgroup_size, 1, 1};
+
+ // Set start_size scalar
+ const auto& memory_deps = params.memory_deps;
+ const auto start_size_mem = memory_deps.at(PagedAttentionInputIdx::ADAPTIVE_RKV_START_SIZE);
+ mem_lock<int32_t, mem_lock_type::read> start_size_lock(start_size_mem, *params.strm);
+
+ scalars[0].t = ScalarDescriptor::Types::INT32;
+ scalars[0].v.s32 = start_size_lock[0];
+ }};
+ }
+};
+
class KVCacheUpdateGenerator : public KernelGenerator {
public:
KVCacheUpdateGenerator() : KernelGenerator("pa_kv_cache_update_ref") {}
@@ -1085,6 +1193,7 @@ public:
Stage::Ptr pa_sdpa_opt = make_stage<PagedAttentionSDPAOptGeneratorMultiToken>();
Stage::Ptr kv_cache_rotate = make_stage<KVCacheRotateGenerator>();
Stage::Ptr pa_scores_calc = make_stage<PagedAttentionGeneratorScoresCalculation>();
+ Stage::Ptr pa_diversity_calc = make_stage<AdaptiveRKVDiversityGenerator>();
#ifdef ENABLE_ONEDNN_FOR_GPU
Stage::Ptr pa_sdpa_micro = make_stage<SDPAMicroGenerator>(true);
Stage::Ptr pa_sdpa_micro_mixed = make_stage<SDPAMicroGenerator>(false);
@@ -1094,8 +1203,9 @@ public:
PagedAttentionOptImpl() : SDPAImplBase(PagedAttentionOpt::get_type_info_static()) {}
explicit PagedAttentionOptImpl(const kernel_impl_params& params) : PagedAttentionOptImpl() {
const auto desc = params.typed_desc<paged_attention>();
- const bool has_scores_output = params.output_layouts.size() > 1;
+ const bool has_scores_output = desc->has_scores_output();
const bool has_rotated_blocks = desc->has_rotated_blocks;
+ const bool has_adaptive_rkv = desc->has_adaptive_rkv;
#ifdef ENABLE_ONEDNN_FOR_GPU
const bool use_micro_sdpa = supports_micro_sdpa(params);
@@ -1121,6 +1231,10 @@ public:
if (has_scores_output) {
add_stage(pa_scores_calc, params);
}
+
+ if (has_adaptive_rkv) {
+ add_stage(pa_diversity_calc, params);
+ }
}
#ifdef ENABLE_ONEDNN_FOR_GPU
@@ -1153,7 +1267,7 @@ public:
return false;
}
- if (params.output_layouts.size() > 1 || desc->has_score_aggregation) {
+ if (desc->has_scores_output() || desc->has_score_aggregation) {
return false;
}
@@ -1251,8 +1365,9 @@ public:
event::ptr execute(const std::vector<event::ptr>& events, primitive_inst& instance) override {
const auto& params = *instance.get_impl_params();
const auto desc = params.typed_desc<paged_attention>();
- const bool has_scores_output = params.output_layouts.size() > 1;
+ const bool has_scores_output = desc->has_scores_output();
const bool has_rotated_blocks = desc->has_rotated_blocks;
+ const bool has_adaptive_rkv = desc->has_adaptive_rkv;
update_stages_flags(instance);
auto rt_params = static_cast<PagedAttentionRuntimeParams*>(m_rt_params.get());
@@ -1298,6 +1413,14 @@ public:
res_event = {execute_stage(res_event, instance, pa_scores_calc)};
}
+ if (has_adaptive_rkv) {
+ // Check layout to see if evictable_sizes has data before executing diversity kernel
+ const auto& evictable_sizes_layout = params.get_input_layout(PagedAttentionInputIdx::ADAPTIVE_RKV_EVICTABLE_SIZES);
+ if (evictable_sizes_layout.count() > 0) {
+ res_event = {execute_stage(res_event, instance, pa_diversity_calc)};
+ }
+ }
+
return res_event[0];
}
@@ -1314,47 +1437,56 @@ public:
/*
* Internal buffers allocation owners and users (numbers represent unique buffers names,
* not the real indexes in _intermediates_memory structure):
- * +--------------------------------------------------+-----------------------+--------------------+
- * | Stage | Allocates & uses | Reuses |
- * +--------------------------------------------------+-----------------------+--------------------+
- * | KV_CACHE_UPDATE | [0, 1, 2] | |
- * +--------------------------------------------------+-----------------------+--------------------+
- * | SDPA (1st token) | | [0, 1, 2] |
- * +--------------------------------------------------+-----------------------+--------------------+
- * | PA_SDPA (2nd+ token) | [5, 6, 7] | |
- * +--------------------------------------------------+-----------------------+--------------------+
- * | PA_SDPA (mixed mode) | [5, 6, 7, 8] | |
- * +--------------------------------------------------+-----------------------+--------------------+
- * | SDPA (1st token) + scores output | | [0, 1, 2, 3, 4] |
- * +--------------------------------------------------+-----------------------+--------------------+
- * | PA_SDPA (2nd+ token) + scores output | [3, 4, 5, 6, 7] | |
- * +--------------------------------------------------+-----------------------+--------------------+
- * | PA_SDPA (mixed mode) + scores output | [3, 4, 5, 6, 7, 8] | |
- * +--------------------------------------------------+-----------------------+--------------------+
- * | SDPA (1st token) + scores output aggregation | | [0, 1, 2, 3, 4, 5] |
- * +--------------------------------------------------+-----------------------+--------------------+
- * | PA_SDPA (2nd+ token) + scores output aggregation | [3, 4, 5, 6, 7, 8] | |
- * +--------------------------------------------------+-----------------------+--------------------+
- * | PA_SDPA (mixed mode) + scores output aggregation | [3, 4, 5, 6, 7, 8, 9] | |
- * +--------------------------------------------------+-----------------------+--------------------+
- * | SDPA (1st token, micro-kernel) | [last (8/9/10)] | |
- * +--------------------------------------------------+-----------------------+--------------------+
+ * +------------------------------------------------------------+-----------------------+--------------------+
+ * | Stage | Allocates & uses | Reuses |
+ * +------------------------------------------------------------+-----------------------+--------------------+
+ * | KV_CACHE_UPDATE | [0, 1, 2] | |
+ * +------------------------------------------------------------+-----------------------+--------------------+
+ * | SDPA (1st token) | | [0, 1, 2] |
+ * +------------------------------------------------------------+-----------------------+--------------------+
+ * | PA_SDPA (2nd+ token) | [5, 6, 7] | |
+ * +------------------------------------------------------------+-----------------------+--------------------+
+ * | PA_SDPA (mixed mode) | [5, 6, 7, 8] | |
+ * +------------------------------------------------------------+-----------------------+--------------------+
+ * | SDPA (1st token) + scores output | | [0, 1, 2, 3, 4] |
+ * +------------------------------------------------------------+-----------------------+--------------------+
+ * | PA_SDPA (2nd+ token) + scores output | [3, 4, 5, 6, 7] | |
+ * +------------------------------------------------------------+-----------------------+--------------------+
+ * | PA_SDPA (mixed mode) + scores output | [3, 4, 5, 6, 7, 8] | |
+ * +------------------------------------------------------------+-----------------------+--------------------+
+ * | SDPA (1st token) + scores output aggregation | | [0, 1, 2, 3, 4, 5] |
+ * +------------------------------------------------------------+-----------------------+--------------------+
+ * | PA_SDPA (2nd+ token) + scores output aggregation | [3, 4, 5, 6, 7, 8] | |
+ * +------------------------------------------------------------+-----------------------+--------------------+
+ * | PA_SDPA (mixed mode) + scores output aggregation | [3, 4, 5, 6, 7, 8, 9] | |
+ * +------------------------------------------------------------+-----------------------+--------------------+
+ * | SDPA (1st token, micro-kernel) | [last (8/9/10)] | |
+ * +------------------------------------------------------------+-----------------------+--------------------+
+ * | Adaptive RKV Diversity (scores output) | [8, 9, 10, 11] | |
+ * +------------------------------------------------------------+-----------------------+--------------------+
+ * | Adaptive RKV Diversity (scores output + aggregation) | [9, 10, 11, 12] | |
+ * +------------------------------------------------------------+-----------------------+--------------------+
*
* Description:
- * 0, 1, 2 - Buffers used for proper blocks distribution for kv_cache_update and
- * sdpa_opt (1st token calculation) block configuration over target_seq_len dimension.
- * Filled in paged_attention_inst::on_execute() call.
- * 3, 4 - Optional buffers used for PA scores output calculation, storing intermediate
- * softmax values by partitions (filled in PA/SDPA kernels) and sequence length offsets
- * for each subsequence (filled in paged_attention_inst::on_execute() call).
- * 5, 6, 7 - Used for 2nd+ PA calculation (for softmax exp_sums, max_logits, and intermediate output).
- * Filled in PA/SDPA kernels.
- * 8 - Optional buffer used for mixed PA execution mode, mapping gws idx to subsequence id.
- * Filled in paged_attention_inst::on_execute() call.
- * last - Used for defining query block index for the currently processing subsequence and mapping
- * gws index to subsequence idx. Values stored in pairs like:
- * [block_idx0, subsequence_idx0, block_idx1, subsequence_idx0, ..., block_idx0, subsequence_idx1].
- * Filled in paged_attention_inst::on_execute() call for sdpa-micro kernel only.
+ * 0, 1, 2 - Buffers used for proper blocks distribution for kv_cache_update and
+ * sdpa_opt (1st token calculation) block configuration over target_seq_len dimension.
+ * Filled in paged_attention_inst::on_execute() call.
+ * 3, 4 - Optional buffers used for PA scores output calculation, storing intermediate
+ * softmax values by partitions (filled in PA/SDPA kernels) and sequence length offsets
+ * for each subsequence (filled in paged_attention_inst::on_execute() call).
+ * 5, 6, 7 - Used for 2nd+ PA calculation (for softmax exp_sums, max_logits, and intermediate output).
+ * Filled in PA/SDPA kernels.
+ * 8 - Optional buffer used for mixed PA execution mode, mapping gws idx to subsequence id.
+ * Filled in paged_attention_inst::on_execute() call.
+ * 8-11/9-12 - Optional buffers for Adaptive RKV diversity calculation (similarity_matrix,
+ * aggregated_similarities, row_means, block_sums). Allocated when has_adaptive_rkv=true,
+ * regardless of stage. Actual kernel execution determined at runtime by evictable_sizes.
+ * Index range depends on score_aggregation: without=[8-11], with=[9-12].
+ * Filled in pa_diversity_calc kernel.
+ * last - Used for defining query block index for the currently processing subsequence and mapping
+ * gws index to subsequence idx. Values stored in pairs like:
+ * [block_idx0, subsequence_idx0, block_idx1, subsequence_idx0, ..., block_idx0, subsequence_idx1].
+ * Filled in paged_attention_inst::on_execute() call for sdpa-micro kernel only.
*/
std::vector<BufferDescriptor> internal_buffers;
@@ -1403,7 +1535,7 @@ public:
auto buf_elements_count = static_cast<int64_t>(total_tokens * desc->heads_num * num_of_partitions);
auto tmp_out_elements_count = static_cast<int64_t>(total_tokens * desc->heads_num * desc->v_head_size * num_of_partitions);
- const bool has_scores_output = params.output_layouts.size() > 1;
+ const bool has_scores_output = desc->has_scores_output();
if (has_scores_output) {
const auto& past_lens = params.input_layouts[PagedAttentionInputIdx::PAST_LENS];
auto subsequences_number = past_lens.get_partial_shape()[0].get_length();
@@ -1472,6 +1604,43 @@ public:
internal_buffers.emplace_back(indexes_buf_size * 4, indexes_dt, lockable);
}
#endif
+
+ // Adaptive RKV Diversity buffers (allocated when enabled, execution determined by runtime evictable_sizes)
+ const bool has_adaptive_rkv = desc->has_adaptive_rkv;
+ if (has_adaptive_rkv) {
+ const auto& evictable_sizes_layout = params.input_layouts[PagedAttentionInputIdx::ADAPTIVE_RKV_EVICTABLE_SIZES];
+ const auto batch_size = evictable_sizes_layout.get_partial_shape()[0].get_length();
+
+ // Calculate actual buffer sizes based on runtime evictable_sizes
+ size_t total_matrix_elements = 0;
+ size_t total_vector_elements = 0;
+ if (!params.memory_deps.empty() && params.memory_deps.count(PagedAttentionInputIdx::ADAPTIVE_RKV_EVICTABLE_SIZES) > 0) {
+ const auto& evictable_sizes_mem = params.memory_deps.at(PagedAttentionInputIdx::ADAPTIVE_RKV_EVICTABLE_SIZES);
+ mem_lock<int32_t, mem_lock_type::read> evictable_sizes_lock(evictable_sizes_mem, *params.strm);
+
+ // Sum up actual sizes for each batch (dynamic allocation)
+ for (size_t i = 0; i < evictable_sizes_lock.size(); i++) {
+ size_t evictable_size = static_cast<size_t>(evictable_sizes_lock[i]);
+ total_matrix_elements += evictable_size * evictable_size;
+ total_vector_elements += evictable_size;
+ }
+ GPU_DEBUG_TRACE_DETAIL << "Adaptive RKV: Allocating dynamic buffers - "
+ << "matrix: " << total_matrix_elements << ", vector: " << total_vector_elements << std::endl;
+ } else {
+ // Fallback: use maximum size (512) if runtime values not available
+ const size_t max_evictable_size = 512;
+ total_matrix_elements = batch_size * max_evictable_size * max_evictable_size;
+ total_vector_elements = batch_size * max_evictable_size;
+ GPU_DEBUG_TRACE_DETAIL << "Adaptive RKV: Runtime sizes not available, using max=512" << std::endl;
+ }
+
+ // similarity_matrix, aggregated_similarities, row_means, block_sums
+ internal_buffers.emplace_back(total_matrix_elements * sizeof(float), indexes_dt);
+ internal_buffers.emplace_back(total_matrix_elements * sizeof(float), indexes_dt);
+ internal_buffers.emplace_back(total_vector_elements * sizeof(float), indexes_dt);
+ internal_buffers.emplace_back(total_vector_elements * sizeof(float), indexes_dt);
+ }
+
GPU_DEBUG_TRACE_DETAIL << "get_internal_buffer_descs: internal_buffers.size = " << internal_buffers.size() << std::endl;
for (size_t i = 0; i < internal_buffers.size(); i++) {
GPU_DEBUG_TRACE_DETAIL << "\tinternal_buffers[" << i << "] = " << internal_buffers[i].m_layout.to_short_string() << std::endl;
diff --git a/src/plugins/intel_gpu/src/graph/include/paged_attention_inst.h b/src/plugins/intel_gpu/src/graph/include/paged_attention_inst.h
index a2e7cc016d8..01d313363d9 100644
--- a/src/plugins/intel_gpu/src/graph/include/paged_attention_inst.h
+++ b/src/plugins/intel_gpu/src/graph/include/paged_attention_inst.h
@@ -29,6 +29,11 @@ public:
if (typed_desc()->has_score_aggregation)
input_ports.insert(PagedAttentionInputIdx::SCORE_AGGREGATION);
+ if (typed_desc()->has_adaptive_rkv) {
+ input_ports.insert(PagedAttentionInputIdx::ADAPTIVE_RKV_START_SIZE);
+ input_ports.insert(PagedAttentionInputIdx::ADAPTIVE_RKV_EVICTABLE_SIZES);
+ }
+
return input_ports;
}
diff --git a/src/plugins/intel_gpu/src/graph/paged_attention.cpp b/src/plugins/intel_gpu/src/graph/paged_attention.cpp
index 9677e56cd59..a0a14d94bca 100644
--- a/src/plugins/intel_gpu/src/graph/paged_attention.cpp
+++ b/src/plugins/intel_gpu/src/graph/paged_attention.cpp
@@ -128,15 +128,18 @@ std::string paged_attention_inst::to_string(const paged_attention_node& node) {
paged_attention_info.add("v_head_size", desc->v_head_size);
paged_attention_info.add("heads_num", desc->heads_num);
paged_attention_info.add("kv_heads_num", desc->kv_heads_num);
- paged_attention_info.add("scale", desc->scale_val.value_or(1.0f));
paged_attention_info.add("has_alibi", desc->has_alibi);
- paged_attention_info.add("has_score_aggregation", desc->has_score_aggregation);
paged_attention_info.add("has_rotated_blocks", desc->has_rotated_blocks);
- paged_attention_info.add("key_cache_dt", node.get_input_layout(cldnn::paged_attention::PagedAttentionInputIdx::KEY_CACHE).data_type);
- paged_attention_info.add("value_cache_dt", node.get_input_layout(cldnn::paged_attention::PagedAttentionInputIdx::VALUE_CACHE).data_type);
+ paged_attention_info.add("sliding_window", desc->sliding_window);
paged_attention_info.add("score_output", desc->has_scores_output());
+ paged_attention_info.add("has_score_aggregation", desc->has_score_aggregation);
+ paged_attention_info.add("has_xattention", desc->has_xattention);
+ paged_attention_info.add("has_sink_input", desc->has_sink_input);
+ paged_attention_info.add("has_adaptive_rkv", desc->has_adaptive_rkv);
+ paged_attention_info.add("scale", desc->scale_val.value_or(1.0f));
paged_attention_info.add("is_key_by_channel", desc->is_key_by_channel);
- paged_attention_info.add("score_aggregation", desc->has_score_aggregation);
+ paged_attention_info.add("key_cache_dt", node.get_input_layout(cldnn::paged_attention::PagedAttentionInputIdx::KEY_CACHE).data_type);
+ paged_attention_info.add("value_cache_dt", node.get_input_layout(cldnn::paged_attention::PagedAttentionInputIdx::VALUE_CACHE).data_type);
node_info->add("paged_attention primitive info", paged_attention_info);
node_info->dump(primitive_description);
@@ -154,15 +157,15 @@ paged_attention_inst::typed_primitive_inst(network& network, const paged_attenti
const auto pa_block_size = desc->block_size;
if (desc->has_alibi) {
- const auto alibi_input_idx = 11;
+ const auto alibi_input_idx = PagedAttentionInputIdx::ALIBI;
const auto alibi_layout = node.get_input_layout(alibi_input_idx);
- OPENVINO_ASSERT(heads_num == alibi_layout.count());
+ OPENVINO_ASSERT(heads_num == alibi_layout.count(), "[GPU] ALiBi layout count must match heads_num");
}
- OPENVINO_ASSERT(heads_num % kv_heads_num == 0);
+ OPENVINO_ASSERT(heads_num % kv_heads_num == 0, "[GPU] heads_num must be divisible by kv_heads_num");
if (!desc->has_xattention) {
- OPENVINO_ASSERT(k_head_size % pa_block_size == 0);
- OPENVINO_ASSERT(v_head_size % pa_block_size == 0);
+ OPENVINO_ASSERT(k_head_size % pa_block_size == 0, "[GPU] k_head_size must be divisible by block_size");
+ OPENVINO_ASSERT(v_head_size % pa_block_size == 0, "[GPU] v_head_size must be divisible by block_size");
}
}
} // namespace cldnn
diff --git a/src/plugins/intel_gpu/src/plugin/ops/paged_attention.cpp b/src/plugins/intel_gpu/src/plugin/ops/paged_attention.cpp
index 63d45c9476a..f15c9691510 100644
--- a/src/plugins/intel_gpu/src/plugin/ops/paged_attention.cpp
+++ b/src/plugins/intel_gpu/src/plugin/ops/paged_attention.cpp
@@ -122,11 +122,11 @@ static void CreatePagedAttentionExtensionOp(ProgramBuilder& p, const std::shared
prim.num_outputs = 1;
if (op->get_output_size() > 1) {
- const auto scores_output_idx = 1;
- const auto& users = op->get_output_target_inputs(scores_output_idx);
- if (users.size() > 0) {
+ if (!op->get_output_target_inputs(1).empty())
prim.num_outputs++; // Add scores output
- }
+
+ if (!op->get_output_target_inputs(2).empty())
+ prim.num_outputs++; // Add diversity outut
}
p.add_primitive(*op, prim);
diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/paged_attention_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/paged_attention_gpu_test.cpp
index 72d5b1e0c80..14b1f9bed75 100644
--- a/src/plugins/intel_gpu/tests/unit/test_cases/paged_attention_gpu_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/test_cases/paged_attention_gpu_test.cpp
@@ -13,6 +13,7 @@
#include <intel_gpu/primitives/reshape.hpp>
#include <intel_gpu/primitives/softmax.hpp>
#include <openvino/reference/xattention.hpp>
+#include <openvino/reference/adaptive_rkv_diversity.hpp>
#include "openvino/runtime/tensor.hpp"
#include "primitive_inst.h"
@@ -24,39 +25,29 @@ using namespace ov::intel_gpu;
using namespace ::tests;
/*
-* PagedAttention inputs:
-* [0]: query
-* shape: [batch_size_in_tokens, num_heads * head_size], type: f16
-* [1]: key
-* shape: [batch_size_in_tokens, num_kv_heads * head_size], type: f16
-* [2]: value 
-* shape: [batch_size_in_tokens, num_kv_heads * head_size], type: f16
-* [3]: key_cache
-* shape: [num_blocks, num_kv_heads, head_size, block_size], type: f16
-* [4]: value_cache
-* shape: [num_blocks, num_kv_heads, block_size, head_size], type: f16
-* [5]: past_lens
-* shape: [batch_size_in_sequences], type: i32
-* [6]: subsequence_begins
-* shape: [batch_size_in_sequences + 1], type: i32
-* [7]: block_indices
-* Shape: [num_blocks], type: i32
-* [8]: block_indices_begins
-* Shape: [batch_size_in_sequences + 1], type: i32
-* [9]: scale, optional
-* [10]: sliding_window, optional
-* [11]: alibi_slopes, optional
-* [12]: max_context_len
-* shape: [], type: i32
-* [13]: score_aggregation_window​, optional​, shape: [batch_size_in_sequences]
-* [14]: rotated_block_indices​, optional​
-* shape: [num_rotated_blocks]​, type: i32
-* [15]: rotation_deltas​, optional​
-* shape: [num_rotated_blocks, BLOCK_SIZE]​ || [num_rotated_blocks, 1]​, type: i32
-* [16]: rotation_trig_lut​, optional​
-* shape: [max_num_batched_tokens / BLOCK_SIZE, head_size]​ || [max_num_batched_tokens, head_size], type: f16
-*/
-
+ * PagedAttention inputs:
+ * [0]: query, shape: [batch_size_in_tokens, num_heads * head_size], type: f16
+ * [1]: key, shape: [batch_size_in_tokens, num_kv_heads * head_size], type: f16
+ * [2]: value, shape: [batch_size_in_tokens, num_kv_heads * head_size], type: f16
+ * [3]: key_cache, shape: [num_blocks, num_kv_heads, head_size, block_size], type: f16 or i8
+ * [4]: value_cache, shape: [num_blocks, num_kv_heads, block_size, head_size], type: f16 or i8
+ * [5]: past_lens, shape: [batch_size_in_sequences], type: i32
+ * [6]: subsequence_begins, shape: [batch_size_in_sequences + 1], type: i32
+ * [7]: block_indices, shape: [num_blocks], type: i32
+ * [8]: block_indices_begins, shape: [batch_size_in_sequences + 1], type: i32
+ * [9]: scale, optional
+ * [10]: sliding_window, optional
+ * [11]: alibi_slopes, optional
+ * [12]: max_context_len, shape: [], type: i32
+ * [13]: score_aggregation_window, optional, shape: [batch_size_in_sequences], type: i32
+ * [14]: rotated_block_indices, optional, shape: [num_rotated_blocks], type: i32
+ * [15]: rotation_deltas, optional, shape: [num_rotated_blocks, BLOCK_SIZE] or [num_rotated_blocks, 1], type: i32
+ * [16]: rotation_trig_lut, optional, shape: [max_num_batched_tokens, head_size], type: f16
+ * [17]: adaptive_rkv_start_size, optional, shape: [], type: i32
+ * [18]: adaptive_rkv_evictable_sizes, optional, shape: [batch_size_in_sequences], type: i32
+ * [19]: adaptive_rkv_diversity_block_set_indices, optional, shape: [total_blocks], type: i32
+ * [20]: adaptive_rkv_diversity_block_set_indices_begins, optional, shape: [batch_size_in_sequences + 1], type: i32
+ */
enum class ScoresMode {
DISABLED = 0,
@@ -118,7 +109,7 @@ struct PagedAttentionManager {
std::vector<ov::float16> sinks;
- std::vector<int> adaptive_rkv_start_size;
+ int adaptive_rkv_start_size = 0;
std::vector<int> adaptive_rkv_evictable_sizes;
std::vector<int> adaptive_rkv_diversity_block_set_indices;
std::vector<int> adaptive_rkv_diversity_block_set_indices_begins;
@@ -275,7 +266,7 @@ struct PagedAttentionManager {
const size_t off = base + static_cast<size_t>(token_idx) * head_size;
set_values(test_stream, memory, src_ptr, head_size, off);
} else {
- // Compressed Key cache layout:
+ // Compressed Key cache layout:
// logical shape: [num_blocks, num_kv_heads, block_size, adjusted_head_size], dt=i8 (adjusted_head_size=head_size+4).
// Per (block, head) region starts at block_base_i8, byte-packed as:
// data: block_base_i8 + t*head_size (u8 semantics), size=head_size bytes
@@ -444,11 +435,11 @@ struct PagedAttentionManager {
const size_t off = base + static_cast<size_t>(token_idx) * static_cast<size_t>(head_size);
set_values(test_stream, memory, src_ptr, head_size, off);
} else {
- // Compressed Value cache layout:
- // logical shape: [num_blocks, num_kv_heads, block_size, adjusted_head_size], dt=i8 (adjusted_head_size=head_size+4).
- // Per (block, head): data at block_base_i8 + t*head_size; scale/zp are fp16 arrays at scale_base_i8/zp_base_i8
- // (fp16 element offsets: scale_base_i8/2 + t, zp_base_i8/2 + t).
- // has_xattention uses unsigned [0..255] quant; dequant x ≈ (q - zp) * scale, scale=(max-min)/255, zp=(-min)*255/(max-min).
+ // Compressed Value cache layout:
+ // logical shape: [num_blocks, num_kv_heads, block_size, adjusted_head_size], dt=i8 (adjusted_head_size=head_size+4).
+ // Per (block, head): data at block_base_i8 + t*head_size; scale/zp are fp16 arrays at scale_base_i8/zp_base_i8
+ // (fp16 element offsets: scale_base_i8/2 + t, zp_base_i8/2 + t).
+ // has_xattention uses unsigned [0..255] quant; dequant x ≈ (q - zp) * scale, scale=(max-min)/255, zp=(-min)*255/(max-min).
auto [qdata, scale, zp] = quantize_data(src_ptr, head_size, false, has_xattention);
int8_t* qptr = reinterpret_cast<int8_t*>(qdata.data());
@@ -579,49 +570,22 @@ struct PagedAttentionManager {
}
memory::ptr get_adaptive_rkv_start_size_memory() {
- return get_memory_from_vec(adaptive_rkv_start_size);
+ auto mem = test_engine.allocate_memory({{}, data_types::i32, format::bfyx});
+ mem_lock<int> lock(mem, test_stream);
+ lock[0] = adaptive_rkv_start_size;
+ return mem;
}
memory::ptr get_adaptive_rkv_evictable_sizes_memory() {
- auto mem = get_memory_from_vec(adaptive_rkv_evictable_sizes);
- auto layout = mem->get_layout();
- layout.set_partial_shape(ov::PartialShape{ 1 });
-
- if (adaptive_rkv_evictable_sizes.empty()) {
- auto empty_layout = mem->get_layout();
- empty_layout.set_partial_shape(ov::PartialShape{ 0 });
- return test_engine.reinterpret_buffer(*mem, empty_layout);
- }
-
- return test_engine.reinterpret_buffer(*mem, layout);
+ return get_memory_from_vec(adaptive_rkv_evictable_sizes);
}
memory::ptr get_adaptive_rkv_diversity_block_set_indices_memory() {
- auto mem = get_memory_from_vec(adaptive_rkv_diversity_block_set_indices);
- auto layout = mem->get_layout();
- layout.set_partial_shape(ov::PartialShape{ 1 });
-
- if (adaptive_rkv_diversity_block_set_indices.empty()) {
- auto empty_layout = mem->get_layout();
- empty_layout.set_partial_shape(ov::PartialShape{ 0 });
- return test_engine.reinterpret_buffer(*mem, empty_layout);
- }
-
- return test_engine.reinterpret_buffer(*mem, layout);
+ return get_memory_from_vec(adaptive_rkv_diversity_block_set_indices);
}
memory::ptr get_adaptive_rkv_diversity_block_set_indices_begins_memory() {
- auto mem = get_memory_from_vec(adaptive_rkv_diversity_block_set_indices_begins);
- auto layout = mem->get_layout();
- layout.set_partial_shape(ov::PartialShape{ 1 });
-
- if (adaptive_rkv_diversity_block_set_indices_begins.empty()) {
- auto empty_layout = mem->get_layout();
- empty_layout.set_partial_shape(ov::PartialShape{ 0 });
- return test_engine.reinterpret_buffer(*mem, empty_layout);
- }
-
- return test_engine.reinterpret_buffer(*mem, layout);
+ return get_memory_from_vec(adaptive_rkv_diversity_block_set_indices_begins);
}
float get_default_scale() {
@@ -818,9 +782,10 @@ struct PagedAttentionReference {
, test_engine(pam.test_engine)
, test_stream(pam.test_stream) {}
- std::pair<std::vector<ov::float16>, std::vector<ov::float16>> get_reference(bool has_xattention, std::vector<float> threshold) {
+ std::tuple<std::vector<ov::float16>, std::vector<ov::float16>, std::vector<ov::float16>> get_reference(bool has_xattention, std::vector<float> threshold, memory::ptr key_cache_mem = nullptr) {
std::vector<ov::float16> ref_data_output;
std::vector<ov::float16> ref_scores_output;
+ std::vector<ov::float16> ref_diversity_output;
for (size_t i = 0; i < pam.subsequence_descs.size(); i++) {
const auto& subsequence_desc = pam.subsequence_descs[i];
@@ -879,7 +844,11 @@ struct PagedAttentionReference {
subsequence_ref_results.second.end());
}
- return { ref_data_output, ref_scores_output };
+ if (!pam.adaptive_rkv_evictable_sizes.empty()) {
+ ref_diversity_output = compute_diversity_reference(key_cache_mem);
+ }
+
+ return { ref_data_output, ref_scores_output, ref_diversity_output };
}
private:
@@ -1249,6 +1218,155 @@ private:
}
}
+ std::vector<ov::float16> read_key_from_cache(memory::ptr key_cache_mem, size_t seq_idx, int total_tokens) {
+ // Read key vectors from key_cache memory
+ // key_cache layout: [num_blocks, num_kv_heads, head_size, block_size]
+ std::vector<ov::float16> key_data(pam.num_kv_heads * total_tokens * pam.k_head_size);
+
+ const int blocks_start = pam.block_indices_begins[seq_idx];
+ const int blocks_end = pam.block_indices_begins[seq_idx + 1];
+ const int num_blocks = blocks_end - blocks_start;
+
+ const bool is_compressed = pam.kv_cache_compression;
+
+ if (!is_compressed) {
+ // Uncompressed case: read as float16
+ mem_lock<ov::float16, mem_lock_type::read> cache_ptr(key_cache_mem, test_stream);
+
+ for (int block_idx = 0; block_idx < num_blocks; block_idx++) {
+ const int physical_block = pam.block_indices[blocks_start + block_idx];
+ const int tokens_in_block = std::min(pam.block_size, total_tokens - block_idx * pam.block_size);
+
+ for (int token_offset = 0; token_offset < tokens_in_block; token_offset++) {
+ const int token_idx = block_idx * pam.block_size + token_offset;
+
+ for (int head_idx = 0; head_idx < pam.num_kv_heads; head_idx++) {
+ const size_t cache_base = static_cast<size_t>(physical_block) * pam.num_kv_heads * pam.k_head_size * pam.block_size +
+ static_cast<size_t>(head_idx) * pam.k_head_size * pam.block_size;
+
+ const size_t output_base = static_cast<size_t>(head_idx) * total_tokens * pam.k_head_size +
+ static_cast<size_t>(token_idx) * pam.k_head_size;
+
+ for (int dim = 0; dim < pam.k_head_size; dim++) {
+ const size_t cache_offset = cache_base + static_cast<size_t>(dim) * pam.block_size + token_offset;
+ key_data[output_base + dim] = cache_ptr[cache_offset];
+ }
+ }
+ }
+ }
+ } else {
+ // Compressed case: read as int8 and dequantize
+ mem_lock<int8_t, mem_lock_type::read> cache_ptr(key_cache_mem, test_stream);
+
+ if (pam.key_cache_quant_mode == ov::internal::CacheQuantMode::BY_CHANNEL) {
+ // BY_CHANNEL: [num_blocks, num_kv_heads, head_size, block_size+4]
+ // Each dimension quantized across all tokens in block
+ for (int block_idx = 0; block_idx < num_blocks; block_idx++) {
+ const int physical_block = pam.block_indices[blocks_start + block_idx];
+ const int tokens_in_block = std::min(pam.block_size, total_tokens - block_idx * pam.block_size);
+
+ for (int head_idx = 0; head_idx < pam.num_kv_heads; head_idx++) {
+ const size_t cache_base = static_cast<size_t>(physical_block) * pam.num_kv_heads * pam.k_head_size * (pam.block_size + 4) +
+ static_cast<size_t>(head_idx) * pam.k_head_size * (pam.block_size + 4);
+
+ for (int dim = 0; dim < pam.k_head_size; dim++) {
+ // Read scale and zero-point for this dimension
+ const size_t scale_offset = cache_base + static_cast<size_t>(dim) * (pam.block_size + 4) + pam.block_size;
+ ov::float16 scale = *reinterpret_cast<const ov::float16*>(&cache_ptr[scale_offset]);
+ ov::float16 zp = *reinterpret_cast<const ov::float16*>(&cache_ptr[scale_offset + 2]);
+
+ // Dequantize all tokens for this dimension
+ for (int token_offset = 0; token_offset < tokens_in_block; token_offset++) {
+ const int token_idx = block_idx * pam.block_size + token_offset;
+ const size_t cache_offset = cache_base + static_cast<size_t>(dim) * (pam.block_size + 4) + token_offset;
+ const size_t output_offset = static_cast<size_t>(head_idx) * total_tokens * pam.k_head_size +
+ static_cast<size_t>(token_idx) * pam.k_head_size + dim;
+
+ int8_t quantized_value = cache_ptr[cache_offset];
+ float dequantized = (static_cast<float>(quantized_value) - static_cast<float>(zp)) * static_cast<float>(scale);
+ key_data[output_offset] = ov::float16(dequantized);
+ }
+ }
+ }
+ }
+ } else {
+ // BY_TOKEN: [num_blocks, num_kv_heads, head_size+4, block_size]
+ // Token-wise quantization with shared scale/zp per token
+ // Layout: data rows [0..head_size-1], scale at [head_size], zp at [head_size+2] (fp16)
+ for (int block_idx = 0; block_idx < num_blocks; block_idx++) {
+ const int physical_block = pam.block_indices[blocks_start + block_idx];
+ const int tokens_in_block = std::min(pam.block_size, total_tokens - block_idx * pam.block_size);
+
+ for (int token_offset = 0; token_offset < tokens_in_block; token_offset++) {
+ const int token_idx = block_idx * pam.block_size + token_offset;
+
+ for (int head_idx = 0; head_idx < pam.num_kv_heads; head_idx++) {
+ const size_t cache_base = static_cast<size_t>(physical_block) * pam.num_kv_heads * (pam.k_head_size + 4) * pam.block_size +
+ static_cast<size_t>(head_idx) * (pam.k_head_size + 4) * pam.block_size;
+
+ // Read scale and zero-point for this token
+ // Scale is at [head_size][token], ZP is at [head_size+2][token] (2 rows below)
+ // token_offset * 2 because each half is 2 bytes (token 0 at offset 0-1, token 1 at offset 2-3, etc.)
+ const size_t scale_offset = cache_base + static_cast<size_t>(pam.k_head_size) * pam.block_size + token_offset * 2;
+ const size_t zp_offset = scale_offset + 2 * pam.block_size; // ZP is 2 rows below scale
+ ov::float16 scale = *reinterpret_cast<const ov::float16*>(&cache_ptr[scale_offset]);
+ ov::float16 zp = *reinterpret_cast<const ov::float16*>(&cache_ptr[zp_offset]);
+
+ const size_t output_base = static_cast<size_t>(head_idx) * total_tokens * pam.k_head_size +
+ static_cast<size_t>(token_idx) * pam.k_head_size;
+
+ // Dequantize all dimensions for this token
+ for (int dim = 0; dim < pam.k_head_size; dim++) {
+ const size_t cache_offset = cache_base + static_cast<size_t>(dim) * pam.block_size + token_offset;
+
+ int8_t quantized_value = cache_ptr[cache_offset];
+ float dequantized = (static_cast<float>(quantized_value) - static_cast<float>(zp)) * static_cast<float>(scale);
+
+ key_data[output_base + dim] = ov::float16(dequantized);
+ }
+ }
+ }
+ }
+ }
+ }
+ return key_data;
+ }
+
+ std::vector<ov::float16> compute_diversity_reference(memory::ptr key_cache_mem) {
+ std::vector<ov::float16> diversity_output;
+
+ for (size_t seq_idx = 0; seq_idx < pam.subsequence_descs.size(); seq_idx++) {
+ const auto start_size = pam.adaptive_rkv_start_size;
+ const auto evictable_size = pam.adaptive_rkv_evictable_sizes[seq_idx];
+
+ // Read key data from key_cache instead of original key_data
+ const auto& subsequence_desc = pam.subsequence_descs[seq_idx];
+ const auto total_tokens = subsequence_desc.num_tokens + subsequence_desc.past_len;
+
+ // Extract key vectors from key_cache memory
+ std::vector<ov::float16> key_data = read_key_from_cache(key_cache_mem, seq_idx, total_tokens);
+
+ ov::Shape key_shape = {static_cast<size_t>(pam.num_kv_heads),
+ static_cast<size_t>(total_tokens),
+ static_cast<size_t>(pam.k_head_size)};
+
+ // Use reference implementation
+ ov::reference::AdaptiveRKVDiversityCalculator<ov::float16> calculator(start_size, evictable_size, pam.block_size);
+
+ auto block_diversity = calculator.calculate_block_diversity(key_data.data(), key_shape);
+
+ const size_t num_evictable_blocks = static_cast<size_t>(evictable_size) / static_cast<size_t>(pam.block_size);
+ // Flatten 2D to 1D: [num_evictable_blocks, evictable_size] -> [num_evictable_blocks * evictable_size]
+ for (size_t block_idx = 0; block_idx < num_evictable_blocks; block_idx++) {
+ for (size_t token_idx = 0; token_idx < static_cast<size_t>(evictable_size); token_idx++) {
+ diversity_output.push_back(block_diversity[block_idx][token_idx]);
+ }
+ }
+ }
+
+ return diversity_output;
+ }
+
PagedAttentionManager& pam;
cldnn::engine& test_engine;
cldnn::stream& test_stream;
@@ -1283,6 +1401,29 @@ public:
p.rotation_config,
p.threshold);
+ if (p.has_adaptive_rkv) {
+ pam.adaptive_rkv_diversity_block_set_indices_begins.push_back(0);
+ pam.adaptive_rkv_start_size = p.start_size;
+
+ for (size_t i = 0; i < p.subsequences.size(); i++) {
+ // Use per-sequence evictable_size if available, otherwise use first value
+ int evictable_size = i < p.evictable_sizes.size() ? p.evictable_sizes[i] : p.evictable_sizes[0];
+
+ pam.adaptive_rkv_evictable_sizes.push_back(evictable_size);
+
+ int start_block = p.start_size / p.block_size;
+ int evictable_blocks = evictable_size / p.block_size;
+ int global_start_block_idx = pam.block_indices_begins[i] + start_block;
+
+ for (int b = 0; b < evictable_blocks; b++) {
+ pam.adaptive_rkv_diversity_block_set_indices.push_back(global_start_block_idx + b);
+ }
+
+ int prev_begin = pam.adaptive_rkv_diversity_block_set_indices_begins.back();
+ pam.adaptive_rkv_diversity_block_set_indices_begins.push_back(prev_begin + evictable_blocks);
+ }
+ }
+
if (p.kv_cache_compression)
tolerance = 25e-3;
@@ -1447,9 +1588,14 @@ public:
pa_prim.heads_num = p.num_heads;
pa_prim.scale_val = pam.get_default_scale();
pa_prim.has_alibi = false;
- pa_prim.num_outputs = p.scores_mode == ScoresMode::DISABLED ? 1 : 2;
+
+ int num_outputs = 1;
+ if (p.scores_mode != ScoresMode::DISABLED) num_outputs++;
+ if (p.has_adaptive_rkv) num_outputs++;
+ pa_prim.num_outputs = num_outputs;
pa_prim.has_rotated_blocks = p.rotation_config.apply_rotation;
pa_prim.has_score_aggregation = p.scores_mode == ScoresMode::SNAPKV;
+ pa_prim.has_adaptive_rkv = p.has_adaptive_rkv;
pa_prim.sliding_window = p.sliding_window_size;
pa_prim.is_key_by_channel = (p.key_cache_quant_mode == ov::internal::CacheQuantMode::BY_CHANNEL);
if (p.has_xattention) {
@@ -1477,8 +1623,13 @@ public:
reorder("output_data", input_info("paged_attention", 0), format::bfyx, data_types::f16)
);
+ int output_idx = 1;
if (p.scores_mode != ScoresMode::DISABLED) {
- topology.add(reorder("output_scores", input_info("paged_attention", 1), format::bfyx, data_types::f16));
+ topology.add(reorder("output_scores", input_info("paged_attention", output_idx), format::bfyx, data_types::f16));
+ output_idx++;
+ }
+ if (p.has_adaptive_rkv) {
+ topology.add(reorder("output_diversity", input_info("paged_attention", output_idx), format::bfyx, data_types::f16));
}
{
@@ -1537,44 +1688,58 @@ public:
cldnn::memory::ptr output_data_mem = nullptr;
cldnn::memory::ptr output_scores_mem = nullptr;
+ cldnn::memory::ptr output_diversity_mem = nullptr;
output_data_mem = outputs.at("output_data").get_memory();
if (p.scores_mode != ScoresMode::DISABLED) {
output_scores_mem = outputs.at("output_scores").get_memory();
}
- auto ref_data = PagedAttentionReference(pam).get_reference(p.has_xattention, p.threshold);
+ if (p.has_adaptive_rkv) {
+ output_diversity_mem = outputs.at("output_diversity").get_memory();
+ }
+ auto ref_data = PagedAttentionReference(pam).get_reference(p.has_xattention, p.threshold, key_cache_mem);
if (p.has_xattention) {
compare_xattention(output_data_mem, output_scores_mem, ref_data);
} else {
- compare(output_data_mem, output_scores_mem, ref_data);
+ compare(output_data_mem, output_scores_mem, output_diversity_mem, ref_data);
}
}
- void compare(memory::ptr data_output_mem, memory::ptr scores_output_mem, std::pair<std::vector<ov::float16>, std::vector<ov::float16>> ref_data) {
+ void compare(memory::ptr data_output_mem, memory::ptr scores_output_mem, memory::ptr diversity_output_mem, std::tuple<std::vector<ov::float16>, std::vector<ov::float16>, std::vector<ov::float16>> ref_data) {
if (data_output_mem) {
- ASSERT_EQ(data_output_mem->count(), ref_data.first.size());
+ ASSERT_EQ(data_output_mem->count(), std::get<0>(ref_data).size());
mem_lock<ov::float16, mem_lock_type::read> mem_ptr(data_output_mem, get_test_stream());
for (size_t i = 0; i < data_output_mem->count(); i++) {
- ASSERT_NEAR(mem_ptr[i], ref_data.first[i], tolerance) << " at index=" << i;
+ ASSERT_NEAR(mem_ptr[i], std::get<0>(ref_data)[i], tolerance) << " at index=" << i;
}
}
if (scores_output_mem) {
- ASSERT_EQ(scores_output_mem->count(), ref_data.second.size());
+ ASSERT_EQ(scores_output_mem->count(), std::get<1>(ref_data).size());
mem_lock<ov::float16, mem_lock_type::read> mem_ptr(scores_output_mem, get_test_stream());
for (size_t i = 0; i < scores_output_mem->count(); i++) {
- ASSERT_NEAR(mem_ptr[i], ref_data.second[i], tolerance) << " at index=" << i;
+ ASSERT_NEAR(mem_ptr[i], std::get<1>(ref_data)[i], tolerance) << " at index=" << i;
+ }
+ }
+
+ if (diversity_output_mem) {
+ ASSERT_EQ(diversity_output_mem->count(), std::get<2>(ref_data).size());
+ mem_lock<ov::float16, mem_lock_type::read> mem_ptr(diversity_output_mem, get_test_stream());
+ // Relaxed tolerance due to float32 (GPU) vs float16 (reference) accumulator difference
+ float diversity_tolerance = tolerance * 10.0f;
+ for (size_t i = 0; i < diversity_output_mem->count(); i++) {
+ ASSERT_NEAR(mem_ptr[i], std::get<2>(ref_data)[i], diversity_tolerance) << " at index=" << i;
}
}
}
- void compare_xattention(memory::ptr data_output_mem, memory::ptr scores_output_mem, std::pair<std::vector<ov::float16>, std::vector<ov::float16>> ref_data) {
+ void compare_xattention(memory::ptr data_output_mem, memory::ptr scores_output_mem, std::tuple<std::vector<ov::float16>, std::vector<ov::float16>, std::vector<ov::float16>> ref_data) {
if (data_output_mem) {
- ASSERT_EQ(data_output_mem->count(), ref_data.first.size());
+ ASSERT_EQ(data_output_mem->count(), std::get<0>(ref_data).size());
mem_lock<ov::float16, mem_lock_type::read> mem_ptr(data_output_mem, get_test_stream());
int mismatch_count = 0;
for (size_t i = 0; i < data_output_mem->count(); i++) {
- if (std::fabs(static_cast<float>(mem_ptr[i]) - static_cast<float>(ref_data.first[i])) > tolerance) {
+ if (std::fabs(static_cast<float>(mem_ptr[i]) - static_cast<float>(std::get<0>(ref_data)[i])) > tolerance) {
mismatch_count++;
}
}
@@ -1582,11 +1747,11 @@ public:
}
if (scores_output_mem) {
- ASSERT_EQ(scores_output_mem->count(), ref_data.second.size());
+ ASSERT_EQ(scores_output_mem->count(), std::get<1>(ref_data).size());
mem_lock<ov::float16, mem_lock_type::read> mem_ptr(scores_output_mem, get_test_stream());
int mismatch_count = 0;
for (size_t i = 0; i < scores_output_mem->count(); i++) {
- if (std::fabs(static_cast<float>(mem_ptr[i]) - static_cast<float>(ref_data.second[i])) > tolerance) {
+ if (std::fabs(static_cast<float>(mem_ptr[i]) - static_cast<float>(std::get<1>(ref_data)[i])) > tolerance) {
mismatch_count++;
}
}
@@ -1618,6 +1783,9 @@ struct paged_attention_test_params {
ScoresMode scores_mode;
CacheRotationDescriptor rotation_config;
bool disable_flashattn_v2;
+ bool has_adaptive_rkv = false;
+ int start_size = 0; // Common start_size for all sequences
+ std::vector<int> evictable_sizes; // Per-sequence evictable sizes
};
class paged_attention_test : public PagedAttentionTest<paged_attention_test_params> {};
@@ -1636,6 +1804,13 @@ TEST_P(xattention_test, basic) {
execute(p);
}
+class adaptive_rkv_diversity_test : public PagedAttentionTest<paged_attention_test_params> {};
+TEST_P(adaptive_rkv_diversity_test, basic) {
+ auto p = GetParam();
+
+ execute(p);
+}
+
const auto ENABLE_CACHE_COMPRESSION = true;
const auto DISABLE_CACHE_COMPRESSION = false;
const auto DISABLE_SCORES = ScoresMode::DISABLED;
@@ -1648,6 +1823,8 @@ const auto STATIC_INPUT_PAD = false;
const auto DYNAMIC_INPUT_PAD = true;
const auto ENABLE_FA_V2 = false;
const auto DISABLE_FA_V2 = true;
+const auto ENABLE_DIVERSITY = true;
+const auto DISABLE_DIVERSITY = false;
INSTANTIATE_TEST_SUITE_P(smoke_paged_attention, paged_attention_test, ::testing::ValuesIn(std::vector<paged_attention_test_params>{
/* with scores output, use SnapKV */
@@ -1770,7 +1947,7 @@ INSTANTIATE_TEST_SUITE_P(smoke_paged_attention, paged_attention_test, ::testing:
paged_attention_test_params{ {{1008, 692}}, 32, 32, 128, 128, 16, {100.0}, 128, false, ENABLE_CACHE_COMPRESSION,ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, PER_TOKEN_ROTATION, DISABLE_FA_V2 }, // mixed: prefix caching
paged_attention_test_params{ {{1008, 792}}, 32, 32, 128, 128, 16, {100.0}, 256, false, ENABLE_CACHE_COMPRESSION,ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, PER_TOKEN_ROTATION, DISABLE_FA_V2 }, // mixed: prefix caching
paged_attention_test_params{ {{1, 34}, {2, 20}, {10, 34}}, 2, 2, 64, 64, 16, {100.0}, 10, false, ENABLE_CACHE_COMPRESSION,ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, PER_TOKEN_ROTATION, DISABLE_FA_V2 }, // mixed: 2nd token + 1st token + part of 1st token
- /* Per-Block rotation cases with Per-Channel quantization*/
+ /* Per-Block rotation cases with Per-Channel quantization*/
paged_attention_test_params{ {{16, 32}}, 2, 2, 32, 32, 16, {100.0}, 0, false, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, STATIC_INPUT_PAD, ENABLE_SCORES, PER_BLOCK_ROTATION, DISABLE_FA_V2 }, // 2nd token, per block rotate
paged_attention_test_params{ {{8, 34}}, 2, 2, 64, 64, 16, {100.0}, 0, false, ENABLE_CACHE_COMPRESSION,ov::internal::CacheQuantMode::BY_CHANNEL, STATIC_INPUT_PAD, ENABLE_SCORES, PER_BLOCK_ROTATION, DISABLE_FA_V2 }, // 2nd token, per block rotate
paged_attention_test_params{ {{256, 56}}, 2, 2, 64, 32, 16, {100.0}, 0, false, ENABLE_CACHE_COMPRESSION,ov::internal::CacheQuantMode::BY_CHANNEL, STATIC_INPUT_PAD, ENABLE_SCORES, PER_BLOCK_ROTATION, DISABLE_FA_V2 }, // 2nd token, per block rotate
@@ -1820,3 +1997,47 @@ INSTANTIATE_TEST_SUITE_P(smoke_cm_xattention, xattention_test, ::testing::Values
paged_attention_test_params{ {{1, 1023}}, 2, 2, 64, 64, 256, {0.9}, 0, true, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2 }, // 2nd token
paged_attention_test_params{ {{1, 1024}}, 2, 2, 64, 64, 256, {0.9}, 0, true, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2 }, // 2nd token
}));
+
+INSTANTIATE_TEST_SUITE_P(smoke_adaptive_rkv, adaptive_rkv_diversity_test, ::testing::ValuesIn(std::vector<paged_attention_test_params>{
+ // Small evictable_size tests (uniform across sequences)
+ paged_attention_test_params{ {{64, 0}}, 2, 2, 64, 64, 16, {100.0}, 0, false, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 16, {32} },
+ paged_attention_test_params{ {{128, 0}}, 4, 2, 64, 64, 16, {100.0}, 0, false, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 32, {64} },
+
+ // Edge cases - empty evictable_size (kernel skip test)
+ paged_attention_test_params{ {{64, 0}}, 2, 2, 64, 64, 16, {100.0}, 0, false, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 0, {0} }, // Empty - skip kernel
+ paged_attention_test_params{ {{32, 0}}, 2, 2, 64, 64, 16, {100.0}, 0, false, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 16, {16} }, // Minimal valid size (block-aligned)
+
+ // Multi-sequence tests - uniform evictable_sizes
+ paged_attention_test_params{ {{128, 0}, {128, 0}}, 2, 2, 64, 64, 16, {100.0}, 0, false, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 16, {32} }, // 2 sequences: same size
+ paged_attention_test_params{ {{128, 0}, {192, 0}, {160, 0}}, 2, 2, 64, 64, 16, {100.0}, 0, false, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 16, {32} }, // 3 sequences: same size
+
+ // Multi-sequence tests - varying evictable_sizes per sequence
+ paged_attention_test_params{ {{128, 0}, {128, 0}}, 2, 2, 64, 64, 16, {100.0}, 0, false, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 16, {32, 48} }, // 2 sequences: different evictable sizes
+ paged_attention_test_params{ {{128, 0}, {192, 0}, {160, 0}}, 2, 2, 64, 64, 16, {100.0}, 0, false, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 16, {32, 48, 32} }, // 3 sequences: different sizes
+ paged_attention_test_params{ {{128, 0}, {128, 0}, {128, 0}, {128, 0}}, 2, 2, 64, 64, 16, {100.0}, 0, false, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 16, {16, 32, 48, 32} }, // 4 sequences: varied sizes
+
+ // With KV cache compression - BY_TOKEN
+ paged_attention_test_params{ {{64, 0}}, 2, 2, 64, 64, 16, {100.0}, 0, false, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 16, {32} },
+ paged_attention_test_params{ {{128, 0}}, 4, 2, 64, 64, 16, {100.0}, 0, false, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 32, {64} },
+ paged_attention_test_params{ {{128, 0}, {128, 0}}, 2, 2, 64, 64, 16, {100.0}, 0, false, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 16, {32, 48} },
+ paged_attention_test_params{ {{128, 0}, {192, 0}, {160, 0}}, 2, 2, 64, 64, 16, {100.0}, 0, false, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 16, {32, 48, 32} },
+
+ // With KV cache compression - BY_CHANNEL
+ paged_attention_test_params{ {{64, 0}}, 2, 2, 64, 64, 16, {100.0}, 0, false, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 16, {32} },
+ paged_attention_test_params{ {{128, 0}}, 4, 2, 64, 64, 16, {100.0}, 0, false, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 32, {64} },
+ paged_attention_test_params{ {{128, 0}, {128, 0}}, 2, 2, 64, 64, 16, {100.0}, 0, false, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 16, {32, 48} },
+ paged_attention_test_params{ {{128, 0}, {192, 0}, {160, 0}}, 2, 2, 64, 64, 16, {100.0}, 0, false, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 16, {32, 48, 32} },
+
+ // Large evictable_size tests
+ paged_attention_test_params{ {{192, 0}}, 2, 2, 64, 64, 16, {100.0}, 0, false, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 48, {96} },
+ paged_attention_test_params{ {{256, 0}}, 2, 2, 64, 64, 16, {100.0}, 0, false, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 64, {128} },
+ paged_attention_test_params{ {{512, 0}}, 4, 2, 128, 128, 16, {100.0}, 0, false, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 128, {256} },
+
+ // GQA configurations
+ paged_attention_test_params{ {{128, 0}}, 8, 2, 64, 64, 16, {100.0}, 0, false, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 32, {64} }, // heads_num=8, start+evict=96
+ paged_attention_test_params{ {{160, 0}}, 16, 4, 128, 128, 16, {100.0}, 0, false, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 32, {48} }, // heads_num=16, start+evict=80
+
+ // Different head sizes
+ paged_attention_test_params{ {{128, 0}}, 2, 2, 128, 128, 16, {100.0}, 0, false, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 32, {64} }, // head_size=128, start+evict=96
+ paged_attention_test_params{ {{160, 0}}, 4, 4, 256, 256, 16, {100.0}, 0, false, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, ENABLE_DIVERSITY, 32, {48} }, // head_size=256, start+evict=80
+}));