Skip to content

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

[GPU][CM] support SD in CM path (#36684)

yanlan song739e9f860a68
diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/pa_kv_reorder.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/pa_kv_reorder.hpp
index 2d67caa1c96..387a17b0248 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/primitives/pa_kv_reorder.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/pa_kv_reorder.hpp
@@ -36,6 +36,7 @@ struct pa_kv_reorder : public primitive_base<pa_kv_reorder> {
seed = hash_combine(seed, adjusted_v_head_size);
seed = hash_combine(seed, static_cast<size_t>(cache_dt));
seed = hash_combine(seed, is_kv_compressed);
+ seed = hash_combine(seed, has_xattention);
return seed;
}
@@ -47,7 +48,8 @@ struct pa_kv_reorder : public primitive_base<pa_kv_reorder> {
return is_key_by_channel == rhs_casted.is_key_by_channel && scales_zp_size == rhs_casted.scales_zp_size && kv_heads_num == rhs_casted.kv_heads_num &&
adjusted_k_head_size == rhs_casted.adjusted_k_head_size &&
adjusted_paged_attention_block_size == rhs_casted.adjusted_paged_attention_block_size &&
- adjusted_v_head_size == rhs_casted.adjusted_v_head_size && cache_dt == rhs_casted.cache_dt && is_kv_compressed == rhs_casted.is_kv_compressed;
+ adjusted_v_head_size == rhs_casted.adjusted_v_head_size && cache_dt == rhs_casted.cache_dt && is_kv_compressed == rhs_casted.is_kv_compressed &&
+ has_xattention == rhs_casted.has_xattention;
}
void save(BinaryOutputBuffer& ob) const override {
@@ -60,6 +62,7 @@ struct pa_kv_reorder : public primitive_base<pa_kv_reorder> {
ob << adjusted_v_head_size;
ob << static_cast<int64_t>(cache_dt);
ob << is_kv_compressed;
+ ob << has_xattention;
}
void load(BinaryInputBuffer& ib) override {
@@ -74,6 +77,7 @@ struct pa_kv_reorder : public primitive_base<pa_kv_reorder> {
ib >> cache_dt_val;
cache_dt = static_cast<data_types>(cache_dt_val);
ib >> is_kv_compressed;
+ ib >> has_xattention;
}
bool is_key_by_channel = false;
@@ -84,6 +88,8 @@ struct pa_kv_reorder : public primitive_base<pa_kv_reorder> {
size_t adjusted_v_head_size = 0;
data_types cache_dt = data_types::f16;
bool is_kv_compressed = false;
+ // Align with paged_attention::has_xattention
+ bool has_xattention = false;
};
} // namespace cldnn
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/include/cm_attention_common.hpp b/src/plugins/intel_gpu/src/graph/impls/cm/include/cm_attention_common.hpp
index 7dc8c6ca0d2..87626d23f47 100644
--- a/src/plugins/intel_gpu/src/graph/impls/cm/include/cm_attention_common.hpp
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/include/cm_attention_common.hpp
@@ -5,6 +5,8 @@
#include <cm/cm.h>
#include <cm/cmtl.h>
+#include "cm_qq_bias_mask.hpp"
+
//# CM-compiler is C++17
static_assert(__cplusplus >= 201703L);
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/include/cm_pa_xe1.hpp b/src/plugins/intel_gpu/src/graph/impls/cm/include/cm_pa_xe1.hpp
index 6eec4e4a8f8..fa467da13f0 100644
--- a/src/plugins/intel_gpu/src/graph/impls/cm/include/cm_pa_xe1.hpp
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/include/cm_pa_xe1.hpp
@@ -23,6 +23,10 @@ void pa_lsc_u8(
#if SPARSE_BLOCK_SIZE > 1
svmptr_t sparse_mask_base [[type("svmptr_t")]],
svmptr_t wg_sparse_mask_base [[type("svmptr_t")]],
+#endif
+#if HAS_QQ_BIAS
+ svmptr_t qq_bias_base [[type("svmptr_t")]],
+ int32_t qq_bias_spec_num,
#endif
svmptr_t o_base [[type("svmptr_t")]],
int32_t past_lens,
@@ -299,6 +303,10 @@ void pa_lsc_u8(
// LSC ensures no overflow-access, but mask off k-tails attn-score is still required
for(int p = kv_tokens; p < kv_step; p++) St[p] = -3.4e38f;
}
+#if HAS_QQ_BIAS
+ apply_qq_bias_tree_mask(St, qq_bias_base, qq_bias_spec_num,
+ kv_pos, q_start, (int)past_lens);
+#endif
auto max_comp = cm_online_softmax_update(St, cur_max, cur_sum);
matrix<half, REG_N, REG_K> P;
@@ -404,6 +412,10 @@ void pa_kernel_lsc_prefetch_f16(
#if SPARSE_BLOCK_SIZE > 1
svmptr_t sparse_mask_base [[type("svmptr_t")]],
svmptr_t wg_sparse_mask_base [[type("svmptr_t")]],
+#endif
+#if HAS_QQ_BIAS
+ svmptr_t qq_bias_base [[type("svmptr_t")]],
+ int32_t qq_bias_spec_num,
#endif
svmptr_t o_base [[type("svmptr_t")]],
int32_t past_lens,
@@ -567,6 +579,12 @@ void pa_kernel_lsc_prefetch_f16(
for(int p = kv_tokens; p < kv_step; p++) St[p] = -3.4e38f;
}
+#if HAS_QQ_BIAS
+ apply_qq_bias_tree_mask(St, qq_bias_base, qq_bias_spec_num,
+ kv_pos, q_start, (int)past_lens);
+#endif
+
+ // show(St);
auto max_comp = cm_online_softmax_update(St, cur_max, cur_sum);
matrix<half, REG_N, REG_K> P;
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/include/cm_pa_xe2.hpp b/src/plugins/intel_gpu/src/graph/impls/cm/include/cm_pa_xe2.hpp
index bc60e3077ed..8723cdc9b21 100644
--- a/src/plugins/intel_gpu/src/graph/impls/cm/include/cm_pa_xe2.hpp
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/include/cm_pa_xe2.hpp
@@ -60,6 +60,10 @@ void pa_lsc_u8(
#if SPARSE_BLOCK_SIZE > 1
svmptr_t sparse_mask_base [[type("svmptr_t")]],
svmptr_t wg_sparse_mask_base [[type("svmptr_t")]],
+#endif
+#if HAS_QQ_BIAS
+ svmptr_t qq_bias_base [[type("svmptr_t")]],
+ int32_t qq_bias_spec_num,
#endif
svmptr_t o_base [[type("svmptr_t")]],
int32_t past_lens,
@@ -398,6 +402,10 @@ void pa_lsc_u8(
}
int kv_tokens = kv_stop - kv_pos;
for (int p = kv_tokens; p < kv_step; p++) St[p] = -3.4e38f;
+#if HAS_QQ_BIAS
+ apply_qq_bias_tree_mask(St, qq_bias_base, qq_bias_spec_num,
+ kv_pos, q_start, (int)past_lens);
+#endif
auto max_comp = cm_online_softmax_update(St, cur_max, cur_sum);
matrix<half, REG_N, REG_K> P;
@@ -632,6 +640,10 @@ void pa_lsc_u8(
}
int kv_tokens = kv_stop - kv_pos;
for (int p = kv_tokens; p < kv_step; p++) St[p] = -3.4e38f;
+#if HAS_QQ_BIAS
+ apply_qq_bias_tree_mask(St, qq_bias_base, qq_bias_spec_num,
+ kv_pos, q_start, (int)past_lens);
+#endif
auto max_comp = cm_online_softmax_update(St, cur_max, cur_sum);
matrix<half, REG_N, REG_K> P;
@@ -769,6 +781,12 @@ void pa_kernel_lsc_prefetch_f16(
#if SPARSE_BLOCK_SIZE > 1
svmptr_t sparse_mask_base [[type("svmptr_t")]],
svmptr_t wg_sparse_mask_base [[type("svmptr_t")]],
+#endif
+#if HAS_QQ_BIAS
+ // Speculative tree mask. Layout per subsequence: [spec_num, spec_num] row-major,
+ // i.e. qq_bias[query_spec * spec_num + key_spec]. Zero entries imply masked-out pairs.
+ svmptr_t qq_bias_base [[type("svmptr_t")]],
+ int32_t qq_bias_spec_num,
#endif
svmptr_t o_base [[type("svmptr_t")]],
int32_t past_lens,
@@ -967,6 +985,13 @@ void pa_kernel_lsc_prefetch_f16(
int kv_tokens = kv_stop - kv_pos;
// LSC ensures no overflow-access, but mask off k-tails attn-score is still required
for(int p = kv_tokens; p < kv_step; p++) St[p] = -3.4e38f;
+
+#if HAS_QQ_BIAS
+ apply_qq_bias_tree_mask(St, qq_bias_base, qq_bias_spec_num,
+ kv_pos, q_start, (int)past_lens);
+#endif
+
+ //show(St);
auto max_comp = cm_online_softmax_update(St, cur_max, cur_sum);
matrix<half, REG_N, REG_K> P;
@@ -1270,6 +1295,13 @@ void pa_kernel_lsc_prefetch_f16(
int kv_tokens = kv_stop - kv_pos;
// LSC ensures no overflow-access, but mask off k-tails attn-score is still required
for(int p = kv_tokens; p < kv_step; p++) St[p] = -3.4e38f;
+
+#if HAS_QQ_BIAS
+ apply_qq_bias_tree_mask(St, qq_bias_base, qq_bias_spec_num,
+ kv_pos, q_start, (int)past_lens);
+#endif
+
+ //show(St);
auto max_comp = cm_online_softmax_update(St, cur_max, cur_sum);
matrix<half, REG_N, REG_K> P;
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/include/cm_qq_bias_mask.hpp b/src/plugins/intel_gpu/src/graph/impls/cm/include/cm_qq_bias_mask.hpp
new file mode 100644
index 00000000000..c00fe84e3e3
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/include/cm_qq_bias_mask.hpp
@@ -0,0 +1,64 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+// Speculative-decoding tree mask shared by the CM paged-attention kernels.
+//
+// qq_bias layout: u8 row-major [spec_num, spec_num], indexed as
+// qq_bias[query_spec * spec_num + key_spec]; a zero entry means the pair is masked.
+// The mask applies only to the "new" K range (key_spec >= 0) and to queries that
+// fall inside the spec window (query_spec in [0, spec_num)).
+//
+// This header is intentionally free of tile-geometry macros (REG_N, kv_step, ...)
+// and jit constants so kernels with their own geometry can include it directly.
+
+// Transposed layout: St[k_row][q_col], k_row in [0, N), q_col in [0, M).
+template <int N, int M>
+inline void apply_qq_bias_tree_mask(matrix_ref<float, N, M> St,
+ svmptr_t qq_bias_base,
+ int qq_bias_spec_num,
+ int kv_pos,
+ int q_start,
+ int past_lens) {
+ if (qq_bias_spec_num <= 0) return;
+ const uchar* qq_bias_ptr = reinterpret_cast<const uchar*>(qq_bias_base);
+ #pragma unroll
+ for (int k_row = 0; k_row < N; ++k_row) {
+ const int key_local = kv_pos + k_row;
+ const int key_spec = key_local - past_lens;
+ if (key_spec < 0 || key_spec >= qq_bias_spec_num) continue;
+ #pragma unroll
+ for (int q_col = 0; q_col < M; ++q_col) {
+ const int query_spec = q_start + q_col;
+ if (query_spec < 0 || query_spec >= qq_bias_spec_num) continue;
+ const int qq_off = query_spec * qq_bias_spec_num + key_spec;
+ if (qq_bias_ptr[qq_off] == 0) {
+ St[k_row][q_col] = -3.4e38f;
+ }
+ }
+ }
+}
+
+// Query-major counterpart, for kernels whose S tile is laid out S[q_row][k_col].
+// Builds the merge mask for one query row over K contiguous keys starting at
+// key_local_start; a lane is set when the (query_spec, key_spec) pair is masked out.
+// Lanes whose key falls outside the spec window stay clear, so the caller can merge
+// the result unconditionally. The mask depends only on query_spec, so callers that
+// replicate a query across GQA heads should build it once and reuse it per head.
+template <int K>
+inline vector<unsigned short, K> build_qq_bias_tree_mask_row(const uchar* qq_bias_ptr,
+ int qq_bias_spec_num,
+ int query_spec,
+ int key_local_start,
+ int past_lens) {
+ vector<unsigned short, K> m = 0;
+ if (qq_bias_spec_num <= 0) return m;
+ if (query_spec < 0 || query_spec >= qq_bias_spec_num) return m;
+ const int row_off = query_spec * qq_bias_spec_num;
+ #pragma unroll
+ for (int c = 0; c < K; ++c) {
+ const int key_spec = key_local_start + c - past_lens;
+ if (key_spec < 0 || key_spec >= qq_bias_spec_num) continue;
+ if (qq_bias_ptr[row_off + key_spec] == 0) m[c] = 1;
+ }
+ return m;
+}
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/pa_kv_cache_reorder_ref.cm b/src/plugins/intel_gpu/src/graph/impls/cm/pa_kv_cache_reorder_ref.cm
new file mode 100644
index 00000000000..19eaa68331a
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/pa_kv_cache_reorder_ref.cm
@@ -0,0 +1,398 @@
+/*******************************************************************************
+ * Copyright (c) 2018-2026 Intel Corporation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *******************************************************************************/
+
+#include <cm/cm.h>
+#include <cm/cmtl.h>
+
+#ifndef ATTR
+#define ATTR [[type("svmptr_t")]]
+#define ATTR_BUF [[type("buffer_t")]]
+#endif
+
+// JIT constants:
+// KV_HEADS_NUM
+// K_HEAD_SIZE, V_HEAD_SIZE
+// BLOCK_SIZE (paged attention block size)
+// KV_CACHE_COMPRESSION (0=non, 1=per-token int8, 2=per-channel K + per-token V)
+// SUB_BLOCK_SIZE (per-channel quant sub-block size; only used when ==2)
+//
+// Layout per head (offset relative to (block_id*KV_HEADS_NUM+head_idx) * stride_per_head):
+// mode 0: [BLOCK_SIZE * head_size halves]
+// mode 1: [BLOCK_SIZE * head_size bytes][BLOCK_SIZE halves scale][BLOCK_SIZE halves zp]
+// mode 2 K: [BLOCK_SIZE * head_size bytes][(BLOCK_SIZE/SUB) * head_size halves scale][... zp]
+// mode 2 V: same as mode 1 V
+
+// ---------------- helpers (load/store full head_size vectors) ----------------
+
+template <int N>
+CM_INLINE void load_half_vec(vector_ref<half, N> dst, const half* base [[type("svmptr_t")]], uint offset_bytes) {
+ if constexpr (N == 16 || N == 32 || N == 64 || N == 128) {
+ dst.template format<int>() = cm_ptr_load<int, N / 2>((int*)base, offset_bytes);
+ } else if constexpr (N == 96) {
+ dst.template select<64, 1>(0).template format<int>() = cm_ptr_load<int, 32>((int*)base, offset_bytes);
+ dst.template select<32, 1>(64).template format<int>() = cm_ptr_load<int, 16>((int*)base, offset_bytes + 32 * sizeof(int));
+ } else {
+ #pragma unroll
+ for (int i = 0; i < N / 16; i++) {
+ dst.template select<16, 1>(16 * i).template format<int>() = cm_ptr_load<int, 8>((int*)base, offset_bytes + i * 8 * sizeof(int));
+ }
+ }
+}
+
+template <int N>
+CM_INLINE void store_half_vec(half* base [[type("svmptr_t")]], uint offset_bytes, vector_ref<half, N> src) {
+ if constexpr (N == 16 || N == 32 || N == 64 || N == 128) {
+ cm_ptr_store<int, N / 2>((int*)base, offset_bytes, src.template format<int>());
+ } else if constexpr (N == 96) {
+ cm_ptr_store<int, 32>((int*)base, offset_bytes, src.template select<64, 1>(0).template format<int>());
+ cm_ptr_store<int, 16>((int*)base, offset_bytes + 32 * sizeof(int), src.template select<32, 1>(64).template format<int>());
+ } else {
+ #pragma unroll
+ for (int i = 0; i < N / 16; i++) {
+ cm_ptr_store<int, 8>((int*)base, offset_bytes + i * 8 * sizeof(int), src.template select<16, 1>(16 * i).template format<int>());
+ }
+ }
+}
+
+template <int N>
+CM_INLINE void load_u8_vec(vector_ref<uchar, N> dst, const uchar* base [[type("svmptr_t")]], uint offset_bytes) {
+ if constexpr (N == 16 || N == 32 || N == 64 || N == 128) {
+ dst.template format<int>() = cm_ptr_load<int, N / 4>((int*)base, offset_bytes);
+ } else if constexpr (N == 96) {
+ dst.template select<64, 1>(0).template format<int>() = cm_ptr_load<int, 16>((int*)base, offset_bytes);
+ dst.template select<32, 1>(64).template format<int>() = cm_ptr_load<int, 8>((int*)base, offset_bytes + 16 * sizeof(int));
+ } else {
+ #pragma unroll
+ for (int i = 0; i < N / 16; i++) {
+ dst.template select<16, 1>(16 * i).template format<int>() = cm_ptr_load<int, 4>((int*)base, offset_bytes + i * 4 * sizeof(int));
+ }
+ }
+}
+
+template <int N>
+CM_INLINE void store_u8_vec(uchar* base [[type("svmptr_t")]], uint offset_bytes, vector_ref<uchar, N> src) {
+ if constexpr (N == 32 || N == 64 || N == 128 || N == 256) {
+ cm_ptr_store<int, N / 4>((int*)base, offset_bytes, src.template format<int>());
+ } else if constexpr (N == 96) {
+ cm_ptr_store<int, 16>((int*)base, offset_bytes, src.template select<64, 1>(0).template format<int>());
+ cm_ptr_store<int, 8>((int*)base, offset_bytes + 16 * sizeof(int), src.template select<32, 1>(64).template format<int>());
+ } else {
+ #pragma unroll
+ for (int i = 0; i < N / 16; i++) {
+ cm_ptr_store<int, 4>((int*)base, offset_bytes + i * 4 * sizeof(int), src.template select<16, 1>(16 * i).template format<int>());
+ }
+ }
+}
+
+#if KV_CACHE_COMPRESSION
+// Read one half scalar from cache (used for per-token scale/zp).
+CM_INLINE half read_half_scalar(const uchar* base [[type("svmptr_t")]], uint offset_bytes) {
+ vector<ushort, 1> tmp;
+ cm_svm_block_read(reinterpret_cast<svmptr_t>(base + offset_bytes), tmp);
+ return tmp.format<half>()[0];
+}
+
+CM_INLINE void write_half_scalar(uchar* base [[type("svmptr_t")]], uint offset_bytes, half value) {
+ vector<half, 1> tmp;
+ tmp[0] = value;
+ cm_svm_block_write(reinterpret_cast<svmptr_t>(base + offset_bytes), tmp.format<ushort>());
+}
+#endif
+
+// -------- Compute per-head base byte offset for compressed cache, or per-head element
+// offset for non-compressed cache. The unit (byte vs half) matches the
+// underlying pointer type, so callers can use it directly with load/store.
+//
+// For compressed mode the cache pointer is uint8_t* and the returned offset is a byte
+// offset; for non-compressed mode the pointer is half* and the offset is in halves.
+
+#if KV_CACHE_COMPRESSION == 0
+constexpr uint K_PER_HEAD_ELEMS = K_HEAD_SIZE * BLOCK_SIZE;
+constexpr uint V_PER_HEAD_ELEMS = V_HEAD_SIZE * BLOCK_SIZE;
+constexpr uint K_BLOCK_STRIDE_ELEMS = KV_HEADS_NUM * K_PER_HEAD_ELEMS;
+constexpr uint V_BLOCK_STRIDE_ELEMS = KV_HEADS_NUM * V_PER_HEAD_ELEMS;
+#elif KV_CACHE_COMPRESSION == 1
+constexpr uint K_PER_HEAD_BYTES = (K_HEAD_SIZE + 4) * BLOCK_SIZE;
+constexpr uint V_PER_HEAD_BYTES = (V_HEAD_SIZE + 4) * BLOCK_SIZE;
+constexpr uint K_BLOCK_STRIDE_BYTES = KV_HEADS_NUM * K_PER_HEAD_BYTES;
+constexpr uint V_BLOCK_STRIDE_BYTES = KV_HEADS_NUM * V_PER_HEAD_BYTES;
+constexpr uint K_DATA_BYTES = K_HEAD_SIZE * BLOCK_SIZE;
+constexpr uint V_DATA_BYTES = V_HEAD_SIZE * BLOCK_SIZE;
+#elif KV_CACHE_COMPRESSION == 2
+// Per-channel K: scales/zps live as (BLOCK_SIZE/SUB_BLOCK_SIZE) entries per channel.
+constexpr uint K_PER_HEAD_BYTES = K_HEAD_SIZE * (BLOCK_SIZE + BLOCK_SIZE / SUB_BLOCK_SIZE * 4);
+constexpr uint V_PER_HEAD_BYTES = (V_HEAD_SIZE + 4) * BLOCK_SIZE;
+constexpr uint K_BLOCK_STRIDE_BYTES = KV_HEADS_NUM * K_PER_HEAD_BYTES;
+constexpr uint V_BLOCK_STRIDE_BYTES = KV_HEADS_NUM * V_PER_HEAD_BYTES;
+constexpr uint K_DATA_BYTES = K_HEAD_SIZE * BLOCK_SIZE;
+constexpr uint V_DATA_BYTES = V_HEAD_SIZE * BLOCK_SIZE;
+constexpr uint NUM_SUB_BLOCKS = BLOCK_SIZE / SUB_BLOCK_SIZE;
+#endif
+
+// Per-token V: copy the token's full data row + scalar scale + scalar zp.
+#if KV_CACHE_COMPRESSION
+CM_INLINE void copy_value_slot(uchar* value_cache,
+ uint head_base_src,
+ uint head_base_dst,
+ uint src_slot,
+ uint dst_slot) {
+ // data
+ vector<uchar, V_HEAD_SIZE> data;
+ load_u8_vec<V_HEAD_SIZE>(data, value_cache, head_base_src + src_slot * V_HEAD_SIZE);
+ store_u8_vec<V_HEAD_SIZE>(value_cache, head_base_dst + dst_slot * V_HEAD_SIZE, data);
+
+ // per-token scale + zp (each: half)
+ const uint scale_src = head_base_src + V_DATA_BYTES + src_slot * (uint)sizeof(half);
+ const uint scale_dst = head_base_dst + V_DATA_BYTES + dst_slot * (uint)sizeof(half);
+ const uint zp_src = head_base_src + V_DATA_BYTES + (BLOCK_SIZE + src_slot) * (uint)sizeof(half);
+ const uint zp_dst = head_base_dst + V_DATA_BYTES + (BLOCK_SIZE + dst_slot) * (uint)sizeof(half);
+
+ write_half_scalar(value_cache, scale_dst, read_half_scalar(value_cache, scale_src));
+ write_half_scalar(value_cache, zp_dst, read_half_scalar(value_cache, zp_src));
+}
+#endif
+
+#if KV_CACHE_COMPRESSION == 2
+// Per-channel K: re-quantize the dst sub-block after replacing the dst slot with the
+// dequantized src value. valid_rows bounds the sub-block to the rows pa_kv_cache_update
+// actually wrote; the tail of a sequence's last sub-block is never written (pad_lens in
+// pa_kv_cache_update_ref.cm). Always >= 1 since dst_slot itself is valid.
+CM_INLINE void requantize_dst_subblock(uchar* key_cache,
+ uint head_base_src,
+ uint head_base_dst,
+ uint src_slot,
+ uint dst_slot,
+ uint valid_rows) {
+ constexpr uint scales_off_base = K_DATA_BYTES;
+ constexpr uint zps_off_base = K_DATA_BYTES + NUM_SUB_BLOCKS * K_HEAD_SIZE * (uint)sizeof(half);
+
+ const uint src_sub = src_slot / SUB_BLOCK_SIZE;
+ const uint dst_sub = dst_slot / SUB_BLOCK_SIZE;
+ const uint dst_sub_first_slot = dst_sub * SUB_BLOCK_SIZE;
+
+ // Fast path: src and dst are the same sub-block of the same physical block
+ if (head_base_src == head_base_dst && src_sub == dst_sub) {
+ vector<uchar, K_HEAD_SIZE> q_row;
+ load_u8_vec<K_HEAD_SIZE>(q_row, key_cache, head_base_src + src_slot * K_HEAD_SIZE);
+ store_u8_vec<K_HEAD_SIZE>(key_cache, head_base_dst + dst_slot * K_HEAD_SIZE, q_row);
+ return;
+ }
+
+ // Load src and dst sub_block scales/zps along the channel dimension.
+ vector<half, K_HEAD_SIZE> scale_src;
+ vector<half, K_HEAD_SIZE> zp_src;
+ vector<half, K_HEAD_SIZE> scale_dst;
+ vector<half, K_HEAD_SIZE> zp_dst;
+ load_half_vec<K_HEAD_SIZE>(scale_src, (const half*)key_cache, head_base_src + scales_off_base + src_sub * K_HEAD_SIZE * (uint)sizeof(half));
+ load_half_vec<K_HEAD_SIZE>(zp_src, (const half*)key_cache, head_base_src + zps_off_base + src_sub * K_HEAD_SIZE * (uint)sizeof(half));
+ load_half_vec<K_HEAD_SIZE>(scale_dst, (const half*)key_cache, head_base_dst + scales_off_base + dst_sub * K_HEAD_SIZE * (uint)sizeof(half));
+ load_half_vec<K_HEAD_SIZE>(zp_dst, (const half*)key_cache, head_base_dst + zps_off_base + dst_sub * K_HEAD_SIZE * (uint)sizeof(half));
+
+ // Dequant src slot -> val_src (per-channel).
+ vector<uchar, K_HEAD_SIZE> q_src_row;
+ load_u8_vec<K_HEAD_SIZE>(q_src_row, key_cache, head_base_src + src_slot * K_HEAD_SIZE);
+ vector<half, K_HEAD_SIZE> q_src_row_h = q_src_row;
+ vector<half, K_HEAD_SIZE> val_src = (q_src_row_h - zp_src) * scale_src;
+
+ // Dequant the valid rows of the dst sub-block, replacing the dst slot row.
+ matrix<half, SUB_BLOCK_SIZE, K_HEAD_SIZE> dequant_rows;
+ #pragma unroll
+ for (int i = 0; i < SUB_BLOCK_SIZE; ++i) {
+ if ((uint)i >= valid_rows) {
+ continue;
+ }
+ const uint slot = dst_sub_first_slot + i;
+ if (slot == dst_slot) {
+ dequant_rows.row(i) = val_src;
+ } else {
+ vector<uchar, K_HEAD_SIZE> q_row;
+ load_u8_vec<K_HEAD_SIZE>(q_row, key_cache, head_base_dst + slot * K_HEAD_SIZE);
+ vector<half, K_HEAD_SIZE> q_row_h = q_row;
+ dequant_rows.row(i) = (q_row_h - zp_dst) * scale_dst;
+ }
+ }
+
+ // Recompute per-channel min/max across the valid rows only.
+ vector<half, K_HEAD_SIZE> max_vals = dequant_rows.row(0);
+ vector<half, K_HEAD_SIZE> min_vals = dequant_rows.row(0);
+ #pragma unroll
+ for (int i = 1; i < SUB_BLOCK_SIZE; ++i) {
+ if ((uint)i >= valid_rows) {
+ continue;
+ }
+ max_vals = cm_max<half>(max_vals, dequant_rows.row(i));
+ min_vals = cm_min<half>(min_vals, dequant_rows.row(i));
+ }
+
+ // Per-channel scale/zp computation mirroring CM update kernel's small-range guard.
+ vector<float, K_HEAD_SIZE> qrange = max_vals - min_vals;
+ vector<ushort, K_HEAD_SIZE> mask = (qrange == (half)0.0f);
+ vector<float, K_HEAD_SIZE> min_range = cm_abs<float>(max_vals) * 0.1f;
+ vector<float, K_HEAD_SIZE> adjust_val = cm_max<float>(min_range, 1.0f);
+ qrange.merge(qrange + adjust_val, qrange <= min_range);
+
+#ifdef CM_HAS_IEEE_DIV_SQRT
+ vector<float, K_HEAD_SIZE> scale_vals = cm_div_ieee(255.0f, qrange);
+#else
+ vector<float, K_HEAD_SIZE> scale_vals = 255.0f / qrange;
+#endif
+ scale_vals.merge(1.0f, mask);
+ vector<half, K_HEAD_SIZE> zp_vals = cm_mul<half>((0.0f - min_vals), scale_vals);
+
+ #pragma unroll
+ for (int i = 0; i < SUB_BLOCK_SIZE; ++i) {
+ if ((uint)i >= valid_rows) {
+ continue;
+ }
+ vector<half, K_HEAD_SIZE> q = cm_mul<half>(dequant_rows.row(i), scale_vals) + zp_vals;
+ q = cm_min<half>(cm_max<half>(q, (half)0.0f), (half)255.0f);
+ vector<uchar, K_HEAD_SIZE> q_u8 = cm_rnde<uchar, K_HEAD_SIZE>(q);
+ store_u8_vec<K_HEAD_SIZE>(key_cache, head_base_dst + (dst_sub_first_slot + i) * K_HEAD_SIZE, q_u8);
+ }
+
+ // Store new scale/zp for the dst sub_block.
+#ifdef CM_HAS_IEEE_DIV_SQRT
+ vector<half, K_HEAD_SIZE> scale_out = cm_div_ieee(1.0f, scale_vals);
+#else
+ vector<half, K_HEAD_SIZE> scale_out = 1.0f / scale_vals;
+#endif
+ store_half_vec<K_HEAD_SIZE>((half*)key_cache, head_base_dst + scales_off_base + dst_sub * K_HEAD_SIZE * (uint)sizeof(half), scale_out);
+ store_half_vec<K_HEAD_SIZE>((half*)key_cache, head_base_dst + zps_off_base + dst_sub * K_HEAD_SIZE * (uint)sizeof(half), zp_vals);
+}
+#endif
+
+extern "C" _GENX_MAIN_ void KERNEL_NAME(
+#if KV_CACHE_COMPRESSION
+ uchar* key_cache [[type("svmptr_t")]],
+ uchar* value_cache [[type("svmptr_t")]],
+#else
+ half* key_cache [[type("svmptr_t")]],
+ half* value_cache [[type("svmptr_t")]],
+#endif
+ const int32_t* block_indices [[type("svmptr_t")]],
+ const int32_t* block_indices_begins [[type("svmptr_t")]],
+ const int32_t* block_update_indices [[type("svmptr_t")]],
+ const int32_t* block_update_indices_begins [[type("svmptr_t")]]) {
+ // Dispatch: GWS = (sequences_num, kv_heads_num, 1), LWS = (1, 1, 1).
+ // Per (seq, head) thread sequentially applies all (src, dst) slot pairs for that
+ // sequence. Sequential order is required because src and dst ranges may overlap.
+
+ const uint seq_idx = cm_group_id(0);
+ const uint head_idx = cm_group_id(1);
+
+ const uint block_indices_base = (uint)block_indices_begins[seq_idx];
+ const uint blocks_in_seq = (uint)block_indices_begins[seq_idx + 1] - block_indices_base;
+ const uint pos_begin = (uint)block_update_indices_begins[seq_idx];
+ const uint pos_end = (uint)block_update_indices_begins[seq_idx + 1];
+
+#if KV_CACHE_COMPRESSION == 2
+ // Upper bound on the sequence positions this reorder touches, used to keep the per-channel
+ // requantization away from rows pa_kv_cache_update never wrote.
+ uint touched_len = 0;
+ for (uint pos = pos_begin; pos < pos_end; ++pos) {
+ const int s = block_update_indices[pos * 2 + 0];
+ const int d = block_update_indices[pos * 2 + 1];
+ if (s < 0 || d < 0)
+ continue;
+ if ((uint)s / BLOCK_SIZE >= blocks_in_seq || (uint)d / BLOCK_SIZE >= blocks_in_seq)
+ continue;
+ const uint hi = (uint)(s > d ? s : d) + 1;
+ if (hi > touched_len)
+ touched_len = hi;
+ }
+#endif
+
+ for (uint pos = pos_begin; pos < pos_end; ++pos) {
+ const int src_id_s = block_update_indices[pos * 2 + 0];
+ const int dst_id_s = block_update_indices[pos * 2 + 1];
+ if (src_id_s < 0 || dst_id_s < 0)
+ continue;
+
+ const uint src_id = (uint)src_id_s;
+ const uint dst_id = (uint)dst_id_s;
+ const uint src_block_in_seq = src_id / BLOCK_SIZE;
+ const uint src_slot = src_id - src_block_in_seq * BLOCK_SIZE;
+ const uint dst_block_in_seq = dst_id / BLOCK_SIZE;
+ const uint dst_slot = dst_id - dst_block_in_seq * BLOCK_SIZE;
+ if (src_block_in_seq >= blocks_in_seq || dst_block_in_seq >= blocks_in_seq)
+ continue;
+
+ const uint src_block_id = (uint)block_indices[block_indices_base + src_block_in_seq];
+ const uint dst_block_id = (uint)block_indices[block_indices_base + dst_block_in_seq];
+
+#if KV_CACHE_COMPRESSION == 0
+ // ---- KEY (mode 0): half token-major copy.
+ {
+ const uint src_off = (src_block_id * KV_HEADS_NUM + head_idx) * K_PER_HEAD_ELEMS + src_slot * K_HEAD_SIZE;
+ const uint dst_off = (dst_block_id * KV_HEADS_NUM + head_idx) * K_PER_HEAD_ELEMS + dst_slot * K_HEAD_SIZE;
+ vector<half, K_HEAD_SIZE> tmp;
+ load_half_vec<K_HEAD_SIZE>(tmp, key_cache, src_off * (uint)sizeof(half));
+ store_half_vec<K_HEAD_SIZE>(key_cache, dst_off * (uint)sizeof(half), tmp);
+ }
+ // ---- VALUE (mode 0): half token-major copy.
+ {
+ const uint src_off = (src_block_id * KV_HEADS_NUM + head_idx) * V_PER_HEAD_ELEMS + src_slot * V_HEAD_SIZE;
+ const uint dst_off = (dst_block_id * KV_HEADS_NUM + head_idx) * V_PER_HEAD_ELEMS + dst_slot * V_HEAD_SIZE;
+ vector<half, V_HEAD_SIZE> tmp;
+ load_half_vec<V_HEAD_SIZE>(tmp, value_cache, src_off * (uint)sizeof(half));
+ store_half_vec<V_HEAD_SIZE>(value_cache, dst_off * (uint)sizeof(half), tmp);
+ }
+#elif KV_CACHE_COMPRESSION == 1
+ // ---- KEY (per-token int8): copy data row + per-token scale + per-token zp.
+ {
+ const uint head_base_src = src_block_id * K_BLOCK_STRIDE_BYTES + head_idx * K_PER_HEAD_BYTES;
+ const uint head_base_dst = dst_block_id * K_BLOCK_STRIDE_BYTES + head_idx * K_PER_HEAD_BYTES;
+
+ vector<uchar, K_HEAD_SIZE> data;
+ load_u8_vec<K_HEAD_SIZE>(data, key_cache, head_base_src + src_slot * K_HEAD_SIZE);
+ store_u8_vec<K_HEAD_SIZE>(key_cache, head_base_dst + dst_slot * K_HEAD_SIZE, data);
+
+ const uint scale_src = head_base_src + K_DATA_BYTES + src_slot * (uint)sizeof(half);
+ const uint scale_dst = head_base_dst + K_DATA_BYTES + dst_slot * (uint)sizeof(half);
+ const uint zp_src = head_base_src + K_DATA_BYTES + (BLOCK_SIZE + src_slot) * (uint)sizeof(half);
+ const uint zp_dst = head_base_dst + K_DATA_BYTES + (BLOCK_SIZE + dst_slot) * (uint)sizeof(half);
+
+ write_half_scalar(key_cache, scale_dst, read_half_scalar(key_cache, scale_src));
+ write_half_scalar(key_cache, zp_dst, read_half_scalar(key_cache, zp_src));
+ }
+ // ---- VALUE (per-token int8): same shape as key for V.
+ {
+ const uint head_base_src = src_block_id * V_BLOCK_STRIDE_BYTES + head_idx * V_PER_HEAD_BYTES;
+ const uint head_base_dst = dst_block_id * V_BLOCK_STRIDE_BYTES + head_idx * V_PER_HEAD_BYTES;
+ copy_value_slot(value_cache, head_base_src, head_base_dst, src_slot, dst_slot);
+ }
+#elif KV_CACHE_COMPRESSION == 2
+ // ---- KEY (per-channel int8): dequantize src slot, requantize the dst sub-block.
+ {
+ const uint head_base_src = src_block_id * K_BLOCK_STRIDE_BYTES + head_idx * K_PER_HEAD_BYTES;
+ const uint head_base_dst = dst_block_id * K_BLOCK_STRIDE_BYTES + head_idx * K_PER_HEAD_BYTES;
+ // Sequence position of the dst sub-block's first row: dst_id is the position of
+ // dst_slot, so drop its offset inside the sub-block.
+ const uint dst_sub_first_pos = dst_id - dst_slot % SUB_BLOCK_SIZE;
+ uint valid_rows = touched_len > dst_sub_first_pos ? touched_len - dst_sub_first_pos : 0;
+ if (valid_rows > SUB_BLOCK_SIZE)
+ valid_rows = SUB_BLOCK_SIZE;
+ requantize_dst_subblock(key_cache, head_base_src, head_base_dst, src_slot, dst_slot, valid_rows);
+ }
+ // ---- VALUE (per-token int8): identical to mode 1.
+ {
+ const uint head_base_src = src_block_id * V_BLOCK_STRIDE_BYTES + head_idx * V_PER_HEAD_BYTES;
+ const uint head_base_dst = dst_block_id * V_BLOCK_STRIDE_BYTES + head_idx * V_PER_HEAD_BYTES;
+ copy_value_slot(value_cache, head_base_src, head_base_dst, src_slot, dst_slot);
+ }
+#endif
+ }
+}
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/pa_kv_reorder.cpp b/src/plugins/intel_gpu/src/graph/impls/cm/pa_kv_reorder.cpp
new file mode 100644
index 00000000000..f8958d78cf0
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/pa_kv_reorder.cpp
@@ -0,0 +1,171 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "pa_kv_reorder.hpp"
+
+#include <memory>
+
+#include "common_utils/jitter.hpp"
+#include "intel_gpu/graph/kernel_impl_params.hpp"
+#include "intel_gpu/primitives/pa_kv_reorder.hpp"
+#include "intel_gpu/primitives/paged_attention.hpp"
+#include "paged_attention_gen.hpp"
+#include "primitive_cm_base.hpp"
+#include "utils/kernel_generator.hpp"
+
+namespace ov::intel_gpu::cm {
+
+using namespace cldnn;
+
+namespace {
+
+constexpr size_t reorder_sub_block_size = 16;
+
+struct KVCacheGeometry {
+ size_t block_size = 0;
+ size_t k_head_size = 0;
+ size_t v_head_size = 0;
+};
+
+KVCacheGeometry resolve_geometry_from_desc(const std::shared_ptr<const pa_kv_reorder>& desc) {
+ OPENVINO_ASSERT(desc->kv_heads_num > 0, "[GPU][CM] pa_kv_reorder expects positive kv_heads_num");
+ OPENVINO_ASSERT(desc->adjusted_k_head_size > 0 && desc->adjusted_v_head_size > 0, "[GPU][CM] pa_kv_reorder expects positive adjusted head sizes");
+ OPENVINO_ASSERT(desc->adjusted_paged_attention_block_size > 0, "[GPU][CM] pa_kv_reorder expects positive block size");
+
+ const bool is_kv_compressed = desc->is_kv_compressed;
+ const bool is_key_by_channel = desc->is_key_by_channel;
+ const size_t scales_zp = desc->scales_zp_size;
+
+ KVCacheGeometry g;
+
+ // adjusted_paged_attention_block_size already accounts for the per-channel scale/zp tail
+ // in mode 2 ("block_size + scales_zp_size"), so subtract scales_zp_size to recover the
+ // logical block_size. For modes 0/1 the adjusted value equals the logical value.
+ if (is_kv_compressed && is_key_by_channel) {
+ g.block_size = desc->adjusted_paged_attention_block_size - scales_zp;
+ } else {
+ g.block_size = desc->adjusted_paged_attention_block_size;
+ }
+
+ // adjusted_k_head_size = head_size + scales_zp_size for per-token int8 K (mode 1);
+ // for modes 0 and 2 it equals the logical head_size.
+ if (is_kv_compressed && !is_key_by_channel) {
+ OPENVINO_ASSERT(desc->adjusted_k_head_size > scales_zp,
+ "[GPU][CM] adjusted_k_head_size (",
+ desc->adjusted_k_head_size,
+ ") must exceed scales_zp_size (",
+ scales_zp,
+ ")");
+ g.k_head_size = desc->adjusted_k_head_size - scales_zp;
+ } else {
+ g.k_head_size = desc->adjusted_k_head_size;
+ }
+
+ // V is per-token in modes 1 and 2; adjusted_v_head_size = head_size + scales_zp_size.
+ if (is_kv_compressed) {
+ OPENVINO_ASSERT(desc->adjusted_v_head_size > scales_zp,
+ "[GPU][CM] adjusted_v_head_size (",
+ desc->adjusted_v_head_size,
+ ") must exceed scales_zp_size (",
+ scales_zp,
+ ")");
+ g.v_head_size = desc->adjusted_v_head_size - scales_zp;
+ } else {
+ g.v_head_size = desc->adjusted_v_head_size;
+ }
+
+ return g;
+}
+
+class PaKVReorderGenerator : public KernelGenerator {
+public:
+ PaKVReorderGenerator() : KernelGenerator("pa_kv_cache_reorder_ref", "_cm") {}
+
+ [[nodiscard]] std::string get_build_options(const RuntimeParams& params) const override {
+ return KernelGenerator::get_build_options(params) + get_pa_build_options();
+ }
+
+ [[nodiscard]] JitConstants get_jit_constants(const kernel_impl_params& params) const override {
+ auto jit = KernelGenerator::get_jit_constants(params);
+ jit.add(make_jit_constant("KERNEL_NAME", get_entry_point(params)));
+
+ const auto desc = params.typed_desc<pa_kv_reorder>();
+ OPENVINO_ASSERT(desc->kv_heads_num > 0, "[GPU][CM] pa_kv_reorder expects positive kv_heads_num in descriptor");
+
+ jit.make("KV_HEADS_NUM", desc->kv_heads_num);
+
+ const bool is_kv_compressed = desc->is_kv_compressed;
+ const bool is_key_by_channel = desc->is_key_by_channel;
+ const int compression_mode = !is_kv_compressed ? 0 : (is_key_by_channel ? 2 : 1);
+ jit.make("KV_CACHE_COMPRESSION", compression_mode);
+ jit.make("SUB_BLOCK_SIZE", reorder_sub_block_size);
+
+ const auto geometry = resolve_geometry_from_desc(desc);
+ OPENVINO_ASSERT(geometry.block_size > 0, "[GPU][CM] resolved block_size must be positive");
+
+ jit.make("BLOCK_SIZE", geometry.block_size);
+ jit.make("K_HEAD_SIZE", geometry.k_head_size);
+ jit.make("V_HEAD_SIZE", geometry.v_head_size);
+
+ return jit;
+ }
+
+ [[nodiscard]] Arguments get_arguments_desc(const kernel_impl_params& /*params*/) const override {
+ Arguments args;
+ args.push_back({ArgumentDescriptor::Types::INPUT, pa_kv_reorder::PaKVReorderInputIdx::KEY_CACHE});
+ args.push_back({ArgumentDescriptor::Types::INPUT, pa_kv_reorder::PaKVReorderInputIdx::VALUE_CACHE});
+ args.push_back({ArgumentDescriptor::Types::INPUT, pa_kv_reorder::PaKVReorderInputIdx::BLOCK_INDICES});
+ args.push_back({ArgumentDescriptor::Types::INPUT, pa_kv_reorder::PaKVReorderInputIdx::BLOCK_INDICES_BEGINS});
+ args.push_back({ArgumentDescriptor::Types::INPUT, pa_kv_reorder::PaKVReorderInputIdx::BLOCK_UPDATE_INDICES});
+ args.push_back({ArgumentDescriptor::Types::INPUT, pa_kv_reorder::PaKVReorderInputIdx::BLOCK_UPDATE_INDICES_BEGINS});
+ return args;
+ }
+
+ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {
+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* /*rt_params*/) {
+ OPENVINO_ASSERT(!params.is_dynamic());
+ auto& wgs = kd.params.workGroups;
+
+ const auto desc = params.typed_desc<pa_kv_reorder>();
+ OPENVINO_ASSERT(desc->kv_heads_num > 0, "[GPU][CM] pa_kv_reorder expects positive kv_heads_num in descriptor");
+
+ const auto& begins_layout = params.input_layouts[pa_kv_reorder::PaKVReorderInputIdx::BLOCK_UPDATE_INDICES_BEGINS];
+ const auto begins_len = static_cast<size_t>(begins_layout.get_partial_shape()[0].get_length());
+ OPENVINO_ASSERT(begins_len >= 1, "[GPU][CM] BLOCK_UPDATE_INDICES_BEGINS must have at least 1 element");
+ const size_t sequences_number = begins_len - 1;
+
+ // One thread per (subsequence, kv_head); slot pairs are processed sequentially
+ // in-kernel because src/dst ranges may overlap.
+ wgs.global = {std::max<size_t>(1, sequences_number), desc->kv_heads_num, 1};
+ wgs.local = {1, 1, 1};
+ }};
+ }
+};
+
+class PaKVReorderImpl : public PrimitiveImplCM {
+public:
+ DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::cm::PaKVReorderImpl)
+
+ Stage::Ptr kv_reorder = make_stage<PaKVReorderGenerator>();
+
+ PaKVReorderImpl() : PrimitiveImplCM(PaKVReorderImplementationManager::get_type_info_static()) {}
+ PaKVReorderImpl(const program_node& /*node*/, const RuntimeParams& params) : PaKVReorderImpl() {
+ add_stage(kv_reorder, params);
+ }
+
+ [[nodiscard]] std::unique_ptr<primitive_impl> clone() const override {
+ return make_deep_copy<PaKVReorderImpl>(this);
+ }
+};
+
+} // namespace
+
+std::unique_ptr<primitive_impl> PaKVReorderImplementationManager::create_impl(const program_node& node, const kernel_impl_params& params) const {
+ OPENVINO_ASSERT(node.is_type<pa_kv_reorder>());
+ return std::make_unique<PaKVReorderImpl>(node, params);
+}
+
+} // namespace ov::intel_gpu::cm
+
+BIND_BINARY_BUFFER_WITH_TYPE(ov::intel_gpu::cm::PaKVReorderImpl)
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/pa_kv_reorder.hpp b/src/plugins/intel_gpu/src/graph/impls/cm/pa_kv_reorder.hpp
new file mode 100644
index 00000000000..4ad6871e685
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/pa_kv_reorder.hpp
@@ -0,0 +1,37 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <memory>
+#include <utility>
+
+#include "intel_gpu/primitives/pa_kv_reorder.hpp"
+#include "program_node.h"
+#include "registry/implementation_manager.hpp"
+
+namespace ov::intel_gpu::cm {
+
+struct PaKVReorderImplementationManager : public cldnn::ImplementationManager {
+ OV_GPU_PRIMITIVE_IMPL("cm::pa_kv_reorder")
+ explicit PaKVReorderImplementationManager(cldnn::shape_types shape_type, cldnn::ValidateFunc vf = nullptr)
+ : ImplementationManager(cldnn::impl_types::cm, shape_type, std::move(vf)) {}
+
+ [[nodiscard]] std::unique_ptr<cldnn::primitive_impl> create_impl(const cldnn::program_node& node, const cldnn::kernel_impl_params& params) const override;
+
+ [[nodiscard]] bool validate_impl(const cldnn::program_node& node) const override {
+ if (node.has_fused_primitives()) {
+ return false;
+ }
+ const auto desc = node.as<cldnn::pa_kv_reorder>().get_primitive();
+ // CM reorder kernel handles only fp16 / int8 caches (matches CM PA validate_impl).
+ if (!(desc->cache_dt == cldnn::data_types::f16 || desc->cache_dt == cldnn::data_types::i8 || desc->cache_dt == cldnn::data_types::u8)) {
+ return false;
+ }
+
+ return desc->has_xattention;
+ }
+};
+
+} // namespace ov::intel_gpu::cm
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/pa_multi_token.cm b/src/plugins/intel_gpu/src/graph/impls/cm/pa_multi_token.cm
index dbefadb13bd..58ff97cea74 100644
--- a/src/plugins/intel_gpu/src/graph/impls/cm/pa_multi_token.cm
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/pa_multi_token.cm
@@ -103,6 +103,12 @@ extern "C" _GENX_MAIN_ void KERNEL_NAME(
, bool* sparse_block_mask [[type("svmptr_t")]],
bool* sparse_block_mask_wg [[type("svmptr_t")]],
int32_t* xattn_subseq_meta [[type("svmptr_t")]]
+#endif
+#if HAS_QQ_BIAS
+ // qq_bias is stored as element::u8 (0 = masked, !=0 = visible). One byte per
+ // (query_spec, key_spec) pair, row-major within each subsequence.
+ , uchar* qq_bias [[type("svmptr_t")]],
+ int32_t* qq_bias_begins [[type("svmptr_t")]]
#endif
) {
constexpr int is_causal = CMFLA_IS_CAUSAL;
@@ -297,6 +303,22 @@ extern "C" _GENX_MAIN_ void KERNEL_NAME(
}
#endif
+#if HAS_QQ_BIAS
+ // Per-subsequence qq_bias slice. qq_bias_begins[i] is the cumulative element count
+ // (each element a half), qq_bias_num_subseq is row-major flatten of [spec_num,spec_num].
+ int qq_bias_num_subseq = qq_bias_begins[subsequence_id + 1] - qq_bias_begins[subsequence_id];
+ int qq_bias_off_subseq = qq_bias_begins[subsequence_id];
+ // spec_num = sqrt(qq_bias_num_subseq); use integer sqrt because qq_bias_num is always
+ // a perfect square spec_num*spec_num.
+ int qq_bias_spec_num = 0;
+ {
+ int s = 0;
+ while ((s + 1) * (s + 1) <= qq_bias_num_subseq) ++s;
+ qq_bias_spec_num = s;
+ }
+ uchar* qq_bias_subseq_ptr = qq_bias + qq_bias_off_subseq;
+#endif
+
#if KV_CACHE_COMPRESSION
#if KV_CACHE_COMPRESSION == 1
uint k_offset = hkv * (head_size + 4) * pa_block_sz;
@@ -335,6 +357,10 @@ extern "C" _GENX_MAIN_ void KERNEL_NAME(
#if SPARSE_BLOCK_SIZE > 1
reinterpret_cast<svmptr_t>(block_mask_base),
reinterpret_cast<svmptr_t>(wg_block_mask_base),
+#endif
+#if HAS_QQ_BIAS
+ reinterpret_cast<svmptr_t>(qq_bias_subseq_ptr),
+ qq_bias_spec_num,
#endif
reinterpret_cast<svmptr_t>(output + q_offset),
past_q_lens,
@@ -369,6 +395,10 @@ extern "C" _GENX_MAIN_ void KERNEL_NAME(
#if SPARSE_BLOCK_SIZE > 1
reinterpret_cast<svmptr_t>(block_mask_base),
reinterpret_cast<svmptr_t>(wg_block_mask_base),
+#endif
+#if HAS_QQ_BIAS
+ reinterpret_cast<svmptr_t>(qq_bias_subseq_ptr),
+ qq_bias_spec_num,
#endif
reinterpret_cast<svmptr_t>(output + q_offset),
past_q_lens,
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/pa_small_q.cm b/src/plugins/intel_gpu/src/graph/impls/cm/pa_small_q.cm
new file mode 100644
index 00000000000..4c4cada2a04
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/pa_small_q.cm
@@ -0,0 +1,903 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "cm_qq_bias_mask.hpp"
+
+namespace KERNEL_NAME {
+
+// TILE_Q optimisation: each SG packs TILE_Q q-tokens of the same subsequence
+// so K/V loads are amortised across the spec window and DPAS RepeatCount stays
+// saturated at Q_head_chunk_size * TILE_Q (≤ 8). Mapping is host-packed as i32
+// triples (orig_seq_idx, q_start_in_subseq, valid_count); valid_count is in the
+// range [1, TILE_Q] and equals TILE_Q for full tiles. Tail tiles (valid_count <
+// TILE_Q) write neutral output (lse = -inf) for the dummy rows so finalize can
+// safely reduce a fixed-size partition buffer.
+//
+// Layout invariants:
+// selected_q_mapping : i32 triples, length = 3 * tile_count
+// output : f32 [tile_count * TILE_Q, head, partition, head_size]
+// lse : f32 [tile_count * TILE_Q, head, partition]
+// Causal: row t in a tile sees past_lens + q_start + t + 1 keys.
+
+#if XE_ARCH==1
+#define REG_N 8
+#define USE_LSC_BLOCK_2D_DESC 0
+#else
+#define REG_N 16
+#define USE_LSC_BLOCK_2D_DESC 1
+#endif
+
+#define SystolicDepth 8
+#define RepeatCount 1
+#define VNNI_WIDTH 2
+#define REG_K (SystolicDepth * VNNI_WIDTH)
+#define REG_M RepeatCount
+#define KV_PARTITION_STEP_NUM (KV_PARTITION_SIZE / KV_STEP)
+
+#define Q_ROWS (Q_head_chunk_size * TILE_Q)
+
+// Online softmax tile configuration
+// Each online tile processes ONLINE_TILE_STEPS * KV_STEP columns of the partition.
+// Overridable via JIT: -DONLINE_TILE_STEPS=N. When N == KV_PARTITION_STEP_NUM,
+// the online loop degenerates to a single iteration ("disable online softmax").
+#ifndef ONLINE_TILE_STEPS
+#define ONLINE_TILE_STEPS 8
+#endif
+#define ONLINE_TILE_SIZE (ONLINE_TILE_STEPS * KV_STEP)
+#define NUM_ONLINE_TILES (KV_PARTITION_STEP_NUM / ONLINE_TILE_STEPS)
+
+#if KV_CACHE_COMPRESSION
+ #if KV_CACHE_COMPRESSION == 2
+ #define GROUPS_PER_BLOCK (KV_BLOCK_SIZE / SUB_BLOCK_SIZE)
+ #define K_SCALE_ZP_SIZE (4 * GROUPS_PER_BLOCK)
+ #define V_SCALE_ZP_SIZE 4
+ #elif KV_CACHE_COMPRESSION == 1
+ #define K_SCALE_ZP_SIZE 4
+ #define V_SCALE_ZP_SIZE 4
+ #endif
+ #define KV_ELEMENT_TYPE uint8_t
+#else
+ #define V_SCALE_ZP_SIZE 0
+ #define KV_ELEMENT_TYPE half
+#endif
+
+template <typename T1, typename T2>
+CM_INLINE void Transpose_8x8(matrix_ref<T1, 8, 8> in, matrix_ref<T2, 8, 8> out) {
+ matrix<T2, 8, 8> temp;
+ #pragma unroll
+ for (int i = 0; i < 4; ++i) {
+ temp.row(i) = in.template select<2, 1, 4, 2>(i * 2, 0);
+ temp.row(i + 4) = in.template select<2, 1, 4, 2>(i * 2, 1);
+ }
+
+ #pragma unroll
+ for (int i = 0; i < 4; ++i) {
+ out.row(i * 2) = temp.template select<4, 1, 2, 4>(0, i);
+ out.row(i * 2 + 1) = temp.template select<4, 1, 2, 4>(4, i);
+ }
+}
+
+// selected_q_mapping is packed as i32 triples:
+// [orig_seq_idx_0, q_start_0, valid_count_0,
+// orig_seq_idx_1, q_start_1, valid_count_1, ...]
+// Length = 3 * tile_count. cm_global_id(0) indexes the tile list directly.
+extern "C" _GENX_MAIN_ void KERNEL_NAME(
+ half* query [[type("svmptr_t")]],
+ KV_ELEMENT_TYPE* key [[type("svmptr_t")]],
+ KV_ELEMENT_TYPE* value [[type("svmptr_t")]],
+ int* past_lens [[type("svmptr_t")]],
+ int* block_indices [[type("svmptr_t")]],
+ int* block_indices_begins [[type("svmptr_t")]],
+ int* subsequence_begins [[type("svmptr_t")]],
+#if HAS_QQ_BIAS
+ // qq_bias is stored as u8 row-major [spec_num, spec_num], 0 = masked.
+ uchar* qq_bias [[type("svmptr_t")]],
+ int32_t* qq_bias_begins [[type("svmptr_t")]],
+#endif
+ int* selected_q_mapping [[type("svmptr_t")]],
+ float* output [[type("svmptr_t")]],
+ float* lse [[type("svmptr_t")]],
+ int q_len_unused,
+ int selected_token_count
+ ) {
+ // tile_idx indexes the host-packed (orig_seq, q_start, valid_count) triple list.
+ const uint tile_idx = cm_global_id(0);
+
+ if (tile_idx >= (uint)selected_token_count) {
+ return;
+ }
+ const uint orig_seq_idx = (uint)selected_q_mapping[tile_idx * 3 + 0];
+ const uint q_start = (uint)selected_q_mapping[tile_idx * 3 + 1];
+ const uint valid_count = (uint)selected_q_mapping[tile_idx * 3 + 2];
+
+ const uint kv_head_num_idx = cm_global_id(1) / Q_head_chunks_per_kv_head;
+ const uint head_num_idx = cm_global_id(1) * Q_head_chunk_size;
+ const uint wg_thread_id = cm_global_id(2);
+ const uint kv_partition_num = cm_group_count(2);
+ const uint kv_partition_idx = cm_group_id(2);
+
+ const int subseq_q_begin_i = subsequence_begins[orig_seq_idx];
+ const int subseq_q_end_i = subsequence_begins[orig_seq_idx + 1];
+ if (subseq_q_end_i <= subseq_q_begin_i) {
+ return;
+ }
+
+ const uint subseq_q_begin = (uint)subseq_q_begin_i;
+
+ // Causal cap: row t sees past + q_start + t + 1 keys. The whole tile uses the
+ // largest of these caps to size the partition iteration; per-row masking
+ // re-applies the tighter bound on rS columns.
+ const uint past_q_lens = (uint)past_lens[orig_seq_idx];
+ const uint kv_len_max = past_q_lens + q_start + valid_count; // tile-wide upper bound
+ const uint seq_kv_partition_num = (kv_len_max + KV_PARTITION_SIZE - 1) / KV_PARTITION_SIZE;
+
+#if HAS_QQ_BIAS
+ // Per-subsequence qq_bias slice: row-major [spec_num, spec_num] over speculative tokens.
+ const int qq_bias_num_subseq = qq_bias_begins[orig_seq_idx + 1] - qq_bias_begins[orig_seq_idx];
+ const int qq_bias_off_subseq = qq_bias_begins[orig_seq_idx];
+ int qq_bias_spec_num = 0;
+ {
+ int s = 0;
+ while ((s + 1) * (s + 1) <= qq_bias_num_subseq) ++s;
+ qq_bias_spec_num = s;
+ }
+ uchar* qq_bias_subseq_ptr = qq_bias + qq_bias_off_subseq;
+#endif
+
+ const uint block_begin = block_indices_begins[orig_seq_idx];
+ const uint block_end = block_indices_begins[orig_seq_idx + 1];
+
+ const uint blocks_per_partition = (KV_PARTITION_SIZE / KV_BLOCK_SIZE);
+ constexpr uint kv_pitch = HEAD_SIZE * sizeof(KV_ELEMENT_TYPE);
+
+ // Load Q for this tile once (shared across all partitions).
+ // Q is [TILE_Q q-tokens × Q_head_chunk_size heads × HEAD_SIZE].
+ matrix<half, Q_ROWS, HEAD_SIZE> Qmat = 0;
+ #pragma unroll
+ for (int t = 0; t < TILE_Q; t++) {
+ if (t >= (int)valid_count) continue;
+ const uint q_token_idx = subseq_q_begin + q_start + t;
+ const uint qo_offset = (q_token_idx * HEADS_NUM + head_num_idx) * HEAD_SIZE;
+ cm_svm_block_read<half, Q_head_chunk_size * HEAD_SIZE>(
+ (svmptr_t)(query + qo_offset),
+ Qmat.select<Q_head_chunk_size, 1, HEAD_SIZE, 1>(t * Q_head_chunk_size, 0).format<half>());
+ }
+
+ constexpr uint per_v_block_element_num = KV_BLOCK_SIZE * KV_HEADS_NUM * (HEAD_SIZE + V_SCALE_ZP_SIZE);
+#if KV_CACHE_COMPRESSION == 1
+ constexpr uint per_k_block_element_num = KV_BLOCK_SIZE * KV_HEADS_NUM * (HEAD_SIZE + K_SCALE_ZP_SIZE);
+#elif KV_CACHE_COMPRESSION == 2
+ constexpr uint per_k_block_element_num = KV_HEADS_NUM * HEAD_SIZE * (KV_BLOCK_SIZE + K_SCALE_ZP_SIZE);
+#else
+ constexpr uint per_k_block_element_num = KV_BLOCK_SIZE * KV_HEADS_NUM * HEAD_SIZE;
+#endif
+
+ // Early exit if this partition is beyond what this sequence needs
+ if (kv_partition_idx >= seq_kv_partition_num) {
+ // Still need to write neutral output for finalization
+ #pragma unroll
+ for (int t = 0; t < TILE_Q; t++) {
+ const uint token_row = tile_idx * TILE_Q + t;
+ #pragma unroll
+ for (int qi = 0; qi < Q_head_chunk_size; qi++) {
+ matrix<float, REG_M, REG_N> zero = 0.0f;
+ uint o_offset = token_row * kv_partition_num * HEADS_NUM * HEAD_SIZE
+ + kv_partition_num * (head_num_idx + qi) * HEAD_SIZE
+ + kv_partition_idx * HEAD_SIZE;
+ #pragma unroll
+ for (int k = 0; k < HEAD_SIZE; k += REG_N) {
+ cm_svm_block_write<float, REG_N>((svmptr_t)(output + o_offset + k), zero.format<float>());
+ }
+ uint lse_offset = token_row * HEADS_NUM * kv_partition_num
+ + (head_num_idx + qi) * kv_partition_num
+ + kv_partition_idx;
+ lse[lse_offset] = -3e38f;
+ }
+ }
+ return; // Nothing else to do; this SG is done
+ }
+
+ const uint start_block_idx = block_begin + kv_partition_idx * blocks_per_partition;
+
+ // Buffer base index for this tile's TILE_Q output rows (tile-major layout).
+ const uint base_token_row = tile_idx * TILE_Q;
+
+ // Inactive partition (this tile is shorter than the dispatched grid). Write
+ // neutral so finalize can blindly reduce all partitions.
+ if (kv_partition_idx * KV_PARTITION_SIZE >= kv_len_max || start_block_idx >= block_end) {
+ #pragma unroll
+ for (int t = 0; t < TILE_Q; t++) {
+ const uint token_row = base_token_row + t;
+ #pragma unroll
+ for (int qi = 0; qi < Q_head_chunk_size; qi++) {
+ matrix<float, REG_M, REG_N> zero = 0.0f;
+ uint o_offset = token_row * kv_partition_num * HEADS_NUM * HEAD_SIZE
+ + kv_partition_num * (head_num_idx + qi) * HEAD_SIZE
+ + kv_partition_idx * HEAD_SIZE;
+ #pragma unroll
+ for (int k = 0; k < HEAD_SIZE; k += REG_N) {
+ cm_svm_block_write<float, REG_N>((svmptr_t)(output + o_offset + k), zero.format<float>());
+ }
+ uint lse_offset = token_row * HEADS_NUM * kv_partition_num
+ + (head_num_idx + qi) * kv_partition_num
+ + kv_partition_idx;
+ lse[lse_offset] = -3e38f;
+ }
+ }
+ return; // Nothing else to do; this SG is done
+ }
+
+ // Q matrix is already loaded outside the loop (shared across all partitions)
+
+ uint block_num = blocks_per_partition;
+ if (block_num > block_end - start_block_idx) {
+ block_num = block_end - start_block_idx;
+ }
+
+ // leftover_size is computed against the tile-wide kv_len_max so K loads cover
+ // the longest causal cap in the tile. Per-row tighter caps are applied later
+ // via the causal mask pass.
+ uint leftover_size = 0;
+ if (kv_partition_idx == seq_kv_partition_num - 1) {
+ leftover_size = (kv_len_max - KV_PARTITION_SIZE * kv_partition_idx) % KV_PARTITION_SIZE;
+ }
+
+ // =========================================================================
+ // Online softmax fused Q@K + softmax + P@V
+ // reducing peak register pressure.
+ // =========================================================================
+
+ constexpr float log2e = 1.4426950408889634f;
+ constexpr float loge2 = 0.6931471805599453f;
+
+ vector<float, Q_ROWS> running_max = -3e38f;
+ vector<float, Q_ROWS> running_sum = 0.0f;
+ matrix<float, Q_ROWS, HEAD_SIZE> Omat = 0;
+
+#if !USE_LSC_BLOCK_2D_DESC && KV_CACHE_COMPRESSION
+ constexpr uint VALUE_TILE_NUM = 2;
+#else
+ constexpr uint VALUE_TILE_NUM = 1;
+#endif
+
+ #pragma unroll
+ for (int online_tile = 0; online_tile < NUM_ONLINE_TILES; online_tile++) {
+ const int tile_kv_start = online_tile * ONLINE_TILE_SIZE;
+
+ // =====================================================================
+ // Phase 1: Q @ K for this online tile
+ // =====================================================================
+ matrix<float, Q_ROWS, ONLINE_TILE_STEPS * REG_N> rS_tile = 0;
+
+ {
+ const uint tile_block_start = tile_kv_start / KV_BLOCK_SIZE;
+ const uint tile_block_end = (tile_kv_start + ONLINE_TILE_SIZE + KV_BLOCK_SIZE - 1) / KV_BLOCK_SIZE;
+ #pragma unroll
+ for (uint block_idx = tile_block_start; block_idx < block_num && block_idx < tile_block_end; block_idx++) {
+ uint blk_indices = block_indices[start_block_idx + block_idx];
+ uint k_base_offset = blk_indices * per_k_block_element_num + kv_head_num_idx * (per_k_block_element_num / KV_HEADS_NUM);
+ uint k_scale_zp_offset = k_base_offset + KV_BLOCK_SIZE * HEAD_SIZE;
+
+#if USE_LSC_BLOCK_2D_DESC
+ #if KV_CACHE_COMPRESSION
+ lsc::block_2d_desc<uint, 1, REG_N, REG_K/4> b2dK(reinterpret_cast<uint*>(key + k_base_offset), KV_BLOCK_SIZE - 1, HEAD_SIZE*sizeof(uint8_t) - 1, kv_pitch - 1, 0, 0);
+ #else
+ lsc::block_2d_desc<uint, 1, REG_N, REG_K/2> b2dK(reinterpret_cast<uint*>(key + k_base_offset), KV_BLOCK_SIZE - 1, HEAD_SIZE*sizeof(half) - 1, kv_pitch - 1, 0, 0);
+ #endif
+#else
+ uint kv_offset = k_base_offset;
+ uint kv_stride = HEAD_SIZE;
+#endif
+
+ uint block_start_in_partition = block_idx * KV_BLOCK_SIZE;
+ uint kv_pos_begin_in_block = (tile_kv_start > (int)block_start_in_partition)
+ ? (tile_kv_start - (int)block_start_in_partition) : 0;
+ const uint partition_valid = (leftover_size > 0) ? leftover_size : (uint)KV_PARTITION_SIZE;
+ uint kv_pos_end_in_block = 0;
+ if (partition_valid > block_start_in_partition) {
+ kv_pos_end_in_block = partition_valid - block_start_in_partition;
+ if (kv_pos_end_in_block > KV_BLOCK_SIZE)
+ kv_pos_end_in_block = KV_BLOCK_SIZE;
+ }
+ uint tile_end_in_partition = tile_kv_start + ONLINE_TILE_SIZE;
+ if (block_start_in_partition + kv_pos_end_in_block > tile_end_in_partition)
+ kv_pos_end_in_block = tile_end_in_partition - block_start_in_partition;
+ uint effective_kv_pos_end = kv_pos_end_in_block;
+ if (effective_kv_pos_end == 0)
+ continue;
+
+#if KV_CACHE_COMPRESSION == 1
+ vector<half, KV_BLOCK_SIZE> scale_vec;
+ vector<half, KV_BLOCK_SIZE> zp_vec;
+ cm_svm_block_read(reinterpret_cast<svmptr_t>(key + k_scale_zp_offset), scale_vec);
+ cm_svm_block_read(reinterpret_cast<svmptr_t>(key + k_scale_zp_offset + KV_BLOCK_SIZE * sizeof(half)), zp_vec);
+ if (effective_kv_pos_end < KV_BLOCK_SIZE) {
+ #pragma unroll
+ for (int i = effective_kv_pos_end; i < KV_BLOCK_SIZE; i++) {
+ scale_vec[i] = 0.0;
+ zp_vec[i] = 0.0;
+ }
+ }
+#endif
+
+ int ki_base = (int)(block_start_in_partition + kv_pos_begin_in_block - tile_kv_start) / KV_STEP;
+ for (int kv_pos = (int)kv_pos_begin_in_block, ki = ki_base;
+ ki < ONLINE_TILE_STEPS && kv_pos < (int)effective_kv_pos_end;
+ kv_pos += KV_STEP, ki++) {
+#if KV_CACHE_COMPRESSION == 1
+ #if USE_LSC_BLOCK_2D_DESC
+ vector<half, REG_N * 2> temp_scale, temp_zp;
+ temp_scale.select<REG_N,2>(0) = scale_vec.select<REG_N,1>(kv_pos);
+ temp_scale.select<REG_N,2>(1) = scale_vec.select<REG_N,1>(kv_pos);
+ temp_zp.select<REG_N,2>(0) = zp_vec.select<REG_N,1>(kv_pos);
+ temp_zp.select<REG_N,2>(1) = zp_vec.select<REG_N,1>(kv_pos);
+ #else
+ matrix<half, REG_N, REG_K> temp_scale;
+ matrix<half, REG_N, REG_K> temp_zp;
+ #pragma unroll
+ for (int kk = 0; kk < REG_K; kk++) {
+ temp_scale.select<REG_N, 1, 1, 1>(0, kk) = scale_vec.select<REG_N,1>(kv_pos);
+ temp_zp.select<REG_N, 1, 1, 1>(0, kk) = zp_vec.select<REG_N,1>(kv_pos);
+ }
+ #endif
+#endif
+
+ #pragma unroll
+#if KV_CACHE_COMPRESSION
+ #if !USE_LSC_BLOCK_2D_DESC && KV_CACHE_COMPRESSION == 1 && XE_ARCH==1
+ for (int k = 0, ri = 0; k < HEAD_SIZE/4; k += (REG_K/4)*4, ri += 4) {
+ #else
+ for (int k = 0, ri = 0; k < HEAD_SIZE/4; k += REG_K/4, ri++) {
+ #endif
+#else
+ for (int k = 0, ri = 0; k < HEAD_SIZE/2; k += REG_K/2, ri++) {
+#endif
+#if !USE_LSC_BLOCK_2D_DESC && KV_CACHE_COMPRESSION == 1 && XE_ARCH==1
+ matrix<uint8_t, REG_N, REG_K*4> temp4;
+ uint cur_kv_offset4 = kv_offset + kv_pos * kv_stride + k * 4;
+ #pragma unroll
+ for (int kk = 0; kk < REG_N; kk++) {
+ vector<uint, (REG_K*4)/4> tmp_dw;
+ cm_svm_block_read<uint, (REG_K*4)/4>((svmptr_t)(reinterpret_cast<uint*>(key + cur_kv_offset4 + kk * kv_stride)), tmp_dw);
+ temp4[kk].format<uint>() = tmp_dw;
+ }
+ #pragma unroll
+ for (int ur = 0; ur < 4; ur++) {
+ if (ri + ur >= HEAD_SIZE / REG_K) break;
+ matrix<half, REG_K, REG_N> Kt = 0;
+ matrix<uint8_t, REG_N, REG_K> temp;
+ #pragma unroll
+ for (int kk = 0; kk < REG_N; kk++) {
+ temp[kk] = temp4[kk].select<REG_K,1>(ur*REG_K);
+ }
+ matrix<half, REG_N, REG_K> KtNormal = temp;
+ KtNormal = KtNormal - temp_zp;
+ KtNormal = cm_mul<half>(KtNormal, temp_scale);
+ Transpose_8x8(KtNormal.format<uint, REG_N, REG_K/2>(), Kt.format<uint, REG_K/2, REG_N>());
+ {
+ matrix<half, Q_ROWS, REG_K> Qmat_data = Qmat.select<Q_ROWS,1,REG_K,1>(0, (ri+ur)*REG_K);
+ matrix<float, Q_ROWS, REG_N> rS_data = 0;
+ rS_data = cm_dpas<CM_PRECISION_HF, CM_PRECISION_HF, SystolicDepth, Q_ROWS>(
+ rS_data.format<float>(),
+ Kt.format<int32_t>(),
+ Qmat_data.format<int32_t>());
+ rS_tile.select<Q_ROWS, 1, REG_N, 1>(0, ki*REG_N) += rS_data;
+ }
+ }
+ continue;
+#endif
+ matrix<half, REG_K, REG_N> Kt = 0;
+#if USE_LSC_BLOCK_2D_DESC
+ b2dK.set_block_x(k);
+ #if KV_CACHE_COMPRESSION
+ matrix<uint8_t, REG_K, REG_N> Kt_quant_temp, Kt_quant;
+ cm_load<lsc::Transpose>(Kt_quant_temp.format<uint>(), b2dK.set_block_y(kv_pos));
+ auto quant_src = Kt_quant_temp.format<ushort, REG_K/2, REG_N>();
+ auto quant_dst = Kt_quant.format<ushort, REG_K/2, REG_N>();
+
+ #pragma unroll
+ for (int r = 0; r < REG_K / 2; r += 2) {
+ quant_dst.row(r ) = quant_src.select<2,1,8,2>(r,0);
+ quant_dst.row(r+1) = quant_src.select<2,1,8,2>(r,1);
+ }
+ #if KV_CACHE_COMPRESSION == 2
+ uint group_idx = (kv_pos / SUB_BLOCK_SIZE);
+ vector<half, REG_K> temp_scale, temp_zp;
+ svmptr_t scale_ptr = (svmptr_t)(key + k_scale_zp_offset
+ + group_idx * HEAD_SIZE * sizeof(half)
+ + k * 4 * sizeof(half));
+ svmptr_t zp_ptr = (svmptr_t)(key + k_scale_zp_offset
+ + GROUPS_PER_BLOCK * HEAD_SIZE * sizeof(half)
+ + group_idx * HEAD_SIZE * sizeof(half)
+ + k * 4 * sizeof(half));
+ cm_svm_block_read<half, REG_K>(scale_ptr, temp_scale);
+ cm_svm_block_read<half, REG_K>(zp_ptr, temp_zp);
+
+ auto Kt_dequant_out = Kt.format<half, REG_K/2, 2*REG_N>();
+ auto Kt_dequant_tmp = Kt_quant.format<uint8_t, REG_K/2, 2*REG_N>();
+ #pragma unroll
+ for (int r = 0; r < REG_K/2; r++) {
+ Kt_dequant_out[r].select<REG_N, 2>(0) = Kt_dequant_tmp[r].select<REG_N, 2>(0) - temp_zp[r*2];
+ Kt_dequant_out[r].select<REG_N, 2>(0) = cm_mul<half>(Kt_dequant_out[r].select<REG_N, 2>(0), temp_scale[r*2]);
+ Kt_dequant_out[r].select<REG_N, 2>(1) = Kt_dequant_tmp[r].select<REG_N, 2>(1) - temp_zp[r*2+1];
+ Kt_dequant_out[r].select<REG_N, 2>(1) = cm_mul<half>(Kt_dequant_out[r].select<REG_N, 2>(1), temp_scale[r*2+1]);
+ }
+ #elif KV_CACHE_COMPRESSION == 1
+ // Vectorized dequantization: explicitly format to ensure vector operations
+ auto scale_mat = temp_scale.format<half, 2, REG_N>();
+ auto zp_mat = temp_zp.format<half, 2, REG_N>();
+
+ #pragma unroll
+ for (int r = 0; r < REG_K; r++) {
+ int scale_idx = r % 2;
+ // Vector operations on entire row (REG_N elements processed together)
+ Kt[r] = Kt_quant[r] - zp_mat[scale_idx];
+ Kt[r] = cm_mul<half>(Kt[r], scale_mat[scale_idx]);
+ }
+ #endif
+ #else
+ cm_load<lsc::Transpose>(Kt.format<uint>(), b2dK.set_block_y(kv_pos));
+ #endif
+#else
+ #if KV_CACHE_COMPRESSION
+ matrix<uint8_t, REG_N, REG_K> temp;
+ uint cur_kv_offset = kv_offset + kv_pos * kv_stride + k * 4;
+ #pragma unroll
+ for (int kk = 0; kk < REG_N; kk++) {
+ cm_svm_block_read<uint8_t, REG_K>((svmptr_t)(key + cur_kv_offset + kk * kv_stride), temp[kk].format<uint8_t>());
+ }
+ #if KV_CACHE_COMPRESSION == 1
+ matrix<half, REG_N, REG_K> KtNormal = temp;
+ KtNormal = KtNormal - temp_zp;
+ KtNormal = cm_mul<half>(KtNormal, temp_scale);
+ #else
+ uint group_idx = (kv_pos / SUB_BLOCK_SIZE);
+ vector<half, REG_K> temp_scale, temp_zp;
+ svmptr_t scale_ptr = (svmptr_t)(key + k_scale_zp_offset
+ + group_idx * HEAD_SIZE * sizeof(half)
+ + k * 4 * sizeof(half));
+ svmptr_t zp_ptr = (svmptr_t)(key + k_scale_zp_offset
+ + GROUPS_PER_BLOCK * HEAD_SIZE * sizeof(half)
+ + group_idx * HEAD_SIZE * sizeof(half)
+ + k * 4 * sizeof(half));
+ cm_svm_block_read<half, REG_K>(scale_ptr, temp_scale);
+ cm_svm_block_read<half, REG_K>(zp_ptr, temp_zp);
+ matrix<half, REG_N, REG_K> KtNormal;
+ #pragma unroll
+ for (int kk = 0; kk < REG_N; kk++) {
+ KtNormal[kk] = temp[kk] - temp_zp;
+ KtNormal[kk] = cm_mul<half>(KtNormal[kk], temp_scale);
+ }
+ #endif
+ #else
+ matrix<uint, REG_N, REG_K/2> KtNormal;
+ uint cur_kv_offset = kv_offset + kv_pos * kv_stride + k * 2;
+ #pragma unroll
+ for (int kk = 0; kk < REG_N; kk++) {
+ cm_svm_block_read<uint, REG_K/2>((svmptr_t)(key + cur_kv_offset + kk * kv_stride), KtNormal[kk].format<uint>());
+ }
+ #endif
+ #if XE_ARCH==1
+ Transpose_8x8(KtNormal.format<uint, REG_N, REG_K/2>(), Kt.format<uint, REG_K/2, REG_N>());
+ #else
+ Transpose_8x8(KtNormal.format<uint, REG_N, REG_K/2>().select<8,1,8,1>(0,0), Kt.format<uint, REG_K/2, REG_N>().select<8,1,8,1>(0,0));
+ Transpose_8x8(KtNormal.format<uint, REG_N, REG_K/2>().select<8,1,8,1>(8,0), Kt.format<uint, REG_K/2, REG_N>().select<8,1,8,1>(0,8));
+ #endif
+#endif
+ {
+ matrix<half, Q_ROWS, REG_K> Qmat_data = Qmat.select<Q_ROWS,1,REG_K,1>(0, ri*REG_K);
+ matrix<float, Q_ROWS, REG_N> rS_data = 0;
+ rS_data = cm_dpas<CM_PRECISION_HF, CM_PRECISION_HF, SystolicDepth, Q_ROWS>(
+ rS_data.format<float>(),
+ Kt.format<int32_t>(),
+ Qmat_data.format<int32_t>());
+ rS_tile.select<Q_ROWS, 1, REG_N, 1>(0, ki*REG_N) += rS_data;
+ }
+ }
+ }
+ }
+ } // end Phase 1 block scope
+
+ // =====================================================================
+ // Phase 2: Scale + causal mask on rS_tile
+ // =====================================================================
+ // Apply scale factor
+ rS_tile = cm_mul<float>(rS_tile, (float)SCALE_FACTOR);
+
+ // Per-row causal mask on tile columns
+ {
+ const int kv_global_start = (int)(kv_partition_idx * KV_PARTITION_SIZE);
+ vector<int, REG_N> col_index;
+ #pragma unroll
+ for (int c = 0; c < REG_N; ++c) col_index[c] = c;
+ const float NEG_INF = -3.4e38f;
+
+ #pragma unroll
+ for (int t = 0; t < TILE_Q; ++t) {
+ const int kv_len_t = (t < (int)valid_count) ? (int)(past_q_lens + q_start + t + 1) : 0;
+ const int row_kv_in_partition = kv_len_t - kv_global_start;
+ // mask_from is relative to partition start
+ const int mask_from = row_kv_in_partition > 0 ? row_kv_in_partition : 0;
+ #pragma unroll
+ for (int qi = 0; qi < Q_head_chunk_size; ++qi) {
+ const int row = t * Q_head_chunk_size + qi;
+ auto rs_row = rS_tile[row].format<float, ONLINE_TILE_STEPS, REG_N>();
+ #pragma unroll
+ for (int b = 0; b < ONLINE_TILE_STEPS; ++b) {
+ // blk_lo is the partition-relative column index for this tile block
+ const int blk_lo = online_tile * ONLINE_TILE_SIZE + b * REG_N;
+ if (blk_lo >= mask_from) {
+ rs_row.row(b) = NEG_INF;
+ } else if (blk_lo + REG_N > mask_from) {
+ vector<unsigned short, REG_N> m = col_index >= (mask_from - blk_lo);
+ auto blk = rs_row.row(b);
+ blk.merge(NEG_INF, m);
+ }
+ }
+ }
+ }
+
+#if HAS_QQ_BIAS
+ // Speculative tree mask on the "new token" K-range only.
+ // key_spec = key_local - past_q_lens
+ // query_spec = q_start + t
+ if (qq_bias_num_subseq > 0 && qq_bias_spec_num > 0) {
+ #pragma unroll
+ for (int t = 0; t < TILE_Q; ++t) {
+ if (t >= (int)valid_count) {
+ continue;
+ }
+ const int query_spec = (int)q_start + t;
+ if (query_spec < 0 || query_spec >= qq_bias_spec_num) {
+ continue;
+ }
+ #pragma unroll
+ for (int b = 0; b < ONLINE_TILE_STEPS; ++b) {
+ const int blk_lo = online_tile * ONLINE_TILE_SIZE + b * REG_N;
+ vector<unsigned short, REG_N> m =
+ build_qq_bias_tree_mask_row<REG_N>(qq_bias_subseq_ptr, qq_bias_spec_num,
+ query_spec, kv_global_start + blk_lo,
+ (int)past_q_lens);
+ #pragma unroll
+ for (int qi = 0; qi < Q_head_chunk_size; ++qi) {
+ const int row = t * Q_head_chunk_size + qi;
+ auto rs_row = rS_tile[row].format<float, ONLINE_TILE_STEPS, REG_N>();
+ auto blk = rs_row.row(b);
+ blk.merge(NEG_INF, m);
+ }
+ }
+ }
+ }
+#endif
+
+ // Also mask columns beyond kv_pos_end for the last tile
+ {
+ uint partition_kv_pos_end = KV_PARTITION_SIZE; // = kv_pos_end for single block
+ if (leftover_size > 0) {
+ partition_kv_pos_end = leftover_size % KV_BLOCK_SIZE;
+ if (partition_kv_pos_end == 0) partition_kv_pos_end = KV_BLOCK_SIZE;
+ }
+ // Mask tile columns beyond the valid range
+ #pragma unroll
+ for (int b = 0; b < ONLINE_TILE_STEPS; ++b) {
+ const int col_abs = tile_kv_start + b * REG_N;
+ if (col_abs >= (int)partition_kv_pos_end) {
+ // Entire block is past valid data
+ #pragma unroll
+ for (int row = 0; row < Q_ROWS; ++row) {
+ rS_tile.select<1, 1, REG_N, 1>(row, b * REG_N) = NEG_INF;
+ }
+ } else if (col_abs + REG_N > (int)partition_kv_pos_end) {
+ // Straddling block
+ int local_mask = (int)partition_kv_pos_end - col_abs;
+ vector<unsigned short, REG_N> m = col_index >= local_mask;
+ #pragma unroll
+ for (int row = 0; row < Q_ROWS; ++row) {
+ auto blk = rS_tile.select<1, 1, REG_N, 1>(row, b * REG_N).format<float, 1, REG_N>().row(0);
+ blk.merge(NEG_INF, m);
+ }
+ }
+ }
+ }
+ }
+
+ // =====================================================================
+ // Phase 3: Online softmax update
+ // =====================================================================
+ matrix<half, Q_ROWS, ONLINE_TILE_STEPS * REG_N> P_tile = 0;
+
+ #pragma unroll
+ for (int row = 0; row < Q_ROWS; row++) {
+ auto rS_row = rS_tile[row].format<float>();
+
+ // Find tile max
+#if XE_ARCH==1
+ float tile_max = cm_reduced_max<float>(rS_row);
+#else
+ float tile_max = rS_row[0];
+ #if KV_CACHE_COMPRESSION
+ #pragma unroll
+ #endif
+ for (int r = 1; r < rS_row.n_elems(); r++)
+ tile_max = cm_max<float>(tile_max, rS_row[r]);
+#endif
+
+ // Compute new running max and correction factor
+ float new_max = cm_max<float>(running_max[row], tile_max);
+ float correction = cm_exp((running_max[row] - new_max) * log2e);
+
+ // Correct running state
+ running_sum[row] *= correction;
+ Omat[row] *= correction;
+
+ // Compute exp values for this tile
+ vector<float, ONLINE_TILE_STEPS * REG_N> exp_vals = cm_exp((rS_row - new_max) * log2e);
+
+ // Accumulate sum and update max
+ running_sum[row] += cm_sum<float>(exp_vals);
+ running_max[row] = new_max;
+
+ // Store P_tile as half for DPAS
+ P_tile[row] = exp_vals;
+ }
+
+ // =====================================================================
+ // Phase 4: P_tile @ V for this online tile
+ // =====================================================================
+ {
+ const uint tile_block_start_v = tile_kv_start / KV_BLOCK_SIZE;
+ const uint tile_block_end_v = (tile_kv_start + ONLINE_TILE_SIZE + KV_BLOCK_SIZE - 1) / KV_BLOCK_SIZE;
+ #pragma unroll
+ for (uint block_idx = tile_block_start_v; block_idx < block_num && block_idx < tile_block_end_v; block_idx++) {
+ uint blk_indices = block_indices[start_block_idx + block_idx];
+ uint v_base_offset = blk_indices * per_v_block_element_num + kv_head_num_idx * (per_v_block_element_num / KV_HEADS_NUM);
+ uint v_scale_zp_offset = v_base_offset + KV_BLOCK_SIZE * HEAD_SIZE;
+
+#if USE_LSC_BLOCK_2D_DESC
+ #if KV_CACHE_COMPRESSION
+ lsc::block_2d_desc<uint8_t, 1, REG_K, REG_N> b2dV(value + v_base_offset, KV_BLOCK_SIZE - 1, HEAD_SIZE*sizeof(uint8_t) - 1, kv_pitch - 1, 0, 0);
+ #else
+ lsc::block_2d_desc<half, 1, REG_K, REG_N> b2dV(value + v_base_offset, KV_BLOCK_SIZE - 1, HEAD_SIZE * sizeof(half) - 1, kv_pitch - 1, 0, 0);
+ #endif
+#else
+ uint kv_offset = v_base_offset;
+ uint kv_stride = HEAD_SIZE;
+#endif
+ uint block_start_in_partition_v = block_idx * KV_BLOCK_SIZE;
+ uint kv_pos_begin_in_block_v = (tile_kv_start > (int)block_start_in_partition_v)
+ ? (tile_kv_start - (int)block_start_in_partition_v) : 0;
+ const uint partition_valid_v = (leftover_size > 0) ? leftover_size : (uint)KV_PARTITION_SIZE;
+ uint kv_pos_end_in_block_v = 0;
+ if (partition_valid_v > block_start_in_partition_v) {
+ kv_pos_end_in_block_v = partition_valid_v - block_start_in_partition_v;
+ if (kv_pos_end_in_block_v > KV_BLOCK_SIZE)
+ kv_pos_end_in_block_v = KV_BLOCK_SIZE;
+ }
+ uint tile_end_in_partition_v = tile_kv_start + ONLINE_TILE_SIZE;
+ if (block_start_in_partition_v + kv_pos_end_in_block_v > tile_end_in_partition_v)
+ kv_pos_end_in_block_v = tile_end_in_partition_v - block_start_in_partition_v;
+ uint effective_kv_pos_end = kv_pos_end_in_block_v;
+ if (effective_kv_pos_end == 0)
+ continue;
+
+#if KV_CACHE_COMPRESSION
+ vector<half, KV_BLOCK_SIZE> scale_vec;
+ vector<half, KV_BLOCK_SIZE> zp_vec;
+ cm_svm_block_read(reinterpret_cast<svmptr_t>(value + v_scale_zp_offset), scale_vec);
+ cm_svm_block_read(reinterpret_cast<svmptr_t>(value + v_scale_zp_offset + KV_BLOCK_SIZE * sizeof(half)), zp_vec);
+ if (effective_kv_pos_end < KV_BLOCK_SIZE) {
+ for (int i = effective_kv_pos_end; i < KV_BLOCK_SIZE; i++) {
+ scale_vec[i] = 0.0;
+ zp_vec[i] = 0.0;
+ }
+ }
+#endif
+
+ int ki_base_v = (int)(block_start_in_partition_v + kv_pos_begin_in_block_v - tile_kv_start) / REG_K;
+ #pragma unroll
+ for (int kv_pos = (int)kv_pos_begin_in_block_v, ki = ki_base_v;
+ ki < ONLINE_TILE_STEPS && kv_pos < (int)effective_kv_pos_end;
+ kv_pos += REG_K, ki++) {
+#if KV_CACHE_COMPRESSION
+ vector<half, REG_K> temp_scale = scale_vec.select<REG_K, 1>(kv_pos);
+ vector<half, REG_K> temp_zp = zp_vec.select<REG_K, 1>(kv_pos);
+ matrix<uint8_t, REG_K, REG_N * VALUE_TILE_NUM> Vt_quant;
+#endif
+ #pragma unroll
+#if !USE_LSC_BLOCK_2D_DESC && KV_CACHE_COMPRESSION && XE_ARCH==1
+ for (int k = 0, ri = 0; k < HEAD_SIZE; k += (REG_N * VALUE_TILE_NUM) * 4, ri += VALUE_TILE_NUM * 4) {
+#else
+ for (int k = 0, ri = 0; k < HEAD_SIZE; k += REG_N * VALUE_TILE_NUM, ri += VALUE_TILE_NUM) {
+#endif
+ matrix<half, REG_K, REG_N * VALUE_TILE_NUM> VmatNormal;
+ matrix<half, REG_K, REG_N * VALUE_TILE_NUM> Vmat;
+#if USE_LSC_BLOCK_2D_DESC
+ b2dV.set_block_x(k);
+ #if KV_CACHE_COMPRESSION
+ cm_load<lsc::Normal>(Vt_quant.format<uint8_t>(), b2dV.set_block_y(kv_pos));
+ #else
+ cm_load<lsc::VNNI>(Vmat.format<half>(), b2dV.set_block_y(kv_pos));
+ #endif
+#else
+ #if KV_CACHE_COMPRESSION
+ #if XE_ARCH==1
+ matrix<uint8_t, REG_K, REG_N * VALUE_TILE_NUM * 4> Vt_quant4;
+ uint cur_kv_offset4 = kv_offset + kv_pos * kv_stride + k;
+ #pragma unroll
+ for (int kk = 0; kk < REG_K; kk++) {
+ vector<uint, (REG_N * VALUE_TILE_NUM * 4)/4> tmp_dw;
+ cm_svm_block_read<uint, (REG_N * VALUE_TILE_NUM * 4)/4>((svmptr_t)(reinterpret_cast<uint*>(value + cur_kv_offset4 + kk * kv_stride)), tmp_dw);
+ Vt_quant4[kk].format<uint>() = tmp_dw;
+ }
+ #pragma unroll
+ for (int ur = 0; ur < 4; ur++) {
+ if (k + ur * (REG_N * VALUE_TILE_NUM) >= HEAD_SIZE) break;
+ #pragma unroll
+ for (int kk = 0; kk < REG_K; kk++) {
+ Vt_quant[kk] = Vt_quant4[kk].select<REG_N * VALUE_TILE_NUM, 1>(ur * (REG_N * VALUE_TILE_NUM));
+ }
+ int ri_ur = ri + ur * VALUE_TILE_NUM;
+
+ VmatNormal = Vt_quant;
+ #pragma unroll
+ for (int r = 0; r < REG_K; r++) {
+ VmatNormal[r] = VmatNormal[r] - temp_zp[r];
+ VmatNormal[r] = cm_mul<half>(VmatNormal[r], temp_scale[r]);
+ }
+
+ if ((int)effective_kv_pos_end - kv_pos < KV_STEP) {
+ #pragma unroll
+ for (int r = effective_kv_pos_end - kv_pos; r < KV_STEP; r++) {
+ VmatNormal[r] = 0;
+ }
+ }
+ auto Vref = Vmat.format<half, REG_K/2, 2 * REG_N * VALUE_TILE_NUM>();
+ Vref.select<REG_K/2, 1, REG_N * VALUE_TILE_NUM, 2>(0, 0) = VmatNormal.select<REG_K/2, 2, REG_N * VALUE_TILE_NUM, 1>(0, 0);
+ Vref.select<REG_K/2, 1, REG_N * VALUE_TILE_NUM, 2>(0, 1) = VmatNormal.select<REG_K/2, 2, REG_N * VALUE_TILE_NUM, 1>(1, 0);
+
+ #if CLEAN_UNUSED_KVCACHE
+ if ((int)effective_kv_pos_end - kv_pos < KV_STEP) {
+ auto VmatRef = Vmat.format<half, REG_K/2, REG_N*2*VALUE_TILE_NUM>();
+ uint valid_rows = effective_kv_pos_end - kv_pos;
+ uint valid_rows_vnni = (valid_rows+1)/2;
+ #pragma unroll
+ for (int r = valid_rows_vnni; r < REG_K/2; r++) {
+ VmatRef.row(r) = 0.0f;
+ }
+ if (valid_rows % 2 == 1) {
+ VmatRef.row(valid_rows_vnni-1).select<REG_N*VALUE_TILE_NUM, 2>(1) = 0.0f;
+ }
+ }
+ #endif
+ matrix<half, Q_ROWS, REG_K> Pmat_data = P_tile.select<Q_ROWS,1,REG_K,1>(0, ki*REG_K);
+ #pragma unroll
+ for (int tile = 0; tile < VALUE_TILE_NUM; tile++) {
+ auto Omat_data = Omat.select<Q_ROWS,1,REG_N,1>(0, (ri_ur + tile)*REG_N);
+ Omat_data = cm_dpas<CM_PRECISION_HF, CM_PRECISION_HF, SystolicDepth, Q_ROWS>(
+ Omat_data.format<float>(),
+ Vmat.format<half, REG_K/2, REG_N*2*VALUE_TILE_NUM>().select<REG_K/2, 1, REG_N*2, 1>(0, REG_N*2*tile).format<int32_t>(),
+ Pmat_data.format<int32_t>());
+ }
+ }
+ continue;
+ #else
+ uint cur_kv_offset = kv_offset + kv_pos * kv_stride + k;
+ #pragma unroll
+ for (int kk = 0; kk < REG_K; kk++) {
+ cm_svm_block_read<uint8_t, REG_N * VALUE_TILE_NUM>((svmptr_t)(value + cur_kv_offset + kk * kv_stride), Vt_quant[kk].format<uint8_t>());
+ }
+ #endif
+ #else
+ uint cur_kv_offset = kv_offset + kv_pos * kv_stride + k;
+ #pragma unroll
+ for (int kk = 0; kk < REG_K; kk++) {
+ cm_svm_block_read<half, REG_N * VALUE_TILE_NUM>((svmptr_t)(value + cur_kv_offset + kk * kv_stride), VmatNormal[kk].format<half>());
+ }
+ auto Vref = Vmat.format<half, REG_K/2, 2 * REG_N * VALUE_TILE_NUM>();
+ Vref.select<REG_K/2, 1, REG_N * VALUE_TILE_NUM, 2>(0, 0) = VmatNormal.select<REG_K/2, 2, REG_N * VALUE_TILE_NUM, 1>(0, 0);
+ Vref.select<REG_K/2, 1, REG_N * VALUE_TILE_NUM, 2>(0, 1) = VmatNormal.select<REG_K/2, 2, REG_N * VALUE_TILE_NUM, 1>(1, 0);
+ #endif
+#endif
+
+#if KV_CACHE_COMPRESSION
+ VmatNormal = Vt_quant;
+ #pragma unroll
+ for (int r = 0; r < REG_K; r++) {
+ VmatNormal[r] = VmatNormal[r] - temp_zp[r];
+ VmatNormal[r] = cm_mul<half>(VmatNormal[r], temp_scale[r]);
+ }
+
+ if ((int)effective_kv_pos_end - kv_pos < KV_STEP) {
+ #pragma unroll
+ for (int r = effective_kv_pos_end - kv_pos; r < KV_STEP; r++) {
+ VmatNormal[r] = 0;
+ }
+ }
+ auto Vref = Vmat.format<half, REG_K/2, 2 * REG_N * VALUE_TILE_NUM>();
+ Vref.select<REG_K/2, 1, REG_N * VALUE_TILE_NUM, 2>(0, 0) = VmatNormal.select<REG_K/2, 2, REG_N * VALUE_TILE_NUM, 1>(0, 0);
+ Vref.select<REG_K/2, 1, REG_N * VALUE_TILE_NUM, 2>(0, 1) = VmatNormal.select<REG_K/2, 2, REG_N * VALUE_TILE_NUM, 1>(1, 0);
+#endif
+
+#if CLEAN_UNUSED_KVCACHE
+ if ((int)effective_kv_pos_end - kv_pos < KV_STEP) {
+ auto VmatRef = Vmat.format<half, REG_K/2, REG_N*2*VALUE_TILE_NUM>();
+ uint valid_rows = effective_kv_pos_end - kv_pos;
+ uint valid_rows_vnni = (valid_rows+1)/2;
+ #pragma unroll
+ for (int r = valid_rows_vnni; r < REG_K/2; r++) {
+ VmatRef.row(r) = 0.0f;
+ }
+ if (valid_rows % 2 == 1) {
+ VmatRef.row(valid_rows_vnni-1).select<REG_N*VALUE_TILE_NUM, 2>(1) = 0.0f;
+ }
+ }
+#endif
+ matrix<half, Q_ROWS, REG_K> Pmat_data = P_tile.select<Q_ROWS,1,REG_K,1>(0, ki*REG_K);
+ #pragma unroll
+ for (int tile = 0; tile < VALUE_TILE_NUM; tile++) {
+ auto Omat_data = Omat.select<Q_ROWS,1,REG_N,1>(0, (ri + tile)*REG_N);
+ Omat_data = cm_dpas<CM_PRECISION_HF, CM_PRECISION_HF, SystolicDepth, Q_ROWS>(
+ Omat_data.format<float>(),
+ Vmat.format<half, REG_K/2, REG_N*2*VALUE_TILE_NUM>().select<REG_K/2, 1, REG_N*2, 1>(0, REG_N*2*tile).format<int32_t>(),
+ Pmat_data.format<int32_t>());
+ }
+ }
+ }
+ }
+ } // end Phase 4 block scope
+ } // end online tile loop
+
+ // Compute cur_lse and cur_sum from running state
+ vector<float, Q_ROWS> cur_sum = running_sum;
+ vector<float, Q_ROWS> cur_lse;
+ #pragma unroll
+ for (int row = 0; row < Q_ROWS; row++) {
+ // Guard: if running_sum is 0 (all columns masked), lse = -inf (neutral for finalization)
+ cur_lse[row] = (running_sum[row] > 0.0f)
+ ? (cm_log<float>(running_sum[row]) * loge2 + running_max[row])
+ : -3e38f;
+ }
+
+ // Save partition output / lse. Output is laid out as
+ // [tile_count * TILE_Q, head, partition, head_size]
+ // Each row `t` of this tile writes to (base_token_row + t). Dummy rows
+ // (t >= valid_count) write zeros + lse = -inf so finalize treats them as
+ // having no contribution.
+ #pragma unroll
+ for (int t = 0; t < TILE_Q; t++) {
+ const uint token_row = base_token_row + t;
+ const bool row_valid = (t < (int)valid_count);
+ #pragma unroll
+ for (int qi = 0; qi < Q_head_chunk_size; qi++) {
+ const int row = t * Q_head_chunk_size + qi;
+ matrix<float, REG_M, REG_N> cur_O_f32;
+ uint o_offset = token_row * kv_partition_num * HEADS_NUM * HEAD_SIZE
+ + kv_partition_num * (head_num_idx + qi) * HEAD_SIZE
+ + kv_partition_idx * HEAD_SIZE;
+ // Guard: row_valid AND cur_sum > 0 (causal mask may zero out entire rows in a partition)
+ float div_cur_sum = (row_valid && cur_sum[row] > 0.0f) ? (1.0f / cur_sum[row]) : 0.0f;
+ auto Omat_slice = Omat[row].format<float, HEAD_SIZE/REG_N * REG_M, REG_N>();
+ #pragma unroll
+ for (int k = 0, ri = 0; k < HEAD_SIZE; k += REG_N, ri++) {
+ auto cO = Omat_slice[ri].format<float, REG_M, REG_N>();
+ if (row_valid && cur_sum[row] > 0.0f) {
+#if XE_ARCH==1
+ cur_O_f32 = cm_mul<float>(cO, div_cur_sum);
+#else
+ cur_O_f32 = cm_div_ieee(cO, cur_sum[row]);
+#endif
+ } else {
+ cur_O_f32 = 0.0f;
+ }
+ cm_svm_block_write<float, REG_N>((svmptr_t)(output + o_offset + k), cur_O_f32.format<float>());
+ }
+ uint lse_offset = token_row * HEADS_NUM * kv_partition_num
+ + (head_num_idx + qi) * kv_partition_num
+ + kv_partition_idx;
+ lse[lse_offset] = (row_valid && cur_sum[row] > 0.0f) ? cur_lse[row] : -3e38f;
+ }
+ }
+}
+
+} // namespace KERNEL_NAME
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/pa_small_q_finalization.cm b/src/plugins/intel_gpu/src/graph/impls/cm/pa_small_q_finalization.cm
new file mode 100644
index 00000000000..3c1790c488c
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/pa_small_q_finalization.cm
@@ -0,0 +1,104 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+namespace KERNEL_NAME {
+
+// pa_small_q_finalization: cross-partition logsumexp reduce for pa_small_q.
+//
+// Tile-major layout: pa_small_q writes its partition output / lse as
+// buffer[tile_count * TILE_Q, head, partition, head_size]
+// so finalize iterates by row index (`token_row`). token_row decomposes as:
+// tile_idx = token_row / TILE_Q
+// t_in_tile = token_row % TILE_Q
+// Dummy rows (t_in_tile >= valid_count) have lse = -inf written by pa_small_q,
+// but we still early-return them here to avoid writing junk into the host output.
+//
+// selected_q_mapping is i32 triples: [orig_seq_idx, q_start, valid_count] per tile.
+extern "C" _GENX_MAIN_ void KERNEL_NAME(
+ float* input [[type("svmptr_t")]],
+ half* output [[type("svmptr_t")]],
+ float* lse [[type("svmptr_t")]],
+ int* subsequence_begins [[type("svmptr_t")]],
+ int* selected_q_mapping [[type("svmptr_t")]],
+ int selected_token_count,
+ int kv_partition_num
+ ) {
+ auto token_row = cm_global_id(0);
+ if (token_row >= (uint)selected_token_count) {
+ return;
+ }
+ const uint tile_idx = token_row / TILE_Q;
+ const uint t_in_tile = token_row % TILE_Q;
+
+ const uint orig_seq_idx = (uint)selected_q_mapping[tile_idx * 3 + 0];
+ const uint q_start = (uint)selected_q_mapping[tile_idx * 3 + 1];
+ const uint valid_count = (uint)selected_q_mapping[tile_idx * 3 + 2];
+ if (t_in_tile >= valid_count) {
+ return; // dummy slot — pa_small_q already wrote -inf, no host output needed
+ }
+ const uint q_in_subseq = q_start + t_in_tile;
+
+ auto head = cm_global_id(1);
+ auto offset = cm_group_id(2) * REDUCE_SPLIT_SIZE;
+ const int total_partition_num = (kv_partition_num * HEADS_NUM);
+
+ // Logsumexp across partitions for this (token_row, head).
+ float total_lse = 0.0;
+ uint lse_offset = token_row * total_partition_num + head * kv_partition_num;
+ constexpr float log2e = 1.4426950408889634f;
+ float* lse_vec = lse + lse_offset;
+ float lse_max = lse_vec[0];
+ for (int k = 1; k < kv_partition_num; k++) {
+ lse_max = cm_max<float>(lse_vec[k], lse_max);
+ }
+
+ int iter = kv_partition_num / 16;
+ for (int k = 0; k < iter * 16; k += 16) {
+ #pragma unroll
+ for (int ki = k; ki < k + 16; ki++) {
+ float lse_value = cm_exp<float>((lse_vec[ki] - lse_max) * log2e);
+ total_lse += lse_value;
+ }
+ }
+ for (int k = iter * 16; k < kv_partition_num; k++) {
+ float lse_value = cm_exp<float>((lse_vec[k] - lse_max) * log2e);
+ total_lse += lse_value;
+ }
+
+ matrix<half, 1, REDUCE_SPLIT_SIZE> out_mat = 0;
+ matrix<float, 1, REDUCE_SPLIT_SIZE> out_mat_f32 = 0;
+ matrix<float, 1, REDUCE_SPLIT_SIZE> data_mat;
+ uint input_offset = token_row * total_partition_num * HEAD_SIZE
+ + head * kv_partition_num * HEAD_SIZE
+ + offset;
+
+ for (int k = 0; k < iter * 16; k += 16) {
+ #pragma unroll
+ for (int ki = k; ki < k + 16; ki++) {
+ cm_svm_block_read<float, REDUCE_SPLIT_SIZE>((svmptr_t)(input + input_offset), data_mat.format<float>());
+ input_offset += HEAD_SIZE;
+ float lse_value = cm_exp<float>((lse_vec[ki] - lse_max) * log2e);
+ out_mat_f32 += cm_mul<float>(data_mat, (float)(lse_value/total_lse));
+ }
+ }
+ for (int k = iter * 16; k < kv_partition_num; k++) {
+ cm_svm_block_read<float, REDUCE_SPLIT_SIZE>((svmptr_t)(input + input_offset), data_mat.format<float>());
+ input_offset += HEAD_SIZE;
+ float lse_value = cm_exp<float>((lse_vec[k] - lse_max) * log2e);
+ out_mat_f32 += cm_mul<float>(data_mat, (float)(lse_value/total_lse));
+ }
+
+ out_mat = cm_mul<half>(out_mat_f32, (float)1.0f);
+
+ uint q_begin = subsequence_begins[orig_seq_idx];
+ uint q_end = subsequence_begins[orig_seq_idx + 1];
+ if (q_end <= q_begin) {
+ return;
+ }
+ uint q_token_idx = q_begin + q_in_subseq;
+ uint output_offset = q_token_idx * HEADS_NUM * HEAD_SIZE + head * HEAD_SIZE + offset;
+ cm_svm_block_write<half, REDUCE_SPLIT_SIZE>((svmptr_t)(output + output_offset), out_mat.format<half>());
+}
+
+} // namespace KERNEL_NAME
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/paged_attention.cpp b/src/plugins/intel_gpu/src/graph/impls/cm/paged_attention.cpp
index 37a148243f0..b1c6e2bbf61 100644
--- a/src/plugins/intel_gpu/src/graph/impls/cm/paged_attention.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/paged_attention.cpp
@@ -11,6 +11,7 @@
#include <limits>
#include <memory>
#include <numeric>
+#include <optional>
#include <utility>
#include <vector>
@@ -80,6 +81,8 @@ public:
Stage::Ptr kv_cache_update = make_stage<PagedAttentionGeneratorKVCacheUpdate>();
Stage::Ptr pa_single_token = make_stage<PagedAttentionGeneratorSingleToken>();
Stage::Ptr pa_single_token_finalization = make_stage<PagedAttentionGeneratorSingleTokenFinalization>();
+ Stage::Ptr pa_small_q = make_stage<PagedAttentionGeneratorSmallQ>();
+ Stage::Ptr pa_small_q_finalization = make_stage<PagedAttentionGeneratorSmallQFinalization>();
Stage::Ptr pa_multi_token_1 = make_stage<PagedAttentionGeneratorMultiToken>(1);
Stage::Ptr pa_multi_token_128 = make_stage<PagedAttentionGeneratorMultiToken>(128);
Stage::Ptr pa_multi_token_256 = make_stage<PagedAttentionGeneratorMultiToken>(256);
@@ -102,6 +105,8 @@ public:
add_stage(kv_cache_update, params);
add_stage(pa_single_token, params);
add_stage(pa_single_token_finalization, params);
+ add_stage(pa_small_q, params);
+ add_stage(pa_small_q_finalization, params);
add_stage(pa_multi_token_1, params);
if (desc->has_xattention) {
add_stage(pa_multi_token_128, params);
@@ -251,6 +256,9 @@ public:
rt_params->batch_size_in_sequences = get_batch_size_in_sequences(params.input_layouts);
rt_params->single_token_selected_count = 0;
rt_params->multi_token_wg_count = 0;
+ rt_params->small_q_token_count = 0;
+ rt_params->small_q_tile_count = 0;
+ rt_params->small_q_max_kv_len = 0;
rt_params->enable_xattn_estimation = false;
rt_params->stage = get_paged_attention_stage(params);
@@ -270,6 +278,13 @@ public:
const auto past_lens = read_i32_input(params, PagedAttentionInputIdx::PAST_LENS);
const auto wg_seq_len = PagedAttentionGeneratorMultiToken::get_wg_seq_len(params);
const bool use_split_mixed = rt_params->stage == PagedAttentionStage::MIXED && m_mixed_route_mode == MixedRouteMode::SPLIT;
+
+ const auto sq_partition_size = PagedAttentionGeneratorSingleToken::get_partition_size(desc->has_xattention);
+ const auto sq_q_chunking = get_single_token_q_chunking(params, *desc, sq_partition_size);
+ const int xe_arch = params.get_device_info().arch < gpu_arch::xe2 ? 1 : 2;
+ const int small_q_tile_q = get_small_q_tile_q(xe_arch, static_cast<int>(sq_q_chunking.q_head_chunk_size));
+ rt_params->small_q_tile_q = small_q_tile_q;
+
for (size_t subsequence_id = 0; subsequence_id + 1 < subsequence_begins.size(); ++subsequence_id) {
const auto q_len = static_cast<size_t>(std::max<int32_t>(subsequence_begins[subsequence_id + 1] - subsequence_begins[subsequence_id], 0));
if (q_len == 0) {
@@ -279,8 +294,14 @@ public:
if (use_split_mixed) {
const auto past_len = static_cast<size_t>(std::max<int32_t>(past_lens[subsequence_id], 0));
const bool decode_subsequence = (q_len == 1) && (past_len > 0);
+ const bool small_q_subsequence = (q_len > 1) && (q_len <= SMALL_Q_THRESHOLD) && (past_len > 0);
+
if (decode_subsequence) {
rt_params->single_token_selected_count++;
+ } else if (small_q_subsequence) {
+ rt_params->small_q_token_count += q_len;
+ rt_params->small_q_tile_count += ceil_div(q_len, static_cast<size_t>(small_q_tile_q));
+ rt_params->small_q_max_kv_len = std::max(rt_params->small_q_max_kv_len, past_len + q_len);
} else {
rt_params->multi_token_wg_count += ceil_div(q_len, wg_seq_len);
}
@@ -289,10 +310,9 @@ public:
}
}
- if (use_split_mixed && rt_params->single_token_selected_count > 0) {
- const auto partition_size = PagedAttentionGeneratorSingleToken::get_partition_size(desc->has_xattention);
- rt_params->num_of_partitions = ceil_div(max_context_len, partition_size);
- rt_params->q_chunking = get_single_token_q_chunking(params, *desc, partition_size);
+ if (use_split_mixed && (rt_params->single_token_selected_count > 0 || rt_params->small_q_token_count > 0)) {
+ rt_params->num_of_partitions = ceil_div(max_context_len, sq_partition_size);
+ rt_params->q_chunking = sq_q_chunking;
}
if (desc->has_xattention) {
@@ -395,6 +415,25 @@ public:
", got ",
mapping_mem->count());
+ // Small-q mapping: triples (orig_seq_idx, q_start, valid_count), one entry per SG tile.
+ // Each subseq is chunked into ceil_div(q_len, TILE_Q) tiles; the last tile may have
+ // valid_count < TILE_Q (padded rows use valid_count check in kernel/finalize).
+ const bool has_small_q = rt_params->small_q_token_count > 0;
+ std::optional<mem_lock<int32_t, mem_lock_type::write>> small_q_lock;
+ size_t small_q_capacity = 0;
+ size_t small_q_idx = 0;
+ const size_t expected_small_q_size = rt_params->small_q_tile_count * 3;
+ if (has_small_q) {
+ auto small_q_mem = instance.get_intermediates_memories()[PagedAttentionInternBuffIdx::SMALL_Q_SELECTED_MAPPING];
+ small_q_capacity = small_q_mem->count();
+ OPENVINO_ASSERT(small_q_capacity >= expected_small_q_size,
+ "Insufficient small-q mapping buffer size: expected at least ",
+ expected_small_q_size,
+ ", got ",
+ small_q_capacity);
+ small_q_lock.emplace(small_q_mem, stream);
+ }
+
const int32_t wg_seq_len = static_cast<int32_t>(PagedAttentionGeneratorMultiToken::get_wg_seq_len(params));
size_t selected_count = 0;
size_t mapping_idx = 0;
@@ -409,6 +448,7 @@ public:
const int32_t q_len = q_end - q_begin;
const int32_t past_len = std::max<int32_t>(past_lens[sequence_id], 0);
const bool decode_subsequence = (q_len == 1) && (past_len > 0);
+ const bool small_q_subsequence = (q_len > 1) && (q_len <= static_cast<int32_t>(SMALL_Q_THRESHOLD)) && (past_len > 0);
if (decode_subsequence) {
OPENVINO_ASSERT(selected_count < selected_capacity,
@@ -420,6 +460,25 @@ public:
continue;
}
+ if (small_q_subsequence) {
+ OPENVINO_ASSERT(small_q_lock.has_value(), "Small-q mapping buffer not locked but a small-q subsequence was found");
+ // Split subseq into ceil_div(q_len, TILE_Q) tiles. Each tile handled by one SG.
+ // Triple: (orig_seq_idx, q_start_in_subseq, valid_count in [1, TILE_Q]).
+ const int32_t tile_q = std::max(1, rt_params->small_q_tile_q);
+ for (int32_t q_start = 0; q_start < q_len; q_start += tile_q) {
+ const int32_t valid_count = std::min(tile_q, q_len - q_start);
+ OPENVINO_ASSERT(small_q_idx + 2 < small_q_capacity,
+ "Small-q mapping write out of bounds: idx=",
+ small_q_idx,
+ ", capacity=",
+ small_q_capacity);
+ (*small_q_lock)[small_q_idx++] = static_cast<int32_t>(sequence_id);
+ (*small_q_lock)[small_q_idx++] = q_start;
+ (*small_q_lock)[small_q_idx++] = valid_count;
+ }
+ continue;
+ }
+
for (int32_t block_start = q_begin; block_start < q_end; block_start += wg_seq_len) {
OPENVINO_ASSERT(mapping_idx + 1 < expected_mapping_size,
"Multi-token mapping write out of bounds: idx=",
@@ -437,6 +496,7 @@ public:
", got ",
selected_count);
OPENVINO_ASSERT(mapping_idx == expected_mapping_size, "Unexpected multi-token mapping size: expected ", expected_mapping_size, ", got ", mapping_idx);
+ OPENVINO_ASSERT(small_q_idx == expected_small_q_size, "Unexpected small-q mapping size: expected ", expected_small_q_size, ", got ", small_q_idx);
rt_params->single_token_selected_count = selected_count;
}
@@ -548,6 +608,10 @@ public:
res_event = {execute_stage(res_event, instance, pa_single_token)};
res_event = {execute_stage(res_event, instance, pa_single_token_finalization)};
}
+ if (rt_params->small_q_token_count > 0) {
+ res_event = {execute_stage(res_event, instance, pa_small_q)};
+ res_event = {execute_stage(res_event, instance, pa_small_q_finalization)};
+ }
execute_multi_token_path();
} else {
prepare_multi_token_mapping(instance);
@@ -605,6 +669,8 @@ public:
int64_t decode_buf_elements_count = 16;
const bool needs_single_token_buffers =
stage == PagedAttentionStage::MIXED && m_mixed_route_mode == MixedRouteMode::SPLIT && rt_params->single_token_selected_count > 0;
+ const bool needs_small_q_buffers =
+ stage == PagedAttentionStage::MIXED && m_mixed_route_mode == MixedRouteMode::SPLIT && rt_params->small_q_token_count > 0;
if (needs_single_token_buffers) {
OPENVINO_ASSERT(rt_params->num_of_partitions != 0);
decode_buf_elements_count = static_cast<int64_t>(rt_params->single_token_selected_count * desc->heads_num * rt_params->num_of_partitions);
@@ -665,7 +731,34 @@ public:
<< " count_elements_mask_merged=" << count_elements_mask_merged << " count_meta_int32s=" << count_meta_int32s
<< " count_find_map_int32s=" << count_find_map_int32s << " count_post_map_int32s=" << count_post_map_int32s
<< std::endl;
+ } else {
+ const size_t pad_to_index = static_cast<size_t>(PagedAttentionInternBuffIdx::SMALL_Q_PARTITIONOUT);
+ while (internal_buffers.size() < pad_to_index) {
+ internal_buffers.emplace_back(1, ov::element::i32, true, false);
+ }
+ }
+
+ // Small-q decode scratch buffers. Always emitted in MIXED so the small-q stage
+ // can be added unconditionally; sized to 1 when not used to avoid wasted memory.
+ //
+ // Layout notes: pa_small_q writes partition output as tile-major
+ // [tile_count * TILE_Q, head, partition, head_size]
+ // so buffers are sized by (tile_count * TILE_Q), NOT by small_q_token_count
+ // (padded tail rows in a tile need slots too).
+ // Mapping buffer is triples (orig_seq_idx, q_start, valid_count) per tile.
+ int64_t small_q_tmp_out_elems = 16;
+ int64_t small_q_buf_elems = 16;
+ int64_t small_q_mapping_elems = 3;
+ if (needs_small_q_buffers) {
+ OPENVINO_ASSERT(rt_params->num_of_partitions != 0);
+ const size_t partition_token_rows = rt_params->small_q_tile_count * static_cast<size_t>(std::max(1, rt_params->small_q_tile_q));
+ small_q_buf_elems = static_cast<int64_t>(partition_token_rows * desc->heads_num * rt_params->num_of_partitions);
+ small_q_tmp_out_elems = static_cast<int64_t>(partition_token_rows * desc->heads_num * desc->v_head_size * rt_params->num_of_partitions);
+ small_q_mapping_elems = static_cast<int64_t>(rt_params->small_q_tile_count * 3);
}
+ internal_buffers.emplace_back(small_q_tmp_out_elems, ov::element::f32); // SMALL_Q_PARTITIONOUT
+ internal_buffers.emplace_back(small_q_buf_elems, ov::element::f32); // SMALL_Q_EXPSUMS
+ internal_buffers.emplace_back(small_q_mapping_elems, ov::element::i32, true, false); // SMALL_Q_SELECTED_MAPPING
}
return internal_buffers;
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/paged_attention_gen.cpp b/src/plugins/intel_gpu/src/graph/impls/cm/paged_attention_gen.cpp
index 27778bab936..33ac788b835 100644
--- a/src/plugins/intel_gpu/src/graph/impls/cm/paged_attention_gen.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/paged_attention_gen.cpp
@@ -22,8 +22,24 @@ using namespace ov;
using namespace ov::intel_gpu::ocl;
using namespace cldnn;
namespace {
+// single_token finalization uses the original split (16 head_size columns per thread).
constexpr size_t reduce_split_step = 16;
constexpr size_t KV_SUB_BLOCK_SIZE = 16;
+
+// small_q finalization uses a larger split (64 by default) to reduce cross-partition
+// reduce overhead at long contexts — fewer threads but each does more work, amortising
+// fixed per-thread overhead (LSE read, launch cost). head_size (128) stays divisible.
+// Overridable via env OV_GPU_PA_SMALL_Q_REDUCE_SPLIT for A/B testing.
+inline size_t get_small_q_reduce_split_step() {
+ size_t v = 64;
+ if (const char* env = std::getenv("OV_GPU_PA_SMALL_Q_REDUCE_SPLIT")) {
+ int parsed = std::atoi(env);
+ if (parsed >= 1 && parsed <= 128) {
+ v = static_cast<size_t>(parsed);
+ }
+ }
+ return v;
+}
} // namespace
#define DEBUG_ENABLED 0
@@ -353,6 +369,10 @@ Arguments PagedAttentionGeneratorMultiToken::get_arguments_desc(const kernel_imp
args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::XATTN_BLOCKMASK_MERGED}); // sparse_block_mask_wg
args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::XATTN_SUBSEQ_META}); // xattn_subseq_meta
}
+ if (desc->has_qq_bias) {
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::QQ_BIAS}); // qq_bias
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::QQ_BIAS_BEGINS}); // qq_bias_begins
+ }
return args;
}
@@ -385,6 +405,12 @@ JitConstants PagedAttentionGeneratorMultiToken::get_jit_constants(const kernel_i
// regresses ~9% on FP16 (extra scratch matrix increases register pressure).
jit.make("CMFLA_USE_TREE_SOFTMAX", get_kv_compressed(params) ? 1 : 0);
+ if (desc->has_qq_bias) {
+ jit.make("HAS_QQ_BIAS", 1);
+ } else {
+ jit.make("HAS_QQ_BIAS", 0);
+ }
+
return jit;
}
@@ -576,6 +602,179 @@ DispatchDataFunc PagedAttentionGeneratorSingleTokenFinalization::get_dispatch_da
}};
}
+//-----------------------------------------------------------------------------------------------------------------
+// small-q decode generator (q_len > 1 spec-decoding subsequences)
+//-----------------------------------------------------------------------------------------------------------------
+JitConstants PagedAttentionGeneratorSmallQ::get_jit_constants(const kernel_impl_params& params) const {
+ auto jit = PagedAttentionGeneratorBase::get_jit_constants(params);
+ auto desc = params.typed_desc<paged_attention>();
+ const float scale_factor = 1.0f / std::sqrt(static_cast<float>(desc->k_head_size));
+ const size_t kv_partition_size = get_partition_size(desc->has_xattention);
+ jit.make("KV_PARTITION_SIZE", kv_partition_size);
+ if (desc->has_xattention) {
+ jit.make("KV_BLOCK_SIZE", PA_KV_CACHE_BLOCK_SIZE_XATTN);
+ } else {
+ jit.make("KV_BLOCK_SIZE", PA_KV_CACHE_BLOCK_SIZE_LEGACY);
+ }
+ jit.add(make_jit_constant("SCALE_FACTOR", scale_factor));
+ jit.make("HEAD_SIZE", desc->k_head_size);
+ jit.make("HEADS_NUM", desc->heads_num);
+ jit.make("KV_HEADS_NUM", desc->kv_heads_num);
+
+ const auto q_chunking = get_single_token_q_chunking(params, *desc, kv_partition_size);
+ jit.make("Q_head_chunks_per_kv_head", q_chunking.q_head_chunks_per_kv_head);
+ jit.make("Q_head_chunk_size", q_chunking.q_head_chunk_size);
+
+ // TILE_Q packs multiple q-tokens per SG. Constraint: Q_head_chunk_size*TILE_Q<=8
+ // (DPAS RepeatCount cap). Helper clamps automatically.
+ const int xe_arch = params.get_device_info().arch < gpu_arch::xe2 ? 1 : 2;
+ const int tile_q = get_small_q_tile_q(xe_arch, static_cast<int>(q_chunking.q_head_chunk_size));
+ jit.make("TILE_Q", tile_q);
+
+ // ONLINE_TILE_STEPS: online-softmax tile granularity. Overridable via env
+ // OV_GPU_PA_ONLINE_TILE_STEPS for A/B testing. Set to KV_PARTITION_STEP_NUM
+ // (= KV_PARTITION_SIZE / KV_STEP) to collapse online loop to 1 iter (behaves
+ // like the pre-online-softmax baseline for this partition size).
+ if (const char* env = std::getenv("OV_GPU_PA_ONLINE_TILE_STEPS")) {
+ int v = std::atoi(env);
+ if (v >= 1) {
+ jit.make("ONLINE_TILE_STEPS", v);
+ }
+ }
+
+ // Small-q kernel supports qq_bias speculative tree mask (u8 row-major [spec,spec]).
+ jit.make("HAS_QQ_BIAS", desc->has_qq_bias ? 1 : 0);
+ return jit;
+}
+
+Arguments PagedAttentionGeneratorSmallQ::get_arguments_desc(const kernel_impl_params& params) const {
+ Arguments args;
+ const auto desc = params.typed_desc<paged_attention>();
+ const auto has_scores_output = params.output_layouts.size() > 1;
+ OPENVINO_ASSERT(!has_scores_output, "[GPU][CM] PagedAttentionGeneratorSmallQ with scores output is not supported yet");
+
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::QUERY});
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::KEY_CACHE});
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::VALUE_CACHE});
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::PAST_LENS});
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::BLOCK_INDICES});
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::BLOCK_INDICES_BEGINS});
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::SUBSEQUENCE_BEGINS});
+ if (desc->has_qq_bias) {
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::QQ_BIAS});
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::QQ_BIAS_BEGINS});
+ }
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::SMALL_Q_SELECTED_MAPPING});
+
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::SMALL_Q_PARTITIONOUT});
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::SMALL_Q_EXPSUMS});
+
+ args.push_back({ArgumentDescriptor::Types::SCALAR, 0}); // q_len_unused (kept for ABI parity with single-token)
+ args.push_back({ArgumentDescriptor::Types::SCALAR, 1}); // selected_token_count
+
+ return args;
+}
+
+DispatchDataFunc PagedAttentionGeneratorSmallQ::get_dispatch_data_func() const {
+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {
+ OPENVINO_ASSERT(!params.is_dynamic());
+ auto& wgs = kd.params.workGroups;
+ const auto desc = params.typed_desc<paged_attention>();
+ auto rtp = static_cast<PagedAttentionRuntimeParams*>(rt_params);
+ OPENVINO_ASSERT(rt_params != nullptr);
+
+ const size_t kv_heads_num = desc->kv_heads_num;
+ const size_t partition_num = rtp->num_of_partitions;
+
+ OPENVINO_ASSERT(rtp->q_chunking.q_head_chunks_per_kv_head > 0, "Invalid q_head_chunks_per_kv_head in runtime params");
+ // gws[0] = tile count (one SG per TILE_Q consecutive q-tokens of a subseq).
+ // selected_token_count scalar carries tile_count too (kernel indexes mapping triples).
+ const size_t tile_count = rtp->small_q_tile_count;
+ wgs.global = {tile_count, kv_heads_num * static_cast<size_t>(rtp->q_chunking.q_head_chunks_per_kv_head), partition_num};
+ wgs.local = {1, 1, 1};
+
+ auto& scalars = kd.params.scalars;
+ std::vector<size_t> scaler_value = {1, tile_count};
+ scalars.resize(scaler_value.size());
+ for (size_t i = 0; i < scaler_value.size(); ++i) {
+ scalars[i].t = ScalarDescriptor::Types::INT32;
+ scalars[i].v.s32 = static_cast<int32_t>(scaler_value[i]);
+ }
+
+ if (DEBUG_ENABLED) {
+ std::cout << "PagedAttentionGeneratorSmallQ::get_dispatch_data_func: small_q_tokens=" << rtp->small_q_token_count << ", tile_count=" << tile_count
+ << ", TILE_Q=" << rtp->small_q_tile_q << ", partition_num=" << partition_num << ", gws=[" << wgs.global[0] << ", " << wgs.global[1]
+ << ", " << wgs.global[2] << "]\n";
+ }
+ }};
+}
+
+//-----------------------------------------------------------------------------------------------------------------
+// small-q finalization generator
+//-----------------------------------------------------------------------------------------------------------------
+JitConstants PagedAttentionGeneratorSmallQFinalization::get_jit_constants(const kernel_impl_params& params) const {
+ auto jit = PagedAttentionGeneratorBase::get_jit_constants(params);
+ const auto desc = params.typed_desc<paged_attention>();
+ jit.make("REDUCE_SPLIT_SIZE", get_small_q_reduce_split_step());
+ jit.make("HEAD_SIZE", desc->k_head_size);
+ jit.make("HEADS_NUM", desc->heads_num);
+
+ // Finalization decomposes token_row into (tile_idx, t_in_tile) via TILE_Q,
+ // so TILE_Q must match PagedAttentionGeneratorSmallQ.
+ const auto sq_partition_size = PagedAttentionGeneratorSingleToken::get_partition_size(desc->has_xattention);
+ const auto sq_q_chunking = get_single_token_q_chunking(params, *desc, sq_partition_size);
+ const int xe_arch = params.get_device_info().arch < gpu_arch::xe2 ? 1 : 2;
+ const int tile_q = get_small_q_tile_q(xe_arch, static_cast<int>(sq_q_chunking.q_head_chunk_size));
+ jit.make("TILE_Q", tile_q);
+ return jit;
+}
+
+Arguments PagedAttentionGeneratorSmallQFinalization::get_arguments_desc(const kernel_impl_params& params) const {
+ Arguments args;
+ const auto has_scores_output = params.output_layouts.size() > 1;
+ if (has_scores_output)
+ OPENVINO_THROW("[GPU][CM] PagedAttentionGeneratorSmallQFinalization with scores output is not supported yet");
+
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::SMALL_Q_PARTITIONOUT});
+ args.push_back({ArgumentDescriptor::Types::OUTPUT, 0});
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::SMALL_Q_EXPSUMS});
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::SUBSEQUENCE_BEGINS});
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::SMALL_Q_SELECTED_MAPPING});
+
+ args.push_back({ArgumentDescriptor::Types::SCALAR, 0}); // selected_token_count
+ args.push_back({ArgumentDescriptor::Types::SCALAR, 1}); // kv_partition_num
+ return args;
+}
+
+DispatchDataFunc PagedAttentionGeneratorSmallQFinalization::get_dispatch_data_func() const {
+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {
+ OPENVINO_ASSERT(!params.is_dynamic());
+ auto& wgs = kd.params.workGroups;
+ const auto desc = params.typed_desc<paged_attention>();
+ auto rtp = static_cast<PagedAttentionRuntimeParams*>(rt_params);
+ OPENVINO_ASSERT(rt_params != nullptr);
+
+ const size_t heads_num = desc->heads_num;
+ const size_t head_size = desc->k_head_size;
+ // Partition buffer is [tile_count * TILE_Q, head, partition, head_size] — one row
+ // per potential q-token slot (including padding). Finalization walks all these
+ // rows; padded rows early-return via t_in_tile >= valid_count check.
+ const size_t partition_token_rows = rtp->small_q_tile_count * static_cast<size_t>(std::max(1, rtp->small_q_tile_q));
+ const size_t sq_reduce_step = get_small_q_reduce_split_step();
+ wgs.global = {partition_token_rows, heads_num, head_size / sq_reduce_step};
+ wgs.local = {1, 1, 1};
+
+ auto& scalars = kd.params.scalars;
+ const size_t partition_num = rtp->num_of_partitions;
+ std::vector<size_t> scaler_value = {partition_token_rows, partition_num};
+ scalars.resize(scaler_value.size());
+ for (size_t i = 0; i < scaler_value.size(); ++i) {
+ scalars[i].t = ScalarDescriptor::Types::INT32;
+ scalars[i].v.s32 = static_cast<int32_t>(scaler_value[i]);
+ }
+ }};
+}
+
//-----------------------------------------------------------------------------------------------------------------
// Helpers of XAttention
//-----------------------------------------------------------------------------------------------------------------
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/paged_attention_gen.hpp b/src/plugins/intel_gpu/src/graph/impls/cm/paged_attention_gen.hpp
index 8bf062bbeed..85fb29abe02 100644
--- a/src/plugins/intel_gpu/src/graph/impls/cm/paged_attention_gen.hpp
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/paged_attention_gen.hpp
@@ -6,6 +6,7 @@
#include <algorithm>
#include <array>
+#include <cstdlib>
#include <memory>
#include <utility>
@@ -84,6 +85,30 @@ inline std::string get_pa_build_options() {
return " -cmc -Qxcm_register_file_size=" + std::to_string(PA_CM_REGISTER_FILE_SIZE);
}
+// TILE_Q: how many q-tokens each pa_small_q SG packs into the DPAS M dim.
+// Constraint: Q_head_chunk_size * TILE_Q <= 8 (DPAS RepeatCount cap).
+// Default: 2 on xe2/xe3 (satiates DPAS at Q_ROWS=8 for GQA-4), 1 on xe1
+// (register file half as big → wider M spills). Overridable via env
+// OV_GPU_PA_TILE_Q for testing.
+//
+// The caller is responsible for clamping to at most (8 / q_head_chunk_size).
+inline int get_small_q_tile_q_raw(int xe_arch) {
+ int default_val = (xe_arch >= 2) ? 2 : 1;
+ if (const char* env = std::getenv("OV_GPU_PA_TILE_Q")) {
+ int v = std::atoi(env);
+ if (v >= 1 && v <= 8) {
+ default_val = v;
+ }
+ }
+ return default_val;
+}
+
+inline int get_small_q_tile_q(int xe_arch, int q_head_chunk_size) {
+ int tile_q = get_small_q_tile_q_raw(xe_arch);
+ const int max_tile_q = std::max(1, 8 / std::max(1, q_head_chunk_size));
+ return std::min(tile_q, max_tile_q);
+}
+
#define FIND_DEBUG_ACC 0
// The block size for KV cache is set to 256 for xattn to achieve better performance.
// For non-xattn case, it can be set to 16 for compatibility to legacy implementations.
@@ -96,6 +121,12 @@ constexpr int STRIDE = 16;
enum class PagedAttentionStage : uint8_t { GENERATE = 0, PREFILL = 1, MIXED = 2, UNKNOWN = 3 };
enum class MixedRouteMode : uint8_t { MULTI = 0, SPLIT = 1 };
+
+// Subsequences with q_len in (1, SMALL_Q_THRESHOLD] and past_len > 0 are routed
+// to pa_small_q in split-mixed mode. Bound matches the typical EAGLE/draft
+// spec_num = 16 and the Q_head_chunk_size × KV_PARTITION_STEP_NUM register
+// budget that fits the rS tile under -Qxcm_register_file_size.
+constexpr size_t SMALL_Q_THRESHOLD = 16;
struct PagedAttentionRuntimeParams : public ImplRuntimeParams {
// common runtime state
PagedAttentionStage stage; // Current PA execution stage
@@ -110,6 +141,12 @@ struct PagedAttentionRuntimeParams : public ImplRuntimeParams {
// multi-token dispatch size
size_t multi_token_wg_count = 0; // Number of WGs required by pa_multi_token
+ // small-q decode path (q_len > 1 spec-decoding subsequences)
+ size_t small_q_token_count = 0; // Total (subseq, q-token) pairs routed to pa_small_q
+ size_t small_q_tile_count = 0; // Number of SG tiles = ceil_div(small_q_token_count, TILE_Q)
+ int small_q_tile_q = 1; // TILE_Q value chosen at JIT time (must match kernel)
+ size_t small_q_max_kv_len = 0; // Max kv_len across small-q subsequences (for partition count)
+
// xattention runtime state
bool enable_xattn_estimation = false; // Whether xattn estimate stages are enabled
size_t xattn_block_size = 1; // Selected xattn sparse block size (1/128/256)
@@ -147,6 +184,14 @@ enum PagedAttentionInternBuffIdx {
XATTN_POST_WG_MAP = 10, // 10: i32 pairs [subseq_id, merged_q_block_idx] for post-proc dispatch
#if FIND_DEBUG_ACC
XATTN_FIND_DEBUG_ACC = 11, // 11: f16 debug-only KQ accumulation buffer
+ SMALL_Q_PARTITIONOUT = 12,
+ SMALL_Q_EXPSUMS = 13,
+ SMALL_Q_SELECTED_MAPPING = 14,
+#else
+ // Small-q decode scratch buffers (q_len > 1 spec-decoding path).
+ SMALL_Q_PARTITIONOUT = 11, // f32 partial outputs indexed by (sel_idx, head, partition, head_size)
+ SMALL_Q_EXPSUMS = 12, // f32 lse per (sel_idx, head, partition)
+ SMALL_Q_SELECTED_MAPPING = 13, // triples (orig_seq_idx, q_start, valid_count)
#endif
};
@@ -243,6 +288,31 @@ public:
[[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override;
};
+// Small-q decode kernel for q_len > 1 subsequences. GWS fans the (subseq, q-token,
+// kv-partition, head-chunk) combinations out one per SG; reuses pa_single_token's
+// per-partition FA layout but indexes everything by a packed sel_idx.
+class PagedAttentionGeneratorSmallQ : public PagedAttentionGeneratorBase {
+public:
+ PagedAttentionGeneratorSmallQ() : PagedAttentionGeneratorBase("pa_small_q") {}
+ [[nodiscard]] JitConstants get_jit_constants(const kernel_impl_params& params) const override;
+ [[nodiscard]] Arguments get_arguments_desc(const kernel_impl_params& params) const override;
+ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override;
+
+ // Reuse single-token's partition-size policy: spec windows are short relative
+ // to past KV, so the large 256-token partition still amortises K/V loads well.
+ static size_t get_partition_size(const bool has_xattention = false) {
+ return PagedAttentionGeneratorSingleToken::get_partition_size(has_xattention);
+ }
+};
+
+class PagedAttentionGeneratorSmallQFinalization : public PagedAttentionGeneratorBase {
+public:
+ PagedAttentionGeneratorSmallQFinalization() : PagedAttentionGeneratorBase("pa_small_q_finalization") {}
+ [[nodiscard]] JitConstants get_jit_constants(const kernel_impl_params& params) const override;
+ [[nodiscard]] Arguments get_arguments_desc(const kernel_impl_params& params) const override;
+ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override;
+};
+
//-----------------------------------------------------------------------------------------------------------------
// XAttention Estimate generators
//-----------------------------------------------------------------------------------------------------------------
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_kv_reorder.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_kv_reorder.hpp
index a6084b7463c..a0a192719f9 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_kv_reorder.hpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_kv_reorder.hpp
@@ -7,6 +7,7 @@
#include <memory>
#include <utility>
+#include "intel_gpu/primitives/pa_kv_reorder.hpp"
#include "program_node.h"
#include "registry/implementation_manager.hpp"
@@ -23,7 +24,9 @@ struct PA_KV_reorder : public ImplementationManager {
[[nodiscard]] bool validate_impl(const program_node& node) const override {
if (node.has_fused_primitives())
return false;
- return true;
+
+ const auto desc = node.as<cldnn::pa_kv_reorder>().get_primitive();
+ return !desc->has_xattention;
}
};
diff --git a/src/plugins/intel_gpu/src/graph/registry/pa_kv_reorder_impls.cpp b/src/plugins/intel_gpu/src/graph/registry/pa_kv_reorder_impls.cpp
index 33519183504..431fa757059 100644
--- a/src/plugins/intel_gpu/src/graph/registry/pa_kv_reorder_impls.cpp
+++ b/src/plugins/intel_gpu/src/graph/registry/pa_kv_reorder_impls.cpp
@@ -10,13 +10,20 @@
# include "impls/ocl_v2/pa_kv_reorder.hpp"
#endif
+#if OV_GPU_WITH_CM
+# include "impls/cm/pa_kv_reorder.hpp"
+#endif
+
namespace ov {
namespace intel_gpu {
using namespace cldnn;
const std::vector<std::shared_ptr<cldnn::ImplementationManager>>& Registry<pa_kv_reorder>::get_implementations() {
- static const std::vector<std::shared_ptr<ImplementationManager>> impls = {OV_GPU_CREATE_INSTANCE_OCL(ocl::PA_KV_reorder, shape_types::any)};
+ static const std::vector<std::shared_ptr<ImplementationManager>> impls = {
+ OV_GPU_CREATE_INSTANCE_OCL(ocl::PA_KV_reorder, shape_types::any)
+ OV_GPU_CREATE_INSTANCE_CM(cm::PaKVReorderImplementationManager, shape_types::any)
+ };
return impls;
}
diff --git a/src/plugins/intel_gpu/src/plugin/ops/pa_kv_reorder.cpp b/src/plugins/intel_gpu/src/plugin/ops/pa_kv_reorder.cpp
index 65c3a81271d..1d72d398f27 100644
--- a/src/plugins/intel_gpu/src/plugin/ops/pa_kv_reorder.cpp
+++ b/src/plugins/intel_gpu/src/plugin/ops/pa_kv_reorder.cpp
@@ -10,6 +10,7 @@
#include "intel_gpu/plugin/program_builder.hpp"
#include "intel_gpu/primitives/pa_kv_reorder.hpp"
#include "intel_gpu/primitives/paged_attention.hpp"
+#include "openvino/core/model.hpp"
#include "openvino/runtime/internal_properties.hpp"
namespace ov {
@@ -61,6 +62,14 @@ static void CreatePA_KV_ReorderOp(ProgramBuilder& p, const std::shared_ptr<ov::o
prim.is_kv_compressed = prim.scales_zp_size > 0;
prim.is_key_by_channel = (key_cache_quant_mode == ov::internal::CacheQuantMode::BY_CHANNEL);
+ if (auto model = p.get_model()) {
+ const auto& model_rt_info = model->get_rt_info();
+ const auto it = model_rt_info.find("sparse_enabled");
+ if (it != model_rt_info.end()) {
+ prim.has_xattention = it->second.as<bool>();
+ }
+ }
+
const auto key_cache_ps = op->get_input_partial_shape(cldnn::pa_kv_reorder::PaKVReorderInputIdx::KEY_CACHE);
const auto value_cache_ps = op->get_input_partial_shape(cldnn::pa_kv_reorder::PaKVReorderInputIdx::VALUE_CACHE);
@@ -83,7 +92,8 @@ static void CreatePA_KV_ReorderOp(ProgramBuilder& p, const std::shared_ptr<ov::o
const size_t k_head_size = rt_info.at(k_head_size_id).as<int64_t>();
const size_t v_head_size = rt_info.at(v_head_size_id).as<int64_t>();
const size_t kv_heads_num = rt_info.at(num_k_heads_id).as<int64_t>();
- const size_t block_size = cldnn::paged_attention::block_size;
+
+ const size_t block_size = prim.has_xattention ? cldnn::paged_attention::block_size_xattn : cldnn::paged_attention::block_size;
prim.kv_heads_num = kv_heads_num;
if (prim.is_kv_compressed) {
diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/pa_kv_reorder_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/pa_kv_reorder_gpu_test.cpp
index 18d92e55f57..8d0fcf720a1 100644
--- a/src/plugins/intel_gpu/tests/unit/test_cases/pa_kv_reorder_gpu_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/test_cases/pa_kv_reorder_gpu_test.cpp
@@ -11,6 +11,7 @@
#include <type_traits>
#include <vector>
+#include "graph/impls/ocl/kernel_selector_helper.h" // check_cm_jit_support
#include "test_utils.h"
using namespace cldnn;
@@ -262,6 +263,72 @@ void fill_value_cache(memory::ptr value_cache_mem,
set_values(value_cache_mem, values);
}
+// ---------------------------------------------------------------------------------------------
+// CM kernel path (impls/cm/pa_kv_cache_reorder_ref.cm).
+//
+// The CM kernel is selected when has_xattention is set: cm::PaKVReorderImplementationManager
+// requires it and ocl::PA_KV_reorder rejects it, so the two managers are mutually exclusive and
+// no force_implementations is needed.
+//
+// CM uses its own cache layout, different from the OCL one the helpers above describe:
+// K: token-major data [BLOCK_SIZE][K_HEAD_SIZE], then all scales, then all zps, each indexed
+// as [sub][channel]. Per-channel quant groups are SUB_BLOCK_SIZE tokens.
+// V: per-token rows [BLOCK_SIZE][V_HEAD_SIZE], then BLOCK_SIZE scales, then BLOCK_SIZE zps.
+// ---------------------------------------------------------------------------------------------
+
+// Mirrors reorder_sub_block_size in impls/cm/pa_kv_reorder.cpp.
+constexpr size_t cm_sub_block_size = 16;
+
+bool cm_reorder_available() {
+ auto& engine = tests::get_test_engine();
+ auto config = tests::get_test_default_config(engine);
+ return cldnn::check_cm_jit_support(engine, config) && engine.get_device_info().supports_immad;
+}
+
+size_t cm_key_head_base(size_t block, size_t head, size_t kv_heads, size_t k_head_size, size_t block_size) {
+ const size_t per_head = k_head_size * (block_size + block_size / cm_sub_block_size * 2 * sizeof(ov::float16));
+ return (block * kv_heads + head) * per_head;
+}
+
+size_t cm_key_data_offset(size_t block, size_t head, size_t slot, size_t channel, size_t kv_heads, size_t k_head_size, size_t block_size) {
+ return cm_key_head_base(block, head, kv_heads, k_head_size, block_size) + slot * k_head_size + channel;
+}
+
+// byte offset of the fp16 scale (is_zp == false) or zp (is_zp == true) of one (sub-block, channel).
+size_t cm_key_comp_offset(size_t block,
+ size_t head,
+ size_t sub,
+ size_t channel,
+ bool is_zp,
+ size_t kv_heads,
+ size_t k_head_size,
+ size_t block_size) {
+ const size_t num_subs = block_size / cm_sub_block_size;
+ const size_t comp_base = cm_key_head_base(block, head, kv_heads, k_head_size, block_size) + k_head_size * block_size;
+ const size_t region = is_zp ? num_subs * k_head_size : 0;
+ return comp_base + (region + sub * k_head_size + channel) * sizeof(ov::float16);
+}
+
+size_t cm_value_head_base(size_t block, size_t head, size_t kv_heads, size_t v_head_size, size_t block_size) {
+ const size_t per_head = (v_head_size + 2 * sizeof(ov::float16)) * block_size;
+ return (block * kv_heads + head) * per_head;
+}
+
+size_t cm_value_data_offset(size_t block, size_t head, size_t slot, size_t v, size_t kv_heads, size_t v_head_size, size_t block_size) {
+ return cm_value_head_base(block, head, kv_heads, v_head_size, block_size) + slot * v_head_size + v;
+}
+
+size_t cm_value_comp_offset(size_t block, size_t head, size_t slot, bool is_zp, size_t kv_heads, size_t v_head_size, size_t block_size) {
+ const size_t comp_base = cm_value_head_base(block, head, kv_heads, v_head_size, block_size) + v_head_size * block_size;
+ return comp_base + ((is_zp ? block_size : 0) + slot) * sizeof(ov::float16);
+}
+
+void write_fp16_at(std::vector<uint8_t>& buffer, size_t byte_offset, float value) {
+ const auto bits = ov::float16(value).to_bits();
+ buffer[byte_offset] = static_cast<uint8_t>(bits & 0xFF);
+ buffer[byte_offset + 1] = static_cast<uint8_t>((bits >> 8) & 0xFF);
+}
+
} // namespace
TEST(pa_kv_reorder_gpu, copy_between_blocks_single_sequence) {
@@ -1076,3 +1143,454 @@ TEST(pa_kv_reorder_gpu, copy_between_blocks_single_sequence_compressed_u4_key_by
value_cache_ref[value_comp_byte_offset_int4_per_token(0, 0, 0, byte, true, kv_heads, packed_v_head_size, adjusted_v_head_size, block_size)]);
}
}
+
+// ---- CM kernel path ------------------------------------------------------------------------
+
+namespace {
+
+constexpr size_t cm_blocks_num = 2;
+constexpr size_t cm_kv_heads = 1;
+constexpr size_t cm_k_head_size = 16;
+constexpr size_t cm_v_head_size = 16;
+// The CM impl is only reachable with has_xattention, which pairs with the 256-token block size.
+constexpr size_t cm_block_size = cldnn::paged_attention::block_size_xattn;
+constexpr size_t cm_num_subs = cm_block_size / cm_sub_block_size;
+constexpr size_t cm_scales_zp_size = 2 * sizeof(ov::float16);
+
+layout cm_key_layout() {
+ return layout{ov::PartialShape{static_cast<int64_t>(cm_blocks_num),
+ static_cast<int64_t>(cm_kv_heads),
+ static_cast<int64_t>(cm_k_head_size),
+ static_cast<int64_t>(cm_block_size + cm_num_subs * cm_scales_zp_size)},
+ data_types::u8,
+ format::bfyx};
+}
+
+layout cm_value_layout() {
+ return layout{ov::PartialShape{static_cast<int64_t>(cm_blocks_num),
+ static_cast<int64_t>(cm_kv_heads),
+ static_cast<int64_t>(cm_block_size),
+ static_cast<int64_t>(cm_v_head_size + cm_scales_zp_size)},
+ data_types::u8,
+ format::bfyx};
+}
+
+size_t cm_k_off(size_t block, size_t slot, size_t channel) {
+ return cm_key_data_offset(block, 0, slot, channel, cm_kv_heads, cm_k_head_size, cm_block_size);
+}
+
+size_t cm_k_comp_off(size_t block, size_t sub, size_t channel, bool is_zp) {
+ return cm_key_comp_offset(block, 0, sub, channel, is_zp, cm_kv_heads, cm_k_head_size, cm_block_size);
+}
+
+size_t cm_v_off(size_t block, size_t slot, size_t v) {
+ return cm_value_data_offset(block, 0, slot, v, cm_kv_heads, cm_v_head_size, cm_block_size);
+}
+
+size_t cm_v_comp_off(size_t block, size_t slot, bool is_zp) {
+ return cm_value_comp_offset(block, 0, slot, is_zp, cm_kv_heads, cm_v_head_size, cm_block_size);
+}
+
+// Every K sub-block starts with scale_inv = 1 and zp = 0, so a stored byte dequantizes to
+// itself. That keeps the expected values in the assertions readable.
+void cm_fill_caches(std::vector<uint8_t>& key_ref, std::vector<uint8_t>& value_ref) {
+ for (size_t b = 0; b < cm_blocks_num; b++) {
+ for (size_t t = 0; t < cm_block_size; t++) {
+ for (size_t c = 0; c < cm_k_head_size; c++) {
+ key_ref[cm_k_off(b, t, c)] = static_cast<uint8_t>((7 * t + 3 * c + b) % 256);
+ }
+ for (size_t v = 0; v < cm_v_head_size; v++) {
+ value_ref[cm_v_off(b, t, v)] = static_cast<uint8_t>((5 * t + 11 * v + b) % 256);
+ }
+ write_fp16_at(value_ref, cm_v_comp_off(b, t, false), 0.25f * static_cast<float>(1 + (t % 3)));
+ write_fp16_at(value_ref, cm_v_comp_off(b, t, true), static_cast<float>((t % 5) - 2));
+ }
+ for (size_t s = 0; s < cm_num_subs; s++) {
+ for (size_t c = 0; c < cm_k_head_size; c++) {
+ write_fp16_at(key_ref, cm_k_comp_off(b, s, c, false), 1.0f);
+ write_fp16_at(key_ref, cm_k_comp_off(b, s, c, true), 0.0f);
+ }
+ }
+ }
+}
+
+void cm_run_by_channel_reorder(const std::vector<uint8_t>& key_ref,
+ const std::vector<uint8_t>& value_ref,
+ const std::vector<int32_t>& pairs,
+ std::vector<uint8_t>& key_out,
+ std::vector<uint8_t>& value_out) {
+ auto& engine = get_test_engine();
+
+ auto block_indices_layout = layout{ov::PartialShape{static_cast<int64_t>(cm_blocks_num)}, data_types::i32, format::bfyx};
+ auto block_indices_begins_layout = layout{ov::PartialShape{2}, data_types::i32, format::bfyx};
+ auto update_layout = layout{ov::PartialShape{static_cast<int64_t>(pairs.size())}, data_types::i32, format::bfyx};
+ auto update_begins_layout = layout{ov::PartialShape{2}, data_types::i32, format::bfyx};
+
+ auto key_mem = engine.allocate_memory(cm_key_layout());
+ auto value_mem = engine.allocate_memory(cm_value_layout());
+ auto block_indices_mem = engine.allocate_memory(block_indices_layout);
+ auto block_indices_begins_mem = engine.allocate_memory(block_indices_begins_layout);
+ auto update_mem = engine.allocate_memory(update_layout);
+ auto update_begins_mem = engine.allocate_memory(update_begins_layout);
+
+ set_values<uint8_t>(key_mem, key_ref);
+ set_values<uint8_t>(value_mem, value_ref);
+ set_values<int32_t>(block_indices_mem, {0, 1});
+ set_values<int32_t>(block_indices_begins_mem, {0, static_cast<int32_t>(cm_blocks_num)});
+ set_values<int32_t>(update_mem, pairs);
+ set_values<int32_t>(update_begins_mem, {0, static_cast<int32_t>(pairs.size() / 2)});
+
+ topology topo;
+ topo.add(mutable_data("key_cache", key_mem));
+ topo.add(mutable_data("value_cache", value_mem));
+ topo.add(input_layout("block_indices", block_indices_layout));
+ topo.add(input_layout("block_indices_begins", block_indices_begins_layout));
+ topo.add(input_layout("block_update_indices", update_layout));
+ topo.add(input_layout("block_update_indices_begins", update_begins_layout));
+
+ auto prim = pa_kv_reorder("pa_kv_reorder",
+ {input_info("key_cache"),
+ input_info("value_cache"),
+ input_info("block_indices"),
+ input_info("block_indices_begins"),
+ input_info("block_update_indices"),
+ input_info("block_update_indices_begins")});
+ prim.kv_heads_num = cm_kv_heads;
+ prim.adjusted_k_head_size = cm_k_head_size;
+ prim.adjusted_paged_attention_block_size = cm_block_size + cm_scales_zp_size;
+ prim.adjusted_v_head_size = cm_v_head_size + cm_scales_zp_size;
+ prim.cache_dt = data_types::u8;
+ prim.is_kv_compressed = true;
+ prim.is_key_by_channel = true;
+ prim.scales_zp_size = cm_scales_zp_size;
+
+ prim.has_xattention = true;
+ topo.add(prim);
+
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ auto network = get_network(engine, topo, config, get_test_stream_ptr(), false);
+
+ network->set_input_data("block_indices", block_indices_mem);
+ network->set_input_data("block_indices_begins", block_indices_begins_mem);
+ network->set_input_data("block_update_indices", update_mem);
+ network->set_input_data("block_update_indices_begins", update_begins_mem);
+ network->execute();
+ network->get_stream().finish();
+
+ cldnn::mem_lock<uint8_t, mem_lock_type::read> key_ptr(key_mem, network->get_stream());
+ cldnn::mem_lock<uint8_t, mem_lock_type::read> value_ptr(value_mem, network->get_stream());
+ key_out.assign(key_ptr.begin(), key_ptr.end());
+ value_out.assign(value_ptr.begin(), value_ptr.end());
+}
+
+} // namespace
+
+// src and dst share a physical block and a sub-block, so requantize_dst_subblock takes its fast
+// path: the quantized row is copied verbatim and scale/zp are left alone.
+TEST(pa_kv_reorder_gpu, cm_key_by_channel_same_sub_block_is_exact_copy) {
+ if (!cm_reorder_available())
+ GTEST_SKIP() << "CM JIT support and an Xe1+ device are required for the CM reorder kernel";
+
+ std::vector<uint8_t> key_ref(cm_key_layout().count(), 0);
+ std::vector<uint8_t> value_ref(cm_value_layout().count(), 0);
+ cm_fill_caches(key_ref, value_ref);
+
+ std::vector<uint8_t> key_out;
+ std::vector<uint8_t> value_out;
+ // Both slots live in block 0, sub-block 1.
+ cm_run_by_channel_reorder(key_ref, value_ref, {20, 25}, key_out, value_out);
+
+ for (size_t c = 0; c < cm_k_head_size; c++) {
+ ASSERT_EQ(key_out[cm_k_off(0, 25, c)], key_ref[cm_k_off(0, 20, c)]) << "channel " << c;
+
+ // No requantization: every other row and all scale/zp bytes stay byte-identical.
+ for (size_t t = 0; t < cm_block_size; t++) {
+ if (t == 25)
+ continue;
+ ASSERT_EQ(key_out[cm_k_off(0, t, c)], key_ref[cm_k_off(0, t, c)]) << "slot " << t << " channel " << c;
+ }
+ for (size_t s = 0; s < cm_num_subs; s++) {
+ for (bool is_zp : {false, true}) {
+ const auto off = cm_k_comp_off(0, s, c, is_zp);
+ ASSERT_EQ(key_out[off], key_ref[off]) << "sub " << s << " channel " << c << " is_zp " << is_zp;
+ ASSERT_EQ(key_out[off + 1], key_ref[off + 1]);
+ }
+ }
+ }
+}
+
+// dst lands in a sequence's last sub-block, which pa_kv_cache_update only partially filled.
+// touched_len = max(src, dst) + 1 must confine both the range recomputation and the stores to
+// the rows that were actually written.
+TEST(pa_kv_reorder_gpu, cm_key_by_channel_partial_sub_block_leaves_tail_untouched) {
+ if (!cm_reorder_available())
+ GTEST_SKIP() << "CM JIT support and an Xe1+ device are required for the CM reorder kernel";
+
+ // src 100 (block 0, sub-block 6) -> dst 264 (block 1, sub-block 0, row 8). Cross-block, so
+ // the slow path runs; touched_len = 265 leaves rows 0..8 valid and rows 9..15 never written.
+ constexpr size_t src_id = 100;
+ constexpr size_t dst_id = 264;
+ constexpr size_t dst_slot = dst_id - cm_block_size; // 8
+ constexpr size_t valid_rows = dst_slot + 1; // 9
+
+ std::vector<uint8_t> key_ref(cm_key_layout().count(), 0);
+ std::vector<uint8_t> value_ref(cm_value_layout().count(), 0);
+ cm_fill_caches(key_ref, value_ref);
+
+ constexpr float expected_range = 35.0f;
+ for (size_t c = 0; c < cm_k_head_size; c++) {
+ for (size_t r = 0; r < cm_sub_block_size; r++) {
+ key_ref[cm_k_off(1, r, c)] = (r < valid_rows) ? static_cast<uint8_t>(10 + 5 * r) : static_cast<uint8_t>(200 + r);
+ }
+ // scale_inv = 1 / zp = 0 for every sub-block, so this byte dequantizes to 30.
+ key_ref[cm_k_off(0, src_id, c)] = 30;
+ }
+
+ std::vector<uint8_t> key_out;
+ std::vector<uint8_t> value_out;
+ cm_run_by_channel_reorder(key_ref, value_ref, {static_cast<int32_t>(src_id), static_cast<int32_t>(dst_id)}, key_out, value_out);
+
+ for (size_t c = 0; c < cm_k_head_size; c++) {
+ for (size_t r = valid_rows; r < cm_sub_block_size; r++) {
+ ASSERT_EQ(key_out[cm_k_off(1, r, c)], key_ref[cm_k_off(1, r, c)]) << "tail row " << r << " channel " << c;
+ }
+
+ // scale/zp must describe the valid rows' range, not the tail's.
+ const float scale_inv = static_cast<float>(read_fp16_from_u8_vector(key_out, cm_k_comp_off(1, 0, c, false)));
+ const float zp = static_cast<float>(read_fp16_from_u8_vector(key_out, cm_k_comp_off(1, 0, c, true)));
+ ASSERT_NEAR(scale_inv, expected_range / 255.0f, 0.01f) << "channel " << c;
+
+ // Valid rows keep their values; the dst row now carries the src value.
+ for (size_t r = 0; r < valid_rows; r++) {
+ const float expected = (r == dst_slot) ? 30.0f : static_cast<float>(10 + 5 * r);
+ const float dequant = (static_cast<float>(key_out[cm_k_off(1, r, c)]) - zp) * scale_inv;
+ ASSERT_NEAR(dequant, expected, 0.3f) << "row " << r << " channel " << c;
+ }
+
+ // A sub-block the reorder never targets stays byte-identical.
+ for (size_t r = 0; r < cm_sub_block_size; r++) {
+ const size_t slot = cm_sub_block_size + r;
+ ASSERT_EQ(key_out[cm_k_off(1, slot, c)], key_ref[cm_k_off(1, slot, c)]) << "sub-block 1 row " << r;
+ }
+ }
+
+ // V is a plain per-token copy in this mode.
+ for (size_t v = 0; v < cm_v_head_size; v++) {
+ ASSERT_EQ(value_out[cm_v_off(1, dst_slot, v)], value_ref[cm_v_off(0, src_id, v)]) << "v " << v;
+ }
+ for (bool is_zp : {false, true}) {
+ const auto dst_off = cm_v_comp_off(1, dst_slot, is_zp);
+ const auto src_off = cm_v_comp_off(0, src_id, is_zp);
+ ASSERT_EQ(value_out[dst_off], value_ref[src_off]);
+ ASSERT_EQ(value_out[dst_off + 1], value_ref[src_off + 1]);
+ }
+}
+
+TEST(pa_kv_reorder_gpu, cm_key_by_channel_two_pairs_single_sequence) {
+ if (!cm_reorder_available())
+ GTEST_SKIP() << "CM JIT support and an Xe1+ device are required for the CM reorder kernel";
+
+ // Pair A: src 30 (block 0, sub-block 1) -> dst 264 (block 1, sub-block 0, row 8). dst is the
+ // largest position, so touched_len = 265 and this sub-block has 9 valid rows.
+ // Pair B: src 100 (block 0, sub-block 6) -> dst 50 (block 0, sub-block 3, row 2). Same block
+ // but a different sub-block, so it still takes the requantizing path; the sub-block
+ // sits well below touched_len, so all 16 rows are valid.
+ constexpr size_t a_src = 30;
+ constexpr size_t a_dst = 264;
+ constexpr size_t a_dst_slot = a_dst - cm_block_size; // 8
+ constexpr size_t a_valid_rows = a_dst_slot + 1; // 9
+
+ constexpr size_t b_src = 100;
+ constexpr size_t b_dst = 50;
+ constexpr size_t b_sub_first_slot = 48;
+ constexpr size_t b_dst_row = b_dst - b_sub_first_slot; // 2
+
+ std::vector<uint8_t> key_ref(cm_key_layout().count(), 0);
+ std::vector<uint8_t> value_ref(cm_value_layout().count(), 0);
+ cm_fill_caches(key_ref, value_ref);
+
+ // A's dst sub-block: rows 0..8 hold 10..50, the tail holds much larger never-written bytes.
+ // Row 8 is the dst and becomes 30, so the surviving values are 10..45 -> range 35.
+ constexpr float a_expected_range = 35.0f;
+ // B's dst sub-block: rows hold 60..90. Row 2 becomes 70, which is inside that span, so the
+ // range stays 30.
+ constexpr float b_expected_range = 30.0f;
+
+ for (size_t c = 0; c < cm_k_head_size; c++) {
+ for (size_t r = 0; r < cm_sub_block_size; r++) {
+ key_ref[cm_k_off(1, r, c)] = (r < a_valid_rows) ? static_cast<uint8_t>(10 + 5 * r) : static_cast<uint8_t>(200 + r);
+ key_ref[cm_k_off(0, b_sub_first_slot + r, c)] = static_cast<uint8_t>(60 + 2 * r);
+ }
+ // scale_inv = 1 / zp = 0 everywhere, so these bytes dequantize to themselves.
+ key_ref[cm_k_off(0, a_src, c)] = 30;
+ key_ref[cm_k_off(0, b_src, c)] = 70;
+ }
+
+ std::vector<uint8_t> key_out;
+ std::vector<uint8_t> value_out;
+ cm_run_by_channel_reorder(key_ref,
+ value_ref,
+ {static_cast<int32_t>(a_src),
+ static_cast<int32_t>(a_dst),
+ static_cast<int32_t>(b_src),
+ static_cast<int32_t>(b_dst)},
+ key_out,
+ value_out);
+
+ for (size_t c = 0; c < cm_k_head_size; c++) {
+ // ---- pair A: partial sub-block, tail must survive untouched.
+ for (size_t r = a_valid_rows; r < cm_sub_block_size; r++) {
+ ASSERT_EQ(key_out[cm_k_off(1, r, c)], key_ref[cm_k_off(1, r, c)]) << "A tail row " << r << " channel " << c;
+ }
+
+ const float a_scale = static_cast<float>(read_fp16_from_u8_vector(key_out, cm_k_comp_off(1, 0, c, false)));
+ const float a_zp = static_cast<float>(read_fp16_from_u8_vector(key_out, cm_k_comp_off(1, 0, c, true)));
+ ASSERT_NEAR(a_scale, a_expected_range / 255.0f, 0.01f) << "channel " << c;
+
+ for (size_t r = 0; r < a_valid_rows; r++) {
+ const float expected = (r == a_dst_slot) ? 30.0f : static_cast<float>(10 + 5 * r);
+ const float dequant = (static_cast<float>(key_out[cm_k_off(1, r, c)]) - a_zp) * a_scale;
+ ASSERT_NEAR(dequant, expected, 0.3f) << "A row " << r << " channel " << c;
+ }
+
+ // ---- pair B: full sub-block, every row requantized.
+ const float b_scale = static_cast<float>(read_fp16_from_u8_vector(key_out, cm_k_comp_off(0, 3, c, false)));
+ const float b_zp = static_cast<float>(read_fp16_from_u8_vector(key_out, cm_k_comp_off(0, 3, c, true)));
+ ASSERT_NEAR(b_scale, b_expected_range / 255.0f, 0.01f) << "channel " << c;
+
+ for (size_t r = 0; r < cm_sub_block_size; r++) {
+ const float expected = (r == b_dst_row) ? 70.0f : static_cast<float>(60 + 2 * r);
+ const float dequant = (static_cast<float>(key_out[cm_k_off(0, b_sub_first_slot + r, c)]) - b_zp) * b_scale;
+ ASSERT_NEAR(dequant, expected, 0.3f) << "B row " << r << " channel " << c;
+ }
+
+ // ---- sub-blocks that only supplied sources, or were never named, stay byte-identical.
+ for (size_t sub : {size_t{1}, size_t{6}}) {
+ for (size_t r = 0; r < cm_sub_block_size; r++) {
+ const size_t slot = sub * cm_sub_block_size + r;
+ ASSERT_EQ(key_out[cm_k_off(0, slot, c)], key_ref[cm_k_off(0, slot, c)]) << "block 0 sub " << sub << " row " << r;
+ }
+ for (bool is_zp : {false, true}) {
+ const auto off = cm_k_comp_off(0, sub, c, is_zp);
+ ASSERT_EQ(key_out[off], key_ref[off]) << "block 0 sub " << sub << " is_zp " << is_zp;
+ ASSERT_EQ(key_out[off + 1], key_ref[off + 1]);
+ }
+ }
+ for (size_t r = 0; r < cm_sub_block_size; r++) {
+ const size_t slot = cm_sub_block_size + r;
+ ASSERT_EQ(key_out[cm_k_off(1, slot, c)], key_ref[cm_k_off(1, slot, c)]) << "block 1 sub 1 row " << r;
+ }
+ }
+
+ // V is a plain per-token copy for both pairs.
+ for (size_t v = 0; v < cm_v_head_size; v++) {
+ ASSERT_EQ(value_out[cm_v_off(1, a_dst_slot, v)], value_ref[cm_v_off(0, a_src, v)]) << "A v " << v;
+ ASSERT_EQ(value_out[cm_v_off(0, b_dst, v)], value_ref[cm_v_off(0, b_src, v)]) << "B v " << v;
+ }
+ for (bool is_zp : {false, true}) {
+ ASSERT_EQ(value_out[cm_v_comp_off(1, a_dst_slot, is_zp)], value_ref[cm_v_comp_off(0, a_src, is_zp)]);
+ ASSERT_EQ(value_out[cm_v_comp_off(1, a_dst_slot, is_zp) + 1], value_ref[cm_v_comp_off(0, a_src, is_zp) + 1]);
+ ASSERT_EQ(value_out[cm_v_comp_off(0, b_dst, is_zp)], value_ref[cm_v_comp_off(0, b_src, is_zp)]);
+ ASSERT_EQ(value_out[cm_v_comp_off(0, b_dst, is_zp) + 1], value_ref[cm_v_comp_off(0, b_src, is_zp) + 1]);
+ }
+}
+
+TEST(pa_kv_reorder_gpu, cm_key_by_channel_chained_moves_single_sequence) {
+ if (!cm_reorder_available())
+ GTEST_SKIP() << "CM JIT support and an Xe1+ device are required for the CM reorder kernel";
+
+ // Pair 1: src 100 (block 0, sub-block 6, row 4) -> dst 20 (block 0, sub-block 1, row 4).
+ // Pair 2: src 300 (block 1, sub-block 2) -> dst 100 (the slot pair 1 just read).
+ constexpr size_t first_src = 100;
+ constexpr size_t first_src_sub = 6;
+ constexpr size_t first_src_row = first_src - first_src_sub * cm_sub_block_size; // 4
+ constexpr size_t first_dst = 20;
+ constexpr size_t first_dst_sub = 1;
+ constexpr size_t first_dst_row = first_dst - first_dst_sub * cm_sub_block_size; // 4
+
+ constexpr size_t second_src = 300;
+ constexpr size_t second_src_slot = second_src - cm_block_size; // 44
+ constexpr size_t second_dst = first_src;
+
+ std::vector<uint8_t> key_ref(cm_key_layout().count(), 0);
+ std::vector<uint8_t> value_ref(cm_value_layout().count(), 0);
+ cm_fill_caches(key_ref, value_ref);
+
+ // Sub-block 6 holds 40..100 (step 4), so slot 100 arrives holding 56. Sub-block 1 holds
+ // 30..105 (step 5). Block 1's source slot holds 77.
+ constexpr float relayed_value = 40.0f + 4.0f * static_cast<float>(first_src_row); // 56, 100 -> 20
+ constexpr float incoming_value = 77.0f; // 300 -> 100
+ // Pair 1 drops 56 into sub-block 1, inside its 30..105 span, so that range stays 75.
+ // Pair 2 drops 77 into sub-block 6, inside its 40..100 span, so that range stays 60.
+ constexpr float first_expected_range = 75.0f;
+ constexpr float second_expected_range = 60.0f;
+
+ for (size_t c = 0; c < cm_k_head_size; c++) {
+ for (size_t r = 0; r < cm_sub_block_size; r++) {
+ key_ref[cm_k_off(0, first_src_sub * cm_sub_block_size + r, c)] = static_cast<uint8_t>(40 + 4 * r);
+ key_ref[cm_k_off(0, first_dst_sub * cm_sub_block_size + r, c)] = static_cast<uint8_t>(30 + 5 * r);
+ }
+ // scale_inv = 1 / zp = 0 everywhere, so this byte dequantizes to incoming_value.
+ key_ref[cm_k_off(1, second_src_slot, c)] = static_cast<uint8_t>(incoming_value);
+ }
+
+ std::vector<uint8_t> key_out;
+ std::vector<uint8_t> value_out;
+ cm_run_by_channel_reorder(
+ key_ref,
+ value_ref,
+ {static_cast<int32_t>(first_src), static_cast<int32_t>(first_dst), static_cast<int32_t>(second_src), static_cast<int32_t>(second_dst)},
+ key_out,
+ value_out);
+
+ for (size_t c = 0; c < cm_k_head_size; c++) {
+ // ---- pair 1's dst sub-block: row 4 must hold what slot 100 contained on entry (56),
+ // not the 77 that pair 2 writes into slot 100 afterwards.
+ const float first_scale = static_cast<float>(read_fp16_from_u8_vector(key_out, cm_k_comp_off(0, first_dst_sub, c, false)));
+ const float first_zp = static_cast<float>(read_fp16_from_u8_vector(key_out, cm_k_comp_off(0, first_dst_sub, c, true)));
+ ASSERT_NEAR(first_scale, first_expected_range / 255.0f, 0.01f) << "channel " << c;
+
+ for (size_t r = 0; r < cm_sub_block_size; r++) {
+ const float expected = (r == first_dst_row) ? relayed_value : static_cast<float>(30 + 5 * r);
+ const float dequant = (static_cast<float>(key_out[cm_k_off(0, first_dst_sub * cm_sub_block_size + r, c)]) - first_zp) * first_scale;
+ ASSERT_NEAR(dequant, expected, 0.3f) << "pair 1 row " << r << " channel " << c;
+ }
+
+ // ---- pair 2's dst sub-block: the same sub-block pair 1 sourced from, now requantized
+ // with row 4 replaced by the value that came from block 1.
+ const float second_scale = static_cast<float>(read_fp16_from_u8_vector(key_out, cm_k_comp_off(0, first_src_sub, c, false)));
+ const float second_zp = static_cast<float>(read_fp16_from_u8_vector(key_out, cm_k_comp_off(0, first_src_sub, c, true)));
+ ASSERT_NEAR(second_scale, second_expected_range / 255.0f, 0.01f) << "channel " << c;
+
+ for (size_t r = 0; r < cm_sub_block_size; r++) {
+ const float expected = (r == first_src_row) ? incoming_value : static_cast<float>(40 + 4 * r);
+ const float dequant = (static_cast<float>(key_out[cm_k_off(0, first_src_sub * cm_sub_block_size + r, c)]) - second_zp) * second_scale;
+ ASSERT_NEAR(dequant, expected, 0.3f) << "pair 2 row " << r << " channel " << c;
+ }
+
+ // ---- the source sub-block in block 1 is only read, never written.
+ for (size_t r = 0; r < cm_sub_block_size; r++) {
+ const size_t slot = 2 * cm_sub_block_size + r;
+ ASSERT_EQ(key_out[cm_k_off(1, slot, c)], key_ref[cm_k_off(1, slot, c)]) << "block 1 sub 2 row " << r;
+ }
+ for (bool is_zp : {false, true}) {
+ const auto off = cm_k_comp_off(1, 2, c, is_zp);
+ ASSERT_EQ(key_out[off], key_ref[off]) << "block 1 sub 2 is_zp " << is_zp;
+ ASSERT_EQ(key_out[off + 1], key_ref[off + 1]);
+ }
+ }
+
+ // V is copied verbatim, so both hops are exact: slot 20 ends up with slot 100's entry bytes,
+ // and slot 100 with block 1's, scale and zp included.
+ for (size_t v = 0; v < cm_v_head_size; v++) {
+ ASSERT_EQ(value_out[cm_v_off(0, first_dst, v)], value_ref[cm_v_off(0, first_src, v)]) << "pair 1 v " << v;
+ ASSERT_EQ(value_out[cm_v_off(0, second_dst, v)], value_ref[cm_v_off(1, second_src_slot, v)]) << "pair 2 v " << v;
+ }
+ for (bool is_zp : {false, true}) {
+ ASSERT_EQ(value_out[cm_v_comp_off(0, first_dst, is_zp)], value_ref[cm_v_comp_off(0, first_src, is_zp)]);
+ ASSERT_EQ(value_out[cm_v_comp_off(0, first_dst, is_zp) + 1], value_ref[cm_v_comp_off(0, first_src, is_zp) + 1]);
+ ASSERT_EQ(value_out[cm_v_comp_off(0, second_dst, is_zp)], value_ref[cm_v_comp_off(1, second_src_slot, is_zp)]);
+ ASSERT_EQ(value_out[cm_v_comp_off(0, second_dst, is_zp) + 1], value_ref[cm_v_comp_off(1, second_src_slot, is_zp) + 1]);
+ }
+}
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 b5610dff62e..20957895997 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
@@ -20,6 +20,31 @@ TEST_P(xattention_test, basic) {
execute(p, p.run_reference);
}
+// Subsequences with q_len in (1, SMALL_Q_THRESHOLD] and past_len > 0 are routed to the CM
+// pa_small_q kernel in split-mixed mode (the default GPU_PA_MIXED_ROUTE_MODE). Reaching CM at all
+// requires has_xattention, since ocl::PagedAttentionOpt is registered first and only bails out on
+// that flag.
+class cm_small_q_test : public PagedAttentionTest<paged_attention_test_params> {};
+TEST_P(cm_small_q_test, basic) {
+ auto p = GetParam();
+ if (!check_cm_available())
+ GTEST_SKIP() << "CM JIT support is required for CM paged attention tests, and the device must be Xe1 or later";
+
+ execute(p, p.run_reference);
+}
+
+// qq_bias on the CM kernels. smoke_qq_bias covers the same masks on the OCL path; these cases add
+// has_xattention so the CM kernels carry the mask instead - pa_small_q.cm for the small-q
+// subsequences and cm_pa_xe*.hpp for the rest.
+class cm_qq_bias_test : public PagedAttentionTest<paged_attention_test_params> {};
+TEST_P(cm_qq_bias_test, basic) {
+ auto p = GetParam();
+ if (!check_cm_available())
+ GTEST_SKIP() << "CM JIT support is required for CM paged attention tests, and the device must be Xe1 or later";
+
+ execute(p, p.run_reference);
+}
+
class xattention_invalid_test : public PagedAttentionTest<paged_attention_test_params> {};
TEST_P(xattention_invalid_test, throws_on_invalid_xattention_inputs) {
auto p = GetParam();
@@ -69,6 +94,37 @@ static paged_attention_test_params disable_reference_compare(paged_attention_tes
return p;
}
+// n x n speculative-decoding tree mask: query i may attend key j when j is i itself or one of its
+// ancestors in a binary tree (parent of j is (j - 1) / 2), which is the shape EAGLE-style drafts
+// produce. The diagonal is always set, so no query row ends up fully masked.
+static std::vector<uint8_t> make_tree_mask(int n) {
+ std::vector<uint8_t> mask(static_cast<size_t>(n) * static_cast<size_t>(n), 0);
+ for (int i = 0; i < n; i++) {
+ for (int j = i;; j = (j - 1) / 2) {
+ mask[static_cast<size_t>(i) * static_cast<size_t>(n) + static_cast<size_t>(j)] = 1;
+ if (j == 0)
+ break;
+ }
+ }
+ return mask;
+}
+
+// One entry per subsequence, in order; 0 means "this subsequence carries no mask" (which is what
+// the harness expects for past_len == 0). qq_bias_begins holds cumulative element offsets.
+static QueryToQueryAttentionDescriptor make_tree_qq_bias(const std::vector<int>& masked_q_lens) {
+ QueryToQueryAttentionDescriptor desc;
+ int offset = 0;
+ desc.qq_bias_begins.push_back(0);
+ for (int q_len : masked_q_lens) {
+ if (q_len > 0) {
+ desc.qq_bias.push_back(make_tree_mask(q_len));
+ offset += q_len * q_len;
+ }
+ desc.qq_bias_begins.push_back(offset);
+ }
+ return desc;
+}
+
static std::vector<int32_t> gen_tokens_ids_test_data(size_t seq_len, int num_images, size_t avg_img_len) {
std::vector<int32_t> v(seq_len, 0);
size_t gap = seq_len / (num_images + 1);
@@ -668,6 +724,82 @@ 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}} },
}));
+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} },
+ paged_attention_test_params{ {{3, 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} },
+ paged_attention_test_params{ {{5, 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} },
+ paged_attention_test_params{ {{8, 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} },
+ paged_attention_test_params{ {{15, 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} },
+ paged_attention_test_params{ {{16, 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} }, // inclusive upper bound
+ paged_attention_test_params{ {{17, 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} }, // control: just above the bound, must take the multi-token path
+
+ // past_len variations at a fixed q_len, including the KV block/partition boundaries
+ paged_attention_test_params{ {{8, 1}}, 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} },
+ paged_attention_test_params{ {{8, 15}}, 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} },
+ paged_attention_test_params{ {{8, 255}}, 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} },
+ paged_attention_test_params{ {{8, 256}}, 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} },
+ paged_attention_test_params{ {{8, 300}}, 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} },
+ paged_attention_test_params{ {{8, 1023}}, 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} },
+
+ // GQA ratios and head sizes
+ paged_attention_test_params{ {{8, 34}}, 4, 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} },
+ paged_attention_test_params{ {{8, 34}}, 8, 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} },
+ paged_attention_test_params{ {{8, 34}}, 4, 2, 128, 128, 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} },
+ paged_attention_test_params{ {{5, 34}}, 28, 28, 128, 128, 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} },
+
+ // compressed KV cache, both quantization modes
+ paged_attention_test_params{ {{8, 34}}, 2, 2, 64, 64, 256, 0, ENABLE_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} },
+ paged_attention_test_params{ {{8, 34}}, 2, 2, 64, 64, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128} },
+ paged_attention_test_params{ {{16, 34}}, 4, 2, 64, 64, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128} },
+ paged_attention_test_params{ {{8, 300}}, 2, 2, 64, 64, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128} },
+
+ // small-q alongside the other routes the split-mixed path dispatches
+ paged_attention_test_params{ {{8, 34}, {1, 100}}, 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, 100.0f}, std::vector<int>{128, 128} }, // small-q + single-token
+ paged_attention_test_params{ {{8, 34}, {32, 0}}, 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, 100.0f}, std::vector<int>{128, 128} }, // small-q + prefill
+ paged_attention_test_params{ {{4, 20}, {8, 34}, {16, 50}}, 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, 100.0f, 100.0f}, std::vector<int>{128, 128, 128} }, // three small-q of different lengths
+ paged_attention_test_params{ {{2, 34}, {1, 515}, {40, 0}, {16, 7}}, 4, 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, 100.0f, 100.0f, 100.0f}, std::vector<int>{128, 128, 128, 128} }, // all four routes at once
+ paged_attention_test_params{ {{8, 34}, {1, 100}}, 2, 2, 64, 64, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f, 100.0f}, std::vector<int>{128, 128} },
+
+ // dynamic input padding on the small-q route
+ paged_attention_test_params{ {{8, 34}}, 2, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128} },
+}));
+
+INSTANTIATE_TEST_SUITE_P(smoke_cm_qq_bias, cm_qq_bias_test, ::testing::ValuesIn(std::vector<paged_attention_test_params>{
+ // single sequence, q_len sweep - all of these are small-q subsequences
+ paged_attention_test_params{ {{2, 32}}, 2, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, DISABLE_DIVERSITY, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128}, ov::element::dynamic, true, make_tree_qq_bias({2}) },
+ paged_attention_test_params{ {{4, 32}}, 2, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, DISABLE_DIVERSITY, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128}, ov::element::dynamic, true, make_tree_qq_bias({4}) },
+ paged_attention_test_params{ {{8, 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, DISABLE_DIVERSITY, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128}, ov::element::dynamic, true, make_tree_qq_bias({8}) },
+ paged_attention_test_params{ {{16, 40}}, 2, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, DISABLE_DIVERSITY, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128}, ov::element::dynamic, true, make_tree_qq_bias({16}) }, // spec_num 16, the typical EAGLE draft width
+
+ // above the small-q bound: the mask is applied by the multi-token kernel instead
+ paged_attention_test_params{ {{17, 40}}, 2, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, DISABLE_DIVERSITY, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128}, ov::element::dynamic, true, make_tree_qq_bias({17}) },
+ paged_attention_test_params{ {{32, 40}}, 2, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, DISABLE_DIVERSITY, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128}, ov::element::dynamic, true, make_tree_qq_bias({32}) },
+
+ // past_len crossing the KV block and partition boundaries with the mask on
+ paged_attention_test_params{ {{8, 255}}, 2, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, DISABLE_DIVERSITY, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128}, ov::element::dynamic, true, make_tree_qq_bias({8}) },
+ paged_attention_test_params{ {{8, 256}}, 2, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, DISABLE_DIVERSITY, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128}, ov::element::dynamic, true, make_tree_qq_bias({8}) },
+ paged_attention_test_params{ {{8, 1023}}, 2, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, DISABLE_DIVERSITY, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128}, ov::element::dynamic, true, make_tree_qq_bias({8}) },
+
+ // GQA: the mask depends only on the query, so it must be shared correctly across the heads
+ // that replicate one KV head.
+ paged_attention_test_params{ {{8, 34}}, 4, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, DISABLE_DIVERSITY, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128}, ov::element::dynamic, true, make_tree_qq_bias({8}) },
+ paged_attention_test_params{ {{8, 34}}, 8, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, DISABLE_DIVERSITY, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128}, ov::element::dynamic, true, make_tree_qq_bias({8}) },
+ paged_attention_test_params{ {{8, 34}}, 4, 2, 128, 128, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, DISABLE_DIVERSITY, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128}, ov::element::dynamic, true, make_tree_qq_bias({8}) },
+
+ // compressed KV cache, both quantization modes
+ paged_attention_test_params{ {{8, 34}}, 2, 2, 64, 64, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, DISABLE_DIVERSITY, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128}, ov::element::dynamic, true, make_tree_qq_bias({8}) },
+ paged_attention_test_params{ {{8, 34}}, 2, 2, 64, 64, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, DISABLE_DIVERSITY, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128}, ov::element::dynamic, true, make_tree_qq_bias({8}) },
+ paged_attention_test_params{ {{16, 40}}, 4, 2, 64, 64, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, DISABLE_DIVERSITY, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128}, ov::element::dynamic, true, make_tree_qq_bias({16}) },
+
+ // multi-sequence: only the subsequences with past_len > 0 carry a mask
+ paged_attention_test_params{ {{8, 34}, {64, 0}}, 2, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, DISABLE_DIVERSITY, 0, {}, true, std::vector<float>{100.0f, 100.0f}, std::vector<int>{128, 128}, ov::element::dynamic, true, make_tree_qq_bias({8, 0}) },
+ paged_attention_test_params{ {{64, 0}, {8, 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, DISABLE_DIVERSITY, 0, {}, true, std::vector<float>{100.0f, 100.0f}, std::vector<int>{128, 128}, ov::element::dynamic, true, make_tree_qq_bias({0, 8}) },
+ paged_attention_test_params{ {{4, 20}, {8, 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, DISABLE_DIVERSITY, 0, {}, true, std::vector<float>{100.0f, 100.0f}, std::vector<int>{128, 128}, ov::element::dynamic, true, make_tree_qq_bias({4, 8}) },
+ paged_attention_test_params{ {{16, 40}, {1, 100}, {8, 34}}, 4, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, DISABLE_DIVERSITY, 0, {}, true, std::vector<float>{100.0f, 100.0f, 100.0f}, std::vector<int>{128, 128, 128}, ov::element::dynamic, true, make_tree_qq_bias({16, 1, 8}) },
+ paged_attention_test_params{ {{8, 34}, {32, 0}, {2, 16}}, 2, 2, 64, 64, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, DISABLE_DIVERSITY, 0, {}, true, std::vector<float>{100.0f, 100.0f, 100.0f}, std::vector<int>{128, 128, 128}, ov::element::dynamic, true, make_tree_qq_bias({8, 0, 2}) },
+}));
+
// Performance-focused tests with larger sequence lengths, single/multi-subsequences, and CM v.s. OCL/micro path (which is triggered with xattention ON/OFF).
// These tests are not validating correctness (outputs are not checked), but are intended to be run in a performance benchmarking mode to evaluate kernel performance and behavior of the paged attention implementation.
INSTANTIATE_TEST_SUITE_P(DISABLED_smoke_paged_attention_perf_ocl, paged_attention_test, ::testing::ValuesIn(std::vector<paged_attention_test_params>{