Skip to content

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

[GPU]pa optimization for speculative verify stage (#38493)

yanlan songdf348d6faf3d
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_small_q_opt.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_small_q_opt.cl
new file mode 100644
index 00000000000..62de6b568a3
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_small_q_opt.cl
@@ -0,0 +1,406 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+// PagedAttention for the MIXED stage with a few query tokens per subsequence (speculative decoding).
+// A work-group processes one subsequence x one KV head x one partition. Each subgroup owns
+// TOKENS_PER_SG query tokens x KV_HEADS_GROUP_SIZE heads = 8 rows (the DPAS M tile), so QK^T and P@V
+// both run on DPAS with online softmax in registers. The dequantized K/V tile is shared through SLM.
+// Partial results per partition are merged by paged_attention_opt.cl (SDPA_STAGE_1, MULTI_TOKENS_PROCESSING).
+
+#include "include/batch_headers/common.cl"
+
+#if HAS_SINK_INPUT || PAGED_ATTENTION_SCORES_OUTPUT
+ #error "pa_small_q_opt.cl: sink input and scores output are not supported"
+#endif
+
+#if K_HEAD_SIZE != V_HEAD_SIZE || K_HEAD_SIZE % 32 != 0
+ #error "pa_small_q_opt.cl: K and V head sizes must be equal and a multiple of 32"
+#endif
+
+#if SUBGROUP_SIZE != 16 || PAGED_ATTENTION_BLOCK_SIZE != 16
+ #error "pa_small_q_opt.cl: SUBGROUP_SIZE and PAGED_ATTENTION_BLOCK_SIZE must be 16"
+#endif
+
+#if TOKENS_PER_SG * KV_HEADS_GROUP_SIZE != 8
+ #error "pa_small_q_opt.cl: each subgroup must own exactly 8 query rows"
+#endif
+
+#if SEQ_LEN_PARTITION_SIZE % PAGED_ATTENTION_BLOCK_SIZE != 0
+ #error "pa_small_q_opt.cl: SEQ_LEN_PARTITION_SIZE must be a multiple of PAGED_ATTENTION_BLOCK_SIZE"
+#endif
+
+#define HEAD_SIZE K_HEAD_SIZE
+#define BLOCK PAGED_ATTENTION_BLOCK_SIZE
+#define CHUNKS (HEAD_SIZE / SUBGROUP_SIZE)
+#define ROWS 8
+#define QUERY_ROW_STRIDE (K_HEAD_SIZE * HEADS_NUM + INPUT0_PAD_BEFORE_FEATURE_NUM + INPUT0_PAD_AFTER_FEATURE_NUM)
+
+#if IS_KV_COMPRESSED && IS_INT4_COMPRESSED
+ #define K_BLOCK_ELEMS (PACKED_ADJUSTED_K_HEAD_SIZE * ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE)
+ #define V_BLOCK_ELEMS (PACKED_ADJUSTED_V_HEAD_SIZE * BLOCK)
+#else
+ #define K_BLOCK_ELEMS (ADJUSTED_K_HEAD_SIZE * ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE)
+ #define V_BLOCK_ELEMS (ADJUSTED_V_HEAD_SIZE * BLOCK)
+#endif
+
+// Writes the K tile transposed to [token][head_dim] so each lane (key token) reads a contiguous DPAS B operand
+inline void FUNC(dequant_key)(const __global INPUT1_TYPE* key_block, __local half* dst, uint lid, uint local_size) {
+#if !IS_KV_COMPRESSED
+ for (uint d = lid; d < HEAD_SIZE; d += local_size) {
+ unroll_for (uint t = 0; t < BLOCK; t++) {
+ dst[t * HEAD_SIZE + d] = key_block[d * BLOCK + t];
+ }
+ }
+#elif IS_INT4_COMPRESSED && defined(IS_KEY_BY_CHANNEL)
+ const __global uchar* key_bytes = (const __global uchar*)key_block;
+ for (uint d = lid; d < HEAD_SIZE; d += local_size) {
+ const __global uchar* row = key_bytes + d * ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE;
+ const __global INPUT0_TYPE* comp = (const __global INPUT0_TYPE*)(row + PACKED_K_BLOCK_SIZE);
+ const float comp_scale = convert_float(comp[0]);
+ const float comp_zp = convert_float(comp[1]);
+ const ulong packed = as_ulong(vload8(0, row));
+ unroll_for (uint i = 0; i < PACKED_K_BLOCK_SIZE; i++) {
+ const uint codes = (uint)((packed >> (i * 8)) & 0xfful);
+ dst[(2 * i) * HEAD_SIZE + d] = convert_half(((float)(codes & 15u) - comp_zp) * comp_scale);
+ dst[(2 * i + 1) * HEAD_SIZE + d] = convert_half(((float)(codes >> 4) - comp_zp) * comp_scale);
+ }
+ }
+#elif IS_INT4_COMPRESSED
+ const __global uchar* key_bytes = (const __global uchar*)key_block;
+ const __global INPUT0_TYPE* comp = (const __global INPUT0_TYPE*)(key_bytes + PACKED_K_HEAD_SIZE * BLOCK);
+ for (uint packed_dim = lid; packed_dim < HEAD_SIZE / 2; packed_dim += local_size) {
+ unroll_for (uint t = 0; t < BLOCK; t++) {
+ const uint codes = key_bytes[packed_dim * BLOCK + t];
+ const float comp_scale = convert_float(comp[t]);
+ const float comp_zp = convert_float(comp[BLOCK + t]);
+ dst[t * HEAD_SIZE + 2 * packed_dim] = convert_half(((float)(codes & 15u) - comp_zp) * comp_scale);
+ dst[t * HEAD_SIZE + 2 * packed_dim + 1] = convert_half(((float)(codes >> 4) - comp_zp) * comp_scale);
+ }
+ }
+#elif defined(IS_KEY_BY_CHANNEL)
+ const __global char* key_bytes = (const __global char*)key_block;
+ for (uint d = lid; d < HEAD_SIZE; d += local_size) {
+ const __global char* row = key_bytes + d * ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE;
+ const __global INPUT0_TYPE* comp = (const __global INPUT0_TYPE*)(row + BLOCK);
+ const float comp_scale = convert_float(comp[0]);
+ const float comp_zp = convert_float(comp[1]);
+ unroll_for (uint t = 0; t < BLOCK; t++) {
+ dst[t * HEAD_SIZE + d] = convert_half(((float)row[t] - comp_zp) * comp_scale);
+ }
+ }
+#else
+ const __global char* key_bytes = (const __global char*)key_block;
+ const __global INPUT0_TYPE* comp = (const __global INPUT0_TYPE*)(key_bytes + HEAD_SIZE * BLOCK);
+ for (uint d = lid; d < HEAD_SIZE; d += local_size) {
+ unroll_for (uint t = 0; t < BLOCK; t++) {
+ const float comp_scale = convert_float(comp[t]);
+ const float comp_zp = convert_float(comp[BLOCK + t]);
+ dst[t * HEAD_SIZE + d] = convert_half(((float)key_bytes[d * BLOCK + t] - comp_zp) * comp_scale);
+ }
+ }
+#endif
+}
+
+// Writes the V tile transposed to [head_dim][token] so each lane (head dim) reads a contiguous DPAS B operand.
+// Rows at or beyond valid_tokens are zeroed: they may hold uninitialized data (NaN/Inf) and P.V would compute 0 * NaN.
+inline void FUNC(dequant_value)(const __global INPUT2_TYPE* value_block, __local half* dst, uint lid, uint local_size, uint valid_tokens) {
+ for (uint slot = lid; slot < BLOCK * CHUNKS; slot += local_size) {
+ const uint token = slot / CHUNKS;
+ const uint dim_base = (slot % CHUNKS) * SUBGROUP_SIZE;
+ if (token >= valid_tokens) {
+ unroll_for (uint j = 0; j < SUBGROUP_SIZE; j++) {
+ dst[(dim_base + j) * BLOCK + token] = 0;
+ }
+ continue;
+ }
+#if !IS_KV_COMPRESSED
+ const __global INPUT2_TYPE* row = value_block + token * HEAD_SIZE;
+ unroll_for (uint j = 0; j < SUBGROUP_SIZE; j++) {
+ dst[(dim_base + j) * BLOCK + token] = row[dim_base + j];
+ }
+#elif IS_INT4_COMPRESSED
+ const __global uchar* row = (const __global uchar*)value_block + token * PACKED_ADJUSTED_V_HEAD_SIZE;
+ const __global INPUT0_TYPE* comp = (const __global INPUT0_TYPE*)(row + PACKED_V_HEAD_SIZE);
+ const float comp_scale = convert_float(comp[0]);
+ const float comp_zp = convert_float(comp[1]);
+ const ulong packed = as_ulong(vload8(0, row + dim_base / 2));
+ unroll_for (uint i = 0; i < SUBGROUP_SIZE / 2; i++) {
+ const uint codes = (uint)((packed >> (i * 8)) & 0xfful);
+ const uint dim = dim_base + 2 * i;
+ dst[dim * BLOCK + token] = convert_half(((float)(codes & 15u) - comp_zp) * comp_scale);
+ dst[(dim + 1) * BLOCK + token] = convert_half(((float)(codes >> 4) - comp_zp) * comp_scale);
+ }
+#else
+ const __global char* value_bytes = (const __global char*)value_block;
+ const __global char* row = value_bytes + token * HEAD_SIZE;
+ const __global INPUT0_TYPE* comp = (const __global INPUT0_TYPE*)(value_bytes + HEAD_SIZE * BLOCK);
+ const float comp_scale = convert_float(comp[token]);
+ const float comp_zp = convert_float(comp[BLOCK + token]);
+ unroll_for (uint j = 0; j < SUBGROUP_SIZE; j++) {
+ dst[(dim_base + j) * BLOCK + token] = convert_half(((float)row[dim_base + j] - comp_zp) * comp_scale);
+ }
+#endif
+ }
+}
+
+REQD_SUB_GROUP_SIZE(SUBGROUP_SIZE)
+KERNEL(pa_small_q_opt)(
+ OPTIONAL_SHAPE_INFO_ARG
+ const __global INPUT0_TYPE* query,
+ const __global INPUT1_TYPE* key_cache,
+ const __global INPUT2_TYPE* value_cache,
+ const __global INPUT3_TYPE* past_lens,
+ const __global INPUT4_TYPE* block_indices,
+ const __global INPUT5_TYPE* block_indices_begins,
+ const __global INPUT6_TYPE* subsequence_begins,
+#if HAS_SCALE_INPUT
+ const __global SCALE_INPUT_TYPE* scale,
+#endif
+#if HAS_ALIBI
+ const __global ALIBI_INPUT_TYPE* alibi_slopes,
+#endif
+#if HAS_QQ_BIAS
+ const __global QQ_BIAS_DATA_T* qq_bias,
+ const __global QQ_BIAS_BEGINS_DATA_T* qq_bias_begins,
+#endif
+ __global OUTPUT_TYPE* output,
+ __global SOFTMAX_ACCUMULATOR_TYPE* exp_sums,
+ __global SOFTMAX_ACCUMULATOR_TYPE* max_logits,
+ __global OUTPUT_TYPE* tmp_out,
+ __global const int* gws_subseq_mapping
+) {
+ // query: [total_tokens, HEADS_NUM * K_HEAD_SIZE]
+ // output: [total_tokens, HEADS_NUM * V_HEAD_SIZE]
+ // exp_sums / max_logits: [total_tokens, HEADS_NUM, total_partitions_num]
+ // tmp_out: [total_tokens, HEADS_NUM, total_partitions_num, V_HEAD_SIZE]
+ const uint lid = get_local_id(2);
+ const uint local_size = get_local_size(2);
+ const uint sgid = get_sub_group_id();
+ const uint sglid = get_sub_group_local_id();
+ const uint subsequence_idx = get_group_id(0);
+ const uint kv_head_idx = get_group_id(1);
+ const uint partition_idx = get_group_id(2);
+ const uint total_partitions_num = get_num_groups(2);
+
+ const uint query_begin = subsequence_begins[subsequence_idx];
+ const uint query_count = subsequence_begins[subsequence_idx + 1] - query_begin;
+ if (query_count == 0)
+ return;
+
+ const uint past_len = past_lens[subsequence_idx];
+ const uint context_len = past_len + query_count;
+ const uint block_table_begin = block_indices_begins[subsequence_idx];
+ const uint head_begin = kv_head_idx * KV_HEADS_GROUP_SIZE;
+ const uint partition_start = partition_idx * SEQ_LEN_PARTITION_SIZE;
+
+#ifdef SCALE_VAL
+ const float scale_val = SCALE_VAL;
+#else
+ const float scale_val = convert_float(scale[0]);
+#endif
+
+#if HAS_QQ_BIAS
+ const uint qq_bias_num = qq_bias_begins[subsequence_idx + 1] - qq_bias_begins[subsequence_idx];
+ const uint qq_bias_spec_num = (uint)native_sqrt((float)qq_bias_num);
+ const uint cumulated_qq_bias_num = qq_bias_begins[subsequence_idx];
+#endif
+
+#ifdef SINGLE_KV_SLM
+ // K and V of a tile share one buffer: halves SLM per work-group at the cost of two extra barriers per tile
+ __local half kv_slm[BLOCK * HEAD_SIZE] __attribute__((aligned(64)));
+#else
+ // Double-buffered so that dequantization of the next tile does not wait for readers of the current one
+ __local half k_slm[2 * BLOCK * HEAD_SIZE] __attribute__((aligned(64)));
+ __local half v_slm[2 * HEAD_SIZE * BLOCK] __attribute__((aligned(64)));
+#endif
+
+ // DPAS A operand: lane holds head dim (c * SUBGROUP_SIZE + sglid) of each row.
+ // Rows beyond query_count clamp to the first token and are masked out below.
+ short8 q_cache[CHUNKS];
+ unroll_for (uint c = 0; c < CHUNKS; c++) {
+ half8 q;
+ unroll_for (uint m = 0; m < ROWS; m++) {
+ const uint token_off = sgid * TOKENS_PER_SG + m / KV_HEADS_GROUP_SIZE;
+ const uint token = query_begin + (token_off < query_count ? token_off : 0);
+ const uint head = head_begin + m % KV_HEADS_GROUP_SIZE;
+ q[m] = query[INPUT0_OFFSET + token * QUERY_ROW_STRIDE + head * HEAD_SIZE + c * SUBGROUP_SIZE + sglid];
+ }
+ q_cache[c] = as_short8(q);
+ }
+
+ float8 acc[CHUNKS];
+ unroll_for (uint c = 0; c < CHUNKS; c++) {
+ acc[c] = (float8)(0.0f);
+ }
+ float8 row_max = (float8)(-INFINITY);
+ float8 row_sum = (float8)(0.0f);
+
+ // The first query row defines the union of keys needed by this subsequence's sliding windows.
+ uint tile_start = partition_start;
+#if SLIDING_WINDOW_SIZE != 0
+ const uint first_query_seq_len = past_len + 1;
+ if (first_query_seq_len > SLIDING_WINDOW_SIZE) {
+ const uint window_start = first_query_seq_len - SLIDING_WINDOW_SIZE;
+ tile_start = max(tile_start, (window_start / BLOCK) * BLOCK);
+ }
+#endif
+
+ uint tile_count = 0;
+ const uint partition_end = partition_start + SEQ_LEN_PARTITION_SIZE;
+ if (tile_start < context_len && tile_start < partition_end) {
+ const uint partition_remaining = partition_end - tile_start;
+ tile_count = min((uint)(partition_remaining / BLOCK), (uint)CEIL_DIV(context_len - tile_start, BLOCK));
+ }
+
+ // Prefetch the next tile's block-table entry so its dependent global load overlaps this tile's
+ // compute instead of stalling each iteration's dequant (matters most for long context / many tiles).
+ uint physical_block = tile_count ? (uint)block_indices[block_table_begin + tile_start / BLOCK] : 0;
+
+ for (uint tile = 0; tile < tile_count; tile++) {
+ const uint key_start = tile_start + tile * BLOCK;
+ const uint valid_tokens = min((uint)BLOCK, context_len - key_start);
+ const __global INPUT1_TYPE* key_block = key_cache + physical_block * KV_HEADS_NUM * K_BLOCK_ELEMS + kv_head_idx * K_BLOCK_ELEMS;
+ const __global INPUT2_TYPE* value_block = value_cache + physical_block * KV_HEADS_NUM * V_BLOCK_ELEMS + kv_head_idx * V_BLOCK_ELEMS;
+ if (tile + 1 < tile_count)
+ physical_block = (uint)block_indices[block_table_begin + (key_start + BLOCK) / BLOCK];
+#ifdef SINGLE_KV_SLM
+ __local half* k_cur = kv_slm;
+ __local half* v_cur = kv_slm;
+ // Previous tile's P.V reads must finish before K overwrites the buffer
+ if (tile > 0)
+ barrier(CLK_LOCAL_MEM_FENCE);
+ FUNC_CALL(dequant_key)(key_block, k_cur, lid, local_size);
+#else
+ __local half* k_cur = k_slm + (tile & 1) * (BLOCK * HEAD_SIZE);
+ __local half* v_cur = v_slm + (tile & 1) * (HEAD_SIZE * BLOCK);
+ FUNC_CALL(dequant_key)(key_block, k_cur, lid, local_size);
+ FUNC_CALL(dequant_value)(value_block, v_cur, lid, local_size, valid_tokens);
+#endif
+ barrier(CLK_LOCAL_MEM_FENCE);
+
+ // S[8 rows, 16 key tokens] = Q . K^T. Interleave the SLM load with the MAD to overlap load latency.
+ float8 s = (float8)(0.0f);
+ for (uint c = 0; c < CHUNKS; c += 2) {
+ const int8 k0 = vload8(sglid * CHUNKS + c, (const __local int*)k_cur);
+ s = intel_sub_group_f16_f16_matrix_mad_k16(q_cache[c], k0, s);
+ const int8 k1 = vload8(sglid * CHUNKS + c + 1, (const __local int*)k_cur);
+ s = intel_sub_group_f16_f16_matrix_mad_k16(q_cache[c + 1], k1, s);
+ }
+ s *= (float8)(scale_val);
+
+ // Lane owns key token key_pos; the causal length differs per row
+ const uint key_pos = key_start + sglid;
+ float scores[ROWS];
+ vstore8(s, 0, scores);
+ unroll_for (uint m = 0; m < ROWS; m++) {
+ const uint token_off = sgid * TOKENS_PER_SG + m / KV_HEADS_GROUP_SIZE;
+ const uint seq_len = past_len + token_off + 1;
+ bool valid = token_off < query_count && key_pos < seq_len;
+#if SLIDING_WINDOW_SIZE != 0
+ valid = valid && !(seq_len > SLIDING_WINDOW_SIZE && key_pos < seq_len - SLIDING_WINDOW_SIZE);
+#endif
+#if HAS_QQ_BIAS
+ // Speculative tree mask between draft tokens of the same subsequence
+ if (valid && qq_bias_num > 0 && key_pos >= past_len) {
+ const uint spec_offset = key_pos - past_len;
+ if (spec_offset < qq_bias_spec_num && qq_bias[cumulated_qq_bias_num + token_off * qq_bias_spec_num + spec_offset] == 0)
+ valid = false;
+ }
+#endif
+#if HAS_ALIBI
+ scores[m] += convert_float(alibi_slopes[head_begin + m % KV_HEADS_GROUP_SIZE]) * ((int)key_pos + 1 - (int)seq_len);
+#endif
+ if (!valid)
+ scores[m] = -INFINITY;
+ }
+
+ // Online softmax; reductions are uniform across the subgroup
+ float tile_max[ROWS];
+ unroll_for (uint m = 0; m < ROWS; m++) {
+ tile_max[m] = sub_group_reduce_max(scores[m]);
+ }
+ const float8 new_max = fmax(row_max, vload8(0, tile_max));
+ const bool rescale_needed = any(new_max != row_max);
+ const float8 old_scale = select(native_exp(row_max - new_max), (float8)(0.0f), isinf(row_max));
+ const float8 p = select(native_exp(vload8(0, scores) - new_max), (float8)(0.0f), isinf(new_max));
+
+ float p_arr[ROWS];
+ vstore8(p, 0, p_arr);
+ float tile_sum[ROWS];
+ unroll_for (uint m = 0; m < ROWS; m++) {
+ tile_sum[m] = sub_group_reduce_add(p_arr[m]);
+ }
+ row_sum = row_sum * old_scale + vload8(0, tile_sum);
+ row_max = new_max;
+
+ if (rescale_needed) {
+ unroll_for (uint c = 0; c < CHUNKS; c++) {
+ acc[c] *= old_scale;
+ }
+ }
+
+#ifdef SINGLE_KV_SLM
+ barrier(CLK_LOCAL_MEM_FENCE);
+ FUNC_CALL(dequant_value)(value_block, v_cur, lid, local_size, valid_tokens);
+ barrier(CLK_LOCAL_MEM_FENCE);
+#endif
+
+ // O[8 rows, head dims] += P . V; A operand lane == key token
+ const short8 p_half = as_short8(convert_half8(p));
+ for (uint c = 0; c < CHUNKS; c += 2) {
+ const int8 v0 = vload8(c * SUBGROUP_SIZE + sglid, (const __local int*)v_cur);
+ acc[c] = intel_sub_group_f16_f16_matrix_mad_k16(p_half, v0, acc[c]);
+ const int8 v1 = vload8((c + 1) * SUBGROUP_SIZE + sglid, (const __local int*)v_cur);
+ acc[c + 1] = intel_sub_group_f16_f16_matrix_mad_k16(p_half, v1, acc[c + 1]);
+ }
+ // Double buffer needs no trailing barrier: the next write to this buffer happens after the next tile's barrier,
+ // which every subgroup reaches only after finishing this tile.
+ }
+
+ float max_arr[ROWS];
+ float sum_arr[ROWS];
+ vstore8(row_max, 0, max_arr);
+ vstore8(row_sum, 0, sum_arr);
+
+ unroll_for (uint m = 0; m < ROWS; m++) {
+ const uint token_off = sgid * TOKENS_PER_SG + m / KV_HEADS_GROUP_SIZE;
+ if (token_off >= query_count)
+ continue;
+
+ const uint seq_len = past_len + token_off + 1;
+ const uint token = query_begin + token_off;
+ const uint head = head_begin + m % KV_HEADS_GROUP_SIZE;
+ const float denom = sum_arr[m];
+ const float inv_denom = denom > 0.0f ? 1.0f / denom : 0.0f;
+
+ // The finalization stage skips tokens fitting into a single partition, so those are written to output directly
+ if (seq_len > SEQ_LEN_PARTITION_SIZE) {
+ if (sglid == 0) {
+ const uint exp_sums_offset = token * HEADS_NUM * total_partitions_num + head * total_partitions_num + partition_idx;
+ exp_sums[exp_sums_offset] = denom;
+ // Finite for fully masked partitions so finalization's exp(max - global_max) never sees -inf
+ max_logits[exp_sums_offset] = isinf(max_arr[m]) ? SOFTMAX_ACCUMULATOR_VAL_MIN : max_arr[m];
+ }
+ const uint tmp_out_offset = token * (HEADS_NUM * V_HEAD_SIZE * total_partitions_num) +
+ head * (V_HEAD_SIZE * total_partitions_num) +
+ partition_idx * V_HEAD_SIZE;
+ unroll_for (uint c = 0; c < CHUNKS; c++) {
+ tmp_out[tmp_out_offset + c * SUBGROUP_SIZE + sglid] = TO_OUTPUT_TYPE(acc[c][m] * inv_denom);
+ }
+ } else if (partition_idx == 0) {
+ const uint output_offset = token * (HEADS_NUM * V_HEAD_SIZE) + head * V_HEAD_SIZE;
+ unroll_for (uint c = 0; c < CHUNKS; c++) {
+ output[output_offset + c * SUBGROUP_SIZE + sglid] = TO_OUTPUT_TYPE(acc[c][m] * inv_denom);
+ }
+ }
+ }
+}
+
+#undef HEAD_SIZE
+#undef BLOCK
+#undef CHUNKS
+#undef ROWS
+#undef QUERY_ROW_STRIDE
+#undef K_BLOCK_ELEMS
+#undef V_BLOCK_ELEMS
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/paged_attention_opt.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/paged_attention_opt.cl
index e58319d9578..6e742235cd6 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/paged_attention_opt.cl
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/paged_attention_opt.cl
@@ -654,20 +654,24 @@ KERNEL(pa_sdpa_opt)(
barrier(CLK_LOCAL_MEM_FENCE);
{
- // Save temporary exm_sums and max_logits values for each partition_num
+ // Save temporary exm_sums and max_logits values for each partition_num.
+ // Subgroups stride over heads: with small head sizes SUBGROUPS_PER_WG may be smaller than HEADS_PER_WI.
#if HEADS_PER_WI > 1 && HEADS_LEFTOVERS_NUM > 0
- if (seq_len > SEQ_LEN_PARTITION_SIZE && sgid < HEADS_PER_WI && sgid < iter_heads_num) {
+ const uint stats_heads_num = iter_heads_num;
#else
- if (seq_len > SEQ_LEN_PARTITION_SIZE && sgid < HEADS_PER_WI) {
-#endif
- const uint head_idx = GET_MULTIPLE_HEAD_IDX_OR_FIXED_VAL(sgid, 0);
- const uint exp_sums_offset = seq_idx * HEADS_NUM * total_partitions_num +
- (head_num_idx + head_idx) * total_partitions_num +
- partition_idx;
- exp_sums[exp_sums_offset] = GET_VECTOR_ELEMENT(exp_sum, head_idx);
-
- const uint max_logits_offset = exp_sums_offset;
- max_logits[max_logits_offset] = GET_VECTOR_ELEMENT(qk_max, head_idx);
+ const uint stats_heads_num = HEADS_PER_WI;
+#endif
+ if (seq_len > SEQ_LEN_PARTITION_SIZE) {
+ for (uint q_idx = sgid; q_idx < stats_heads_num; q_idx += SUBGROUPS_PER_WG) {
+ const uint head_idx = GET_MULTIPLE_HEAD_IDX_OR_FIXED_VAL(q_idx, 0);
+ const uint exp_sums_offset = seq_idx * HEADS_NUM * total_partitions_num +
+ (head_num_idx + head_idx) * total_partitions_num +
+ partition_idx;
+ exp_sums[exp_sums_offset] = GET_VECTOR_ELEMENT(exp_sum, head_idx);
+
+ const uint max_logits_offset = exp_sums_offset;
+ max_logits[max_logits_offset] = GET_VECTOR_ELEMENT(qk_max, head_idx);
+ }
}
#if PAGED_ATTENTION_SCORES_OUTPUT
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 f278ccf9b56..f9b4ae1f3a5 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
@@ -11,7 +11,9 @@
#include <array>
#include <cstdint>
+#include <cstdlib>
#include <memory>
+#include <optional>
#include <utility>
#include "../primitive_ocl_base.hpp"
@@ -33,6 +35,30 @@ constexpr size_t paged_attention_block_size = 16;
constexpr size_t seq_len_partition_size = 256;
constexpr size_t subgroup_size = 16;
constexpr size_t u4_elems_per_byte = 2;
+// Max query tokens per subsequence in MIXED stage to treat it as speculative decoding and use the GQA kernel.
+// Override with OV_GPU_PA_GQA_MULTI_TOKENS_MAX (0 disables the GQA multi-token path).
+inline int32_t get_max_gqa_multi_tokens_per_subsequence() {
+ static const int32_t value = [] {
+ const char* env = std::getenv("OV_GPU_PA_GQA_MULTI_TOKENS_MAX");
+ return env ? static_cast<int32_t>(std::strtol(env, nullptr, 10)) : 16;
+ }();
+ return value;
+}
+
+// Force the GQA multi-token kernel with OV_GPU_PA_GQA_MULTI_TOKENS_KERNEL (values of GQAMultiTokensKernel:
+// 0 none, 1 small_q, 2 fallback). Unsupported choices fall back to automatic selection.
+inline std::optional<GQAMultiTokensKernel> get_forced_gqa_multi_tokens_kernel() {
+ static const auto value = []() -> std::optional<GQAMultiTokensKernel> {
+ const char* env = std::getenv("OV_GPU_PA_GQA_MULTI_TOKENS_KERNEL");
+ if (!env)
+ return std::nullopt;
+ const auto kernel = std::strtol(env, nullptr, 10);
+ if (kernel < 0 || kernel > static_cast<long>(GQAMultiTokensKernel::FALLBACK))
+ return std::nullopt;
+ return static_cast<GQAMultiTokensKernel>(kernel);
+ }();
+ return value;
+}
inline bool get_kv_compressed(const RuntimeParams& params) {
auto key_cache_layout = params.input_layouts[PagedAttentionInputIdx::KEY_CACHE];
@@ -116,6 +142,108 @@ inline bool can_use_gqa_kernel(const kernel_impl_params& params, const PagedAtte
return can_use_gqa_kernel;
}
+// pa_small_q_opt.cl: query rows (tokens x heads of one KV group) handled by one subgroup, equal to the DPAS M tile
+constexpr size_t gqa_multi_tokens_rows_per_sg = 8;
+
+inline size_t get_gqa_multi_tokens_per_sg(const kernel_impl_params& params) {
+ const auto desc = params.typed_desc<paged_attention>();
+ return gqa_multi_tokens_rows_per_sg / (desc->heads_num / desc->kv_heads_num);
+}
+
+inline size_t get_max_subsequence_len(const kernel_impl_params& params) {
+ const auto subsequence_begins_mem = params.memory_deps.at(PagedAttentionInputIdx::SUBSEQUENCE_BEGINS);
+ mem_lock<int32_t, mem_lock_type::read> subsequence_begins_mem_lock(subsequence_begins_mem, *params.strm);
+ size_t max_len = 0;
+ for (size_t i = 0; i + 1 < subsequence_begins_mem_lock.size(); i++) {
+ max_len = std::max(max_len, static_cast<size_t>(subsequence_begins_mem_lock[i + 1] - subsequence_begins_mem_lock[i]));
+ }
+ return max_len;
+}
+
+// GQA multi-token path of paged_attention_opt.cl; the sink and scores output code there assumes one head per work-item
+inline bool supports_gqa_multi_tokens_fallback_kernel(const kernel_impl_params& params) {
+ const auto desc = params.typed_desc<paged_attention>();
+ const size_t kv_group_size = desc->heads_num / desc->kv_heads_num;
+ return kv_group_size > 1 && !desc->has_sink_input && !desc->has_scores_output();
+}
+
+inline bool supports_gqa_multi_tokens_dpas_kernel(const kernel_impl_params& params) {
+ if (!supports_gqa_multi_tokens_fallback_kernel(params))
+ return false;
+
+ const auto& info = params.get_device_info();
+ // SIMD16 DPAS
+ if (!info.supports_immad || info.arch < gpu_arch::xe_hpc)
+ return false;
+
+ const auto desc = params.typed_desc<paged_attention>();
+ if (desc->has_token_type_ids)
+ return false;
+ const size_t kv_group_size = desc->heads_num / desc->kv_heads_num;
+ if (gqa_multi_tokens_rows_per_sg % kv_group_size != 0)
+ return false;
+
+ const size_t head_size = desc->k_head_size;
+ if (head_size != desc->v_head_size || head_size % (u4_elems_per_byte * subgroup_size) != 0 || head_size > 256)
+ return false;
+
+ if (params.get_input_layout(PagedAttentionInputIdx::QUERY).data_type != data_types::f16)
+ return false;
+ if (!get_kv_compressed(params) && params.get_input_layout(PagedAttentionInputIdx::KEY_CACHE).data_type != data_types::f16)
+ return false;
+
+ // Double-buffered f16 K and V tiles
+ const size_t slm_size = 4 * paged_attention_block_size * head_size * sizeof(uint16_t);
+ return slm_size <= info.max_local_mem_size;
+}
+
+// Speculative decoding validation step: MIXED stage where every subsequence has only a few new query tokens
+inline GQAMultiTokensKernel select_gqa_multi_tokens_kernel(const kernel_impl_params& params, const PagedAttentionStage& stage) {
+ if (stage != PagedAttentionStage::MIXED || !supports_gqa_multi_tokens_fallback_kernel(params))
+ return GQAMultiTokensKernel::NONE;
+
+ const auto max_tokens = get_max_gqa_multi_tokens_per_subsequence();
+ const auto max_subsequence_len = get_max_subsequence_len(params);
+ if (max_tokens <= 0 || max_subsequence_len > static_cast<size_t>(max_tokens))
+ return GQAMultiTokensKernel::NONE;
+
+ const auto forced = get_forced_gqa_multi_tokens_kernel();
+ if (forced == GQAMultiTokensKernel::NONE || forced == GQAMultiTokensKernel::FALLBACK)
+ return *forced;
+
+ if (!supports_gqa_multi_tokens_dpas_kernel(params))
+ return GQAMultiTokensKernel::FALLBACK;
+
+ const auto subgroups_num = ceil_div(max_subsequence_len, get_gqa_multi_tokens_per_sg(params));
+ if (subgroups_num * subgroup_size > params.get_device_info().max_work_group_size)
+ return GQAMultiTokensKernel::NONE;
+
+ if (forced.has_value())
+ return *forced;
+
+ return GQAMultiTokensKernel::SMALL_Q;
+}
+
+inline bool can_use_gqa_multi_tokens_kernel(const kernel_impl_params& params, const PagedAttentionStage& stage) {
+ return select_gqa_multi_tokens_kernel(params, stage) != GQAMultiTokensKernel::NONE;
+}
+
+inline void add_gqa_jit_constants(JitConstants& jit, const kernel_impl_params& params) {
+ const auto desc = params.typed_desc<paged_attention>();
+ const size_t kv_group_size = desc->heads_num / desc->kv_heads_num;
+ const auto heads_per_wi = get_heads_per_wi(kv_group_size);
+
+ jit.remove("HEADS_PER_WI");
+ jit.make("HEADS_PER_WI", heads_per_wi);
+ jit.make("ITERATIONS_PER_KV_HEADS_GROUP", ceil_div(kv_group_size, heads_per_wi));
+ jit.make("HEADS_LEFTOVERS_NUM", kv_group_size % heads_per_wi);
+}
+
+inline size_t get_gqa_heads_num(size_t heads_num, size_t kv_heads_num) {
+ const size_t kv_group_size = heads_num / kv_heads_num;
+ return kv_heads_num * ceil_div(kv_group_size, get_heads_per_wi(kv_group_size));
+}
+
static int64_t get_aligned_seq_len(const kernel_impl_params& impl_param, const PagedAttentionStage& stage, int64_t target_seq_len_block_size = 16) {
// Since at prefill stage Q, K, V inputs may contain multiple sequences with arbitrary
// target sequence lengths each (shape is [sequences_num * target_seq_len, num_heads * head_size]),
@@ -283,6 +411,7 @@ JitConstants make_uint4_kv_cache_jit_constants(const kernel_impl_params& params)
class PagedAttentionGeneratorBase : public KernelGenerator {
public:
explicit PagedAttentionGeneratorBase(std::string_view stage_suffix) : KernelGenerator("paged_attention_opt", stage_suffix) {}
+ PagedAttentionGeneratorBase(std::string_view kernel_name, std::string_view stage_suffix) : KernelGenerator(kernel_name, stage_suffix) {}
[[nodiscard]] JitConstants get_jit_constants(const kernel_impl_params& params) const override {
auto jit = make_base_jit_constants(params);
auto desc = params.typed_desc<paged_attention>();
@@ -510,17 +639,7 @@ public:
[[nodiscard]] JitConstants get_jit_constants(const kernel_impl_params& params) const override {
auto jit = PagedAttentionGeneratorSingleToken::get_jit_constants(params);
- const auto desc = params.typed_desc<paged_attention>();
- const size_t kv_group_size = desc->heads_num / desc->kv_heads_num;
- auto heads_per_wi = get_heads_per_wi(kv_group_size);
-
- // GQA
- jit.remove("HEADS_PER_WI");
- jit.make("HEADS_PER_WI", heads_per_wi);
-
- jit.make("ITERATIONS_PER_KV_HEADS_GROUP", ceil_div(kv_group_size, heads_per_wi));
- jit.make("HEADS_LEFTOVERS_NUM", kv_group_size % heads_per_wi);
-
+ add_gqa_jit_constants(jit, params);
return jit;
}
@@ -534,14 +653,11 @@ public:
const size_t total_tokens = params.input_layouts[0].get_partial_shape()[0].get_length();
const size_t heads_num = desc->heads_num;
const size_t v_head_size = desc->v_head_size;
- const size_t kv_group_size = desc->heads_num / desc->kv_heads_num;
const auto kv_cache_dt = params.get_program().get_config().get_kv_cache_precision();
const bool dual_nibble_v = can_use_dual_nibble_v(get_kv_compressed(params), kv_cache_dt, v_head_size);
const size_t head_size = dual_nibble_v ? v_head_size / u4_elems_per_byte : v_head_size;
auto sg_scale = get_pa_sg_number_scale_factor(params.get_device_info(), head_size, SDPAStage::SINGLE_TOKEN, get_kv_compressed(params));
- // GQA
- auto kv_groups = heads_num / kv_group_size;
- auto gqa_heads_num = kv_groups * ceil_div(kv_group_size, get_heads_per_wi(kv_group_size));
+ const auto gqa_heads_num = get_gqa_heads_num(heads_num, desc->kv_heads_num);
wgs.global = {total_tokens, gqa_heads_num, head_size * rtp->num_of_partitions * sg_scale};
wgs.local = {1, 1, head_size * sg_scale};
}};
@@ -606,6 +722,7 @@ public:
class PagedAttentionGeneratorMultiTokens : public PagedAttentionGeneratorBase {
public:
PagedAttentionGeneratorMultiTokens() : PagedAttentionGeneratorBase("_multi_tokens") {}
+ PagedAttentionGeneratorMultiTokens(std::string_view kernel_name, std::string_view stage_suffix) : PagedAttentionGeneratorBase(kernel_name, stage_suffix) {}
[[nodiscard]] JitConstants get_jit_constants(const kernel_impl_params& params) const override {
auto jit = PagedAttentionGeneratorBase::get_jit_constants(params);
@@ -725,6 +842,69 @@ public:
}
};
+// Speculative multi-token decode with GQA: one subgroup owns TOKENS_PER_SG query tokens x KV_HEADS_GROUP_SIZE heads
+// = 8 rows (the DPAS M tile); the K/V tile is dequantized into a single shared SLM buffer.
+class PagedAttentionGeneratorSmallQ : public PagedAttentionGeneratorMultiTokens {
+public:
+ PagedAttentionGeneratorSmallQ() : PagedAttentionGeneratorMultiTokens("pa_small_q_opt", "_gqa_multi_tokens") {}
+
+ [[nodiscard]] JitConstants get_jit_constants(const kernel_impl_params& params) const override {
+ auto jit = PagedAttentionGeneratorMultiTokens::get_jit_constants(params);
+ jit.make("TOKENS_PER_SG", get_gqa_multi_tokens_per_sg(params));
+ jit.make("SINGLE_KV_SLM", 1);
+ return jit;
+ }
+
+ [[nodiscard]] std::string get_build_options(const kernel_impl_params& params) const override {
+ return PagedAttentionGeneratorMultiTokens::get_build_options(params) + " -Dcl_intel_subgroup_matrix_multiply_accumulate";
+ }
+
+ [[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;
+ const auto desc = params.typed_desc<paged_attention>();
+ auto* rtp = static_cast<PagedAttentionRuntimeParams*>(rt_params);
+ const size_t subsequences_num = params.input_layouts[PagedAttentionInputIdx::PAST_LENS].get_partial_shape()[0].get_length();
+ const size_t local_size = ceil_div(get_max_subsequence_len(params), get_gqa_multi_tokens_per_sg(params)) * subgroup_size;
+
+ wgs.global = {subsequences_num, desc->kv_heads_num, local_size * rtp->num_of_partitions};
+ wgs.local = {1, 1, local_size};
+ }};
+ }
+};
+
+// Multi-token (speculative decoding) variant without DPAS, processing several query heads sharing one KV head per work-group
+class PagedAttentionGeneratorGQAMultiTokensFallback : public PagedAttentionGeneratorMultiTokens {
+public:
+ PagedAttentionGeneratorGQAMultiTokensFallback() : PagedAttentionGeneratorMultiTokens("paged_attention_opt", "_gqa_multi_tokens_fallback") {}
+
+ [[nodiscard]] JitConstants get_jit_constants(const kernel_impl_params& params) const override {
+ auto jit = PagedAttentionGeneratorMultiTokens::get_jit_constants(params);
+ add_gqa_jit_constants(jit, params);
+ return jit;
+ }
+
+ [[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;
+ const auto desc = params.typed_desc<paged_attention>();
+ auto* rtp = static_cast<PagedAttentionRuntimeParams*>(rt_params);
+ const size_t total_tokens = params.input_layouts[0].get_partial_shape()[0].get_length();
+ const size_t v_head_size = desc->v_head_size;
+ const auto kv_cache_dt = params.get_program().get_config().get_kv_cache_precision();
+ const bool dual_nibble_v = can_use_dual_nibble_v(get_kv_compressed(params), kv_cache_dt, v_head_size);
+ const size_t head_size = dual_nibble_v ? v_head_size / u4_elems_per_byte : v_head_size;
+
+ auto sg_scale = get_pa_sg_number_scale_factor(params.get_device_info(), head_size, SDPAStage::MULTI_TOKENS, get_kv_compressed(params));
+ const auto gqa_heads_num = get_gqa_heads_num(desc->heads_num, desc->kv_heads_num);
+ wgs.global = {total_tokens, gqa_heads_num, head_size * rtp->num_of_partitions * sg_scale};
+ wgs.local = {1, 1, head_size * sg_scale};
+ }};
+ }
+};
+
class PagedAttentionGeneratorMultiTokensFinalization : public PagedAttentionGeneratorBase {
public:
PagedAttentionGeneratorMultiTokensFinalization() : PagedAttentionGeneratorBase("_multi_tokens_finalization") {}
@@ -1402,6 +1582,8 @@ public:
Stage::Ptr pa_gqa_single_token = make_stage<PagedAttentionGeneratorGQASingleToken>();
Stage::Ptr pa_single_token_finalization = make_stage<PagedAttentionGeneratorSingleTokenFinalization>();
Stage::Ptr pa_multi_token = make_stage<PagedAttentionGeneratorMultiTokens>();
+ Stage::Ptr pa_small_q = make_stage<PagedAttentionGeneratorSmallQ>();
+ Stage::Ptr pa_gqa_multi_token_fallback = make_stage<PagedAttentionGeneratorGQAMultiTokensFallback>();
Stage::Ptr pa_multi_token_finalization = make_stage<PagedAttentionGeneratorMultiTokensFinalization>();
Stage::Ptr pa_sdpa_opt = make_stage<PagedAttentionSDPAOptGeneratorMultiToken>();
Stage::Ptr kv_cache_rotate = make_stage<KVCacheRotateGenerator>();
@@ -1433,6 +1615,13 @@ public:
add_stage(kv_cache_update, params);
add_stage(pa_multi_token, params);
+ if (supports_gqa_multi_tokens_dpas_kernel(params)) {
+ add_stage(pa_small_q, params);
+ }
+ if (supports_gqa_multi_tokens_fallback_kernel(params) &&
+ (!supports_gqa_multi_tokens_dpas_kernel(params) || get_forced_gqa_multi_tokens_kernel() == GQAMultiTokensKernel::FALLBACK)) {
+ add_stage(pa_gqa_multi_token_fallback, params);
+ }
add_stage(pa_multi_token_finalization, params);
add_stage(pa_single_token, params);
add_stage(pa_gqa_single_token, params);
@@ -1463,7 +1652,8 @@ public:
// token_type_ids does not change the choice: micro and OCL kernels both support it.
bool can_use_micro_sdpa_for(const kernel_impl_params& params, const PagedAttentionStage& stage) const {
- const auto can_use_micro_sdpa = supports_micro_sdpa(params) && valid_micro_stage(stage);
+ // Speculative decoding MIXED case is faster with the GQA multi-token kernel than with micro SDPA
+ const auto can_use_micro_sdpa = supports_micro_sdpa(params) && valid_micro_stage(stage) && !can_use_gqa_multi_tokens_kernel(params, stage);
GPU_DEBUG_TRACE_DETAIL << "can_use_micro_sdpa_for: stage = " << static_cast<size_t>(stage)
<< ", token_type_ids = " << params.get_input_layout(PagedAttentionInputIdx::TOKEN_TYPE_IDS).to_short_string()
<< ", can_use_micro_sdpa = " << can_use_micro_sdpa << std::endl;
@@ -1600,17 +1790,32 @@ public:
rt_params->query_block_size = get_query_block_size(rt_params->stage, rt_params->use_micro_sdpa);
+ rt_params->gqa_multi_tokens_kernel = GQAMultiTokensKernel::NONE;
if (rt_params->stage == PagedAttentionStage::GENERATE) {
if (desc->has_sink_input) {
rt_params->use_gqa_kernel = false;
} else {
rt_params->use_gqa_kernel = can_use_gqa_kernel(params, PagedAttentionStage::GENERATE, rt_params->max_context_len);
}
+ } else if (rt_params->stage == PagedAttentionStage::MIXED && !rt_params->use_micro_sdpa) {
+ rt_params->gqa_multi_tokens_kernel = select_gqa_multi_tokens_kernel(params, rt_params->stage);
+ rt_params->use_gqa_kernel = rt_params->gqa_multi_tokens_kernel != GQAMultiTokensKernel::NONE;
} else {
rt_params->use_gqa_kernel = false;
}
}
+ Stage::Ptr& get_gqa_multi_token_stage(GQAMultiTokensKernel kernel) {
+ switch (kernel) {
+ case GQAMultiTokensKernel::SMALL_Q:
+ return pa_small_q;
+ case GQAMultiTokensKernel::FALLBACK:
+ return pa_gqa_multi_token_fallback;
+ default:
+ OPENVINO_THROW("[GPU] Unexpected GQA multi-token kernel for PagedAttention");
+ }
+ }
+
// update impl_parameter and rt_parameter
void update(primitive_inst& inst, const kernel_impl_params& impl_params) override {
SDPAImplBase::update(inst, impl_params);
@@ -1656,7 +1861,9 @@ public:
const auto multi_tokens_mode = rt_params->stage == PagedAttentionStage::MIXED;
auto num_of_partitions = rt_params->num_of_partitions;
if (rt_params->use_gqa_kernel && !rt_params->use_micro_sdpa) {
- res_event = {execute_stage(res_event, instance, multi_tokens_mode ? pa_multi_token : pa_gqa_single_token)};
+ res_event = {execute_stage(res_event,
+ instance,
+ multi_tokens_mode ? get_gqa_multi_token_stage(rt_params->gqa_multi_tokens_kernel) : pa_gqa_single_token)};
} else {
#ifdef ENABLE_ONEDNN_FOR_GPU
if (multi_tokens_mode && rt_params->use_micro_sdpa) {
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.hpp
index 70c159ae440..f5e17919b75 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.hpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.hpp
@@ -26,6 +26,9 @@ inline bool pa_micro_uses_tt_bounds(const paged_attention& desc) {
enum class PagedAttentionStage : uint8_t { GENERATE = 0, PREFILL = 1, MIXED = 2, UNKNOWN = 3 };
+// Kernel used for MIXED stage with few query tokens per subsequence (speculative decoding)
+enum class GQAMultiTokensKernel : uint8_t { NONE = 0, SMALL_Q = 1, FALLBACK = 2 };
+
struct PagedAttentionRuntimeParams : public ImplRuntimeParams {
PagedAttentionStage stage;
size_t num_of_partitions;
@@ -37,6 +40,7 @@ struct PagedAttentionRuntimeParams : public ImplRuntimeParams {
size_t paged_attention_snap_kv_tokens;
bool use_micro_sdpa = false;
bool use_gqa_kernel = false;
+ GQAMultiTokensKernel gqa_multi_tokens_kernel = GQAMultiTokensKernel::NONE;
size_t query_block_size = 16;
};
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 031a574e6a9..5531639d836 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
@@ -914,6 +914,267 @@ INSTANTIATE_TEST_SUITE_P(smoke_qq_bias, qq_bias_test, ::testing::ValuesIn(std::v
paged_attention_test_params{ {{4, 20}, {2, 32}, {4, 25}}, 2, 2, 64, 64, 16, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, DISABLE_DIVERSITY, 0, {}, false, std::nullopt, std::nullopt, ov::element::dynamic, true, QueryToQueryAttentionDescriptor{{{{1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1}, {1, 0, 1, 1}, {1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1}}}, {0, 16, 20, 36}} },
}));
+// Test memory is typically zero-filled, so a kernel that reads rows past the context or skips a write can still match
+// the reference. The second run fills such locations with NaN to make those bugs visible.
+class paged_attention_gqa_multi_tokens_test_base : public PagedAttentionTest<paged_attention_test_params> {
+protected:
+ void check_accuracy_with_poisoned_memory(gpu_outputs& result, const paged_attention_test_params& p) {
+ auto pa_inst = result.network->get_primitive("paged_attention");
+ ASSERT_NE(pa_inst, nullptr);
+ SCOPED_TRACE(pa_inst->get_impl()->get_kernels_dump_info(*pa_inst->get_impl_params()).get_entries());
+
+ const auto reference = PagedAttentionReference(*pam).get_reference(result.key_cache_mem);
+ ASSERT_NO_FATAL_FAILURE(compare(result.outputs.at("output_data").get_memory(), nullptr, nullptr, reference));
+
+ poison_kv_cache_tail_rows(result.key_cache_mem, result.value_cache_mem, p);
+ poison_kernel_written_buffers(*pa_inst, result.outputs.at("output_data").get_memory());
+ result.outputs = result.network->execute();
+ {
+ SCOPED_TRACE("rerun with NaN in unused KV cache rows and kernel-written buffers");
+ compare(result.outputs.at("output_data").get_memory(), nullptr, nullptr, reference);
+ }
+ }
+
+private:
+ // Rows past the context in each subsequence's last block. By-channel key scales are shared with valid rows, so only
+ // uncompressed and by-token keys are poisoned there; every value cache format is.
+ void poison_kv_cache_tail_rows(const cldnn::memory::ptr& key_cache, const cldnn::memory::ptr& value_cache, const paged_attention_test_params& p) {
+ const ov::float16 nan = std::numeric_limits<ov::float16>::quiet_NaN();
+ constexpr size_t f16 = sizeof(ov::float16);
+ cldnn::mem_lock<uint8_t, cldnn::mem_lock_type::write> k(key_cache, tests::get_test_stream());
+ cldnn::mem_lock<uint8_t, cldnn::mem_lock_type::write> v(value_cache, tests::get_test_stream());
+ auto put_nan = [&](uint8_t* base, size_t byte_offset) {
+ std::memcpy(base + byte_offset, &nan, f16);
+ };
+
+ const bool int4 = pam->is_int4_kv_cache();
+ const bool key_by_token = p.key_cache_quant_mode == ov::internal::CacheQuantMode::BY_TOKEN;
+ const size_t bs = p.block_size, kv_heads = p.num_kv_heads, kh = p.k_head_size, vh = p.v_head_size;
+ for (size_t i = 0; i < p.subsequences.size(); ++i) {
+ const size_t valid_rows = static_cast<size_t>(p.subsequences[i].past_len + p.subsequences[i].num_tokens) % bs;
+ if (valid_rows == 0)
+ continue;
+ const size_t block = pam->block_indices[pam->block_indices_begins[i + 1] - 1];
+ for (size_t h = 0; h < kv_heads; ++h) {
+ const size_t block_head = block * kv_heads + h;
+ for (size_t t = valid_rows; t < bs; ++t) {
+ // key: [blocks, kv_heads, head_size (+ per-token scale/zp), block_size]
+ if (!p.kv_cache_compression) {
+ for (size_t d = 0; d < kh; ++d)
+ put_nan(k.data(), ((block_head * kh + d) * bs + t) * f16);
+ } else if (key_by_token) {
+ const size_t data_rows = int4 ? kh / 2 : kh;
+ put_nan(k.data(), block_head * (data_rows + 2 * f16) * bs + data_rows * bs + t * f16);
+ }
+ // value: [blocks, kv_heads, block_size, head_size (+ scale/zp)]
+ if (!p.kv_cache_compression) {
+ for (size_t d = 0; d < vh; ++d)
+ put_nan(v.data(), ((block_head * bs + t) * vh + d) * f16);
+ } else if (int4) {
+ put_nan(v.data(), (block_head * bs + t) * (vh / 2 + 2 * f16) + vh / 2);
+ } else {
+ put_nan(v.data(), block_head * bs * (vh + 2 * f16) + bs * vh + t * f16);
+ }
+ }
+ }
+ }
+ }
+
+ static void poison_kernel_written_buffers(cldnn::primitive_inst& pa_inst, const cldnn::memory::ptr& output) {
+ std::vector<cldnn::memory::ptr> buffers{output};
+ const auto& intermediates = pa_inst.get_intermediates_memories();
+ // MIXED without scores: kv update indexes [0..2], exp_sums [3], max_logits [4], tmp_out [5], subsequence mapping [6]
+ if (intermediates.size() == 7)
+ buffers.insert(buffers.end(), {intermediates[3], intermediates[4], intermediates[5]});
+ for (const auto& buffer : buffers) {
+ cldnn::mem_lock<uint8_t, cldnn::mem_lock_type::write> bytes(buffer, tests::get_test_stream());
+ std::fill(bytes.begin(), bytes.end(), uint8_t{0xFF}); // NaN for both f16 and f32
+ }
+ }
+};
+
+// Speculative decoding MIXED step with GQA: subsequences of at most 16 query tokens go to pa_small_q_opt.cl on DPAS
+// platforms when the KV group size divides 8, otherwise to the GQA multi-token path of paged_attention_opt.cl.
+class paged_attention_gqa_multi_tokens_test : public paged_attention_gqa_multi_tokens_test_base {};
+TEST_P(paged_attention_gqa_multi_tokens_test, basic) {
+ auto p = GetParam();
+ ASSERT_TRUE(this->pam.has_value());
+ auto& pam = *this->pam;
+
+ auto result = run_gpu_inference(pam, p);
+
+ // Mirrors supports_gqa_multi_tokens_dpas_kernel()
+ const auto& info = tests::get_test_engine().get_device_info();
+ const int kv_group_size = p.num_heads / p.num_kv_heads;
+ const bool expect_dpas = info.supports_immad && info.arch >= cldnn::gpu_arch::xe_hpc && 8 % kv_group_size == 0 &&
+ p.k_head_size == p.v_head_size && p.k_head_size % 32 == 0 && p.k_head_size <= 256;
+ const std::string expected_kernel = expect_dpas ? "pa_small_q_opt" : "_gqa_multi_tokens_fallback";
+ auto pa_inst = result.network->get_primitive("paged_attention");
+ ASSERT_NE(pa_inst, nullptr);
+ const auto entries = pa_inst->get_impl()->get_kernels_dump_info(*pa_inst->get_impl_params()).get_entries();
+ ASSERT_NE(entries.find(expected_kernel), std::string::npos) << "Expected " << expected_kernel << ", executed: " << entries;
+
+ check_accuracy_with_poisoned_memory(result, p);
+}
+
+// f16 means an uncompressed KV cache; i8 and u4 enable compression with the given key quantization mode
+static paged_attention_test_params make_gqa_multi_tokens_params(std::vector<SubsequenceDescriptor> subsequences,
+ int num_heads,
+ int num_kv_heads,
+ int head_size,
+ ov::element::Type kv_cache_precision = ov::element::f16,
+ ov::internal::CacheQuantMode key_cache_quant_mode = ov::internal::CacheQuantMode::BY_TOKEN) {
+ const bool compressed = kv_cache_precision != ov::element::f16;
+ paged_attention_test_params p{std::move(subsequences), num_heads, num_kv_heads, head_size, head_size, 16, 0, compressed, key_cache_quant_mode,
+ STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2};
+ p.kv_cache_precision = kv_cache_precision == ov::element::u4 ? ov::element::u4 : ov::element::dynamic;
+ return p;
+}
+
+static paged_attention_test_params with_sliding_window(paged_attention_test_params p, int sliding_window_size) {
+ p.sliding_window_size = sliding_window_size;
+ return p;
+}
+
+static paged_attention_test_params with_dynamic_paddings(paged_attention_test_params p) {
+ p.dynamic_paddings = DYNAMIC_INPUT_PAD;
+ return p;
+}
+
+static paged_attention_test_params with_qq_bias(paged_attention_test_params p, QueryToQueryAttentionDescriptor qq_bias_config) {
+ p.has_qq_bias = true;
+ p.qq_bias_config = std::move(qq_bias_config);
+ return p;
+}
+
+INSTANTIATE_TEST_SUITE_P(smoke_paged_attention_gqa_multi_tokens, paged_attention_gqa_multi_tokens_test, ::testing::ValuesIn(std::vector<paged_attention_test_params>{
+ // GQA ratios 2/4/8, single and double-buffered K/V SLM (cut-off at 4 subgroups)
+ make_gqa_multi_tokens_params({{4, 32}}, 8, 2, 64),
+ make_gqa_multi_tokens_params({{16, 40}}, 4, 2, 64),
+ make_gqa_multi_tokens_params({{16, 300}}, 8, 2, 128),
+ make_gqa_multi_tokens_params({{6, 600}}, 4, 2, 128),
+ make_gqa_multi_tokens_params({{8, 1000}}, 16, 2, 64),
+ make_gqa_multi_tokens_params({{5, 250}}, 8, 2, 256),
+ // query tokens straddle the 256-token partition boundary: some write output directly, others go through finalization
+ make_gqa_multi_tokens_params({{8, 252}}, 8, 2, 128),
+
+ // multiple subsequences with different lengths, including a single-token one
+ make_gqa_multi_tokens_params({{8, 34}, {3, 600}, {1, 100}}, 8, 2, 128),
+ make_gqa_multi_tokens_params({{2, 10}, {16, 520}}, 8, 4, 64),
+
+ // compressed KV cache
+ make_gqa_multi_tokens_params({{8, 300}}, 8, 2, 128, ov::element::i8, ov::internal::CacheQuantMode::BY_TOKEN),
+ make_gqa_multi_tokens_params({{8, 300}}, 8, 2, 128, ov::element::i8, ov::internal::CacheQuantMode::BY_CHANNEL),
+ make_gqa_multi_tokens_params({{8, 300}}, 8, 2, 128, ov::element::u4, ov::internal::CacheQuantMode::BY_CHANNEL),
+ make_gqa_multi_tokens_params({{16, 520}}, 16, 4, 256, ov::element::u4, ov::internal::CacheQuantMode::BY_CHANNEL),
+
+ // sliding window, padded query, speculative tree mask
+ with_sliding_window(make_gqa_multi_tokens_params({{8, 300}}, 8, 2, 128), 64),
+ // The window starts inside a KV block and wholly after the first context partition.
+ with_sliding_window(make_gqa_multi_tokens_params({{8, 300}}, 8, 2, 128), 17),
+ with_dynamic_paddings(make_gqa_multi_tokens_params({{8, 34}}, 8, 2, 128)),
+ with_qq_bias(make_gqa_multi_tokens_params({{8, 34}}, 8, 2, 64), make_tree_qq_bias({8})),
+ with_qq_bias(make_gqa_multi_tokens_params({{16, 40}, {1, 100}, {8, 300}}, 8, 2, 64), make_tree_qq_bias({16, 1, 8})),
+
+ // KV group size 3 does not fit the DPAS tile and always takes the fallback kernel
+ make_gqa_multi_tokens_params({{8, 300}}, 6, 2, 64),
+ make_gqa_multi_tokens_params({{8, 300}}, 12, 4, 128, ov::element::i8, ov::internal::CacheQuantMode::BY_CHANNEL),
+ // Multiple subsequences with different query lengths; GQA ratio 3 forces fallback even on DPAS devices.
+ make_gqa_multi_tokens_params({{4, 32}, {3, 256}, {2, 600}}, 6, 2, 64),
+
+ // Last KV block partially filled (context % 16 != 0) in single and multiple partitions, per cache format
+ make_gqa_multi_tokens_params({{8, 35}}, 8, 2, 128),
+ make_gqa_multi_tokens_params({{8, 35}}, 8, 2, 128, ov::element::i8, ov::internal::CacheQuantMode::BY_TOKEN),
+ make_gqa_multi_tokens_params({{8, 35}}, 8, 2, 128, ov::element::u4, ov::internal::CacheQuantMode::BY_CHANNEL),
+ make_gqa_multi_tokens_params({{8, 291}}, 8, 2, 128, ov::element::u4, ov::internal::CacheQuantMode::BY_CHANNEL),
+ make_gqa_multi_tokens_params({{8, 300}}, 8, 2, 128, ov::element::u4, ov::internal::CacheQuantMode::BY_TOKEN),
+ make_gqa_multi_tokens_params({{5, 27}, {8, 300}, {3, 513}}, 8, 2, 128, ov::element::i8, ov::internal::CacheQuantMode::BY_TOKEN),
+
+ // Fallback with fewer subgroups (v_head_size / 16 * sg_scale) than heads per work-item: every head must still
+ // write its partition statistics
+ make_gqa_multi_tokens_params({{8, 300}}, 4, 2, 16),
+ make_gqa_multi_tokens_params({{8, 300}}, 6, 2, 16),
+ make_gqa_multi_tokens_params({{8, 300}}, 8, 2, 16),
+ make_gqa_multi_tokens_params({{8, 300}}, 6, 2, 32),
+ make_gqa_multi_tokens_params({{8, 300}}, 8, 2, 48),
+ make_gqa_multi_tokens_params({{8, 300}}, 6, 2, 32, ov::element::u4, ov::internal::CacheQuantMode::BY_CHANNEL),
+ make_gqa_multi_tokens_params({{8, 300}}, 6, 2, 16, ov::element::i8, ov::internal::CacheQuantMode::BY_TOKEN),
+ make_gqa_multi_tokens_params({{8, 1000}}, 6, 2, 16),
+ make_gqa_multi_tokens_params({{3, 600}, {8, 20}, {5, 290}}, 6, 2, 32),
+ // KV group sizes 5 and 7 span several work-items, the last one holding leftover heads
+ make_gqa_multi_tokens_params({{8, 300}}, 10, 2, 32),
+ make_gqa_multi_tokens_params({{8, 300}}, 14, 2, 64),
+ // Controls: a single partition, and enough subgroups for every head
+ make_gqa_multi_tokens_params({{8, 35}}, 6, 2, 32),
+ make_gqa_multi_tokens_params({{8, 300}}, 6, 2, 64),
+}));
+
+// Accuracy-only coverage for the default-mode GQA multi-token decode path. Unlike
+// paged_attention_gqa_multi_tokens_test it does not assert the executed kernel name, so it stays valid
+// whichever kernel the current device selects (pa_small_q_opt DPAS variant or the OCL fallback).
+class paged_attention_gqa_multi_tokens_accuracy_test : public paged_attention_gqa_multi_tokens_test_base {};
+TEST_P(paged_attention_gqa_multi_tokens_accuracy_test, matches_reference) {
+ auto p = GetParam();
+ ASSERT_TRUE(this->pam.has_value());
+ auto& pam = *this->pam;
+
+ auto result = run_gpu_inference(pam, p);
+ check_accuracy_with_poisoned_memory(result, p);
+}
+
+INSTANTIATE_TEST_SUITE_P(smoke_paged_attention_gqa_multi_tokens_accuracy, paged_attention_gqa_multi_tokens_accuracy_test, ::testing::ValuesIn(std::vector<paged_attention_test_params>{
+ // Speculative width sweep across the (1, SMALL_Q_THRESHOLD] window at GQA 8/2
+ make_gqa_multi_tokens_params({{2, 48}}, 8, 2, 128),
+ make_gqa_multi_tokens_params({{3, 48}}, 8, 2, 128),
+ make_gqa_multi_tokens_params({{7, 48}}, 8, 2, 128),
+ make_gqa_multi_tokens_params({{9, 48}}, 8, 2, 128),
+ make_gqa_multi_tokens_params({{11, 48}}, 8, 2, 128),
+ make_gqa_multi_tokens_params({{13, 48}}, 8, 2, 128),
+ make_gqa_multi_tokens_params({{16, 48}}, 8, 2, 128),
+
+ // past_len boundaries: unaligned start, block (16) aligned, partition (256) boundary
+ make_gqa_multi_tokens_params({{8, 1}}, 8, 2, 128),
+ make_gqa_multi_tokens_params({{8, 15}}, 8, 2, 128),
+ make_gqa_multi_tokens_params({{8, 16}}, 8, 2, 128),
+ make_gqa_multi_tokens_params({{8, 255}}, 8, 2, 128),
+ make_gqa_multi_tokens_params({{8, 256}}, 8, 2, 128),
+ make_gqa_multi_tokens_params({{8, 257}}, 8, 2, 128),
+
+ // GQA ratios: group 2/4/8 (DPAS tile) and group 3 (fallback)
+ make_gqa_multi_tokens_params({{8, 300}}, 16, 8, 128),
+ make_gqa_multi_tokens_params({{8, 300}}, 16, 4, 128),
+ make_gqa_multi_tokens_params({{8, 300}}, 32, 8, 64),
+ make_gqa_multi_tokens_params({{8, 300}}, 8, 1, 64),
+ make_gqa_multi_tokens_params({{8, 300}}, 24, 8, 128, ov::element::i8, ov::internal::CacheQuantMode::BY_CHANNEL),
+
+ // head size variety
+ make_gqa_multi_tokens_params({{8, 300}}, 8, 2, 96),
+ make_gqa_multi_tokens_params({{8, 300}}, 8, 2, 192),
+
+ // multi-subsequence speculative batches with mixed widths and past lengths
+ make_gqa_multi_tokens_params({{4, 16}, {8, 256}, {16, 600}}, 8, 2, 128),
+ make_gqa_multi_tokens_params({{1, 50}, {5, 50}, {12, 50}}, 8, 4, 64),
+
+ // compressed KV cache combined with sliding window / dynamic paddings / speculative tree mask
+ make_gqa_multi_tokens_params({{12, 300}}, 8, 2, 128, ov::element::i8, ov::internal::CacheQuantMode::BY_TOKEN),
+ make_gqa_multi_tokens_params({{12, 300}}, 16, 4, 256, ov::element::u4, ov::internal::CacheQuantMode::BY_CHANNEL),
+ with_sliding_window(make_gqa_multi_tokens_params({{8, 300}}, 8, 2, 128, ov::element::i8, ov::internal::CacheQuantMode::BY_CHANNEL), 128),
+ with_dynamic_paddings(make_gqa_multi_tokens_params({{8, 300}}, 8, 2, 128, ov::element::u4, ov::internal::CacheQuantMode::BY_CHANNEL)),
+ with_qq_bias(make_gqa_multi_tokens_params({{12, 40}}, 8, 2, 64, ov::element::i8, ov::internal::CacheQuantMode::BY_TOKEN), make_tree_qq_bias({12})),
+
+ // context aligned to a KV block, and one row into a new block
+ make_gqa_multi_tokens_params({{8, 24}}, 8, 2, 128),
+ make_gqa_multi_tokens_params({{8, 25}}, 8, 2, 128),
+ make_gqa_multi_tokens_params({{8, 25}}, 6, 2, 64),
+
+ // small head sizes combined with the widest speculation, group size 8, sliding window and tree mask
+ make_gqa_multi_tokens_params({{16, 300}}, 6, 2, 32),
+ make_gqa_multi_tokens_params({{8, 300}}, 16, 2, 16),
+ with_sliding_window(make_gqa_multi_tokens_params({{8, 300}}, 6, 2, 32), 17),
+ with_qq_bias(make_gqa_multi_tokens_params({{8, 300}}, 6, 2, 32), make_tree_qq_bias({8})),
+ make_gqa_multi_tokens_params({{2, 700}, {16, 40}, {7, 256}}, 12, 4, 64, ov::element::i8, ov::internal::CacheQuantMode::BY_CHANNEL),
+}));
+
INSTANTIATE_TEST_SUITE_P(smoke_cm_small_q, cm_small_q_test, ::testing::ValuesIn(std::vector<paged_attention_test_params>{
// q_len sweep across the (1, SMALL_Q_THRESHOLD] window
paged_attention_test_params{ {{2, 34}}, 2, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128} },