Skip to content

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

[GPU] Multi-subsequence enablement of PA CM path (#34806)

cecilia peng7876e430ee88
diff --git a/src/plugins/intel_gpu/include/intel_gpu/runtime/internal_properties.hpp b/src/plugins/intel_gpu/include/intel_gpu/runtime/internal_properties.hpp
index 3ff1d121895..e928f4bbbc1 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/runtime/internal_properties.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/runtime/internal_properties.hpp
@@ -186,6 +186,7 @@ static constexpr Property<bool, ov::PropertyMutability::RW> allow_bypass_xattn{"
static constexpr Property<bool, ov::PropertyMutability::RW> network_marker{"GPU_NETWORK_MARKER"};
static constexpr Property<bool, ov::PropertyMutability::RW> list_layers{"GPU_LIST_LAYERS"};
static constexpr Property<bool, ov::PropertyMutability::RW> print_input_data_shapes{"GPU_PRINT_INPUT_DATA_SHAPES"};
+static constexpr Property<std::string, ov::PropertyMutability::RW> pa_mixed_route_mode{"GPU_PA_MIXED_ROUTE_MODE"};
} // namespace ov::intel_gpu
namespace cldnn {
diff --git a/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl b/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl
index 7104d60393c..d60d0883b26 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl
+++ b/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl
@@ -60,7 +60,7 @@ OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, dynamic_quantization_threshold,
OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, dynamic_quantization_precomputed_reduction, true, "Precompute reduction of activation for faster dynamic quantization in case of asymmetric weight")
OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, allow_bypass_xattn, true, "Allow bypass xattn execution if threshold >= 1.0.")
OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, weightless_attr, nullptr, "Used to configure ov::WeightlessCacheAttribute for constants that are not loaded from a .bin file. This typically applies to non-IR inputs (e.g., ORT)")
-
+OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, pa_mixed_route_mode, std::string("split"), "Mixed route mode for CM paged attention. Supported values: multi, split")
OV_CONFIG_DEBUG_GLOBAL_OPTION(ov::intel_gpu, help, false, "Print help message for all config options")
OV_CONFIG_DEBUG_GLOBAL_OPTION(ov::intel_gpu, verbose, 0, "Enable logging for debugging purposes. The higher value the more verbose output. 0 - Disabled, 4 - Maximum verbosity")
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 1847f0213ba..9ab9b86930e 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
@@ -390,6 +390,31 @@ constexpr void apply_causal_mask(matrix_ref<float, N, M> St) {
}
}
+template <int N, int M>
+inline void apply_causal_mask_with_offset(matrix_ref<float, N, M> St, int causal_left) {
+ if (causal_left >= (N - 1)) {
+ return;
+ }
+
+ #pragma unroll
+ for (int r = 0; r < N; r++) {
+ int mask_cols = r - causal_left;
+ if (mask_cols <= 0) {
+ continue;
+ }
+ if (mask_cols >= M) {
+ St.row(r) = -3.4e38f;
+ continue;
+ }
+ #pragma unroll
+ for (int c = 0; c < M; c++) {
+ if (c < mask_cols) {
+ St(r, c) = -3.4e38f;
+ }
+ }
+ }
+}
+
//prepack [K, N] to [K/2, N, 2] layout.
template <typename T1, typename T2, int K, int N>
inline void prepackAsVNNIWidth2(matrix_ref<T1, K, N> input, matrix_ref<T2, K/2, N*2> out) {
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 c0f4f954b84..c06e4568322 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
@@ -13,7 +13,7 @@ void pa_lsc_u8(
int local_size,
int q_start,
int kv_stop,
- int q_len,
+ int q_tokens_in_tile,
int kv_len,
SurfaceIndex q_gather,
uint32_t q_gather_offset_bytes,
@@ -39,12 +39,13 @@ void pa_lsc_u8(
cur_max = -3e38f;
cur_sum = 0;
constexpr int num_P_tiles = REG_N / REG_M;
+ static_assert(num_P_tiles == 1, "XE1 kernels currently require REG_N/REG_M == 1");
matrix<half, head_size/REG_K, REG_K*REG_N> rQ;
- matrix <float, head_size/REG_N*num_P_tiles, REG_M*REG_N> rO;
+ matrix <float, head_size/REG_N, REG_M*REG_N> rO;
rO = 0; // Initialize to prevent NaN from uninitialized values
bool first_active = true;
- auto q_tokens_left = q_len;
+ // clamp per-tile valid query tokens to [0, q_step]
static_assert(q_step == REG_N);
static_assert(kv_step == REG_K);
static_assert(head_size % REG_N == 0, "head_size must be divisible by REG_N");
@@ -53,9 +54,9 @@ void pa_lsc_u8(
static_assert(CMPA_BLOCK_SZ % SUB_BLOCK_SIZE == 0, "CMPA_BLOCK_SZ must be divisible by SUB_BLOCK_SIZE");
#endif
- if (q_tokens_left < 0) q_tokens_left = 0;
- if (q_tokens_left > q_step) q_tokens_left = q_step;
- if (q_tokens_left > 0) {
+ if (q_tokens_in_tile < 0) q_tokens_in_tile = 0;
+ if (q_tokens_in_tile > q_step) q_tokens_in_tile = q_step;
+ if (q_tokens_in_tile > 0) {
constexpr int q_tile_uints = REG_K / 2;
constexpr int q_tile_elems = q_tile_uints * REG_N;
vector<ushort, q_tile_elems> gather_pred;
@@ -67,7 +68,7 @@ void pa_lsc_u8(
#pragma unroll
for (int col = 0; col < REG_N; col++) {
- bool active = (col < q_tokens_left);
+ bool active = (col < q_tokens_in_tile);
uint token_base = q_gather_offset_bytes + col * q_pitch;
#pragma unroll
@@ -106,6 +107,7 @@ void pa_lsc_u8(
auto skip_by = [&](const bool* base, int kv_pos) -> bool {
if (sb_shift < 0) return false;
+ if (!base) return false;
return !base[(uint)kv_pos >> sb_shift];
};
@@ -281,29 +283,7 @@ void pa_lsc_u8(
//# St = k @ Qt
matrix<float, kv_step, q_step> St = ugemm_KQ(slm_K, rQ, slm_offset);
if constexpr (use_causal_mask) {
- if constexpr (kv_step == q_step) {
- // since kv_step == q_step == 16, causal_left is n * kv_step
- if (causal_left == 0) {
- apply_causal_mask<1>(St);
- } else if (causal_left < 0) {
- St = -3.4e38f;
- }
- } else {
- if (causal_left == 0) {
- // q_step is half of kv_step
- // calsual mask first half of the kv
- apply_causal_mask<1>(St.select<q_step, 1, q_step, 1>(0, 0));
- St.select<q_step, 1, q_step, 1>(q_step, 0) = -3.4e38f;
- } else if (causal_left < 0) {
- St = -3.4e38f;
- } else if (causal_left < kv_step) {
- // q_step is half of kv_step
- // Workaround for an IGC ICE on ARL-H triggered by submatrix in-place masking.
- // Materialize St before applying the partial causal mask.
- St += 0.f;
- apply_causal_mask<1>(St.select<q_step, 1, q_step, 1>(q_step, 0));
- }
- }
+ apply_causal_mask_with_offset(St, causal_left);
causal_left -= kv_step;
} else {
int kv_tokens = kv_stop - kv_pos;
@@ -323,8 +303,9 @@ void pa_lsc_u8(
}
}
}
- // cm_sbarrier(0);
- if (q_tokens_left == 0) return;
+ // U8 path uses workgroup-level barriers in `pa_lsc_u8`, so every lane in
+ // the workgroup must participate and cannot early exit.
+ if (q_tokens_in_tile == 0) return;
#ifdef CMPA_DEBUG_ALL_MASKED
if (first_active) {
@@ -333,25 +314,21 @@ void pa_lsc_u8(
#endif
//# save cur_O/cur_sum.transpose(0, 1)
- matrix<half, num_P_tiles*REG_M, REG_N> cur_O_f16;
+ matrix<half, REG_M, REG_N> cur_O_f16;
cur_sum = cm_inv(cur_sum);
#pragma unroll
- for(int k = 0, ri=0; k < head_size; k += REG_N, ri += num_P_tiles) {
+ for(int k = 0, ri=0; k < head_size; k += REG_N, ri++) {
+ auto cO = rO[ri].format<float, REG_M, REG_N>();
#pragma unroll
- for(int p = 0; p < num_P_tiles; p++) {
- auto cO = rO[ri + p].format<float, REG_M, REG_N>();
- #pragma unroll
- for(int r = 0; r < cO.n_rows(); r++) {
- cur_O_f16[r + p*REG_M] = cm_mul<float>(cO.row(r), cur_sum[r + p*REG_M]);
- }
- int o_stride_elems = o_pitch / sizeof(half);
- half* output_ptr = (half*)o_base + p * REG_M * o_stride_elems + k;
- auto cur_O_ref = cur_O_f16.format<half, num_P_tiles, REG_M * REG_N>().row(p).format<half, REG_M, REG_N>();
- #pragma unroll
- for (int r = 0; r < REG_M; r++) {
- cm_svm_block_write<half, REG_N>((svmptr_t)(output_ptr + r * o_stride_elems), cur_O_ref.row(r).format<half>());
- }
+ for(int r = 0; r < cO.n_rows(); r++) {
+ cur_O_f16[r] = cm_mul<float>(cO.row(r), cur_sum[r]);
+ }
+ int o_stride_elems = o_pitch / sizeof(half);
+ half* output_ptr = (half*)o_base + k;
+
+ for (int r = 0; r < q_tokens_in_tile; r++) {
+ cm_svm_block_write<half, REG_N>((svmptr_t)(output_ptr + r * o_stride_elems), cur_O_f16.row(r).format<half>());
}
}
}
@@ -363,7 +340,7 @@ void pa_kernel_lsc_prefetch_f16(
int wg_local_id,
int q_start,
int kv_stop, //
- int q_len, //q_step
+ int q_tokens_in_tile, // number of valid query tokens in this q_step tile
int kv_len, //not used for now
SurfaceIndex q_gather,
uint32_t q_gather_offset_bytes,
@@ -391,6 +368,7 @@ void pa_kernel_lsc_prefetch_f16(
cur_max = -3e38f;
cur_sum = 0;
constexpr int num_P_tiles = REG_N / REG_M;
+ static_assert(num_P_tiles == 1, "XE1 kernels currently require REG_N/REG_M == 1");
constexpr int VALUE_TILE_NUM = 2;
matrix<half, head_size/REG_K, REG_K*REG_N> rQ;
matrix <float, head_size/REG_M, REG_M*REG_N> rO;
@@ -401,23 +379,26 @@ void pa_kernel_lsc_prefetch_f16(
const int sb_shift = (SPARSE_BLOCK_SIZE == 128) ? 7 : (SPARSE_BLOCK_SIZE == 256) ? 8 : -1;
auto skip_by = [&](const bool* base, int kv_pos) -> bool {
if (sb_shift < 0) return false;
+ if (!base) return false;
return !base[(uint)kv_pos >> sb_shift];
};
auto skip_compute = [&](int kv_pos) { return skip_by((const bool*)sparse_mask_base, kv_pos); };
#endif
- auto q_tokens_left = q_len;// - q_start;
+ // clamp per-tile valid query tokens to [0, q_step]
static_assert(q_step == REG_N);
static_assert(kv_step == REG_K);
static_assert(REG_N % REG_M == 0, "REG_N must be divisible by REG_M");
static_assert(head_size % REG_M == 0, "head_size must be divisible by REG_M");
- if (q_tokens_left < 0) q_tokens_left = 0;
- if (q_tokens_left > q_step) q_tokens_left = q_step;
- if (q_tokens_left == 0) return;
+ if (q_tokens_in_tile < 0) q_tokens_in_tile = 0;
+ if (q_tokens_in_tile > q_step) q_tokens_in_tile = q_step;
+
+ // Fp16 path does not use workgroup-level barriers as in `pa_lsc_u8`, so lanes with zero valid query tokens can early exit.
+ if (q_tokens_in_tile == 0) return;
- if (q_tokens_left > 0) {
+ if (q_tokens_in_tile > 0) {
constexpr int q_tile_uints = REG_K / 2;
constexpr int q_tile_elems = q_tile_uints * REG_N;
vector<ushort, q_tile_elems> gather_pred;
@@ -428,7 +409,7 @@ void pa_kernel_lsc_prefetch_f16(
uint col_uint_base = ri * q_tile_uints;
#pragma unroll
for (int col = 0; col < REG_N; col++) {
- bool active = (col < q_tokens_left);
+ bool active = (col < q_tokens_in_tile);
uint token_base = q_gather_offset_bytes + col * q_pitch;
#pragma unroll
for (int row = 0; row < q_tile_uints; row++) {
@@ -524,29 +505,7 @@ void pa_kernel_lsc_prefetch_f16(
}
}
if constexpr (use_causal_mask) {
- if constexpr (kv_step == q_step) {
- // since kv_step == q_step == 16, causal_left is n * kv_step
- if (causal_left == 0) {
- apply_causal_mask<1>(St);
- } else if (causal_left < 0) {
- St = -3.4e38f;
- }
- } else {
- if (causal_left == 0) {
- // q_step is half of kv_step
- // calsual mask first half of the kv
- apply_causal_mask<1>(St.select<q_step, 1, q_step, 1>(0, 0));
- St.select<q_step, 1, q_step, 1>(q_step, 0) = -3.4e38f;
- } else if (causal_left < 0) {
- St = -3.4e38f;
- } else if (causal_left < kv_step) {
- // q_step is half of kv_step
- // calsual mask second half of the kv
- // if w/o St += 0.f;, I will meet IGC: Internal Compiler Error: Access violation on ARL-H
- St += 0.f;
- apply_causal_mask<1>(St.select<q_step, 1, q_step, 1>(q_step, 0));
- }
- }
+ apply_causal_mask_with_offset(St, causal_left);
causal_left -= kv_step;
} else {
int kv_tokens = kv_stop - kv_pos;
@@ -560,10 +519,10 @@ void pa_kernel_lsc_prefetch_f16(
matrix<half, REG_N, REG_K> P;
Transpose2DMatrix(St, P);
- auto P2 = P.format<half, num_P_tiles, REG_M * REG_K>();
+ auto P_vec = P.format<half, REG_M, REG_K>();
matrix<half, REG_K/2, REG_N*2*VALUE_TILE_NUM> Vmat;
#pragma unroll
- for(int k = 0, ri=0; k < head_size; k += REG_N * VALUE_TILE_NUM, ri += num_P_tiles * VALUE_TILE_NUM) {
+ for(int k = 0, ri=0; k < head_size; k += REG_N * VALUE_TILE_NUM, ri += VALUE_TILE_NUM) {
matrix<half, REG_K, REG_N*VALUE_TILE_NUM> Vmat_tmp;
constexpr uint elem_size = sizeof(half);
constexpr int value_row_u32 = (REG_N * VALUE_TILE_NUM * sizeof(half)) / sizeof(uint);
@@ -591,43 +550,31 @@ void pa_kernel_lsc_prefetch_f16(
if (first_active) {
#pragma unroll
for (int tile = 0; tile < VALUE_TILE_NUM; tile++) {
- int rO_base = ri + tile * num_P_tiles;
auto Vtile = 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);
- #pragma unroll
- for (int p = 0; p < num_P_tiles; p++) {
- rO[rO_base + p] = cm_dpas<CM_PRECISION_HF, CM_PRECISION_HF, SystolicDepth, RepeatCount, float>(
- 0,
- Vtile.format<int32_t>(),
- P2.row(p).format<int32_t>());
- }
+ rO[ri + tile] = cm_dpas<CM_PRECISION_HF, CM_PRECISION_HF, SystolicDepth, RepeatCount, float>(
+ 0,
+ Vtile.format<int32_t>(),
+ P_vec.format<int32_t>());
}
first_active = false;
} else {
#pragma unroll
for (int tile = 0; tile < VALUE_TILE_NUM; tile++) {
- int rO_base = ri + tile * num_P_tiles;
+ auto cO = rO[ri + tile].format<float, REG_M, REG_N>();
#pragma unroll
- for(int p = 0; p < num_P_tiles; p++) {
- auto cO = rO[rO_base + p].format<float, REG_M, REG_N>();
- #pragma unroll
- for(int r = 0; r < REG_M; r++)
- cO.row(r) = cm_mul<float>(cO.row(r), max_comp[r + p*REG_M]);
- }
+ for(int r = 0; r < REG_M; r++)
+ cO.row(r) = cm_mul<float>(cO.row(r), max_comp[r]);
}
#pragma unroll
for (int tile = 0; tile < VALUE_TILE_NUM; tile++) {
- int rO_base = ri + tile * num_P_tiles;
auto Vtile =
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);
- #pragma unroll
- for (int p = 0; p < num_P_tiles; p++) {
- rO[rO_base + p] = cm_dpas<CM_PRECISION_HF, CM_PRECISION_HF, SystolicDepth, RepeatCount>(
- rO[rO_base + p].format<float>(),
- Vtile.format<int32_t>(),
- P2.row(p).format<int32_t>());
- }
+ rO[ri + tile] = cm_dpas<CM_PRECISION_HF, CM_PRECISION_HF, SystolicDepth, RepeatCount>(
+ rO[ri + tile].format<float>(),
+ Vtile.format<int32_t>(),
+ P_vec.format<int32_t>());
}
}
}
@@ -640,24 +587,20 @@ void pa_kernel_lsc_prefetch_f16(
#endif
//# save cur_O/cur_sum.transpose(0, 1)
- matrix<half, num_P_tiles * REG_M, REG_N> cur_O_f16;
+ matrix<half, REG_M, REG_N> cur_O_f16;
cur_sum = cm_inv(cur_sum);
#pragma unroll
- for(int k = 0, ri=0; k < head_size; k += REG_N, ri += num_P_tiles) {
+ for(int k = 0, ri=0; k < head_size; k += REG_N, ri++) {
+ auto cO = rO[ri].format<float, REG_M, REG_N>();
#pragma unroll
- for(int p = 0; p < num_P_tiles; p++) {
- auto cO = rO[ri + p].format<float, REG_M, REG_N>();
- #pragma unroll
- for(int r = 0; r < cO.n_rows(); r++) {
- cur_O_f16[r + p*REG_M] = cm_mul<float>(cO.row(r), cur_sum[r + p*REG_M]);
- }
- int o_stride_elems = o_pitch / sizeof(half);
- half* output_ptr = (half*)o_base + p * REG_M * o_stride_elems + k;
- auto cur_O_ref = cur_O_f16.format<half, num_P_tiles, REG_M * REG_N>().row(p).format<half, REG_M, REG_N>();
- #pragma unroll
- for (int r = 0; r < REG_M; r++) {
- cm_svm_block_write<half, REG_N>((svmptr_t)(output_ptr + r * o_stride_elems), cur_O_ref.row(r).format<half>());
- }
+ for(int r = 0; r < cO.n_rows(); r++) {
+ cur_O_f16[r] = cm_mul<float>(cO.row(r), cur_sum[r]);
+ }
+ int o_stride_elems = o_pitch / sizeof(half);
+ half* output_ptr = (half*)o_base + k;
+
+ for (int r = 0; r < q_tokens_in_tile; r++) {
+ cm_svm_block_write<half, REG_N>((svmptr_t)(output_ptr + r * o_stride_elems), cur_O_f16.row(r).format<half>());
}
}
}
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 33a129d9c2f..56b011f6f1b 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
@@ -5,7 +5,9 @@
#ifdef CM_HAS_LSC_UNTYPED_2D
#ifndef CMPA_WG_SEQ_LEN
-#error "CMPA_WG_SEQ_LEN must be defined"
+// Keep fixed-WG optimized path optional.
+// When undefined, default to 0 so OPTIMIZED_SPARSE_PIPELINE is disabled.
+#define CMPA_WG_SEQ_LEN 0
#endif
#ifndef SPARSE_BLOCK_SIZE
@@ -49,7 +51,7 @@ void pa_lsc_u8(
int local_size,
int q_start,
int kv_stop,
- int q_len,
+ int q_tokens_in_tile,
int kv_len,
svmptr_t q_base [[type("svmptr_t")]],
svmptr_t k_cache_base [[type("svmptr_t")]],
@@ -80,7 +82,7 @@ void pa_lsc_u8(
matrix<float, head_size / REG_N * num_P_tiles, REG_M * REG_N> rO;
bool first_active = true;
- auto q_tokens_left = q_len;
+ // clamp per-tile valid query tokens to [0, q_step]
static_assert(q_step == REG_N);
static_assert(kv_step == REG_K);
#if KV_CACHE_COMPRESSION == 2
@@ -88,14 +90,14 @@ void pa_lsc_u8(
static_assert(CMPA_BLOCK_SZ % SUB_BLOCK_SIZE == 0, "CMPA_BLOCK_SZ must be divisible by SUB_BLOCK_SIZE");
#endif
- if (q_tokens_left < 0) q_tokens_left = 0;
- if (q_tokens_left > q_step) q_tokens_left = q_step;
+ if (q_tokens_in_tile < 0) q_tokens_in_tile = 0;
+ if (q_tokens_in_tile > q_step) q_tokens_in_tile = q_step;
// ---- Load Q (unchanged) ----
- if (q_tokens_left > 0) {
+ if (q_tokens_in_tile > 0) {
lsc::block_2d_desc<uint, 1, REG_N, REG_K / 2> b2dQ(
reinterpret_cast<uint*>(q_base),
- q_tokens_left - 1,
+ q_tokens_in_tile - 1,
head_size * sizeof(half) - 1,
q_pitch - 1,
0, 0);
@@ -137,6 +139,7 @@ void pa_lsc_u8(
if constexpr (sb_shift < 0) {
return false;
} else {
+ if (!base) return false;
return !base[(uint)kv_pos >> sb_shift];
}
};
@@ -334,13 +337,7 @@ void pa_lsc_u8(
matrix<float, kv_step, q_step> St = ugemm_KQ(slm_K, rQ, slm_offset);
if constexpr (use_causal_mask) {
- if (causal_left == 0) {
- apply_causal_mask<1>(St);
- } else if (causal_left < 0) {
- St = -3.4e38f;
- } else if (causal_left < kv_step) {
- for (int p = causal_left; p < kv_step; p++) St[p] = -3.4e38f;
- }
+ apply_causal_mask_with_offset(St, causal_left);
causal_left -= kv_step;
}
int kv_tokens = kv_stop - kv_pos;
@@ -371,6 +368,7 @@ void pa_lsc_u8(
if constexpr (sb_shift < 0) {
return false;
} else {
+ if (!base) return false;
return !base[(uint)kv_pos >> sb_shift];
}
};
@@ -525,13 +523,7 @@ void pa_lsc_u8(
matrix<float, kv_step, q_step> St = ugemm_KQ(slm_K, rQ, slm_offset);
if constexpr (use_causal_mask) {
- if (causal_left == 0) {
- apply_causal_mask<1>(St);
- } else if (causal_left < 0) {
- St = -3.4e38f;
- } else if (causal_left < kv_step) {
- for (int p = causal_left; p < kv_step; p++) St[p] = -3.4e38f;
- }
+ apply_causal_mask_with_offset(St, causal_left);
causal_left -= kv_step;
}
int kv_tokens = kv_stop - kv_pos;
@@ -554,7 +546,9 @@ void pa_lsc_u8(
// ============================================================
// Store O (unchanged)
// ============================================================
- if (q_tokens_left == 0) return;
+ // U8 path uses workgroup-level barriers in `pa_lsc_u8`, so every lane in
+ // the workgroup must participate and cannot early exit.
+ if (q_tokens_in_tile == 0) return;
#ifdef CMPA_DEBUG_ALL_MASKED
if (first_active) {
@@ -567,7 +561,7 @@ void pa_lsc_u8(
lsc::block_2d_desc<half, 1, REG_M, REG_N> b2dO(
o_base,
- q_tokens_left - 1,
+ q_tokens_in_tile - 1,
head_size * sizeof(half) - 1,
o_pitch - 1,
0, 0);
@@ -600,7 +594,7 @@ void pa_kernel_lsc_prefetch_f16(
int wg_local_id,
int q_start,
int kv_stop, //
- int q_len, //q_step
+ int q_tokens_in_tile, // number of valid query tokens in this q_step tile
int kv_len, //not used for now
svmptr_t q_base [[type("svmptr_t")]],
svmptr_t k_cache_base [[type("svmptr_t")]],
@@ -636,6 +630,7 @@ void pa_kernel_lsc_prefetch_f16(
if constexpr (sb_shift < 0) {
return false;
} else {
+ if (!base) return false;
return !base[(uint)kv_pos >> sb_shift];
}
};
@@ -645,20 +640,21 @@ void pa_kernel_lsc_prefetch_f16(
};
#endif
- auto q_tokens_left = q_len;
+ // clamp per-tile valid query tokens to [0, q_step]
static_assert(q_step == REG_N);
static_assert(kv_step == REG_K);
- if (q_tokens_left < 0) q_tokens_left = 0;
- if (q_tokens_left > q_step) q_tokens_left = q_step;
+ if (q_tokens_in_tile < 0) q_tokens_in_tile = 0;
+ if (q_tokens_in_tile > q_step) q_tokens_in_tile = q_step;
- if (q_tokens_left > 0) {
- lsc::block_2d_desc<uint, 1, REG_N, REG_K/2> b2dQ(reinterpret_cast<uint*>(q_base), q_tokens_left - 1, head_size*sizeof(half) - 1, q_pitch - 1, 0, 0);
- #pragma unroll
- for(int k = 0, ri = 0; k < head_size/2; k += REG_K/2, ri++) {
- cm_load<lsc::Transpose>(rQ[ri].format<uint>(), b2dQ.set_block_x(k));
- rQ[ri].format<half>() = cm_mul<half>(rQ[ri].format<half>(), (half)scale_factor);
- }
+ // Fp16 path does not use workgroup-level barriers as in `pa_lsc_u8`, so lanes with zero valid query tokens can early exit.
+ if (q_tokens_in_tile == 0) return;
+
+ lsc::block_2d_desc<uint, 1, REG_N, REG_K/2> b2dQ(reinterpret_cast<uint*>(q_base), q_tokens_in_tile - 1, head_size*sizeof(half) - 1, q_pitch - 1, 0, 0);
+ #pragma unroll
+ for(int k = 0, ri = 0; k < head_size/2; k += REG_K/2, ri++) {
+ cm_load<lsc::Transpose>(rQ[ri].format<uint>(), b2dQ.set_block_x(k));
+ rQ[ri].format<half>() = cm_mul<half>(rQ[ri].format<half>(), (half)scale_factor);
}
lsc::block_2d_desc<half, 1, kv_step, REG_K> b2dK(k_cache_base, CMPA_BLOCK_SZ - 1, head_size*sizeof(half) - 1, k_pitch - 1, 0, 0);
@@ -741,14 +737,7 @@ void pa_kernel_lsc_prefetch_f16(
}
}
if constexpr (use_causal_mask) {
- // since kv_step == q_step == 16, causal_left is n*kv_step
- if (causal_left == 0) {
- apply_causal_mask<1>(St);
- } else if (causal_left < 0) {
- St = -3.4e38f;
- } else if (causal_left < kv_step) {
- for (int p = causal_left; p < kv_step; p++) St[p] = -3.4e38f;
- }
+ apply_causal_mask_with_offset(St, causal_left);
causal_left -= kv_step;
}
int kv_tokens = kv_stop - kv_pos;
@@ -889,14 +878,7 @@ void pa_kernel_lsc_prefetch_f16(
}
}
if constexpr (use_causal_mask) {
- // since kv_step == q_step == 16, causal_left is n*kv_step
- if (causal_left == 0) {
- apply_causal_mask<1>(St);
- } else if (causal_left < 0) {
- St = -3.4e38f;
- } else if (causal_left < kv_step) {
- for (int p = causal_left; p < kv_step; p++) St[p] = -3.4e38f;
- }
+ apply_causal_mask_with_offset(St, causal_left);
causal_left -= kv_step;
}
int kv_tokens = kv_stop - kv_pos;
@@ -986,13 +968,11 @@ void pa_kernel_lsc_prefetch_f16(
}
#endif
- if (q_tokens_left == 0) return;
-
//# save cur_O/cur_sum.transpose(0, 1)
matrix<half, num_P_tiles*REG_M, REG_N> cur_O_f16;
cur_sum = cm_inv(cur_sum);
- lsc::block_2d_desc<half, 1, REG_M, REG_N> b2dO(o_base, q_tokens_left - 1, head_size*sizeof(half) - 1, o_pitch - 1, 0, 0);
+ lsc::block_2d_desc<half, 1, REG_M, REG_N> b2dO(o_base, q_tokens_in_tile - 1, head_size*sizeof(half) - 1, o_pitch - 1, 0, 0);
#pragma unroll
for(int k = 0, ri=0; k < head_size; k += REG_N, ri += num_P_tiles) {
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/include/estimate.hpp b/src/plugins/intel_gpu/src/graph/impls/cm/include/estimate.hpp
index fb92461ae60..180b63314c4 100644
--- a/src/plugins/intel_gpu/src/graph/impls/cm/include/estimate.hpp
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/include/estimate.hpp
@@ -201,14 +201,14 @@ CM_INLINE void gemm_qk(uint id_wg_m, uint id_wg_n, uint hq, uint slm,
SurfaceIndex query [[type("buffer_t")]],
#endif
svmptr_t block_indices ATTR,
- svmptr_t block_indices_begins ATTR,
+ int block_index_begin,
svmptr_t kq_max_wg ATTR,
#ifdef CM_HAS_LSC_UNTYPED_2D
svmptr_t kq_exp_partial_sum ATTR,
#else
SurfaceIndex kq_exp_partial_sum [[type("buffer_t")]],
#endif
- const uint M, const uint N, const uint K, const uint query_stride, const uint q_start_strided, const uint offset_partial_sum) {
+ const uint M, const uint N, const uint query_stride, const uint q_start_strided, const uint offset_partial_sum) {
constexpr int SG_SIZE = details::get_dpas_execution_size((CmPrecisionType)9);
// constexpr int BLOCK_WG_K = 64; // same in sg // because unroll 4 times along K ??
@@ -248,6 +248,7 @@ CM_INLINE void gemm_qk(uint id_wg_m, uint id_wg_n, uint hq, uint slm,
uint id_sg_mn = id_sg_m * SG_N + id_sg_n;
static_assert(BLOCK_WG_K == 32 || BLOCK_WG_K == 64, "Supported BLOCK_WG_K are 32 or 64");
+ static constexpr uint K = STRIDE * HEAD_SIZE;
constexpr bool IS64 = (BLOCK_WG_K == 64);
constexpr bool IS32 = (BLOCK_WG_K == 32);
constexpr int PHASE_SIZE = IS64 ? 32 : 16;
@@ -307,8 +308,6 @@ CM_INLINE void gemm_qk(uint id_wg_m, uint id_wg_n, uint hq, uint slm,
return;
}
#endif
- // assume block index coming from 0 in block_indices_begins
- int block_index_begin = ((int*)block_indices_begins)[0];
int* block_indices_p = (int*)block_indices + block_index_begin;
int b_adjacent_between_head = query_stride / STRIDE; // HEAD_SIZE * HQ + HEAD_SIZE * HQ (padding 0)
// M[0:16*2]xK[0:16]
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/include/xattn_subseq_meta.hpp b/src/plugins/intel_gpu/src/graph/impls/cm/include/xattn_subseq_meta.hpp
new file mode 100644
index 00000000000..33e85ed32eb
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/include/xattn_subseq_meta.hpp
@@ -0,0 +1,23 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#ifndef XATTN_META_STRIDE
+#define XATTN_META_SUBSEQ_Q_BEGIN 0
+#define XATTN_META_SUBSEQ_Q_LEN 1
+#define XATTN_META_M 2
+#define XATTN_META_N 3
+#define XATTN_META_Q_STRIDE_PAD 4
+#define XATTN_META_N_KQ_GROUPS 5
+#define XATTN_META_Q_BLOCK_PAD 6
+#define XATTN_META_K_BLOCK_PAD 7
+#define XATTN_META_CAUSAL_START 8
+#define XATTN_META_Q_START_STRIDED 9
+#define XATTN_META_BUF_OFF_KQ_MAX 10
+#define XATTN_META_BUF_OFF_EXP_SUM 11
+#define XATTN_META_BUF_OFF_MASK 12
+#define XATTN_META_BUF_OFF_MASK_WG 13
+#define XATTN_META_BLOCK_IDX_BEGIN 14
+#define XATTN_META_WG_OFFSET 15
+#define XATTN_META_STRIDE 16
+#endif
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/pa_kv_cache_update_ref.cm b/src/plugins/intel_gpu/src/graph/impls/cm/pa_kv_cache_update_ref.cm
index 00ead135e67..754645df570 100644
--- a/src/plugins/intel_gpu/src/graph/impls/cm/pa_kv_cache_update_ref.cm
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/pa_kv_cache_update_ref.cm
@@ -22,8 +22,6 @@
#define ATTR_BUF [[type("buffer_t")]]
#endif
-constexpr uint wg_size = WG_SIZE;
-
#if KV_CACHE_COMPRESSION == 2
constexpr uint MAX_SEQS = 256;
#endif
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 9c9404e89c4..a4f6446196c 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
@@ -5,12 +5,69 @@
namespace KERNEL_NAME {
#include "cm_attention_common.hpp"
+#include "xattn_subseq_meta.hpp"
#ifdef CM_HAS_LSC_UNTYPED_2D
#include "cm_pa_xe2.hpp"
#else
#include "cm_pa_xe1.hpp"
#endif
+// ----------------------------------------------------------------------------
+// Dispatch and host-mapping summary
+//
+// 1) Workload dispatch across workgroups and threads
+// Host launches:
+// gws = [1, num_heads, wg_count * wg_size]
+// lws = [1, 1, wg_size]
+// Therefore each workgroup is identified by:
+// - cm_group_id(1) -> attention head `h`
+// - cm_group_id(2) -> query-block workgroup id `wg_id`
+// and each thread/lane in that workgroup is:
+// - cm_local_id(2) -> `wg_local_id`
+//
+// Query processing granularity:
+// - each lane handles up to `q_step` query tokens
+// - each workgroup covers up to `wg_seq_len` query tokens, where:
+// wg_seq_len = CMPA_WG_SEQ_LEN (optimized path), or
+// wg_seq_len = local_size * q_step (dynamic path)
+//
+// For one (subsequence, query-block-start), lane-local query start is:
+// q_start_local = (block_start_pos - subseq_q_begin) + wg_local_id * q_step
+//
+// Notes:
+// - U8/compressed path requires full-workgroup participation due to
+// workgroup barriers; out-of-range lanes use q_len_sg=0.
+// - FP16 path returns early for out-of-range lanes.
+//
+// 2) Multi-subsequence dispatch and host-side preparation of
+// `blocked_q_starts_and_subseq_mapping`
+//
+// Kernel consumes packed pairs from this int32 array:
+// [block_start_pos_0, subsequence_id_0,
+// block_start_pos_1, subsequence_id_1,
+// ...]
+// with length = 2 * wg_count.
+//
+// Each `wg_id` reads one pair:
+// blocked_query_idx = wg_id * 2
+// block_start_pos = mapping[blocked_query_idx]
+// subsequence_id = mapping[blocked_query_idx + 1]
+//
+// Host should build pairs in execution order as:
+// for each selected subsequence_id:
+// subseq_q_begin = subsequence_begins[subsequence_id]
+// subseq_q_end = subsequence_begins[subsequence_id + 1]
+// subseq_q_len = subseq_q_end - subseq_q_begin
+// subseq_wg_cnt = ceil_div(subseq_q_len, wg_seq_len)
+// for k in [0 .. subseq_wg_cnt):
+// append (subseq_q_begin + k * wg_seq_len, subsequence_id)
+//
+// This allows one kernel launch to mix multiple subsequences: each workgroup
+// resolves its own `subsequence_id`, then fetches sequence-local metadata via
+// `subsequence_begins`, `past_lens`, `block_indices_begins`, and
+// `block_indices`.
+// ----------------------------------------------------------------------------
+
extern "C" _GENX_MAIN_ void KERNEL_NAME(
//query [q_len, num_heads, S]
#ifdef CM_HAS_LSC_UNTYPED_2D
@@ -39,13 +96,13 @@ extern "C" _GENX_MAIN_ void KERNEL_NAME(
int32_t* block_indices [[type("svmptr_t")]],
int32_t* block_indices_begins [[type("svmptr_t")]],
int32_t* subsequence_begins [[type("svmptr_t")]],
+ int32_t* blocked_q_starts_and_subseq_mapping [[type("svmptr_t")]],
half* output [[type("svmptr_t")]],
int q_len
#if SPARSE_BLOCK_SIZE > 1
, bool* sparse_block_mask [[type("svmptr_t")]],
bool* sparse_block_mask_wg [[type("svmptr_t")]],
- int num_q_blocks,
- int num_k_blocks
+ int32_t* xattn_subseq_meta [[type("svmptr_t")]]
#endif
) {
constexpr int is_causal = CMFLA_IS_CAUSAL;
@@ -73,27 +130,69 @@ extern "C" _GENX_MAIN_ void KERNEL_NAME(
auto batch = cm_group_id(0);
auto h = cm_group_id(1);
auto hkv = h / (num_heads/num_kv_heads);
- auto wg_id = cm_group_id(2); // each work-group handles a sequence
+ auto wg_id = cm_group_id(2);
auto wg_local_id = cm_local_id(2);
int local_size = cm_local_size(2);
- int q_start_sg, kv_start, kv_seq_len, q_len_sg;
+ int q_start_sg, kv_start, kv_seq_len, q_tokens_in_tile_sg;
// multiple work-groups are required to split a sequence,
// need to figure out which part of query-tokens to process
-#if defined(CMPA_WG_SEQ_LEN)
- constexpr int wg_seq_len = CMPA_WG_SEQ_LEN;
+ // Hybrid dispatch selection:
+ // - dynamic path: derive wg_seq_len from runtime local_size
+ // - optimized path: pass compile-time CMPA_WG_SEQ_LEN in build options
+#if defined(CMPA_WG_SEQ_LEN) && (CMPA_WG_SEQ_LEN > 0)
+ const int wg_seq_len = CMPA_WG_SEQ_LEN;
#else
- int wg_seq_len = local_size * q_step;
+ const int wg_seq_len = local_size * q_step;
#endif
- int past_q_lens = past_lens[0];
+
+ const int blocked_query_idx = wg_id * 2;
+ int block_start_pos = blocked_q_starts_and_subseq_mapping[blocked_query_idx];
+ int subsequence_id = blocked_q_starts_and_subseq_mapping[blocked_query_idx + 1];
+ int subseq_q_begin = subsequence_begins[subsequence_id];
+ if (subseq_q_begin >= q_len) {
+ return;
+ }
+ int subseq_q_end = subsequence_begins[subsequence_id + 1];
+ if (subseq_q_end > q_len) {
+ subseq_q_end = q_len;
+ }
+ int subseq_q_len = subseq_q_end - subseq_q_begin;
+ if (subseq_q_len <= 0) {
+ return;
+ }
+
+ int past_q_lens = past_lens[subsequence_id];
kv_start = 0;
- kv_seq_len = q_len + past_q_lens;
- q_start_sg = (wg_id * local_size + wg_local_id) * q_step;
- q_len_sg = q_step;
- if (q_start_sg + q_len_sg > q_len) {
- q_len_sg = q_len - q_start_sg;
+ kv_seq_len = subseq_q_len + past_q_lens;
+
+ int q_start_local = (block_start_pos - subseq_q_begin) + (wg_local_id * q_step);
+#if KV_CACHE_COMPRESSION
+ // U8 path uses workgroup-level barriers in `pa_lsc_u8`, so every lane in
+ // the workgroup must participate. For out-of-range lanes, pass q_tokens_in_tile_sg=0
+ // so no output is written while still participating in synchronization.
+ bool lane_active = (q_start_local < subseq_q_len);
+ q_start_sg = subseq_q_begin + q_start_local;
+ q_tokens_in_tile_sg = q_step;
+ if (lane_active) {
+ if (q_start_local + q_tokens_in_tile_sg > subseq_q_len) {
+ q_tokens_in_tile_sg = subseq_q_len - q_start_local;
+ }
+ } else {
+ q_start_sg = subseq_q_begin + subseq_q_len;
+ q_tokens_in_tile_sg = 0;
+ }
+#else
+ if (q_start_local >= subseq_q_len) {
+ return;
+ }
+ q_start_sg = subseq_q_begin + q_start_local;
+ q_tokens_in_tile_sg = q_step;
+ if (q_start_local + q_tokens_in_tile_sg > subseq_q_len) {
+ q_tokens_in_tile_sg = subseq_q_len - q_start_local;
}
+#endif
// qkv is fused
int kv_stop = kv_seq_len;
@@ -122,22 +221,37 @@ extern "C" _GENX_MAIN_ void KERNEL_NAME(
//todo:kv_stop is wg level, should we change to sg level?
sglevel would cause sgs in one wg diverge. so leave for now. also one wg has same kvstop makes eaiser for kv copying/loading into SLM/cache.
*/
- kv_stop = (wg_id + 1) * wg_seq_len + past_q_lens;
+ kv_stop = (block_start_pos - subseq_q_begin) + wg_seq_len + past_q_lens;
if (kv_stop > kv_seq_len) kv_stop = kv_seq_len;
}
+ int32_t* block_indices_base = block_indices + block_indices_begins[subsequence_id];
+
//Q/O[B, L, H, S]
uint q_offset = (q_start_sg*num_heads + h)*head_size;
uint q_offset_bytes = q_offset * sizeof(half);
#if SPARSE_BLOCK_SIZE > 1
bool *block_mask_base, *wg_block_mask_base;
- //# sparse_block_mask [num_heads, num_q_blocks, num_k_blocks]
- //# sparse_block_mask_wg [num_heads, wg_count_along_query, num_k_blocks]
- auto q_start_block = q_start_sg/ SPARSE_BLOCK_SIZE;
- block_mask_base = sparse_block_mask + (h * num_q_blocks + q_start_block) * num_k_blocks;
- wg_block_mask_base = sparse_block_mask_wg + (h * cm_group_count(2) + wg_id) * num_k_blocks;
- #endif
+ {
+ int meta_base_pa = subsequence_id * XATTN_META_STRIDE;
+ int mask_offset = xattn_subseq_meta[meta_base_pa + XATTN_META_BUF_OFF_MASK];
+ int mask_wg_offset = xattn_subseq_meta[meta_base_pa + XATTN_META_BUF_OFF_MASK_WG];
+ int subseq_num_q_blocks = xattn_subseq_meta[meta_base_pa + XATTN_META_Q_BLOCK_PAD];
+ int subseq_num_k_blocks = xattn_subseq_meta[meta_base_pa + XATTN_META_K_BLOCK_PAD];
+ if (subseq_num_q_blocks > 0 && subseq_num_k_blocks > 0) {
+ auto q_start_block = q_start_local / SPARSE_BLOCK_SIZE;
+ block_mask_base = sparse_block_mask + mask_offset + (h * subseq_num_q_blocks + q_start_block) * subseq_num_k_blocks;
+ int blocks_per_wg = wg_seq_len / SPARSE_BLOCK_SIZE;
+ int subseq_merged_q_blocks = (subseq_num_q_blocks + blocks_per_wg - 1) / blocks_per_wg;
+ int local_wg_idx = (block_start_pos - subseq_q_begin) / wg_seq_len;
+ wg_block_mask_base = sparse_block_mask_wg + mask_wg_offset + (h * subseq_merged_q_blocks + local_wg_idx) * subseq_num_k_blocks;
+ } else {
+ block_mask_base = 0;
+ wg_block_mask_base = 0;
+ }
+ }
+#endif
#if KV_CACHE_COMPRESSION
#if KV_CACHE_COMPRESSION == 1
@@ -154,9 +268,9 @@ extern "C" _GENX_MAIN_ void KERNEL_NAME(
slm_V,
wg_local_id,
local_size,
- q_start_sg, //q_start for SG,
+ q_start_local, //q_start within current subsequence,
kv_stop,
- q_len_sg, //q_step,
+ q_tokens_in_tile_sg,
kv_seq_len, //kv_len,
#ifdef CM_HAS_LSC_UNTYPED_2D
reinterpret_cast<svmptr_t>(query + q_offset),
@@ -177,7 +291,7 @@ extern "C" _GENX_MAIN_ void KERNEL_NAME(
#endif
reinterpret_cast<svmptr_t>(output + q_offset),
past_q_lens,
- block_indices);
+ block_indices_base);
#else
uint kv_offset = hkv*head_size*pa_block_sz;
#ifndef CM_HAS_LSC_UNTYPED_2D
@@ -185,9 +299,9 @@ extern "C" _GENX_MAIN_ void KERNEL_NAME(
#endif
pa_kernel_lsc_prefetch_f16<is_causal, num_heads, num_kv_heads, head_size, 0, 16>(
wg_local_id,
- q_start_sg, //q_start for SG,
+ q_start_local, //q_start within current subsequence,
kv_stop,
- q_len_sg, //q_step,
+ q_tokens_in_tile_sg,
kv_seq_len, //kv_len,
#ifdef CM_HAS_LSC_UNTYPED_2D
reinterpret_cast<svmptr_t>(query + q_offset),
@@ -208,7 +322,7 @@ extern "C" _GENX_MAIN_ void KERNEL_NAME(
#endif
reinterpret_cast<svmptr_t>(output + q_offset),
past_q_lens,
- block_indices);
+ block_indices_base);
#endif
}
} // namespace KERNEL_NAME
\ No newline at end of file
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/pa_single_token.cm b/src/plugins/intel_gpu/src/graph/impls/cm/pa_single_token.cm
index 2bf74f38cd3..2dab3289ebf 100644
--- a/src/plugins/intel_gpu/src/graph/impls/cm/pa_single_token.cm
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/pa_single_token.cm
@@ -73,6 +73,30 @@ CM_INLINE void Transpose_8x8(matrix_ref<T1, 8, 8> in, matrix_ref<T2, 8, 8> out)
}
}
+// How multi-subsequence is supported in this kernel:
+// Because the single-token kernel often runs on a subset of sequences, not all sequences in the round.
+// Kernel metadata arrays (past_lens, subsequence_begins, block_indices_begins) are indexed by original sequence id.
+// The decode launch dimension is compact (batch_size = len(decode_seq_indices)), especially in mixed-route split.
+// selected_sequence_ids bridges compact decode batch index → original sequence index.
+// selected_sequence_count guards valid entries and avoids out-of-range threads.
+//
+// selected_sequence_ids:
+// Host-selected subsequence IDs for this launch (compact decode subset).
+// Each entry indexes global sequence metadata arrays:
+// past_lens / block_indices_begins / subsequence_begins.
+// Workgroup seq_idx (cm_global_id(0)) maps through this array to get
+// the original sequence index (orig_seq_idx).
+//
+// Host preparation rules:
+// 1) Fill selected_sequence_ids with sequence IDs to run in this kernel.
+// 2) Keep order aligned with the compact output row order for this launch.
+// 3) Ensure every ID is in [0, total_sequence_count), and unique for decode.
+// 4) For this single-token path, each selected sequence must have exactly
+// one query token in the current round (num_tokens == 1).
+//
+// selected_sequence_count:
+// - Number of valid entries in selected_sequence_ids.
+// - Bounds guard in kernel: seq_idx >= selected_sequence_count => return.
extern "C" _GENX_MAIN_ void KERNEL_NAME(
half* query [[type("svmptr_t")]],
KV_ELEMENT_TYPE* key [[type("svmptr_t")]],
@@ -81,9 +105,11 @@ extern "C" _GENX_MAIN_ void KERNEL_NAME(
int* block_indices [[type("svmptr_t")]],
int* block_indices_begins [[type("svmptr_t")]],
int* subsequence_begins [[type("svmptr_t")]],
+ int* selected_sequence_ids [[type("svmptr_t")]],
float* output [[type("svmptr_t")]],
float* lse [[type("svmptr_t")]],
- int q_len// 1
+ int q_len,// 1
+ int selected_sequence_count
) {
//# batch=1, seq_num=1 or >1
//# query [seq_idx, seq_num, head_num, head_size]
@@ -121,6 +147,10 @@ extern "C" _GENX_MAIN_ void KERNEL_NAME(
//# Each WG processes a partition, which is KV_PARTITION_SIZE long and multiple of KV_BLOCK_SIZE.
//# KV_BLOCK_SIZE can be 32/64/128/256, etc.
const uint seq_idx = cm_global_id(0);
+ if (seq_idx >= selected_sequence_count) {
+ return;
+ }
+ const uint orig_seq_idx = selected_sequence_ids[seq_idx];
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;
//# KV_PARTITION_SIZE --> EU thread
@@ -128,18 +158,49 @@ extern "C" _GENX_MAIN_ void KERNEL_NAME(
const uint kv_partition_num = cm_group_count(2);
const uint kv_partition_idx = cm_group_id(2);
- const uint kv_len = past_lens[seq_idx] + 1;
+ 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;
+ const uint subseq_q_end = (uint)subseq_q_end_i;
+ const uint subseq_q_len = (uint)(subseq_q_end_i - subseq_q_begin_i);
+
+ // Single-token path uses the latest token from each subsequence.
+ const uint q_token_idx = subseq_q_end - 1;
+ const uint kv_len = past_lens[orig_seq_idx] + subseq_q_len;
+ const uint seq_kv_partition_num = (kv_len + KV_PARTITION_SIZE - 1) / KV_PARTITION_SIZE;
+
+ const uint block_begin = block_indices_begins[orig_seq_idx];
+ const uint block_end = block_indices_begins[orig_seq_idx + 1];
+ const uint total_blocks_num = block_end - block_begin;
+
// The code here requires KV_PARTITION_SIZE to be an integer multiple of KV_BLOCK_SIZE.
- const uint start_block_idx = block_indices_begins[seq_idx] + kv_partition_idx * (KV_PARTITION_SIZE / KV_BLOCK_SIZE);
+ const uint blocks_per_partition = (KV_PARTITION_SIZE / KV_BLOCK_SIZE);
+ const uint start_block_idx = block_begin + kv_partition_idx * blocks_per_partition;
+
+ if(kv_partition_idx * KV_PARTITION_SIZE >= kv_len || start_block_idx >= block_end) {
+ // For sequences shorter than global kv_partition_num, this partition is inactive.
+ // Write neutral values so reduction kernel can safely process all partitions.
+ #pragma unroll
+ for (int qi = 0; qi < Q_head_chunk_size; qi++) {
+ matrix<float, REG_M, REG_N> zero = 0.0f;
+ uint o_offset = seq_idx * kv_partition_num * HEADS_NUM * HEAD_SIZE + kv_partition_num * (head_num_idx + qi) * HEAD_SIZE + wg_thread_id * 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>());
+ }
- if(kv_partition_idx * KV_PARTITION_SIZE > kv_len) {
+ uint lse_offset = seq_idx * HEADS_NUM * kv_partition_num + (head_num_idx + qi) * kv_partition_num + wg_thread_id;
+ lse[lse_offset] = -3e38f;
+ }
return;
}
- const uint total_blocks_num = (kv_len + KV_BLOCK_SIZE - 1) / KV_BLOCK_SIZE;
constexpr uint kv_pitch = HEAD_SIZE * sizeof(KV_ELEMENT_TYPE);
//# Load Q into register(as dpas-A tile)
- const uint qo_offset = (seq_idx * HEADS_NUM * q_len + head_num_idx) * HEAD_SIZE;
+ const uint qo_offset = (q_token_idx * HEADS_NUM + head_num_idx) * HEAD_SIZE;
matrix <half, Q_head_chunk_size, HEAD_SIZE> Qmat = 0;
cm_svm_block_read<half, Q_head_chunk_size * HEAD_SIZE>((svmptr_t)(query + qo_offset), Qmat.format<half>());
@@ -152,15 +213,15 @@ extern "C" _GENX_MAIN_ void KERNEL_NAME(
#else
constexpr uint per_k_block_element_num = KV_BLOCK_SIZE * KV_HEADS_NUM * HEAD_SIZE;
#endif
- uint block_num = KV_PARTITION_SIZE / KV_BLOCK_SIZE;
+ uint block_num = blocks_per_partition;
uint leftover_size = 0;
- if(kv_partition_idx == kv_partition_num - 1) {
+ if(kv_partition_idx == seq_kv_partition_num - 1) {
// last partition
leftover_size = (kv_len - KV_PARTITION_SIZE * kv_partition_idx) % KV_PARTITION_SIZE;
}
- if(block_num > total_blocks_num - start_block_idx) {
- block_num = total_blocks_num - start_block_idx;
+ if(block_num > block_end - start_block_idx) {
+ block_num = block_end - start_block_idx;
}
//# rS = Q @ Kt
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/pa_single_token_finalization.cm b/src/plugins/intel_gpu/src/graph/impls/cm/pa_single_token_finalization.cm
index 5768eda3e56..6cb92a59478 100644
--- a/src/plugins/intel_gpu/src/graph/impls/cm/pa_single_token_finalization.cm
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/pa_single_token_finalization.cm
@@ -19,9 +19,16 @@ 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_sequence_ids [[type("svmptr_t")]],
+ int selected_sequence_count,
int kv_partition_num
) {
auto batch = cm_global_id(0);
+ if (batch >= selected_sequence_count) {
+ return;
+ }
+ auto orig_batch = selected_sequence_ids[batch];
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);
@@ -73,6 +80,12 @@ extern "C" _GENX_MAIN_ void KERNEL_NAME(
out_mat = cm_mul<half>(out_mat_f32, (float)1.0f);
// write output
- uint output_offset = batch * HEADS_NUM * HEAD_SIZE + head * HEAD_SIZE + offset;
+ uint q_begin = subsequence_begins[orig_batch];
+ uint q_end = subsequence_begins[orig_batch + 1];
+ if (q_end <= q_begin) {
+ return;
+ }
+ uint q_token_idx = q_end - 1;
+ 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>());
}
\ No newline at end of file
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 90977cc577e..b605e585dab 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
@@ -4,13 +4,19 @@
#include "paged_attention.hpp"
+#include <algorithm>
#include <array>
+#include <cctype>
#include <cstdint>
+#include <limits>
#include <memory>
+#include <numeric>
#include <utility>
+#include <vector>
#include "common_utils/jitter.hpp"
#include "common_utils/kernel_generator_base.hpp"
+#include "include/xattn_subseq_meta.hpp"
#include "intel_gpu/graph/kernel_impl_params.hpp"
#include "intel_gpu/primitives/paged_attention.hpp"
#include "kv_cache_inst.h"
@@ -30,6 +36,43 @@
namespace ov::intel_gpu::cm {
+namespace {
+
+// -----------------------------
+// Input readers
+// -----------------------------
+
+std::vector<int32_t> read_i32_input(const kernel_impl_params& params, size_t input_idx) {
+ const auto& memory_deps = params.memory_deps;
+ const auto mem = memory_deps.at(input_idx);
+ mem_lock<int32_t, mem_lock_type::read> lock(mem, *params.strm);
+ return std::vector<int32_t>(lock.begin(), lock.end());
+}
+
+std::vector<int32_t> read_i32_input(const primitive_inst& instance, size_t input_idx) {
+ auto mem = instance.input_memory_ptr(input_idx);
+ mem_lock<int32_t, mem_lock_type::read> lock(mem, instance.get_network().get_stream());
+ return std::vector<int32_t>(lock.begin(), lock.end());
+}
+
+// -----------------------------
+// Routing/config helpers
+// -----------------------------
+
+MixedRouteMode get_mixed_route_mode_from_config(const kernel_impl_params& params) {
+ std::string mode = params.get_program().get_config().get_pa_mixed_route_mode();
+ std::transform(mode.begin(), mode.end(), mode.begin(), [](unsigned char c) {
+ return static_cast<char>(std::tolower(c));
+ });
+ if (mode == "split") {
+ return MixedRouteMode::SPLIT;
+ }
+
+ return MixedRouteMode::MULTI;
+}
+
+} // namespace
+
class PagedAttentionCmImpl : public PrimitiveImplCM {
public:
DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::cm::PagedAttentionCmImpl)
@@ -52,8 +95,10 @@ public:
}
explicit PagedAttentionCmImpl(const kernel_impl_params& params) : PagedAttentionCmImpl() {
const auto desc = params.typed_desc<paged_attention>();
+ m_mixed_route_mode = get_mixed_route_mode_from_config(params);
- GPU_DEBUG_TRACE_DETAIL << "ov::intel_gpu::cm::PagedAttentionCmImpl::PagedAttentionCmImpl()" << std::endl;
+ GPU_DEBUG_TRACE_DETAIL << "ov::intel_gpu::cm::PagedAttentionCmImpl::PagedAttentionCmImpl()"
+ << " with mode: " << (m_mixed_route_mode == MixedRouteMode::SPLIT ? "split" : "multi") << std::endl;
add_stage(kv_cache_update, params);
add_stage(pa_single_token, params);
add_stage(pa_single_token_finalization, params);
@@ -76,45 +121,132 @@ public:
}
}
- void update_xattn_rt_params(const kernel_impl_params& params) {
+ void update_xattn_rt_params(const primitive_inst& instance) {
+ const auto& params = *instance.get_impl_params();
const auto desc = params.typed_desc<paged_attention>();
+ auto rt_params = static_cast<PagedAttentionRuntimeParams*>(m_rt_params.get());
- // XAttention estimate is following afer kvcache_update.
- auto out_shape = params.output_layouts[0].get_shape();
const size_t block_size = get_xattn_block_size(params);
const uint32_t block_wg_n = XAttentionEstimateGeneratorBase::get_block_wg_n(params);
const uint32_t block_wg_m = XAttentionEstimateGeneratorBase::get_block_wg_m(params);
- const size_t kv_len = get_max_context_len(params);
- const size_t q_len = out_shape[0];
- const size_t N = kv_len / STRIDE;
- const size_t N_kq_groups = ceil_div(N, block_wg_n);
-
- const auto q_block_pad = ceil_div(q_len, block_size);
- const auto sum_per_token_in_block = block_size / STRIDE;
- const auto k_block_in_group = block_wg_n / sum_per_token_in_block;
- const auto k_block_pad = k_block_in_group * N_kq_groups;
-
- auto rt_params = static_cast<PagedAttentionRuntimeParams*>(m_rt_params.get());
- rt_params->block_wg_m = block_wg_m;
- rt_params->q_block_pad = q_block_pad;
- rt_params->k_block_pad = k_block_pad;
-
+ const size_t heads_num = desc->heads_num;
const size_t merged_q_num = PagedAttentionGeneratorMultiToken::get_wg_seq_len(params) / block_size;
- rt_params->q_block_pad_merged = ceil_div(q_block_pad, merged_q_num);
+ const size_t sum_per_token_in_block = block_size / STRIDE;
+ const size_t k_block_in_group = block_wg_n / sum_per_token_in_block;
+ const size_t sizeof_softmax = sizeof(float);
+
+ const auto subsequence_begins = read_i32_input(params, PagedAttentionInputIdx::SUBSEQUENCE_BEGINS);
+ const auto past_lens = read_i32_input(params, PagedAttentionInputIdx::PAST_LENS);
+ const auto block_indices_begins = read_i32_input(instance, PagedAttentionInputIdx::BLOCK_INDICES_BEGINS);
+
+ const bool use_split_mixed = rt_params->stage == PagedAttentionStage::MIXED && m_mixed_route_mode == MixedRouteMode::SPLIT;
+
+ size_t total_wg_count = 0;
+ size_t max_q_block_pad = 0;
+ size_t max_merged_q_blocks = 0;
+ size_t cumul_kq_max_bytes = 0;
+ size_t cumul_exp_sum_bytes = 0;
+ size_t cumul_mask_elems = 0;
+ size_t cumul_mask_wg_elems = 0;
+ size_t num_xattn_subseqs = 0;
+
+ m_xattn_meta.clear();
+ m_xattn_find_wg_map.clear();
+ m_xattn_post_wg_map.clear();
+ m_xattn_meta.reserve((subsequence_begins.size() > 0 ? (subsequence_begins.size() - 1) : 0) * XATTN_META_STRIDE);
+ m_xattn_find_wg_map.reserve((subsequence_begins.size() > 0 ? (subsequence_begins.size() - 1) : 0) * 2);
+ m_xattn_post_wg_map.reserve((subsequence_begins.size() > 0 ? (subsequence_begins.size() - 1) : 0) * 2);
+
+ auto to_i32_checked = [](size_t value, const char* field_name) {
+ OPENVINO_ASSERT(value <= static_cast<size_t>(std::numeric_limits<int32_t>::max()),
+ "XAttention metadata value is too large for int32 field ",
+ field_name,
+ ": ",
+ value);
+ return static_cast<int32_t>(value);
+ };
+
+ for (size_t i = 0; i + 1 < subsequence_begins.size(); ++i) {
+ const auto q_len = static_cast<size_t>(std::max<int32_t>(subsequence_begins[i + 1] - subsequence_begins[i], 0));
+ if (q_len == 0)
+ continue;
+
+ if (use_split_mixed) {
+ const auto past_len = static_cast<size_t>(std::max<int32_t>(past_lens[i], 0));
+ const bool decode_subseq = (q_len == 1) && (past_len > 0);
+ if (decode_subseq)
+ continue;
+ }
- const size_t head_size = desc->k_head_size;
+ const auto past_len_s = static_cast<size_t>(std::max<int32_t>(past_lens[i], 0));
+ const size_t kv_len = past_len_s + q_len;
+ const size_t subseq_q_begin = static_cast<size_t>(subsequence_begins[i]);
+ const int32_t bi_begin = (i < block_indices_begins.size()) ? block_indices_begins[i] : 0;
+
+ const size_t M_s = q_len / STRIDE;
+ const size_t N_s = kv_len / STRIDE;
+ const size_t q_stride_pad_s = round_up_to(M_s, block_wg_m);
+ const size_t N_kq_groups_s = ceil_div(N_s, block_wg_n);
+ const size_t q_block_pad_s = ceil_div(q_len, block_size);
+ const size_t k_block_pad_s = k_block_in_group * N_kq_groups_s;
+ const size_t merged_q_blocks_s = ceil_div(q_block_pad_s, merged_q_num);
+ const size_t k_block_s = ceil_div(kv_len, block_size);
+ const size_t q_block_s = ceil_div(q_len, block_size);
+ const size_t causal_start_s = k_block_s - q_block_s;
+ const size_t q_start_strided_s = (kv_len - q_len) / STRIDE;
+ const size_t wg_count_s = N_kq_groups_s * (q_stride_pad_s / block_wg_m);
+ const int32_t subseq_id = to_i32_checked(num_xattn_subseqs, "subseq_id");
+
+ m_xattn_meta.push_back(to_i32_checked(subseq_q_begin, "subseq_q_begin"));
+ m_xattn_meta.push_back(to_i32_checked(q_len, "q_len"));
+ m_xattn_meta.push_back(to_i32_checked(M_s, "M"));
+ m_xattn_meta.push_back(to_i32_checked(N_s, "N"));
+ m_xattn_meta.push_back(to_i32_checked(q_stride_pad_s, "q_stride_pad"));
+ m_xattn_meta.push_back(to_i32_checked(N_kq_groups_s, "N_kq_groups"));
+ m_xattn_meta.push_back(to_i32_checked(q_block_pad_s, "q_block_pad"));
+ m_xattn_meta.push_back(to_i32_checked(k_block_pad_s, "k_block_pad"));
+ m_xattn_meta.push_back(to_i32_checked(causal_start_s, "causal_start"));
+ m_xattn_meta.push_back(to_i32_checked(q_start_strided_s, "q_start_strided"));
+ m_xattn_meta.push_back(to_i32_checked(cumul_kq_max_bytes, "cumul_kq_max_bytes"));
+ m_xattn_meta.push_back(to_i32_checked(cumul_exp_sum_bytes, "cumul_exp_sum_bytes"));
+ m_xattn_meta.push_back(to_i32_checked(cumul_mask_elems, "cumul_mask_elems"));
+ m_xattn_meta.push_back(to_i32_checked(cumul_mask_wg_elems, "cumul_mask_wg_elems"));
+ m_xattn_meta.push_back(bi_begin);
+ // Store global WG start offset for this subsequence (prefix sum before adding this subsequence's wg_count_s).
+ m_xattn_meta.push_back(to_i32_checked(total_wg_count, "total_wg_count"));
+
+ for (size_t m = 0; m < q_block_pad_s; ++m) {
+ m_xattn_find_wg_map.push_back(subseq_id);
+ m_xattn_find_wg_map.push_back(to_i32_checked(m, "find_q_block_idx"));
+ }
- const auto M = q_len / STRIDE; //# will slient drop the tails which is less than `stride`
- const auto K = STRIDE * head_size;
+ for (size_t m_merged = 0; m_merged < merged_q_blocks_s; ++m_merged) {
+ m_xattn_post_wg_map.push_back(subseq_id);
+ m_xattn_post_wg_map.push_back(to_i32_checked(m_merged, "post_merged_q_block_idx"));
+ }
- const size_t q_stride_pad = round_up_to(M, block_wg_m);
+ cumul_kq_max_bytes += N_kq_groups_s * q_stride_pad_s * sizeof_softmax * heads_num;
+ cumul_exp_sum_bytes += q_stride_pad_s * k_block_pad_s * sizeof_softmax * heads_num;
+ cumul_mask_elems += q_block_pad_s * k_block_pad_s * heads_num;
+ cumul_mask_wg_elems += merged_q_blocks_s * k_block_pad_s * heads_num;
+ // Advance prefix sum so the next subsequence gets its own global WG start offset.
+ total_wg_count += wg_count_s;
+
+ max_q_block_pad = std::max(max_q_block_pad, q_block_pad_s);
+ max_merged_q_blocks = std::max(max_merged_q_blocks, merged_q_blocks_s);
+ num_xattn_subseqs++;
+ }
- rt_params->N_kq_groups = N_kq_groups;
- rt_params->M = M;
- rt_params->N = N;
- rt_params->K = K;
- rt_params->q_stride_pad = q_stride_pad;
rt_params->xattn_block_size = block_size;
+ rt_params->xattn_num_subseqs = num_xattn_subseqs;
+ rt_params->xattn_gemmqk_wg_count = total_wg_count;
+ rt_params->xattn_cumul_kq_max_bytes = cumul_kq_max_bytes;
+ rt_params->xattn_cumul_exp_sum_bytes = cumul_exp_sum_bytes;
+ rt_params->xattn_cumul_mask_elems = cumul_mask_elems;
+ rt_params->xattn_cumul_mask_wg_elems = cumul_mask_wg_elems;
+ rt_params->xattn_meta_num_int32s = m_xattn_meta.size();
+ rt_params->xattn_find_wg_count = m_xattn_find_wg_map.size() / 2;
+ rt_params->xattn_post_wg_count = m_xattn_post_wg_map.size() / 2;
}
void update_rt_params(const primitive_inst& instance) override {
@@ -127,6 +259,10 @@ public:
OPENVINO_ASSERT(!params.is_dynamic());
auto rt_params = static_cast<PagedAttentionRuntimeParams*>(m_rt_params.get());
const auto& desc = params.typed_desc<paged_attention>();
+ 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->enable_xattn_estimation = false;
rt_params->stage = get_paged_attention_stage(params);
const auto max_context_len = get_max_context_len(params);
@@ -138,16 +274,219 @@ public:
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);
+ rt_params->single_token_selected_count = rt_params->batch_size_in_sequences;
GPU_DEBUG_TRACE_DETAIL << " partition_size: " << partition_size << " num_of_partitions: " << rt_params->num_of_partitions << std::endl;
} else {
+ const auto subsequence_begins = read_i32_input(params, PagedAttentionInputIdx::SUBSEQUENCE_BEGINS);
+ 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;
+ 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) {
+ continue;
+ }
+
+ 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);
+ if (decode_subsequence) {
+ rt_params->single_token_selected_count++;
+ } else {
+ rt_params->multi_token_wg_count += ceil_div(q_len, wg_seq_len);
+ }
+ } else {
+ rt_params->multi_token_wg_count += ceil_div(q_len, wg_seq_len);
+ }
+ }
+
+ 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 (desc->has_xattention) {
- update_xattn_rt_params(params);
+ validate_xattn_inputs(params, rt_params->batch_size_in_sequences);
+
+ rt_params->enable_xattn_estimation = true;
+ update_xattn_rt_params(instance);
} else {
rt_params->xattn_block_size = 1; // disable xattn for pa
}
}
}
+ void prepare_multi_token_mapping(primitive_inst& instance) {
+ const auto& params = *instance.get_impl_params();
+ auto rt_params = static_cast<PagedAttentionRuntimeParams*>(m_rt_params.get());
+ OPENVINO_ASSERT(rt_params != nullptr);
+ if (rt_params->multi_token_wg_count == 0) {
+ return;
+ }
+ auto& stream = instance.get_network().get_stream();
+
+ const auto subsequence_begins = read_i32_input(params, PagedAttentionInputIdx::SUBSEQUENCE_BEGINS);
+
+ const auto wg_seq_len = static_cast<int32_t>(PagedAttentionGeneratorMultiToken::get_wg_seq_len(params));
+ auto mapping_mem = instance.get_intermediates_memories()[PagedAttentionInternBuffIdx::MULTI_TOKEN_WG_MAPPING];
+ mem_lock<int32_t, mem_lock_type::write> mapping_lock(mapping_mem, stream);
+ const size_t expected_mapping_size = rt_params->multi_token_wg_count * 2;
+ OPENVINO_ASSERT(mapping_mem->count() >= expected_mapping_size,
+ "Insufficient multi-token mapping buffer size: expected at least ",
+ expected_mapping_size,
+ ", got ",
+ mapping_mem->count());
+ size_t mapping_idx = 0;
+
+ for (size_t subsequence_id = 0; subsequence_id + 1 < subsequence_begins.size(); ++subsequence_id) {
+ const int32_t q_begin = subsequence_begins[subsequence_id];
+ const int32_t q_end = subsequence_begins[subsequence_id + 1];
+
+ if (q_end <= q_begin) {
+ 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=",
+ mapping_idx,
+ ", expected_size=",
+ expected_mapping_size);
+ mapping_lock[mapping_idx++] = block_start;
+ mapping_lock[mapping_idx++] = static_cast<int32_t>(subsequence_id);
+ }
+ }
+
+ OPENVINO_ASSERT(mapping_idx == expected_mapping_size, "Unexpected multi-token mapping size: expected ", expected_mapping_size, ", got ", mapping_idx);
+ }
+
+ void prepare_single_token_selected_ids(primitive_inst& instance) {
+ auto rt_params = static_cast<PagedAttentionRuntimeParams*>(m_rt_params.get());
+ OPENVINO_ASSERT(rt_params != nullptr);
+ OPENVINO_ASSERT(rt_params->stage == PagedAttentionStage::GENERATE, "prepare_single_token_selected_ids is expected only for generate/decode stage");
+ auto& stream = instance.get_network().get_stream();
+
+ auto selected_ids_mem = instance.get_intermediates_memories()[PagedAttentionInternBuffIdx::SINGLE_TOKEN_SELECTED_SEQ_IDS];
+
+ mem_lock<int32_t, mem_lock_type::write> selected_ids_lock(selected_ids_mem, stream);
+ const size_t selected_capacity = selected_ids_mem->count();
+ OPENVINO_ASSERT(selected_capacity >= rt_params->batch_size_in_sequences,
+ "Insufficient single-token selected ids buffer size: expected at least ",
+ rt_params->batch_size_in_sequences,
+ ", got ",
+ selected_capacity);
+ std::iota(selected_ids_lock.begin(), selected_ids_lock.begin() + static_cast<std::ptrdiff_t>(rt_params->batch_size_in_sequences), 0);
+
+ rt_params->single_token_selected_count = rt_params->batch_size_in_sequences;
+ }
+
+ void prepare_split_mixed_selected_ids_and_mapping(primitive_inst& instance) {
+ const auto& params = *instance.get_impl_params();
+ auto rt_params = static_cast<PagedAttentionRuntimeParams*>(m_rt_params.get());
+ OPENVINO_ASSERT(rt_params != nullptr);
+ OPENVINO_ASSERT(rt_params->stage == PagedAttentionStage::MIXED && m_mixed_route_mode == MixedRouteMode::SPLIT,
+ "prepare_split_mixed_selected_ids_and_mapping must be used only in split mixed mode");
+
+ auto& stream = instance.get_network().get_stream();
+
+ const auto subsequence_begins = read_i32_input(params, PagedAttentionInputIdx::SUBSEQUENCE_BEGINS);
+ const auto past_lens = read_i32_input(params, PagedAttentionInputIdx::PAST_LENS);
+
+ auto selected_ids_mem = instance.get_intermediates_memories()[PagedAttentionInternBuffIdx::SINGLE_TOKEN_SELECTED_SEQ_IDS];
+ auto mapping_mem = instance.get_intermediates_memories()[PagedAttentionInternBuffIdx::MULTI_TOKEN_WG_MAPPING];
+ mem_lock<int32_t, mem_lock_type::write> selected_ids_lock(selected_ids_mem, stream);
+ mem_lock<int32_t, mem_lock_type::write> mapping_lock(mapping_mem, stream);
+
+ const size_t selected_capacity = selected_ids_mem->count();
+ const size_t expected_mapping_size = rt_params->multi_token_wg_count * 2;
+ OPENVINO_ASSERT(mapping_mem->count() >= expected_mapping_size,
+ "Insufficient multi-token mapping buffer size: expected at least ",
+ expected_mapping_size,
+ ", got ",
+ mapping_mem->count());
+
+ 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;
+
+ for (size_t sequence_id = 0; sequence_id + 1 < subsequence_begins.size(); ++sequence_id) {
+ const int32_t q_begin = subsequence_begins[sequence_id];
+ const int32_t q_end = subsequence_begins[sequence_id + 1];
+ if (q_end <= q_begin) {
+ continue;
+ }
+
+ 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);
+
+ if (decode_subsequence) {
+ OPENVINO_ASSERT(selected_count < selected_capacity,
+ "Single-token selected ids write out of bounds: idx=",
+ selected_count,
+ ", capacity=",
+ selected_capacity);
+ selected_ids_lock[selected_count++] = static_cast<int32_t>(sequence_id);
+ 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=",
+ mapping_idx,
+ ", expected_size=",
+ expected_mapping_size);
+ mapping_lock[mapping_idx++] = block_start;
+ mapping_lock[mapping_idx++] = static_cast<int32_t>(sequence_id);
+ }
+ }
+
+ OPENVINO_ASSERT(selected_count == rt_params->single_token_selected_count,
+ "Unexpected selected ids count in split mixed mode: expected ",
+ rt_params->single_token_selected_count,
+ ", got ",
+ selected_count);
+ OPENVINO_ASSERT(mapping_idx == expected_mapping_size, "Unexpected multi-token mapping size: expected ", expected_mapping_size, ", got ", mapping_idx);
+
+ rt_params->single_token_selected_count = selected_count;
+ }
+
+ void prepare_xattn_metadata(primitive_inst& instance) {
+ auto rt_params = static_cast<PagedAttentionRuntimeParams*>(m_rt_params.get());
+ OPENVINO_ASSERT(rt_params != nullptr);
+ if (!rt_params->enable_xattn_estimation || m_xattn_meta.empty())
+ return;
+
+ auto& stream = instance.get_network().get_stream();
+ auto meta_mem = instance.get_intermediates_memories()[PagedAttentionInternBuffIdx::XATTN_SUBSEQ_META];
+ OPENVINO_ASSERT(meta_mem->count() >= m_xattn_meta.size(),
+ "Insufficient xattn metadata buffer size: expected at least ",
+ m_xattn_meta.size(),
+ ", got ",
+ meta_mem->count());
+ mem_lock<int32_t, mem_lock_type::write> meta_lock(meta_mem, stream);
+ std::copy_n(m_xattn_meta.begin(), m_xattn_meta.size(), meta_lock.begin());
+
+ auto find_map_mem = instance.get_intermediates_memories()[PagedAttentionInternBuffIdx::XATTN_FIND_WG_MAP];
+ OPENVINO_ASSERT(find_map_mem->count() >= m_xattn_find_wg_map.size(),
+ "Insufficient xattn find-map buffer size: expected at least ",
+ m_xattn_find_wg_map.size(),
+ ", got ",
+ find_map_mem->count());
+ mem_lock<int32_t, mem_lock_type::write> find_map_lock(find_map_mem, stream);
+ std::copy_n(m_xattn_find_wg_map.begin(), m_xattn_find_wg_map.size(), find_map_lock.begin());
+
+ auto post_map_mem = instance.get_intermediates_memories()[PagedAttentionInternBuffIdx::XATTN_POST_WG_MAP];
+ OPENVINO_ASSERT(post_map_mem->count() >= m_xattn_post_wg_map.size(),
+ "Insufficient xattn post-map buffer size: expected at least ",
+ m_xattn_post_wg_map.size(),
+ ", got ",
+ post_map_mem->count());
+ mem_lock<int32_t, mem_lock_type::write> post_map_lock(post_map_mem, stream);
+ std::copy_n(m_xattn_post_wg_map.begin(), m_xattn_post_wg_map.size(), post_map_lock.begin());
+ }
+
// update impl_parameter and rt_parameter
void update(primitive_inst& inst, const kernel_impl_params& impl_params) override {
PrimitiveImplCM::update(inst, impl_params);
@@ -166,9 +505,14 @@ public:
std::vector<event::ptr> res_event = events;
res_event = {execute_stage(res_event, instance, kv_cache_update)};
- if (rt_params->stage == PagedAttentionStage::PREFILL || rt_params->stage == PagedAttentionStage::MIXED) {
- const bool is_xattn_bypassed = bypass_xattn(params);
- if (is_xattn_bypassed || desc->has_xattention == false) {
+ const auto execute_multi_token_path = [&]() {
+ if (rt_params->multi_token_wg_count == 0) {
+ return;
+ }
+
+ const bool xattn_enabled = desc->has_xattention && rt_params->enable_xattn_estimation;
+ const bool xattn_disabled = !xattn_enabled || bypass_xattn(params);
+ if (xattn_disabled) {
GPU_DEBUG_TRACE_DETAIL << "Execute multi-token stage w/o XAttention estimation stages." << std::endl;
res_event = {execute_stage(res_event, instance, *pa_multi_token_1)};
@@ -185,6 +529,7 @@ public:
Stage::Ptr& xattn_post_proc = use_256 ? xattn_estimate_post_proc_256 : xattn_estimate_post_proc;
Stage::Ptr& pa_multi_token = use_256 ? pa_multi_token_256 : pa_multi_token_128;
+ prepare_xattn_metadata(instance);
res_event = {execute_stage(res_event, instance, xattn_gemmqk)};
XATTN_DUMP(instance, PagedAttentionInternBuffIdx::XATTN_GEMMQK_MAX); // 2: kq_max_wg
XATTN_DUMP(instance,
@@ -192,15 +537,37 @@ public:
res_event = {execute_stage(res_event, instance, xattn_find_block)};
XATTN_DUMP(instance, PagedAttentionInternBuffIdx::XATTN_BLOCKMASK); // 4: sparse_block_mask
#if FIND_DEBUG_ACC
- XATTN_DUMP(instance, PagedAttentionInternBuffIdx::XATTN_FIND_DEBUG_ACC); // 6: kq_sum for debug purpose only
+ XATTN_DUMP(instance, PagedAttentionInternBuffIdx::XATTN_FIND_DEBUG_ACC);
#endif
res_event = {execute_stage(res_event, instance, xattn_post_proc)};
res_event = {execute_stage(res_event, instance, pa_multi_token)};
}
+ };
+
+ if (rt_params->stage == PagedAttentionStage::PREFILL) {
+ prepare_multi_token_mapping(instance);
+ execute_multi_token_path();
+ } else if (rt_params->stage == PagedAttentionStage::MIXED) {
+ GPU_DEBUG_TRACE_DETAIL << "Execute Mixed stage with mode: " << (m_mixed_route_mode == MixedRouteMode::SPLIT ? "SPLIT" : "MERGE") << ", "
+ << rt_params->single_token_selected_count << " single token selected and " << rt_params->multi_token_wg_count
+ << " workgroups for multi token." << std::endl;
+ if (m_mixed_route_mode == MixedRouteMode::SPLIT) {
+ prepare_split_mixed_selected_ids_and_mapping(instance);
+ if (rt_params->single_token_selected_count > 0) {
+ res_event = {execute_stage(res_event, instance, pa_single_token)};
+ res_event = {execute_stage(res_event, instance, pa_single_token_finalization)};
+ }
+ execute_multi_token_path();
+ } else {
+ prepare_multi_token_mapping(instance);
+ execute_multi_token_path();
+ }
} else {
+ prepare_single_token_selected_ids(instance);
res_event = {execute_stage(res_event, instance, pa_single_token)};
res_event = {execute_stage(res_event, instance, pa_single_token_finalization)};
}
+
return res_event[0];
}
@@ -210,7 +577,8 @@ public:
// In case of MIXED mode execution Paged Attention may require dispatch data update and internal
// buffers reallocation even if the input shapes haven't been changed. Therefore, check the current execution
// mode and update parameters if needed
- return stage == PagedAttentionStage::MIXED;
+ return stage == PagedAttentionStage::MIXED ||
+ ((stage == PagedAttentionStage::PREFILL || stage == PagedAttentionStage::UNKNOWN) && get_batch_size_in_sequences(impl_params.input_layouts) > 1);
}
[[nodiscard]] std::vector<BufferDescriptor> get_internal_buffer_descs(const kernel_impl_params& params) const override {
@@ -234,36 +602,78 @@ public:
internal_buffers.emplace_back(tmp_out_elements_count, ov::element::f32); // 0: intermediate partition output
internal_buffers.emplace_back(buf_elements_count, ov::element::f32); // 1: softmax exp_sums
+ internal_buffers.emplace_back(2, ov::element::i32, true, false); // 2: unused multi-token mapping placeholder (lockable, not shareable)
+ internal_buffers.emplace_back(total_tokens,
+ ov::element::i32,
+ true,
+ false); // 3: selected sequence ids (lockable for mem_lock<write>, not shareable)
GPU_DEBUG_TRACE_DETAIL << " internal buffer sizes: tmp_out=" << tmp_out_elements_count * 4 << " exp_sums=" << buf_elements_count * 4 << std::endl;
} else {
- internal_buffers.emplace_back(16, ov::element::f32); // 0: intermediate partition output
- internal_buffers.emplace_back(16, ov::element::f32); // 1: softmax exp_sums
-
- // internal buffer for XAttention
- if (desc->has_xattention) {
- auto count_kq_max_wg = static_cast<int64_t>(desc->heads_num * rt_params->N_kq_groups * rt_params->q_stride_pad);
- internal_buffers.emplace_back(count_kq_max_wg, ov::element::f32); // 2: kq_max_wg
-
- auto count_kq_exp_partial_sum = static_cast<int64_t>(desc->heads_num * rt_params->q_stride_pad * rt_params->k_block_pad);
- internal_buffers.emplace_back(count_kq_exp_partial_sum, ov::element::f32); // 3: kq_exp_partial_sum
-
- auto count_elements_mask = static_cast<int64_t>(desc->heads_num * rt_params->q_block_pad * rt_params->k_block_pad);
- internal_buffers.emplace_back(count_elements_mask, ov::element::boolean); // 4: sparse_block_mask
+ int64_t decode_tmp_out_elements_count = 16;
+ 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;
+ 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);
+ decode_tmp_out_elements_count =
+ static_cast<int64_t>(rt_params->single_token_selected_count * desc->heads_num * desc->v_head_size * rt_params->num_of_partitions);
+ }
- auto count_elements_mask_merged = static_cast<int64_t>(desc->heads_num * rt_params->q_block_pad_merged * rt_params->k_block_pad);
- internal_buffers.emplace_back(count_elements_mask_merged, ov::element::boolean); // 5: sparse_block_mask_wg
+ internal_buffers.emplace_back(decode_tmp_out_elements_count, ov::element::f32); // 0: intermediate partition output
+ internal_buffers.emplace_back(decode_buf_elements_count, ov::element::f32); // 1: softmax exp_sums
+ internal_buffers.emplace_back(std::max<int64_t>(2, static_cast<int64_t>(rt_params->multi_token_wg_count * 2)),
+ ov::element::i32,
+ true,
+ false); // 2: multi-token mapping (lockable for mem_lock<write>, not shareable)
+ internal_buffers.emplace_back(std::max<int64_t>(1, static_cast<int64_t>(rt_params->batch_size_in_sequences)),
+ ov::element::i32,
+ true,
+ false); // 3: selected ids (lockable for mem_lock<write>, not shareable)
+
+ // internal buffer for XAttention (cumulative sizes across all subsequences)
+ if (rt_params->enable_xattn_estimation) {
+ auto count_kq_max_wg = static_cast<int64_t>(rt_params->xattn_cumul_kq_max_bytes / sizeof(float));
+ internal_buffers.emplace_back(std::max<int64_t>(1, count_kq_max_wg), ov::element::f32); // 4: kq_max_wg
+
+ auto count_kq_exp_partial_sum = static_cast<int64_t>(rt_params->xattn_cumul_exp_sum_bytes / sizeof(float));
+ internal_buffers.emplace_back(std::max<int64_t>(1, count_kq_exp_partial_sum), ov::element::f32); // 5: kq_exp_partial_sum
+
+ auto count_elements_mask = static_cast<int64_t>(rt_params->xattn_cumul_mask_elems);
+ internal_buffers.emplace_back(std::max<int64_t>(1, count_elements_mask), ov::element::boolean); // 6: sparse_block_mask
+
+ auto count_elements_mask_merged = static_cast<int64_t>(rt_params->xattn_cumul_mask_wg_elems);
+ internal_buffers.emplace_back(std::max<int64_t>(1, count_elements_mask_merged), ov::element::boolean); // 7: sparse_block_mask_wg
+
+ auto count_meta_int32s = static_cast<int64_t>(rt_params->xattn_meta_num_int32s);
+ internal_buffers.emplace_back(std::max<int64_t>(16, count_meta_int32s),
+ ov::element::i32,
+ true,
+ false); // 8: xattn_subseq_meta (lockable for mem_lock<write>, not shareable)
+
+ auto count_find_map_int32s = static_cast<int64_t>(rt_params->xattn_find_wg_count * 2);
+ internal_buffers.emplace_back(std::max<int64_t>(2, count_find_map_int32s),
+ ov::element::i32,
+ true,
+ false); // 9: xattn_find_wg_map (lockable for mem_lock<write>, not shareable)
+
+ auto count_post_map_int32s = static_cast<int64_t>(rt_params->xattn_post_wg_count * 2);
+ internal_buffers.emplace_back(std::max<int64_t>(2, count_post_map_int32s),
+ ov::element::i32,
+ true,
+ false); // 10: xattn_post_wg_map (lockable for mem_lock<write>, not shareable)
#if FIND_DEBUG_ACC
- const size_t sum_per_n_token_in_block = static_cast<size_t>(rt_params->xattn_block_size / STRIDE);
- size_t q_block_input = rt_params->q_stride_pad / sum_per_n_token_in_block;
- auto count_elements_kq_sum = static_cast<int64_t>(desc->heads_num * q_block_input * rt_params->k_block_pad);
- internal_buffers.emplace_back(count_elements_kq_sum, ov::element::f16); // 6: kq_sum
+ auto count_elements_kq_sum = static_cast<int64_t>(rt_params->xattn_cumul_mask_elems);
+ internal_buffers.emplace_back(std::max<int64_t>(1, count_elements_kq_sum), ov::element::f16); // 11: kq_sum
#endif
GPU_DEBUG_TRACE_DETAIL << " internal buffer sizes: count_kq_max_wg=" << count_kq_max_wg * 4
- << " count_kq_exp_partial_sum=" << count_kq_exp_partial_sum * 4 << " count_elements_mask=" << count_elements_mask * 1
- << " count_elements_mask_merged=" << count_elements_mask_merged * 1 << std::endl;
+ << " count_kq_exp_partial_sum=" << count_kq_exp_partial_sum * 4 << " count_elements_mask=" << count_elements_mask
+ << " 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;
}
}
@@ -271,17 +681,45 @@ public:
}
[[nodiscard]] std::unique_ptr<primitive_impl> clone() const override {
- return make_deep_copy<PagedAttentionCmImpl>(this);
+ auto copy = make_deep_copy<PagedAttentionCmImpl>(this);
+ copy->m_mixed_route_mode = m_mixed_route_mode;
+ return copy;
}
private:
- // Get XAttention block size from input tensor.
- // If the input is not provided, throw exception.
- // If the input is not valid, return default block size based on GPU architecture.
+ std::vector<int32_t> m_xattn_meta;
+ std::vector<int32_t> m_xattn_find_wg_map;
+ std::vector<int32_t> m_xattn_post_wg_map;
+ MixedRouteMode m_mixed_route_mode = MixedRouteMode::SPLIT;
+
+ void validate_xattn_inputs(const kernel_impl_params& params, size_t batch_size) {
+ const auto& input_mem = params.memory_deps;
+
+ auto validate_input = [&](size_t idx, const char* name) {
+ const auto it = input_mem.find(idx);
+ if (it == input_mem.end() || it->second == nullptr)
+ OPENVINO_THROW("XAttention ", name, " input is required at index ", idx);
+
+ const auto input_size = it->second->count();
+ if (input_size != 1 && input_size != batch_size)
+ OPENVINO_THROW("XAttention ", name, " input size (", input_size, ") must be 1 or equal to batch size (", batch_size, ")");
+ };
+
+ validate_input(PagedAttentionInputIdx::XATTENTION_BLOCK_SIZE, "block size");
+ validate_input(PagedAttentionInputIdx::XATTENTION_THRESHOLD, "threshold");
+ }
+
size_t get_xattn_block_size(const kernel_impl_params& params, const size_t seq_idx = 0) {
constexpr int32_t block_size_128 = 128;
constexpr int32_t block_size_256 = 256;
+ const auto rt_params = static_cast<const PagedAttentionRuntimeParams*>(m_rt_params.get());
+ OPENVINO_ASSERT(rt_params != nullptr, "PagedAttention runtime params are not initialized");
+ OPENVINO_ASSERT(rt_params->enable_xattn_estimation, "XAttention block size must be accessed only when enable_xattn_estimation is true");
+
+ const auto desc = params.typed_desc<paged_attention>();
+ OPENVINO_ASSERT(desc->has_xattention, "XAttention block size must be accessed only when has_xattention is true");
+
const auto& input_mem = params.memory_deps;
const auto it = input_mem.find(PagedAttentionInputIdx::XATTENTION_BLOCK_SIZE);
if (it == input_mem.end() || it->second == nullptr) {
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 ff507ef0335..caeafa3420a 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
@@ -67,17 +67,18 @@ size_t get_max_context_len(const kernel_impl_params& params) {
return paged_attention_max_len;
}
-size_t get_past_len(const kernel_impl_params& params, const size_t seq_idx) {
- const auto& input_mem = params.memory_deps;
- const auto past_len = input_mem.at(PagedAttentionInputIdx::PAST_LENS);
- mem_lock<int32_t, mem_lock_type::read> past_len_mem_lock(past_len, *params.strm);
- const auto paged_attention_past_len = past_len_mem_lock[seq_idx];
- return paged_attention_past_len;
+size_t get_batch_size_in_sequences(const std::vector<layout>& input_layouts) {
+ const auto past_lens_shape = input_layouts[PagedAttentionInputIdx::PAST_LENS].get_shape();
+ OPENVINO_ASSERT(!past_lens_shape.empty(), "PAST_LENS layout must have at least 1 dimension");
+ return past_lens_shape[0];
}
// TODO: change xattn_thresh from scaler to memory... once we remove the converter node
// between parameter node "xattention_threshold.xxx" and paged_attention node.
float get_xattn_thresh(const kernel_impl_params& params, const size_t seq_idx) {
+ const auto desc = params.typed_desc<paged_attention>();
+ OPENVINO_ASSERT(desc->has_xattention, "XAttention threshold must be accessed only when has_xattention is true");
+
const auto& input_mem = params.memory_deps;
const auto it = input_mem.find(PagedAttentionInputIdx::XATTENTION_THRESHOLD);
if (it == input_mem.end() || it->second == nullptr) {
@@ -159,7 +160,6 @@ JitConstants PagedAttentionGeneratorBase::get_jit_constants(const kernel_impl_pa
auto split_size = get_kv_split_size(xe_arch);
jit.make("KV_STEP", split_size.first);
- jit.make("WG_SIZE", WG_SIZE);
jit.make("CAUSAL_MASK", 1);
// 0: no compression, 1: per-token compression for both key and value, 2: per-channel compression for key and per-token compression for value
@@ -212,6 +212,18 @@ JitConstants PagedAttentionGeneratorKVCacheUpdate::get_jit_constants(const kerne
return jit;
}
+size_t PagedAttentionGeneratorKVCacheUpdate::get_kv_update_wg_size(const RuntimeParams& params) {
+ constexpr size_t default_wg_size = 16;
+ const auto desc = params.typed_desc<paged_attention>();
+ if (get_kv_compressed(params) && desc->is_key_by_channel) {
+ const size_t block_size = desc->has_xattention ? PA_KV_CACHE_BLOCK_SIZE_XATTN : PA_KV_CACHE_BLOCK_SIZE_LEGACY;
+ OPENVINO_ASSERT(block_size % KV_SUB_BLOCK_SIZE == 0, "block_size (", block_size, ") must be divisible by KV_SUB_BLOCK_SIZE (", KV_SUB_BLOCK_SIZE, ")");
+ return block_size / KV_SUB_BLOCK_SIZE;
+ }
+
+ return default_wg_size;
+}
+
Arguments PagedAttentionGeneratorKVCacheUpdate::get_arguments_desc(const kernel_impl_params& params) const {
Arguments args;
args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::KEY}); // queries
@@ -240,14 +252,29 @@ DispatchDataFunc PagedAttentionGeneratorKVCacheUpdate::get_dispatch_data_func()
const size_t kv_len = get_input_kv_len(params);
const size_t kv_heads_num = desc->kv_heads_num;
- size_t kv_items = kv_len;
+ const size_t kv_wg_size = PagedAttentionGeneratorKVCacheUpdate::get_kv_update_wg_size(params);
+ size_t kv_items;
if (get_kv_compressed(params) && desc->is_key_by_channel) {
- kv_items = ceil_div(kv_len, KV_SUB_BLOCK_SIZE);
+ const auto past_lens_mem = params.memory_deps.at(PagedAttentionInputIdx::PAST_LENS);
+ mem_lock<int32_t, mem_lock_type::read> past_lens_lock(past_lens_mem, *params.strm);
+ const auto subseq_begins_mem = params.memory_deps.at(PagedAttentionInputIdx::SUBSEQUENCE_BEGINS);
+ mem_lock<int32_t, mem_lock_type::read> subseq_begins_lock(subseq_begins_mem, *params.strm);
+
+ const size_t batch_size = get_batch_size_in_sequences(params.input_layouts);
+ size_t total_sub_blocks = 0;
+ for (size_t i = 0; i < batch_size; ++i) {
+ const size_t past_tail = static_cast<size_t>(past_lens_lock[i]) % KV_SUB_BLOCK_SIZE;
+ const size_t cur_tokens = static_cast<size_t>(subseq_begins_lock[i + 1] - subseq_begins_lock[i]);
+ total_sub_blocks += ceil_div(past_tail + cur_tokens, KV_SUB_BLOCK_SIZE);
+ }
+ kv_items = total_sub_blocks;
+ } else {
+ kv_items = kv_len;
}
- const size_t wg_count = ceil_div(kv_items, WG_SIZE);
+ const size_t wg_count = ceil_div(kv_items, kv_wg_size);
- wgs.global = {1, kv_heads_num, wg_count * WG_SIZE};
- wgs.local = {1, 1, WG_SIZE};
+ wgs.global = {1, kv_heads_num, wg_count * kv_wg_size};
+ wgs.local = {1, 1, kv_wg_size};
auto& scalars = kd.params.scalars;
size_t key_pitch = desc->k_head_size * kv_heads_num;
@@ -290,8 +317,7 @@ DispatchDataFunc PagedAttentionGeneratorKVCacheUpdate::get_dispatch_data_func()
<< ", " << wgs.global[1] << ", " << wgs.global[2] << "]" << ", lws: [" << wgs.local[0] << ", " << wgs.local[1] << ", " << wgs.local[2]
<< "]" << std::endl;
}
- // TODO: support multiple sequences
- size_t batch_size_in_sequences = 1;
+ size_t batch_size_in_sequences = get_batch_size_in_sequences(params.input_layouts);
std::vector<size_t> scaler_value = {key_pitch, key_offset, value_pitch, value_offset, batch_size_in_sequences};
scalars.resize(scaler_value.size());
@@ -310,13 +336,14 @@ Arguments PagedAttentionGeneratorMultiToken::get_arguments_desc(const kernel_imp
Arguments args;
// Doesn't support Query with dynamic_padding
- args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::QUERY}); // query
- args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::KEY_CACHE}); // key_cache
- args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::VALUE_CACHE}); // value_cache
- args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::PAST_LENS}); // past_lens
- args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::BLOCK_INDICES}); // block_indices
- args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::BLOCK_INDICES_BEGINS}); // block_indices_begins
- args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::SUBSEQUENCE_BEGINS}); // subsequence_begins
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::QUERY}); // query
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::KEY_CACHE}); // key_cache
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::VALUE_CACHE}); // value_cache
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::PAST_LENS}); // past_lens
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::BLOCK_INDICES}); // block_indices
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::BLOCK_INDICES_BEGINS}); // block_indices_begins
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::SUBSEQUENCE_BEGINS}); // subsequence_begins
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::MULTI_TOKEN_WG_MAPPING}); // per-WG subsequence mapping
args.push_back({ArgumentDescriptor::Types::OUTPUT, 0});
args.push_back({ArgumentDescriptor::Types::SCALAR, 0}); // q_len
@@ -324,9 +351,7 @@ Arguments PagedAttentionGeneratorMultiToken::get_arguments_desc(const kernel_imp
if (_xattn_block_size > 1 && desc->has_xattention) {
args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::XATTN_BLOCKMASK}); // sparse_block_mask
args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::XATTN_BLOCKMASK_MERGED}); // sparse_block_mask_wg
-
- args.push_back({ArgumentDescriptor::Types::SCALAR, 1}); // q_block_pad
- args.push_back({ArgumentDescriptor::Types::SCALAR, 2}); // k_block_pad
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::XATTN_SUBSEQ_META}); // xattn_subseq_meta
}
return args;
}
@@ -362,43 +387,35 @@ JitConstants PagedAttentionGeneratorMultiToken::get_jit_constants(const kernel_i
DispatchDataFunc PagedAttentionGeneratorMultiToken::get_dispatch_data_func() const {
const size_t xattn_block_size = _xattn_block_size;
- return DispatchDataFunc{[xattn_block_size](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {
+ constexpr size_t wg_size = PagedAttentionGeneratorMultiToken::_wg_size;
+ return DispatchDataFunc{[xattn_block_size, wg_size](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {
auto& wgs = kd.params.workGroups;
auto& scalars = kd.params.scalars;
auto desc = params.typed_desc<paged_attention>();
auto rtp = static_cast<PagedAttentionRuntimeParams*>(rt_params);
- // OPENVINO_ASSERT(rt_params != nullptr);
+ OPENVINO_ASSERT(rt_params != nullptr);
const size_t heads_num = desc->heads_num;
- auto query_layout = params.input_layouts[PagedAttentionInputIdx::QUERY];
auto out_shape = params.output_layouts[0].get_shape();
- const size_t batch = out_shape.size() < 4 ? 1 : out_shape[0];
const size_t q_len = out_shape[0];
const size_t q_step = get_q_step(params);
const size_t wg_seq_len = get_wg_seq_len(params);
- const size_t wg_count = align_to(q_len, wg_seq_len) / wg_seq_len;
+ const size_t wg_count = rtp->multi_token_wg_count;
+ OPENVINO_ASSERT(wg_count > 0, "Invalid multi_token_wg_count in runtime params");
- wgs.global = {batch, heads_num, wg_count * WG_SIZE};
- wgs.local = {1, 1, WG_SIZE};
+ wgs.global = {1, heads_num, wg_count * wg_size};
+ wgs.local = {1, 1, wg_size};
if (DEBUG_ENABLED) { // Debug
std::cout << "PagedAttentionGeneratorMultiToken::get_dispatch_data_func: \n"
- << "\tbatch: " << batch << ", heads_num: " << heads_num << ", q_len: " << q_len << ", q_step: " << q_step
- << ", wg_seq_len: " << wg_seq_len << ", wg_count: " << wg_count << ", gws: [" << wgs.global[0] << ", " << wgs.global[1] << ", "
- << wgs.global[2] << "]" << ", lws: [" << wgs.local[0] << ", " << wgs.local[1] << ", " << wgs.local[2] << "]" << std::endl;
+ << "\theads_num: " << heads_num << ", q_len: " << q_len << ", q_step: " << q_step << ", wg_seq_len: " << wg_seq_len
+ << ", wg_count: " << wg_count << ", gws: [" << wgs.global[0] << ", " << wgs.global[1] << ", " << wgs.global[2] << "]" << ", lws: ["
+ << wgs.local[0] << ", " << wgs.local[1] << ", " << wgs.local[2] << "]" << std::endl;
}
- auto num_scalers = xattn_block_size > 1 && desc->has_xattention ? 3 : 1;
- scalars.resize(num_scalers);
+ scalars.resize(1);
scalars[0].t = ScalarDescriptor::Types::INT32;
scalars[0].v.s32 = static_cast<int32_t>(q_len);
- if (num_scalers > 1) {
- scalars[1].t = ScalarDescriptor::Types::INT32;
- scalars[1].v.s32 = static_cast<int32_t>(rtp->q_block_pad);
-
- scalars[2].t = ScalarDescriptor::Types::INT32;
- scalars[2].v.s32 = static_cast<int32_t>(rtp->k_block_pad);
- }
}};
}
@@ -436,13 +453,14 @@ Arguments PagedAttentionGeneratorSingleToken::get_arguments_desc(const kernel_im
const auto has_scores_output = params.output_layouts.size() > 1;
OPENVINO_ASSERT(!has_scores_output, "[GPU][CM] PagedAttentionGeneratorSingleToken with scores output is not supported yet");
- args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::QUERY}); // queries
- args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::KEY_CACHE}); // keys cache
- args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::VALUE_CACHE}); // values cache
- args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::PAST_LENS}); // past lens
- args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::BLOCK_INDICES}); // block indices
- args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::BLOCK_INDICES_BEGINS}); // block indices begins
- args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::SUBSEQUENCE_BEGINS}); // subsequence begins
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::QUERY}); // queries
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::KEY_CACHE}); // keys cache
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::VALUE_CACHE}); // values cache
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::PAST_LENS}); // past lens
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::BLOCK_INDICES}); // block indices
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::BLOCK_INDICES_BEGINS}); // block indices begins
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::SUBSEQUENCE_BEGINS}); // subsequence begins
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::SINGLE_TOKEN_SELECTED_SEQ_IDS}); // selected sequence ids
// outputs
args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::DECODE_PARTITIONOUT}); // partition output
@@ -450,6 +468,7 @@ Arguments PagedAttentionGeneratorSingleToken::get_arguments_desc(const kernel_im
// scalar
args.push_back({ArgumentDescriptor::Types::SCALAR, 0}); // q_len==1
+ args.push_back({ArgumentDescriptor::Types::SCALAR, 1}); // selected_sequence_count
return args;
}
@@ -462,7 +481,7 @@ DispatchDataFunc PagedAttentionGeneratorSingleToken::get_dispatch_data_func() co
auto rtp = static_cast<PagedAttentionRuntimeParams*>(rt_params);
OPENVINO_ASSERT(rt_params != nullptr);
- const size_t batch = params.input_layouts[0].get_partial_shape()[0].get_length();
+ const size_t batch = rtp->single_token_selected_count;
const size_t heads_num = desc->heads_num;
const size_t kv_heads_num = desc->kv_heads_num;
const size_t partition_num = rtp->num_of_partitions;
@@ -473,17 +492,16 @@ DispatchDataFunc PagedAttentionGeneratorSingleToken::get_dispatch_data_func() co
// generate stage: q_len=1
auto& scalars = kd.params.scalars;
- std::vector<size_t> scaler_value = {1};
+ std::vector<size_t> scaler_value = {1, rtp->single_token_selected_count};
scalars.resize(scaler_value.size());
if (DEBUG_ENABLED) { // Debug
size_t kv_len = get_kv_len(params, PagedAttentionStage::GENERATE);
size_t max_context_len = get_max_context_len(params);
- size_t past_len = get_past_len(params, 0);
std::cout << "PagedAttentionGeneratorSingleToken::get_dispatch_data_func: " << "batch: " << batch << ", heads_num: " << heads_num
- << ", partition_num: " << partition_num << ", kv_len: " << kv_len << ", max_context_len = " << max_context_len
- << ", past_len = " << past_len << ", gws: [" << wgs.global[0] << ", " << wgs.global[1] << ", " << wgs.global[2] << "]" << ", lws: ["
- << wgs.local[0] << ", " << wgs.local[1] << ", " << wgs.local[2] << "]" << std::endl;
+ << ", partition_num: " << partition_num << ", kv_len: " << kv_len << ", max_context_len = " << max_context_len << ", gws: ["
+ << wgs.global[0] << ", " << wgs.global[1] << ", " << wgs.global[2] << "]" << ", lws: [" << wgs.local[0] << ", " << wgs.local[1] << ", "
+ << wgs.local[2] << "]" << std::endl;
}
for (size_t i = 0; i < scaler_value.size(); ++i) {
scalars[i].t = ScalarDescriptor::Types::INT32;
@@ -511,12 +529,15 @@ Arguments PagedAttentionGeneratorSingleTokenFinalization::get_arguments_desc(con
if (has_scores_output)
OPENVINO_THROW("[GPU][CM] PagedAttentionGeneratorSingleTokenFinalization with scores output is not supported yet");
- args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::DECODE_PARTITIONOUT}); // partition data
- args.push_back({ArgumentDescriptor::Types::OUTPUT, 0}); // output
- args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::DECODE_EXPSUMS}); // lse
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::DECODE_PARTITIONOUT}); // partition data
+ args.push_back({ArgumentDescriptor::Types::OUTPUT, 0}); // output
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::DECODE_EXPSUMS}); // lse
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::SUBSEQUENCE_BEGINS}); // subsequence begins
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::SINGLE_TOKEN_SELECTED_SEQ_IDS}); // selected sequence ids
// scalar
- args.push_back({ArgumentDescriptor::Types::SCALAR, 0}); // kv_partition_num
+ args.push_back({ArgumentDescriptor::Types::SCALAR, 0}); // selected_sequence_count
+ args.push_back({ArgumentDescriptor::Types::SCALAR, 1}); // kv_partition_num
return args;
}
@@ -531,7 +552,7 @@ DispatchDataFunc PagedAttentionGeneratorSingleTokenFinalization::get_dispatch_da
OPENVINO_ASSERT(rt_params != nullptr);
- const size_t batch = params.input_layouts[0].get_partial_shape()[0].get_length();
+ const size_t batch = rtp->single_token_selected_count;
const size_t heads_num = desc->heads_num;
const size_t head_size = desc->k_head_size;
wgs.global = {batch, heads_num, head_size / reduce_split_step};
@@ -539,7 +560,7 @@ DispatchDataFunc PagedAttentionGeneratorSingleTokenFinalization::get_dispatch_da
auto& scalars = kd.params.scalars;
const size_t partition_num = rtp->num_of_partitions;
- std::vector<size_t> scaler_value = {partition_num};
+ std::vector<size_t> scaler_value = {rtp->single_token_selected_count, partition_num};
scalars.resize(scaler_value.size());
if (DEBUG_ENABLED) { // Debug
@@ -618,23 +639,18 @@ JitConstants XAttentionEstimateGeneratorBase::get_jit_constants(const kernel_imp
Arguments XAttentionEstimateGEMMQK::get_arguments_desc(const kernel_impl_params& params) const {
Arguments args;
- args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::KEY_CACHE}); // keys cache
- args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::QUERY}); // queries
- args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::BLOCK_INDICES}); // block indices
- args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::BLOCK_INDICES_BEGINS}); // block indices begins
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::KEY_CACHE}); // keys cache
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::QUERY}); // queries
+ args.push_back({ArgumentDescriptor::Types::INPUT, PagedAttentionInputIdx::BLOCK_INDICES}); // block indices
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::XATTN_SUBSEQ_META}); // metadata
// outputs
args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::XATTN_GEMMQK_MAX}); // kq_max_wg
args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::XATTN_GEMMQK_EXPSUMS}); // kq_exp_partial_sum
// scalar
- args.push_back({ArgumentDescriptor::Types::SCALAR, 0}); // M
- args.push_back({ArgumentDescriptor::Types::SCALAR, 1}); // N
- args.push_back({ArgumentDescriptor::Types::SCALAR, 2}); // K
- args.push_back({ArgumentDescriptor::Types::SCALAR, 3}); // query_pitch
- args.push_back({ArgumentDescriptor::Types::SCALAR, 4}); // slice_no
- args.push_back({ArgumentDescriptor::Types::SCALAR, 5}); // slice
- args.push_back({ArgumentDescriptor::Types::SCALAR, 6}); // q_start_strided
+ args.push_back({ArgumentDescriptor::Types::SCALAR, 0}); // query_pitch
+ args.push_back({ArgumentDescriptor::Types::SCALAR, 1}); // num_subseqs
return args;
}
@@ -646,10 +662,6 @@ DispatchDataFunc XAttentionEstimateGEMMQK::get_dispatch_data_func() const {
auto rtp = static_cast<PagedAttentionRuntimeParams*>(rt_params);
const auto desc = params.typed_desc<paged_attention>();
- const auto M = rtp->M;
- const auto N = rtp->N;
- const auto K = rtp->K;
-
auto get_simple_pitch = [](const layout& layout) {
size_t pitch = 1;
auto dims_padding = layout.get_padded_dims();
@@ -663,32 +675,19 @@ DispatchDataFunc XAttentionEstimateGEMMQK::get_dispatch_data_func() const {
};
auto querry_layout = params.input_layouts[PagedAttentionInputIdx::QUERY];
const size_t query_pitch = get_simple_pitch(querry_layout) * STRIDE;
- const size_t slice_no = 0, slice = 0;
- //# loop order walks HQ first and the step is WALK_HQ, 1 means not walk HQ, 2 means walks 2 heads first. Valid value: 1, 2, 4...
const size_t WALK_HQ = desc->heads_num != desc->kv_heads_num ? 2 : 1;
auto& wgs = kd.params.workGroups;
- OPENVINO_ASSERT(rtp->block_wg_m != 0, "Invalid block_wg_m in runtime params");
- wgs.global = {rtp->N_kq_groups * (rtp->q_stride_pad / rtp->block_wg_m) * SG_N * WALK_HQ, SG_M, desc->heads_num / WALK_HQ};
+ wgs.global = {rtp->xattn_gemmqk_wg_count * SG_N * WALK_HQ, SG_M, desc->heads_num / WALK_HQ};
wgs.local = {SG_N, SG_M, 1};
- const size_t q_start_strided = N - M;
- OPENVINO_ASSERT(N >= M, "length of key cache must be greater or equal than query");
-
auto& scalars = kd.params.scalars;
- std::vector<size_t> scaler_value = {M, N, K, query_pitch, slice_no, slice, q_start_strided};
- scalars.resize(scaler_value.size());
-
- for (size_t i = 0; i < scaler_value.size(); ++i) {
- if (i == 4 || i == 5) {
- scalars[i].t = ScalarDescriptor::Types::INT32;
- scalars[i].v.s32 = static_cast<int32_t>(scaler_value[i]);
- } else {
- scalars[i].t = ScalarDescriptor::Types::UINT32;
- scalars[i].v.u32 = static_cast<uint32_t>(scaler_value[i]);
- }
- }
+ scalars.resize(2);
+ scalars[0].t = ScalarDescriptor::Types::UINT32;
+ scalars[0].v.u32 = static_cast<uint32_t>(query_pitch);
+ scalars[1].t = ScalarDescriptor::Types::INT32;
+ scalars[1].v.s32 = static_cast<int32_t>(rtp->xattn_num_subseqs);
}};
}
@@ -717,14 +716,12 @@ Arguments XAttentionEstimateFindBlock::get_arguments_desc(const kernel_impl_para
// outputs
args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::XATTN_BLOCKMASK}); // sparse_block_mask
+ // metadata
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::XATTN_SUBSEQ_META}); // metadata
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::XATTN_FIND_WG_MAP}); // compact [subseq_id, q_block_idx] map
+
// scalar
- args.push_back({ArgumentDescriptor::Types::SCALAR, 0}); // q_len
- args.push_back({ArgumentDescriptor::Types::SCALAR, 1}); // q_stride
- args.push_back({ArgumentDescriptor::Types::SCALAR, 2}); // q_stride_pad
- args.push_back({ArgumentDescriptor::Types::SCALAR, 3}); // q_block_pad
- args.push_back({ArgumentDescriptor::Types::SCALAR, 4}); // k_block_pad
- args.push_back({ArgumentDescriptor::Types::SCALAR, 5}); // causal_start_index
- args.push_back({ArgumentDescriptor::Types::SCALAR, 6}); // thresh
+ args.push_back({ArgumentDescriptor::Types::SCALAR, 0}); // thresh
#if FIND_DEBUG_ACC
args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::XATTN_FIND_DEBUG_ACC}); // kq_sum for debug purpose only
@@ -743,29 +740,15 @@ DispatchDataFunc XAttentionEstimateFindBlock::get_dispatch_data_func() const {
auto& wgs = kd.params.workGroups;
const size_t heads_num = desc->heads_num;
-
- auto out_shape = params.output_layouts[0].get_shape();
- const size_t q_len = out_shape[0];
-
- const size_t sum_per_n_token_in_block = static_cast<size_t>(rtp->xattn_block_size / STRIDE);
- const size_t q_block = static_cast<size_t>(ceil_div(rtp->M, sum_per_n_token_in_block));
- const size_t k_block = static_cast<size_t>(ceil_div(rtp->N, sum_per_n_token_in_block));
-
const float xattn_thresh = get_xattn_thresh(params);
- wgs.global = {rtp->q_block_pad, heads_num, 1};
+ wgs.global = {rtp->xattn_find_wg_count, heads_num, 1};
wgs.local = {1, 1, 1};
auto& scalars = kd.params.scalars;
- std::vector<size_t> scaler_value = {q_len, rtp->M, rtp->q_stride_pad, rtp->q_block_pad, rtp->k_block_pad, k_block - q_block};
- scalars.resize(scaler_value.size() + 1);
-
- for (size_t i = 0; i < scaler_value.size(); ++i) {
- scalars[i].t = ScalarDescriptor::Types::UINT32;
- scalars[i].v.u32 = static_cast<uint32_t>(scaler_value[i]);
- }
- scalars[scaler_value.size()].t = ScalarDescriptor::Types::FLOAT32; // the last is for thresh with f32 dtype
- scalars[scaler_value.size()].v.f32 = static_cast<float>(xattn_thresh);
+ scalars.resize(1);
+ scalars[0].t = ScalarDescriptor::Types::FLOAT32;
+ scalars[0].v.f32 = static_cast<float>(xattn_thresh);
}};
}
@@ -789,10 +772,10 @@ Arguments XAttentionEstimatePostProc::get_arguments_desc(const kernel_impl_param
// outputs
args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::XATTN_BLOCKMASK_MERGED}); // sparse_block_mask_wg
- // scalar
- args.push_back({ArgumentDescriptor::Types::SCALAR, 0}); // q_stride_pad
- args.push_back({ArgumentDescriptor::Types::SCALAR, 1}); // q_block_pad
- args.push_back({ArgumentDescriptor::Types::SCALAR, 2}); // k_block_pad
+ // metadata
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::XATTN_SUBSEQ_META}); // metadata
+ args.push_back(
+ {ArgumentDescriptor::Types::INTERNAL_BUFFER, PagedAttentionInternBuffIdx::XATTN_POST_WG_MAP}); // compact [subseq_id, merged_q_block_idx] map
return args;
}
@@ -806,17 +789,11 @@ DispatchDataFunc XAttentionEstimatePostProc::get_dispatch_data_func() const {
auto& wgs = kd.params.workGroups;
- wgs.global = {rtp->q_block_pad_merged, desc->heads_num, 1};
+ wgs.global = {rtp->xattn_post_wg_count, desc->heads_num, 1};
wgs.local = {1, 1, 1};
auto& scalars = kd.params.scalars;
- std::vector<size_t> scaler_value = {rtp->q_stride_pad, rtp->q_block_pad, rtp->k_block_pad};
- scalars.resize(scaler_value.size());
-
- for (size_t i = 0; i < scaler_value.size(); ++i) {
- scalars[i].t = ScalarDescriptor::Types::UINT32;
- scalars[i].v.u32 = static_cast<uint32_t>(scaler_value[i]);
- }
+ scalars.clear();
}};
}
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 4af94eadaff..305fcb2b467 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
@@ -92,52 +92,73 @@ inline std::string get_pa_build_options() {
constexpr uint32_t SG_M = 4;
constexpr uint32_t SG_N = 8;
-constexpr size_t WG_SIZE = 16;
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 };
struct PagedAttentionRuntimeParams : public ImplRuntimeParams {
- PagedAttentionStage stage;
- size_t max_context_len;
- // below are rt params for decoding
- size_t num_of_partitions;
- // cached single-token Q chunking
- SingleTokenQChunking q_chunking;
- // below are rt params for xattn
- size_t block_wg_m;
- size_t q_block_pad;
- size_t k_block_pad;
- size_t q_stride_pad;
- size_t q_block_pad_merged;
- size_t N_kq_groups;
- size_t M;
- size_t N;
- size_t K;
- size_t xattn_block_size;
+ // common runtime state
+ PagedAttentionStage stage; // Current PA execution stage
+ size_t max_context_len; // Maximum KV context length in current batch
+ size_t batch_size_in_sequences; // Number of subsequences in current request
+
+ // single-token/decode path
+ size_t num_of_partitions; // Number of KV partitions for decode/finalization
+ SingleTokenQChunking q_chunking; // Cached single-token Q-head chunking parameters
+ size_t single_token_selected_count = 0; // Number of subsequences routed to single-token kernel
+
+ // multi-token dispatch size
+ size_t multi_token_wg_count = 0; // Number of WGs required by pa_multi_token
+
+ // 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)
+ size_t xattn_num_subseqs = 1; // Number of subsequences participating in xattn path
+
+ // xattention dispatch sizes
+ size_t xattn_gemmqk_wg_count = 0; // Exact WG count for xattn_gemm_qk
+ size_t xattn_find_wg_count = 0; // Exact WG count for xattn_find_block
+ size_t xattn_post_wg_count = 0; // Exact WG count for xattn_post_proc
+
+ // xattention internal buffer sizing
+ size_t xattn_cumul_kq_max_bytes = 0; // Total bytes for XATTN_GEMMQK_MAX
+ size_t xattn_cumul_exp_sum_bytes = 0; // Total bytes for XATTN_GEMMQK_EXPSUMS
+ size_t xattn_cumul_mask_elems = 0; // Total elements for XATTN_BLOCKMASK
+ size_t xattn_cumul_mask_wg_elems = 0; // Total elements for XATTN_BLOCKMASK_MERGED
+ size_t xattn_meta_num_int32s = 0; // Total int32 count in XATTN_SUBSEQ_META
};
enum PagedAttentionInternBuffIdx {
- // for decoding kernels
- DECODE_PARTITIONOUT = 0, // 0: intermediate partition output
- DECODE_EXPSUMS = 1, // 1: softmax exp_sums
- // for xattn kernels
- XATTN_GEMMQK_MAX = 2, // 2: kq_max_wg
- XATTN_GEMMQK_EXPSUMS = 3, // 3: kq_exp_partial_sum
- XATTN_BLOCKMASK = 4, // 4: sparse_block_mask
- XATTN_BLOCKMASK_MERGED = 5, // 5: sparse_block_mask_wg
+ // Decode scratch buffers used by generate path and split-mixed single-token path.
+ DECODE_PARTITIONOUT = 0, // 0: f32 partial attention outputs before final reduction
+ DECODE_EXPSUMS = 1, // 1: f32 softmax exp-sum accumulators for partition reduction
+
+ // Routing scratch buffers used to map subsequences onto decode/multi-token kernels.
+ MULTI_TOKEN_WG_MAPPING = 2, // 2: i32 pairs [block_start_pos, subsequence_id]
+ SINGLE_TOKEN_SELECTED_SEQ_IDS = 3, // 3: i32 subsequence ids selected for single-token dispatch
+
+ // XAttention estimate scratch buffers for multi-token sparse-attention path.
+ XATTN_GEMMQK_MAX = 4, // 4: f32 max logits per GEMM-QK work-group tile
+ XATTN_GEMMQK_EXPSUMS = 5, // 5: f32 partial exp-sums produced by GEMM-QK stage
+ XATTN_BLOCKMASK = 6, // 6: boolean sparse block mask per q-block / k-block pair
+ XATTN_BLOCKMASK_MERGED = 7, // 7: boolean sparse block mask after q-block merge in post-proc
+ XATTN_SUBSEQ_META = 8, // 8: i32 per-subsequence metadata table (16 entries per subsequence)
+ XATTN_FIND_WG_MAP = 9, // 9: i32 pairs [subseq_id, q_block_idx] for find-block dispatch
+ 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 = 6, // 6: kq_sum for debug purpose only
+ XATTN_FIND_DEBUG_ACC = 11, // 11: f16 debug-only KQ accumulation buffer
#endif
};
//-----------------------------------------------------------------------------------------------------------------
// Helpers of XAttention
//-----------------------------------------------------------------------------------------------------------------
-int64_t get_aligned_seq_len(const kernel_impl_params& impl_param, const PagedAttentionStage& stage, int64_t target_seq_len_block_size);
+// Stage/context helpers shared across CM paged-attention implementation units.
PagedAttentionStage get_paged_attention_stage(const kernel_impl_params& impl_param);
size_t get_max_context_len(const kernel_impl_params& params);
-size_t get_past_len(const kernel_impl_params& params, const size_t seq_idx);
+size_t get_batch_size_in_sequences(const std::vector<layout>& input_layouts);
+// XAttention policy helpers.
float get_xattn_thresh(const kernel_impl_params& impl_param, const size_t seq_idx = 0);
bool bypass_xattn(const kernel_impl_params& impl_param);
@@ -156,10 +177,15 @@ public:
[[nodiscard]] Arguments get_arguments_desc(const kernel_impl_params& params) const override;
[[nodiscard]] JitConstants get_jit_constants(const kernel_impl_params& params) const override;
[[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override;
+
+private:
+ static size_t get_kv_update_wg_size(const RuntimeParams& params);
};
class PagedAttentionGeneratorMultiToken : public PagedAttentionGeneratorBase {
public:
+ static constexpr size_t _wg_size = 16;
+
explicit PagedAttentionGeneratorMultiToken(size_t xattn_block_size = 1)
: PagedAttentionGeneratorBase("pa_multi_token", "_cm_bs" + std::to_string(xattn_block_size)),
_xattn_block_size(xattn_block_size) {}
@@ -174,7 +200,7 @@ public:
}
static size_t get_wg_seq_len(const kernel_impl_params& params) {
- return WG_SIZE * get_q_step(params);
+ return _wg_size * get_q_step(params);
}
[[nodiscard]] Arguments get_arguments_desc(const kernel_impl_params& params) const override;
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/xattn_find_block.cm b/src/plugins/intel_gpu/src/graph/impls/cm/xattn_find_block.cm
index 0a3d19746ea..3597fd0c1b4 100644
--- a/src/plugins/intel_gpu/src/graph/impls/cm/xattn_find_block.cm
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/xattn_find_block.cm
@@ -16,45 +16,52 @@
namespace KERNEL_NAME {
#include "find_block.hpp"
+#include "xattn_subseq_meta.hpp"
#ifndef ATTR
#define ATTR [[type("svmptr_t")]]
#define ATTR_BUF [[type("buffer_t")]]
#endif
-// _GENX_MAIN_ void find_block(
extern "C" _GENX_MAIN_ void KERNEL_NAME(
svmptr_t kq_max_wg ATTR,
svmptr_t kq_exp_partial_sum ATTR,
svmptr_t block_mask ATTR,
- uint q_len,
- uint q_stride,
- uint q_stride_pad,
- uint q_block_pad,
- uint k_block_pad,
- uint causal_start_index,
+ svmptr_t xattn_subseq_meta ATTR,
+ svmptr_t xattn_find_wg_map ATTR,
float thresh
#if DEBUG_ACC == 1
, svmptr_t kq_sum ATTR
#endif
) {
- // kq_max_wg: [b, hq, n_groups, q_stride_pad]
- // kq_exp_partial_sum: [b, hq, q_stride_pad, k_block_pad]
- // kq_sum: [b, hq, q_stride_pad/TOKEN_IN_BLOCK, k_block_pad]
- // block_mask: [b, hq, q_stride_pad/TOKEN_IN_BLOCK, k_block_pad]
- // [1, 32, 256], [1, 32, 64, 256], [1, 32, 256, 64 * 16], A_sum:[1, 32, 32, 64 * 16]
- // global: [q_block_pad, hq, b]
+ // GWS: [xattn_find_wg_count, HQ, 1]
const int TOKEN_IN_BLOCK = BLOCK_SIZE / STRIDE;
const int TOKEN_SHARE_MAX = BLOCK_SHARE_MAX / TOKEN_IN_BLOCK;
- uint m = cm_group_id(0);
+ uint wg_flat = cm_group_id(0);
uint hq = cm_group_id(1);
- uint b = cm_group_id(2);
- kq_max_wg += (b * HQ + hq) * (k_block_pad / TOKEN_SHARE_MAX) * q_stride_pad * (uint)sizeof(SOFTMAX_TYPE);
- kq_exp_partial_sum += (b * HQ + hq) * q_stride_pad * k_block_pad * (uint)sizeof(SOFTMAX_TYPE);
-#if DEBUG_ACC == 1
- kq_sum += (b * HQ + hq) * (q_stride_pad / TOKEN_IN_BLOCK) * k_block_pad * (uint)sizeof(half);
-#endif
- block_mask += (b * HQ + hq) * q_block_pad * k_block_pad;
+
+ int* wg_map = (int*)xattn_find_wg_map;
+ int map_base = wg_flat * 2;
+ uint b = (uint)wg_map[map_base + 0];
+ uint m = (uint)wg_map[map_base + 1];
+
+ int* meta = (int*)xattn_subseq_meta;
+ int meta_base = b * XATTN_META_STRIDE;
+
+ uint q_len = (uint)meta[meta_base + XATTN_META_SUBSEQ_Q_LEN];
+ uint q_stride = (uint)meta[meta_base + XATTN_META_M];
+ uint q_stride_pad = (uint)meta[meta_base + XATTN_META_Q_STRIDE_PAD];
+ uint q_block_pad = (uint)meta[meta_base + XATTN_META_Q_BLOCK_PAD];
+ uint k_block_pad = (uint)meta[meta_base + XATTN_META_K_BLOCK_PAD];
+ uint causal_start_index = (uint)meta[meta_base + XATTN_META_CAUSAL_START];
+
+ uint buf_off_kq_max = (uint)meta[meta_base + XATTN_META_BUF_OFF_KQ_MAX];
+ uint buf_off_exp_sum = (uint)meta[meta_base + XATTN_META_BUF_OFF_EXP_SUM];
+ uint buf_off_mask = (uint)meta[meta_base + XATTN_META_BUF_OFF_MASK];
+
+ kq_max_wg += buf_off_kq_max + hq * (k_block_pad / TOKEN_SHARE_MAX) * q_stride_pad * (uint)sizeof(SOFTMAX_TYPE);
+ kq_exp_partial_sum += buf_off_exp_sum + hq * q_stride_pad * k_block_pad * (uint)sizeof(SOFTMAX_TYPE);
+ block_mask += buf_off_mask + hq * q_block_pad * k_block_pad;
const uint slm_size = NUM_THREADS * 16 * sizeof(ushort);
cm_slm_init(slm_size);
@@ -67,4 +74,4 @@ extern "C" _GENX_MAIN_ void KERNEL_NAME(
);
}
-} // NAMESPACE
\ No newline at end of file
+} // NAMESPACE
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/xattn_gemm_qk.cm b/src/plugins/intel_gpu/src/graph/impls/cm/xattn_gemm_qk.cm
index f79c3066ead..2e8b1d39993 100644
--- a/src/plugins/intel_gpu/src/graph/impls/cm/xattn_gemm_qk.cm
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/xattn_gemm_qk.cm
@@ -16,49 +16,11 @@
namespace KERNEL_NAME {
#include "estimate.hpp"
+#include "xattn_subseq_meta.hpp"
-#define ABS(x) (x) < 0 ? -(x) : (x)
-
-CM_INLINE void get_mn(uint& id_wg_m, uint& id_wg_n, uint M, uint N, int slice_no, int slice, const int BLOCK_WG_M, const int BLOCK_WG_N) {
- uint id_wg_mn = cm_group_id(0) / WALK_HQ;
- if (slice_no == 0) {
- if (slice == 0) {
- // loop M first, N is shared, total = N/256*M+N
- uint WG_MN = (M + BLOCK_WG_M - 1) / BLOCK_WG_M;
- id_wg_m = id_wg_mn % WG_MN;
- id_wg_n = id_wg_mn / WG_MN;
- } else {
- // loop N first, M is shared, total = M/128*N+M
- uint WG_MN = (N + BLOCK_WG_N - 1) / BLOCK_WG_N;
- id_wg_n = id_wg_mn % WG_MN;
- id_wg_m = id_wg_mn / WG_MN;
- }
- } else {
- uint wg_x = slice > 0 ? N / BLOCK_WG_N : M / BLOCK_WG_M;
- uint slice_no_abs = ABS(slice_no);
- uint slice_abs = ABS(slice);
- int id_wg_mn_in_reminder = (int)id_wg_mn - (int)(slice_no_abs * slice_abs * wg_x);
- uint slice_idx;
- // in [slice_no x slice]
- if (id_wg_mn_in_reminder < 0) {
- slice_idx = id_wg_mn / (slice_abs * wg_x);
- uint rem_in_slice = id_wg_mn % (slice_abs * wg_x);
- uint x = rem_in_slice % slice_abs;
- uint y = rem_in_slice / slice_abs;
- id_wg_m = slice > 0 ? x + slice_idx * slice_abs : y;
- id_wg_n = slice < 0 ? x + slice_idx * slice_abs : y;
- } else {
- uint slice_rem = slice_abs + (slice_no > 0 ? 1 : -1);
- slice_idx = id_wg_mn_in_reminder / (slice_rem * wg_x);
- uint rem_in_slice = id_wg_mn_in_reminder % (slice_rem * wg_x);
- uint x = rem_in_slice % slice_rem;
- uint y = rem_in_slice / slice_rem;
- id_wg_m = slice > 0 ? x + slice_idx * slice_rem + slice_no_abs * slice_abs : y;
- id_wg_n = slice < 0 ? x + slice_idx * slice_rem + slice_no_abs * slice_abs : y;
- }
- }
-}
-
+#define CONCAT_IMPL(a, b) KERNEL_NAME::gemm_qk
+#define CONCAT(x, y) CONCAT_IMPL(x, y)
+#define FUNC CONCAT(BLOCK_SG_M, BLOCK_SG_N)
extern "C" _GENX_MAIN_ void KERNEL_NAME(
#ifdef CM_HAS_LSC_UNTYPED_2D
@@ -69,14 +31,14 @@ extern "C" _GENX_MAIN_ void KERNEL_NAME(
SurfaceIndex query [[type("buffer_t")]],
#endif
svmptr_t block_indices ATTR,
- svmptr_t block_indices_begins ATTR,
+ svmptr_t xattn_subseq_meta ATTR,
svmptr_t kq_max_wg ATTR,
#ifdef CM_HAS_LSC_UNTYPED_2D
svmptr_t kq_exp_partial_sum ATTR,
#else
SurfaceIndex kq_exp_partial_sum [[type("buffer_t")]],
#endif
- uint M, uint N, uint K, uint query_stride, int slice_no, int slice, uint q_start_strided) {
+ uint query_stride, int num_subseqs) {
const uint BLOCK_WG_M = BLOCK_SG_M * SG_M;
const uint BLOCK_WG_N = BLOCK_SG_N * SG_N;
uint hq = cm_group_id(2) * WALK_HQ;
@@ -89,39 +51,55 @@ extern "C" _GENX_MAIN_ void KERNEL_NAME(
static_assert(HQ % HK == 0, "HQ must be multiple of HK");
- uint id_wg_m, id_wg_n;
- get_mn(id_wg_m, id_wg_n, M, N, slice_no, slice, BLOCK_WG_M, BLOCK_WG_N);
+ uint wg_mn_flat = cm_group_id(0) / WALK_HQ;
+
+ int subseq_id = 0;
+ int* meta = (int*)xattn_subseq_meta;
+ for (int s = 1; s < num_subseqs; s++) {
+ uint wg_off_next = (uint)meta[s * XATTN_META_STRIDE + XATTN_META_WG_OFFSET];
+ if (wg_mn_flat < wg_off_next)
+ break;
+ subseq_id = s;
+ }
+
+ int meta_base = subseq_id * XATTN_META_STRIDE;
+ uint M = (uint)meta[meta_base + XATTN_META_M];
+ uint N = (uint)meta[meta_base + XATTN_META_N];
+ uint q_start_strided = (uint)meta[meta_base + XATTN_META_Q_START_STRIDED];
+ int block_index_begin = meta[meta_base + XATTN_META_BLOCK_IDX_BEGIN];
+ uint subseq_wg_offset = (uint)meta[meta_base + XATTN_META_WG_OFFSET];
+ uint subseq_q_begin = (uint)meta[meta_base + XATTN_META_SUBSEQ_Q_BEGIN];
+
+ uint wg_local = wg_mn_flat - subseq_wg_offset;
+ uint WG_M_count = (M + BLOCK_WG_M - 1) / BLOCK_WG_M;
+ uint id_wg_m = wg_local % WG_M_count;
+ uint id_wg_n = wg_local / WG_M_count;
+
+ uint buf_off_kq_max = (uint)meta[meta_base + XATTN_META_BUF_OFF_KQ_MAX];
+ uint buf_off_exp_sum = (uint)meta[meta_base + XATTN_META_BUF_OFF_EXP_SUM];
#ifdef CM_HAS_LSC_UNTYPED_2D
- // key cache: [block, HQ, KV_BLOCK_SIZE, HEAD_SIZE_KEY]
#if KV_CACHE_COMPRESSION
key_cache += hk * (KV_BLOCK_SIZE * HEAD_SIZE_KEY * (uint)sizeof(char));
#else
key_cache += hk * (KV_BLOCK_SIZE * HEAD_SIZE_KEY * (uint)sizeof(half));
#endif
- query += hq * HEAD_SIZE * (uint)sizeof(half);
+ query += (subseq_q_begin * (query_stride / STRIDE) + hq * HEAD_SIZE) * (uint)sizeof(half);
#endif
-
- // kq_max: [hq, m_pad]
- // kq_max_wg: [hq, n_groups, m_pad]
- // kq_exp_partial_sum: [hq, m_pad, n_groups*BLOCK_WG_M/(BLOCK_SIZE/STRIDE)]
uint m_pad = (M + BLOCK_WG_M - 1) / BLOCK_WG_M * BLOCK_WG_M;
uint n_groups = (N + BLOCK_WG_N - 1) / BLOCK_WG_N;
- kq_max_wg += hq * n_groups * m_pad * (uint)sizeof(SOFTMAX_TYPE);
+ kq_max_wg += buf_off_kq_max + hq * n_groups * m_pad * (uint)sizeof(SOFTMAX_TYPE);
const uint sum_per_n_token_in_block = BLOCK_SIZE / STRIDE;
const uint n_after_sum_in_group = BLOCK_WG_N / sum_per_n_token_in_block;
const uint n_after_sum_pad = n_after_sum_in_group * n_groups;
- const uint offset_partial_sum = hq * n_after_sum_pad * m_pad * (uint)sizeof(SOFTMAX_TYPE);
+ const uint offset_partial_sum = buf_off_exp_sum + hq * n_after_sum_pad * m_pad * (uint)sizeof(SOFTMAX_TYPE);
#ifdef CM_HAS_LSC_UNTYPED_2D
kq_exp_partial_sum += offset_partial_sum;
#endif
-#define CONCAT_IMPL(a, b) KERNEL_NAME::gemm_qk
-#define CONCAT(x, y) CONCAT_IMPL(x, y)
-#define FUNC CONCAT(BLOCK_SG_M, BLOCK_SG_N)
- FUNC(id_wg_m, id_wg_n, hq, slm, key_cache, query, block_indices, block_indices_begins, kq_max_wg, kq_exp_partial_sum, M, N, K, query_stride, q_start_strided, offset_partial_sum);
+ FUNC(id_wg_m, id_wg_n, hq, slm, key_cache, query, block_indices, block_index_begin, kq_max_wg, kq_exp_partial_sum, M, N, query_stride, q_start_strided, offset_partial_sum);
}
-} // NAMESPACE
\ No newline at end of file
+} // NAMESPACE
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/xattn_post_proc.cm b/src/plugins/intel_gpu/src/graph/impls/cm/xattn_post_proc.cm
index 45cb2a0ed8f..b6690855794 100644
--- a/src/plugins/intel_gpu/src/graph/impls/cm/xattn_post_proc.cm
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/xattn_post_proc.cm
@@ -15,25 +15,20 @@
*******************************************************************************/
namespace KERNEL_NAME {
-#include "estimate.hpp"
+#include "xattn_subseq_meta.hpp"
-extern "C" _GENX_MAIN_ void KERNEL_NAME(svmptr_t block_mask ATTR, svmptr_t merged_block_mask ATTR, uint q_stride_pad, uint q_block_pad, uint k_block_pad) {
- // block_mask: [b, hq, q_block_pad, k_block_pad]
- // merged_block_mask: [b, hq, q_block_pad/MERGED_Q_NUM, k_block_pad]
- // global: [q_block_pad/MERGED_Q_NUM, hq, b]
+#ifndef ATTR
+#define ATTR [[type("svmptr_t")]]
+#endif
+
+CM_INLINE void post_proc_impl(svmptr_t block_mask,
+ svmptr_t merged_block_mask,
+ uint q_stride_pad,
+ uint q_block_pad,
+ uint k_block_pad,
+ uint m_mereged) {
const int TOKEN_IN_BLOCK = BLOCK_SIZE / STRIDE;
- uint m_mereged = cm_group_id(0);
- uint hq = cm_group_id(1);
- uint b = cm_group_id(2);
- block_mask += (b * HQ + hq) * q_block_pad * k_block_pad;
- block_mask += m_mereged * MERGED_Q_NUM * k_block_pad;
- merged_block_mask += (b * HQ + hq) * cm_group_count(0) * k_block_pad;
- merged_block_mask += m_mereged * k_block_pad;
- // mask shape: [div_up(q_len, xattn_block_size), rnd_up(k_stride, WG_N) / sum_per_n_token_in_block]
- // k_block_pad is aligned to 16 or 32, as WG_N of xattn_gemmQK is 128 or 256, and sum_per_n_token_in_block is 8 or 16 w.r.t
- // xattn_block_size 128 or 256 respectively.
- // Hence it is safe to not handle tailing here.
int j = 0;
{
constexpr int STEP = 32;
@@ -65,4 +60,36 @@ extern "C" _GENX_MAIN_ void KERNEL_NAME(svmptr_t block_mask ATTR, svmptr_t merge
}
}
+extern "C" _GENX_MAIN_ void KERNEL_NAME(svmptr_t block_mask ATTR,
+ svmptr_t merged_block_mask ATTR,
+ svmptr_t xattn_subseq_meta ATTR,
+ svmptr_t xattn_post_wg_map ATTR) {
+ // GWS: [xattn_post_wg_count, HQ, 1]
+ uint hq = cm_group_id(1);
+ uint wg_flat = cm_group_id(0);
+
+ int* wg_map = (int*)xattn_post_wg_map;
+ int map_base = wg_flat * 2;
+ uint b = (uint)wg_map[map_base + 0];
+ uint m_mereged = (uint)wg_map[map_base + 1];
+
+ int* meta = (int*)xattn_subseq_meta;
+ int meta_base = b * XATTN_META_STRIDE;
+
+ uint q_stride_pad = (uint)meta[meta_base + XATTN_META_Q_STRIDE_PAD];
+ uint q_block_pad = (uint)meta[meta_base + XATTN_META_Q_BLOCK_PAD];
+ uint k_block_pad = (uint)meta[meta_base + XATTN_META_K_BLOCK_PAD];
+ uint buf_off_mask = (uint)meta[meta_base + XATTN_META_BUF_OFF_MASK];
+ uint buf_off_mask_wg = (uint)meta[meta_base + XATTN_META_BUF_OFF_MASK_WG];
+
+ uint merged_q_blocks = (q_block_pad + MERGED_Q_NUM - 1) / MERGED_Q_NUM;
+
+ svmptr_t mask_base = block_mask + buf_off_mask + hq * q_block_pad * k_block_pad;
+ mask_base += m_mereged * MERGED_Q_NUM * k_block_pad;
+ svmptr_t merged_base = merged_block_mask + buf_off_mask_wg + hq * merged_q_blocks * k_block_pad;
+ merged_base += m_mereged * k_block_pad;
+
+ post_proc_impl(mask_base, merged_base, q_stride_pad, q_block_pad, k_block_pad, m_mereged);
+}
+
} // NAMESPACE
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.cpp
index 3b1a146d0dc..6730e0b106b 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.cpp
@@ -1742,8 +1742,8 @@ public:
total_matrix_elements += evictable_size * evictable_size;
total_vector_elements += evictable_size;
}
- GPU_DEBUG_TRACE_DETAIL << "Adaptive RKV: Allocating dynamic buffers - "
- << "matrix: " << total_matrix_elements << ", vector: " << total_vector_elements << std::endl;
+ GPU_DEBUG_TRACE_DETAIL << "Adaptive RKV: Allocating dynamic buffers - " << "matrix: " << total_matrix_elements
+ << ", vector: " << total_vector_elements << std::endl;
} else {
// Fallback: use maximum size (512) if runtime values not available
const size_t max_evictable_size = 512;
diff --git a/src/plugins/intel_gpu/src/graph/paged_attention.cpp b/src/plugins/intel_gpu/src/graph/paged_attention.cpp
index 61121b209bb..7c7b5676260 100644
--- a/src/plugins/intel_gpu/src/graph/paged_attention.cpp
+++ b/src/plugins/intel_gpu/src/graph/paged_attention.cpp
@@ -72,16 +72,6 @@ std::vector<layout> paged_attention_inst::calc_output_layouts(paged_attention_no
OPENVINO_ASSERT(valid_block_size, "[GPU] Incorrect block size for Paged Attention operation for key cache quant mode "
, key_cache_quant_mode, ". Expected ", expected_block_size, ", but got ", key_cache_ps[block_size_idx].get_length());
- // TODO: as a preview feature, only single sequence is supported so far. Will remove this check once
- // full function ready in near future.
- if (desc->has_xattention) {
- const auto& subseq_begins_ps = impl_param.get_input_layout(PagedAttentionInputIdx::SUBSEQUENCE_BEGINS).get_partial_shape();
- bool valid_subseq_count = subseq_begins_ps.is_dynamic() ||
- (subseq_begins_ps[0].get_length() == static_cast<ov::Dimension::value_type>(2));
- if (!valid_subseq_count)
- OPENVINO_THROW("[GPU] Unexpected sub sequences count for XAttention. Got ", subseq_begins_ps[0].get_length() - 1);
- }
-
std::vector<layout> output_layouts{ data_layout };
if (desc->has_scores_output()) {
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 871a92ef93a..d4a2b2857d7 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
@@ -12,6 +12,7 @@
#include <intel_gpu/primitives/reorder.hpp>
#include <intel_gpu/primitives/reshape.hpp>
#include <intel_gpu/primitives/softmax.hpp>
+#include <intel_gpu/runtime/debug_configuration.hpp>
#include <openvino/core/except.hpp>
#include <openvino/reference/xattention.hpp>
#include <openvino/reference/adaptive_rkv_diversity.hpp>
@@ -1277,36 +1278,6 @@ private:
{static_cast<size_t>(num_heads), padded_q, static_cast<size_t>(k_head_size)},
key_padded.data(),
{static_cast<size_t>(num_heads), padded_k, static_cast<size_t>(k_head_size)});
-
- // Dump reference block mask for comparison
-#if XATTENTION_DEBUG_VERBOSE
- if (std::getenv("DUMP_XATTN_TENSORS")) {
- std::string dump_dir = std::getenv("DUMP_XATTN_TENSORS");
- size_t q_blocks = padded_q / block_size;
- size_t k_blocks = padded_k / block_size;
-
- // Create a dense block mask from retained_blocks
- std::vector<uint8_t> ref_mask(num_heads * q_blocks * k_blocks, 0);
- for (int h = 0; h < num_heads; ++h) {
- if (h < static_cast<int>(retained_blocks.size())) {
- for (const auto& [q_idx, k_idx] : retained_blocks[h]) {
- size_t idx = h * q_blocks * k_blocks + q_idx * k_blocks + k_idx;
- if (idx < ref_mask.size()) {
- ref_mask[idx] = 1;
- }
- }
- }
- }
-
- std::string mask_file = dump_dir + "/reference_block_mask.bin";
- std::ofstream mask_out(mask_file, std::ios::binary);
- mask_out.write(reinterpret_cast<const char*>(ref_mask.data()), ref_mask.size());
- mask_out.close();
- std::cout << "[dump_reference] Saved reference block mask to: " << mask_file << std::endl;
- std::cout << "[dump_reference] Shape: [" << num_heads << ", " << q_blocks << ", " << k_blocks << "]" << std::endl;
- std::cout << "[dump_reference] Total retained blocks: " << std::count(ref_mask.begin(), ref_mask.end(), 1) << std::endl;
- }
-#endif
}
auto mask_mem = get_mask_mem_combined_multi_head(num_queries,
num_keys,
@@ -1823,9 +1794,12 @@ private:
template <typename T>
struct PagedAttentionTest : public ::testing::TestWithParam<T> {
public:
- random_generator rg;
+ tests::random_generator rg;
cldnn::engine& engine = get_test_engine();
float tolerance = 2e-3;
+ memory::ptr last_key_cache_mem = nullptr;
+ std::vector<int> last_block_indices;
+ std::vector<int> last_block_indices_begins;
void SetUp() override {
rg.set_seed(GET_SUITE_NAME);
@@ -2178,106 +2152,16 @@ public:
network->set_input_data("qq_bias", qq_bias);
network->set_input_data("qq_bias_begins", qq_bias_begins);
+ last_key_cache_mem = key_cache_mem;
+ last_block_indices = pam.block_indices;
+ last_block_indices_begins = pam.block_indices_begins;
+
auto outputs = network->execute();
if (!run_reference) {
return;
}
- // Dump tensors for debugging (controlled by environment variable)
-#if XATTENTION_DEBUG_VERBOSE
- if (std::getenv("DUMP_XATTN_TENSORS")) {
- std::string dump_dir = std::getenv("DUMP_XATTN_TENSORS");
- std::cout << "Dumping xattention tensors to: " << dump_dir << std::endl;
-
- // Helper lambda to dump memory to numpy file
- auto dump_memory = [&](const std::string& name, memory::ptr mem) {
- if (!mem) return;
- mem_lock<uint8_t, mem_lock_type::read> lock(mem, get_test_stream());
- std::string filepath = dump_dir + "/" + name + ".npy";
-
- // Get layout info
- auto layout = mem->get_layout();
- auto shape = layout.get_partial_shape();
- size_t elem_size = data_type_traits::size_of(layout.data_type);
- size_t total_size = mem->count() * elem_size;
-
- // Write NPY format: magic + version + header length + header + data
- std::ofstream file(filepath, std::ios::binary);
- file.write("\x93NUMPY", 6);
- file.put(1); file.put(0); // version 1.0
-
- // Build header
- std::string dtype;
- if (layout.data_type == data_types::f16) dtype = "'<f2'";
- else if (layout.data_type == data_types::f32) dtype = "'<f4'";
- else if (layout.data_type == data_types::i32) dtype = "'<i4'";
- else if (layout.data_type == data_types::i8) dtype = "'<i1'";
- else if (layout.data_type == data_types::u8) dtype = "'<u1'";
- else dtype = "'<f4'";
-
- std::string shape_str = "(";
- for (size_t i = 0; i < shape.size(); i++) {
- shape_str += std::to_string(shape[i].get_length());
- if (i < shape.size() - 1) shape_str += ",";
- }
- if (shape.size() == 1) shape_str += ",";
- shape_str += ")";
-
- std::string header = "{'descr': " + dtype + ", 'fortran_order': False, 'shape': " + shape_str + "}";
- while ((header.size() + 10) % 64 != 0) header += " ";
- header += "\n";
-
- uint16_t header_len = header.size();
- file.write((char*)&header_len, 2);
- file.write(header.c_str(), header.size());
- file.write((char*)lock.data(), total_size);
- file.close();
-
- std::cout << " Dumped " << name << " shape=" << shape_str << " dtype=" << dtype << std::endl;
- };
-
- dump_memory("query", query_mem);
- dump_memory("key_cache", key_cache_mem);
- dump_memory("value_cache", value_cache_mem);
- dump_memory("past_lens", past_lens_mem);
- dump_memory("block_indices", block_indices_mem);
- dump_memory("block_indices_begins", block_indices_begins_mem);
- dump_memory("scale", scale_mem);
- dump_memory("xattention_threshold", xattention_threshold_mem);
- dump_memory("xattention_block_size", xattention_block_size_mem);
- dump_memory("output_data", outputs.at("output_data").get_memory());
-
- std::cout << "Tensor dump complete!" << std::endl;
- }
-
- // Also dump reference output for comparison
- if (std::getenv("DUMP_XATTN_TENSORS") && p.has_xattention) {
- std::string dump_dir = std::getenv("DUMP_XATTN_TENSORS");
- auto ref_data = PagedAttentionReference(pam).get_reference(key_cache_mem);
- auto& ref_output = std::get<0>(ref_data);
-
- // Write reference output as numpy array
- std::string filepath = dump_dir + "/reference_output.npy";
- std::ofstream file(filepath, std::ios::binary);
- file.write("\x93NUMPY", 6);
- file.put(1); file.put(0);
-
- std::string shape_str = "(" + std::to_string(ref_output.size()) + ",)";
- std::string header = "{'descr': '<f2', 'fortran_order': False, 'shape': " + shape_str + "}";
- while ((header.size() + 10) % 64 != 0) header += " ";
- header += "\n";
-
- uint16_t header_len = header.size();
- file.write((char*)&header_len, 2);
- file.write(header.c_str(), header.size());
- file.write((char*)ref_output.data(), ref_output.size() * sizeof(ov::float16));
- file.close();
-
- std::cout << " Dumped reference_output shape=" << shape_str << std::endl;
- }
-#endif
-
cldnn::memory::ptr output_data_mem = nullptr;
cldnn::memory::ptr output_scores_mem = nullptr;
cldnn::memory::ptr output_diversity_mem = nullptr;
@@ -2289,6 +2173,12 @@ public:
if (p.has_adaptive_rkv) {
output_diversity_mem = outputs.at("output_diversity").get_memory();
}
+
+ // Verify KV cache was correctly written (CM PA path only)
+ // NOTE: This verification is specific to CM PA layout and should NOT run for OCL micro_sdpa
+ // because they use different layouts (key cache is [N,K,H,B] in OCL vs [N,K,B,H] in CM)
+ verify_cm_kv_cache_write(p);
+
auto ref_data = PagedAttentionReference(pam).get_reference(key_cache_mem);
if (p.has_xattention) {
compare_xattention(output_data_mem, output_scores_mem, ref_data, p.num_heads, p.k_head_size);
@@ -2330,232 +2220,586 @@ public:
ASSERT_EQ(data_output_mem->count(), std::get<0>(ref_data).size());
mem_lock<ov::float16, mem_lock_type::read> mem_ptr(data_output_mem, get_test_stream());
int mismatch_count = 0;
+
#if XATTENTION_DEBUG_VERBOSE
- int catastrophic_count = 0; // NaN, Inf, or error > 1.0
- int large_error_count = 0; // error > 0.1
- float max_error = 0.0f;
- float avg_error = 0.0f;
- float avg_mismatch_error = 0.0f;
- size_t first_mismatch_idx = 0;
- float first_mismatch_actual = 0.0f;
- float first_mismatch_expected = 0.0f;
- bool found_first = false;
-
- // Separate counters for different abnormal value types
- int actual_nan_count = 0;
- int expected_nan_count = 0;
- int actual_inf_count = 0;
- int expected_inf_count = 0;
- int actual_gt1_count = 0;
- int expected_gt1_count = 0;
- int error_gt1_count = 0;
-#endif
+ XAttentionErrorStats stats;
+ collect_xattention_error_stats(mem_ptr.data(), std::get<0>(ref_data), num_heads, head_size, tolerance, stats);
+ mismatch_count = stats.mismatch_count;
- // Collect error statistics
+ // Print detailed statistics on failure
+ if (mismatch_count > int(data_output_mem->count() * 0.04)) {
+ print_xattention_error_details(stats, mem_ptr.data(), std::get<0>(ref_data), num_heads, head_size, tolerance);
+ }
+#else
+ // Simple counting when verbose debug is disabled
for (size_t i = 0; i < data_output_mem->count(); i++) {
float actual = static_cast<float>(mem_ptr[i]);
float expected = static_cast<float>(std::get<0>(ref_data)[i]);
float error = std::fabs(actual - expected);
-
-#if XATTENTION_DEBUG_VERBOSE
- avg_error += error;
- max_error = std::max(max_error, error);
-
- // Separate checks for actual vs expected
- if (std::isnan(actual)) actual_nan_count++;
- if (std::isnan(expected)) expected_nan_count++;
- if (std::isinf(actual)) actual_inf_count++;
- if (std::isinf(expected)) expected_inf_count++;
- if (!std::isnan(actual) && !std::isinf(actual) && std::fabs(actual) > 1.0f) actual_gt1_count++;
- if (!std::isnan(expected) && !std::isinf(expected) && std::fabs(expected) > 1.0f) expected_gt1_count++;
- if (error > 1.0f) error_gt1_count++;
-
- if (std::isnan(actual) || std::isinf(actual) || error > 1.0f) {
- catastrophic_count++;
- }
- if (error > 0.1f) {
- large_error_count++;
- }
-#endif
-
if (error > tolerance) {
-#if XATTENTION_DEBUG_VERBOSE
- if (!found_first) {
- first_mismatch_idx = i;
- first_mismatch_actual = actual;
- first_mismatch_expected = expected;
- found_first = true;
- }
- avg_mismatch_error += error;
-#endif
mismatch_count++;
}
}
-#if XATTENTION_DEBUG_VERBOSE
- avg_error /= data_output_mem->count();
- if (mismatch_count > 0) {
- avg_mismatch_error /= mismatch_count;
- }
#endif
- // Print detailed statistics on failure
- if (mismatch_count > int(data_output_mem->count() * 0.04)) {
-#if XATTENTION_DEBUG_VERBOSE
- auto& engine = get_test_engine();
- auto arch = engine.get_device_info().arch;
- std::string arch_name = (arch == gpu_arch::xe2) ? "Xe2" : (arch == gpu_arch::xe3) ? "Xe3" : "Xe1";
-
- std::cout << "\n=== XAttention Data Comparison Failed ===" << std::endl;
- std::cout << "GPU Architecture: " << arch_name << " (arch=" << static_cast<int>(arch) << ")" << std::endl;
- std::cout << "Total elements: " << data_output_mem->count() << std::endl;
- std::cout << "\nError Summary:" << std::endl;
- std::cout << " Mismatches (> tolerance): " << mismatch_count << " ("
- << (100.0 * mismatch_count / data_output_mem->count()) << "%)" << std::endl;
- std::cout << " Allowed mismatches: " << int(data_output_mem->count() * 0.04) << " (4%)" << std::endl;
- std::cout << " Large errors (> 0.1): " << large_error_count << " ("
- << (100.0 * large_error_count / data_output_mem->count()) << "%)" << std::endl;
- std::cout << " Catastrophic (NaN/Inf/>1.0): " << catastrophic_count << std::endl;
-
- std::cout << "\nAbnormal Value Analysis:" << std::endl;
- std::cout << " Actual output (GPU):" << std::endl;
- std::cout << " NaN values: " << actual_nan_count << std::endl;
- std::cout << " INF values: " << actual_inf_count << std::endl;
- std::cout << " Values > 1.0: " << actual_gt1_count << std::endl;
- std::cout << " Expected output (CPU reference):" << std::endl;
- std::cout << " NaN values: " << expected_nan_count << std::endl;
- std::cout << " INF values: " << expected_inf_count << std::endl;
- std::cout << " Values > 1.0: " << expected_gt1_count << std::endl;
- std::cout << " Error magnitude:" << std::endl;
- std::cout << " Errors > 1.0: " << error_gt1_count << std::endl;
- std::cout << "\nError Magnitudes:" << std::endl;
- std::cout << " Tolerance threshold: " << tolerance << std::endl;
- std::cout << " Max error: " << max_error << std::endl;
- std::cout << " Avg error (all): " << avg_error << std::endl;
- std::cout << " Avg error (mismatches only): " << avg_mismatch_error << std::endl;
- std::cout << "First mismatch at index " << first_mismatch_idx << ":" << std::endl;
- std::cout << " Actual: " << first_mismatch_actual << std::endl;
- std::cout << " Expected: " << first_mismatch_expected << std::endl;
- std::cout << " Error: " << std::fabs(first_mismatch_actual - first_mismatch_expected) << std::endl;
-
- // Sample first 10 mismatches
- std::cout << "\nFirst 10 mismatches:" << std::endl;
- int sample_count = 0;
- for (size_t i = 0; i < data_output_mem->count() && sample_count < 10; i++) {
- float actual = static_cast<float>(mem_ptr[i]);
- float expected = static_cast<float>(std::get<0>(ref_data)[i]);
- float error = std::fabs(actual - expected);
- if (error > tolerance) {
- std::cout << " [" << i << "] actual=" << actual
- << " expected=" << expected
- << " error=" << error << std::endl;
- sample_count++;
- }
+ EXPECT_LE(mismatch_count, int(data_output_mem->count() * 0.04));
+ }
+
+ if (scores_output_mem) {
+ ASSERT_EQ(scores_output_mem->count(), std::get<1>(ref_data).size());
+ mem_lock<ov::float16, mem_lock_type::read> mem_ptr(scores_output_mem, get_test_stream());
+ int mismatch_count = 0;
+ for (size_t i = 0; i < scores_output_mem->count(); i++) {
+ if (std::fabs(static_cast<float>(mem_ptr[i]) - static_cast<float>(std::get<1>(ref_data)[i])) > tolerance) {
+ mismatch_count++;
}
+ }
+ EXPECT_LE(mismatch_count, int(scores_output_mem->count() * 0.04));
+ }
+ }
- // Show catastrophic error locations
- if (catastrophic_count > 0 && catastrophic_count <= 20) {
- std::cout << "\nCatastrophic error locations (NaN/Inf/error>1.0):" << std::endl;
- // Use passed parameters for correct dimensions
- size_t total_tokens = data_output_mem->count() / (num_heads * head_size);
-
- std::cout << " Dimensions: tokens=" << total_tokens
- << " heads=" << num_heads
- << " head_size=" << head_size
- << " (total=" << data_output_mem->count() << ")" << std::endl;
-
- for (size_t i = 0; i < data_output_mem->count(); i++) {
- float actual = static_cast<float>(mem_ptr[i]);
- float expected = static_cast<float>(std::get<0>(ref_data)[i]);
- float error = std::fabs(actual - expected);
- if (std::isnan(actual) || std::isnan(expected) || std::isinf(actual) || std::isinf(expected) || error > 1.0f) {
- // Memory layout: [token][head][dim] with innermost dimension first
- size_t elements_per_token = num_heads * head_size;
- size_t token = i / elements_per_token;
- size_t within_token = i % elements_per_token;
- size_t head = within_token / head_size;
- size_t dim = within_token % head_size;
-
- std::cout << " Index[" << i << "]: token=" << token << " head=" << head << " dim=" << dim
- << " | actual=" << actual << " expected=" << expected << " error=" << error;
-
- // Tag each type
- std::vector<std::string> tags;
- if (std::isnan(actual)) tags.push_back("ACTUAL_NaN");
- if (std::isnan(expected)) tags.push_back("EXPECTED_NaN");
- if (std::isinf(actual)) tags.push_back("ACTUAL_INF");
- if (std::isinf(expected)) tags.push_back("EXPECTED_INF");
- if (!std::isnan(actual) && !std::isinf(actual) && std::fabs(actual) > 1.0f) tags.push_back("ACTUAL_>1.0");
- if (!std::isnan(expected) && !std::isinf(expected) && std::fabs(expected) > 1.0f) tags.push_back("EXPECTED_>1.0");
- if (error > 1.0f) tags.push_back("ERROR_>1.0");
-
- if (!tags.empty()) {
- std::cout << " [";
- for (size_t t = 0; t < tags.size(); t++) {
- if (t > 0) std::cout << ", ";
- std::cout << tags[t];
- }
- std::cout << "]";
+private:
+ // Helper: Verify CM PA KV cache was correctly written (CM path only)
+ void verify_cm_kv_cache_write(const T& p) {
+ if (last_key_cache_mem == nullptr || !p.has_xattention) return;
+
+ // Count total tokens for single-token BY_CHANNEL skip logic
+ int total_new_tokens = 0;
+ for (const auto& s : p.subsequences) total_new_tokens += s.num_tokens;
+
+ constexpr int kv_sub_block_size = 16;
+ const bool is_by_channel = p.kv_cache_compression &&
+ p.key_cache_quant_mode == ov::internal::CacheQuantMode::BY_CHANNEL;
+ const bool is_by_token = p.kv_cache_compression &&
+ p.key_cache_quant_mode == ov::internal::CacheQuantMode::BY_TOKEN;
+
+ // CM cache layout: [num_blocks, num_kv_heads, adjusted_block_size, adjusted_head_size]
+ const int adj_head_size = is_by_token ? (p.k_head_size + 4) : p.k_head_size;
+ const int adj_block_size = is_by_channel ? (p.block_size + (p.block_size / kv_sub_block_size) * 4) : p.block_size;
+ const int elem_size = p.kv_cache_compression ? 1 : 2;
+ const size_t head_region_bytes = static_cast<size_t>(adj_block_size) * adj_head_size * elem_size;
+ const size_t block_stride_bytes = static_cast<size_t>(p.num_kv_heads) * head_region_bytes;
+ const int token_data_stride = p.k_head_size * elem_size;
+
+ mem_lock<int8_t, mem_lock_type::read> cache_lock(last_key_cache_mem, get_test_stream());
+
+ int missing_count = 0, nan_count = 0, inf_count = 0, zero_scale_count = 0, out_of_range_zp_count = 0;
+ std::vector<std::tuple<int, int, int, int, int>> nan_locations, inf_locations;
+ std::vector<std::tuple<int, int, int, int, float, float>> zero_scale_locations, out_of_range_zp_locations;
+
+ int total_tokens = 0;
+ for (int i = 0; i < static_cast<int>(p.subsequences.size()); i++) {
+ const int past_len = p.subsequences[i].past_len;
+ const int num_tokens = p.subsequences[i].num_tokens;
+ for (int t = 0; t < num_tokens; t++) {
+ total_tokens++;
+ const int absolute_pos = past_len + t;
+ const int block_idx = absolute_pos / p.block_size;
+ const int token_in_block = absolute_pos % p.block_size;
+ const int physical_block = last_block_indices[last_block_indices_begins[i] + block_idx];
+ const size_t block_base = static_cast<size_t>(physical_block) * block_stride_bytes;
+
+ for (int head = 0; head < p.num_kv_heads; head++) {
+ const size_t head_base = block_base + static_cast<size_t>(head) * head_region_bytes;
+ const size_t token_offset = head_base + static_cast<size_t>(token_in_block) * token_data_stride;
+
+ // Check for missing token write (all-zero data)
+ bool skip_zero_check = is_by_channel && (total_new_tokens <= 1);
+ if (!skip_zero_check) {
+ bool all_zero = true;
+ for (int b = 0; b < token_data_stride; b++) {
+ if (cache_lock[token_offset + b] != 0) {
+ all_zero = false;
+ break;
}
- std::cout << std::endl;
+ }
+ if (all_zero && head == 0) {
+ missing_count++;
+ GPU_DEBUG_LOG << "KV cache update MISSING: seq=" << i << " token=" << t
+ << " (absolute_pos=" << absolute_pos << ") at byte_offset=" << token_offset << std::endl;
}
}
+
+ // Check for NaN/INF in data or scale/zp
+ check_kv_cache_nan_inf(cache_lock.data(), p, is_by_token, is_by_channel,
+ head_base, token_in_block, i, t, absolute_pos, head,
+ nan_count, inf_count, zero_scale_count, out_of_range_zp_count,
+ nan_locations, inf_locations, zero_scale_locations, out_of_range_zp_locations);
}
+ }
+ }
- // Check if errors are clustered or distributed
- // Analyze error type
- std::cout << "\nError Analysis:" << std::endl;
- if (catastrophic_count > 0) {
- std::cout << " ERROR TYPE: CATASTROPHIC - Contains NaN/Inf or very large errors" << std::endl;
- std::cout << " This indicates a serious bug, not just precision issues." << std::endl;
- } else if (large_error_count > mismatch_count * 0.5) {
- std::cout << " ERROR TYPE: LARGE - Most mismatches have error > 0.1" << std::endl;
- std::cout << " This suggests wrong calculations, not precision drift." << std::endl;
+ report_kv_cache_issues(nan_count, inf_count, zero_scale_count, out_of_range_zp_count,
+ nan_locations, inf_locations, zero_scale_locations, out_of_range_zp_locations,
+ total_tokens, p, is_by_token, is_by_channel);
+ EXPECT_EQ(missing_count, 0) << missing_count << " out of " << total_tokens
+ << " tokens were not written to key cache by KV update kernel";
+ EXPECT_EQ(nan_count, 0) << "KV cache contains NaN values";
+ EXPECT_EQ(inf_count, 0) << "KV cache contains INF values";
+ EXPECT_EQ(zero_scale_count, 0) << "KV cache contains zero/near-zero scale values (causes division by zero in dequant)";
+ // ZP can be outside [0, 255] legitimately - see pa-quantization skill for details
+ }
+
+ // Helper: Check for NaN/INF in KV cache token
+ void check_kv_cache_nan_inf(const int8_t* cache_data, const T& p,
+ bool is_by_token, bool is_by_channel,
+ size_t head_base, int token_in_block,
+ int seq_idx, int token_idx, int absolute_pos, int head,
+ int& nan_count, int& inf_count, int& zero_scale_count, int& out_of_range_zp_count,
+ std::vector<std::tuple<int, int, int, int, int>>& nan_locations,
+ std::vector<std::tuple<int, int, int, int, int>>& inf_locations,
+ std::vector<std::tuple<int, int, int, int, float, float>>& zero_scale_locations,
+ std::vector<std::tuple<int, int, int, int, float, float>>& out_of_range_zp_locations) {
+ constexpr int kv_sub_block_size = 16;
+ const size_t token_offset = head_base + static_cast<size_t>(token_in_block) * p.k_head_size * (p.kv_cache_compression ? 1 : 2);
+
+ if (!p.kv_cache_compression) {
+ // FP16 cache: check data for NaN/INF
+ const ov::float16* fp16_ptr = reinterpret_cast<const ov::float16*>(cache_data + token_offset);
+ for (int dim = 0; dim < p.k_head_size; dim++) {
+ float val = static_cast<float>(fp16_ptr[dim]);
+ if (std::isnan(val)) {
+ nan_count++;
+ if (nan_locations.size() < 10) {
+ nan_locations.push_back(std::make_tuple(seq_idx, token_idx, absolute_pos, head, dim));
+ }
+ }
+ if (std::isinf(val)) {
+ inf_count++;
+ if (inf_locations.size() < 10) {
+ inf_locations.push_back(std::make_tuple(seq_idx, token_idx, absolute_pos, head, dim));
+ }
+ }
+ }
+ } else if (is_by_token) {
+ // BY_TOKEN: check scale/zp
+ const size_t scale_offset = head_base + static_cast<size_t>(p.block_size) * p.k_head_size
+ + static_cast<size_t>(token_in_block) * 2;
+ const size_t zp_offset = scale_offset + static_cast<size_t>(p.block_size) * 2;
+ const ov::float16* scale_ptr = reinterpret_cast<const ov::float16*>(cache_data + scale_offset);
+ const ov::float16* zp_ptr = reinterpret_cast<const ov::float16*>(cache_data + zp_offset);
+ float scale = static_cast<float>(*scale_ptr);
+ float zp = static_cast<float>(*zp_ptr);
+
+ check_scale_zp_validity(scale, zp, seq_idx, token_idx, absolute_pos, head, -1,
+ nan_count, inf_count, zero_scale_count, out_of_range_zp_count,
+ nan_locations, inf_locations, zero_scale_locations, out_of_range_zp_locations);
+ } else if (is_by_channel) {
+ // BY_CHANNEL: check scale/zp per channel (only first 4 channels to limit overhead)
+ int sub_block_idx = token_in_block / kv_sub_block_size;
+ int group_num = p.block_size / kv_sub_block_size;
+ for (int ch = 0; ch < std::min(p.k_head_size, 4); ch++) {
+ size_t scale_offset = head_base + static_cast<size_t>(p.block_size) * p.k_head_size
+ + (static_cast<size_t>(sub_block_idx) * p.k_head_size + ch) * 2;
+ size_t zp_offset = scale_offset + static_cast<size_t>(group_num) * p.k_head_size * 2;
+ const ov::float16* scale_ptr = reinterpret_cast<const ov::float16*>(cache_data + scale_offset);
+ const ov::float16* zp_ptr = reinterpret_cast<const ov::float16*>(cache_data + zp_offset);
+ float scale = static_cast<float>(*scale_ptr);
+ float zp = static_cast<float>(*zp_ptr);
+
+ check_scale_zp_validity(scale, zp, seq_idx, token_idx, absolute_pos, head, ch,
+ nan_count, inf_count, zero_scale_count, out_of_range_zp_count,
+ nan_locations, inf_locations, zero_scale_locations, out_of_range_zp_locations);
+ }
+ }
+ }
+
+ // Helper: Check scale/zp for NaN/INF/zero
+ void check_scale_zp_validity(float scale, float zp, int seq_idx, int token_idx, int absolute_pos, int head, int dim,
+ int& nan_count, int& inf_count, int& zero_scale_count, int& out_of_range_zp_count,
+ std::vector<std::tuple<int, int, int, int, int>>& nan_locations,
+ std::vector<std::tuple<int, int, int, int, int>>& inf_locations,
+ std::vector<std::tuple<int, int, int, int, float, float>>& zero_scale_locations,
+ std::vector<std::tuple<int, int, int, int, float, float>>& out_of_range_zp_locations) {
+ if (std::isnan(scale) || std::isnan(zp)) {
+ nan_count += (std::isnan(scale) ? 1 : 0) + (std::isnan(zp) ? 1 : 0);
+ if (nan_locations.size() < 10) {
+ nan_locations.push_back(std::make_tuple(seq_idx, token_idx, absolute_pos, head, dim));
+ }
+ }
+ if (std::isinf(scale) || std::isinf(zp)) {
+ inf_count += (std::isinf(scale) ? 1 : 0) + (std::isinf(zp) ? 1 : 0);
+ if (inf_locations.size() < 10) {
+ inf_locations.push_back(std::make_tuple(seq_idx, token_idx, absolute_pos, head, dim));
+ }
+ }
+ if (std::fabs(scale) < 1e-6f) {
+ zero_scale_count++;
+ if (zero_scale_locations.size() < 10) {
+ zero_scale_locations.push_back(std::make_tuple(seq_idx, token_idx, absolute_pos, head, scale, zp));
+ }
+ }
+ if (zp < -1.0f || zp > 256.0f) {
+ out_of_range_zp_count++;
+ if (out_of_range_zp_locations.size() < 10) {
+ out_of_range_zp_locations.push_back(std::make_tuple(seq_idx, token_idx, absolute_pos, head, scale, zp));
+ }
+ }
+ }
+
+ // Helper: Report KV cache verification issues
+ void report_kv_cache_issues(int nan_count, int inf_count, int zero_scale_count, int out_of_range_zp_count,
+ const std::vector<std::tuple<int, int, int, int, int>>& nan_locations,
+ const std::vector<std::tuple<int, int, int, int, int>>& inf_locations,
+ const std::vector<std::tuple<int, int, int, int, float, float>>& zero_scale_locations,
+ const std::vector<std::tuple<int, int, int, int, float, float>>& out_of_range_zp_locations,
+ int total_tokens, const T& p, bool is_by_token, bool is_by_channel) {
+ if (nan_count > 0) {
+ GPU_DEBUG_LOG << "\nKV cache contains " << nan_count << " NaN values:" << std::endl;
+ for (const auto& [seq, tok, abs_pos, h, d] : nan_locations) {
+ GPU_DEBUG_LOG << " seq=" << seq << " token=" << tok << " (absolute_pos=" << abs_pos << ") head=" << h;
+ if (d == -1) {
+ GPU_DEBUG_LOG << " [BY_TOKEN scale/zp]";
+ } else if (d >= 0) {
+ GPU_DEBUG_LOG << " [BY_CHANNEL scale/zp channel=" << d << "]";
} else {
- std::cout << " ERROR TYPE: PRECISION - Most errors are small" << std::endl;
- std::cout << " This suggests accumulated floating-point errors." << std::endl;
+ GPU_DEBUG_LOG << " [FP16 dim=" << d << "]";
+ }
+ GPU_DEBUG_LOG << std::endl;
+ }
+ if (nan_locations.size() < static_cast<size_t>(nan_count)) {
+ GPU_DEBUG_LOG << " ... and " << (nan_count - nan_locations.size()) << " more" << std::endl;
+ }
+ }
+ if (inf_count > 0) {
+ GPU_DEBUG_LOG << "\nKV cache contains " << inf_count << " INF values:" << std::endl;
+ for (const auto& [seq, tok, abs_pos, h, d] : inf_locations) {
+ GPU_DEBUG_LOG << " seq=" << seq << " token=" << tok << " (absolute_pos=" << abs_pos << ") head=" << h;
+ if (d == -1) {
+ GPU_DEBUG_LOG << " [BY_TOKEN scale/zp]";
+ } else if (d >= 0) {
+ GPU_DEBUG_LOG << " [BY_CHANNEL scale/zp channel=" << d << "]";
+ } else {
+ GPU_DEBUG_LOG << " [FP16 dim=" << d << "]";
+ }
+ GPU_DEBUG_LOG << std::endl;
+ }
+ if (inf_locations.size() < static_cast<size_t>(inf_count)) {
+ GPU_DEBUG_LOG << " ... and " << (inf_count - inf_locations.size()) << " more" << std::endl;
+ }
+ }
+ if (zero_scale_count > 0) {
+ GPU_DEBUG_LOG << "\nKV cache contains " << zero_scale_count << " zero/near-zero scale values:" << std::endl;
+ for (const auto& [seq, tok, abs_pos, h, scale, zp] : zero_scale_locations) {
+ GPU_DEBUG_LOG << " seq=" << seq << " token=" << tok << " (absolute_pos=" << abs_pos
+ << ") head=" << h << " scale=" << scale << " zp=" << zp << std::endl;
+ }
+ if (zero_scale_locations.size() < static_cast<size_t>(zero_scale_count)) {
+ GPU_DEBUG_LOG << " ... and " << (zero_scale_count - zero_scale_locations.size()) << " more" << std::endl;
+ }
+ }
+ if (out_of_range_zp_count > 0) {
+ GPU_DEBUG_LOG << "\nKV cache contains " << out_of_range_zp_count << " ZP values outside typical [0,255] range (NOTE: this is valid for shifted data distributions):" << std::endl;
+ for (const auto& [seq, tok, abs_pos, h, scale, zp] : out_of_range_zp_locations) {
+ GPU_DEBUG_LOG << " seq=" << seq << " token=" << tok << " (absolute_pos=" << abs_pos
+ << ") head=" << h << " scale=" << scale << " zp=" << zp << std::endl;
+ }
+ if (out_of_range_zp_locations.size() < static_cast<size_t>(out_of_range_zp_count)) {
+ GPU_DEBUG_LOG << " ... and " << (out_of_range_zp_count - out_of_range_zp_locations.size()) << " more" << std::endl;
+ }
+ }
+
+ if (nan_count == 0 && inf_count == 0 && zero_scale_count == 0 && out_of_range_zp_count == 0) {
+ GPU_DEBUG_LOG << "\nKV cache verification PASSED: " << total_tokens << " tokens checked";
+ if (p.kv_cache_compression) {
+ GPU_DEBUG_LOG << " (compression mode: "
+ << (is_by_token ? "BY_TOKEN" : (is_by_channel ? "BY_CHANNEL" : "UNKNOWN")) << ")";
+ } else {
+ GPU_DEBUG_LOG << " (FP16 mode)";
+ }
+ GPU_DEBUG_LOG << std::endl;
+ }
+ }
+
+private:
+ // Helper structure to hold XAttention error statistics
+ struct XAttentionErrorStats {
+ int mismatch_count = 0;
+ int catastrophic_count = 0; // NaN, Inf, or error > 1.0
+ int large_error_count = 0; // error > 0.1
+ float max_error = 0.0f;
+ float avg_error = 0.0f;
+ float avg_mismatch_error = 0.0f;
+ size_t first_mismatch_idx = 0;
+ float first_mismatch_actual = 0.0f;
+ float first_mismatch_expected = 0.0f;
+ bool found_first = false;
+
+ // Separate counters for different abnormal value types
+ int actual_nan_count = 0;
+ int expected_nan_count = 0;
+ int actual_inf_count = 0;
+ int expected_inf_count = 0;
+ int actual_gt1_count = 0;
+ int expected_gt1_count = 0;
+ int error_gt1_count = 0;
+
+ // Track coordinates of abnormal values
+ std::vector<std::tuple<size_t, size_t, size_t, float>> actual_nan_coords; // (token, head, dim, value)
+ std::vector<std::tuple<size_t, size_t, size_t, float>> expected_nan_coords;
+ std::vector<std::tuple<size_t, size_t, size_t, float>> actual_inf_coords;
+ std::vector<std::tuple<size_t, size_t, size_t, float>> expected_inf_coords;
+ std::vector<std::tuple<size_t, size_t, size_t, float>> actual_gt1_coords;
+ std::vector<std::tuple<size_t, size_t, size_t, float>> expected_gt1_coords;
+ };
+
+ // Collect XAttention error statistics by comparing GPU output with CPU reference
+ static void collect_xattention_error_stats(const ov::float16* mem_ptr,
+ const std::vector<ov::float16>& ref_output,
+ size_t num_heads,
+ size_t head_size,
+ float tolerance,
+ XAttentionErrorStats& stats) {
+ size_t total_elements = ref_output.size();
+ for (size_t i = 0; i < total_elements; i++) {
+ float actual = static_cast<float>(mem_ptr[i]);
+ float expected = static_cast<float>(ref_output[i]);
+ float error = std::fabs(actual - expected);
+
+ stats.avg_error += error;
+ stats.max_error = std::max(stats.max_error, error);
+
+ // Calculate coordinates: output layout is [T, Q * H]
+ size_t head_dim_flat = i % (num_heads * head_size);
+ size_t token_idx = i / (num_heads * head_size);
+ size_t head_idx = head_dim_flat / head_size;
+ size_t dim_idx = head_dim_flat % head_size;
+
+ // Separate checks for actual vs expected with coordinate tracking
+ if (std::isnan(actual)) {
+ stats.actual_nan_count++;
+ stats.actual_nan_coords.push_back(std::make_tuple(token_idx, head_idx, dim_idx, actual));
+ }
+ if (std::isnan(expected)) {
+ stats.expected_nan_count++;
+ stats.expected_nan_coords.push_back(std::make_tuple(token_idx, head_idx, dim_idx, expected));
+ }
+ if (std::isinf(actual)) {
+ stats.actual_inf_count++;
+ stats.actual_inf_coords.push_back(std::make_tuple(token_idx, head_idx, dim_idx, actual));
+ }
+ if (std::isinf(expected)) {
+ stats.expected_inf_count++;
+ stats.expected_inf_coords.push_back(std::make_tuple(token_idx, head_idx, dim_idx, expected));
+ }
+ if (!std::isnan(actual) && !std::isinf(actual) && std::fabs(actual) > 1.0f) {
+ stats.actual_gt1_count++;
+ stats.actual_gt1_coords.push_back(std::make_tuple(token_idx, head_idx, dim_idx, actual));
+ }
+ if (!std::isnan(expected) && !std::isinf(expected) && std::fabs(expected) > 1.0f) {
+ stats.expected_gt1_count++;
+ stats.expected_gt1_coords.push_back(std::make_tuple(token_idx, head_idx, dim_idx, expected));
+ }
+ if (error > 1.0f) stats.error_gt1_count++;
+
+ if (std::isnan(actual) || std::isinf(actual) || error > 1.0f) {
+ stats.catastrophic_count++;
+ }
+ if (error > 0.1f) {
+ stats.large_error_count++;
+ }
+
+ if (error > tolerance) {
+ if (!stats.found_first) {
+ stats.first_mismatch_idx = i;
+ stats.first_mismatch_actual = actual;
+ stats.first_mismatch_expected = expected;
+ stats.found_first = true;
}
+ stats.avg_mismatch_error += error;
+ stats.mismatch_count++;
+ }
+ }
+
+ stats.avg_error /= total_elements;
+ if (stats.mismatch_count > 0) {
+ stats.avg_mismatch_error /= stats.mismatch_count;
+ }
+ }
+
+ // Print coordinates of abnormal values (NaN/INF/large values)
+ static void print_abnormal_value_coords(const std::string& label,
+ const std::vector<std::tuple<size_t, size_t, size_t, float>>& coords,
+ int count) {
+ GPU_DEBUG_LOG << " " << label << ": " << count << std::endl;
+ if (count > 0) {
+ GPU_DEBUG_LOG << " Coordinates (token, head, dim, value):" << std::endl;
+ size_t show_count = std::min(coords.size(), size_t(10));
+ for (size_t j = 0; j < show_count; j++) {
+ auto [t, h, d, v] = coords[j];
+ GPU_DEBUG_LOG << " [" << t << ", " << h << ", " << d << "] = " << v << std::endl;
+ }
+ if (coords.size() > 10) {
+ GPU_DEBUG_LOG << " ... and " << (coords.size() - 10) << " more" << std::endl;
+ }
+ }
+ }
- // Comment on tolerance metric
- std::cout << "\nTolerance Metric Analysis:" << std::endl;
- std::cout << " Using: Absolute error with threshold " << tolerance << std::endl;
- std::cout << " Input range: Normal(0, 0.1), typically [-0.3, 0.3]" << std::endl;
- std::cout << " Relative error at typical values: ~" << (tolerance / 0.1 * 100) << "%" << std::endl;
- std::cout << " Verdict: Tolerance is reasonable for FP16 attention calculations" << std::endl;
-
- std::cout << "\nError distribution (by 1024-element blocks):" << std::endl;
- size_t block_size = 1024;
- for (size_t block = 0; block < (data_output_mem->count() + block_size - 1) / block_size && block < 10; block++) {
- int block_mismatches = 0;
- size_t start = block * block_size;
- size_t end = std::min(start + block_size, data_output_mem->count());
- for (size_t i = start; i < end; i++) {
- float error = std::fabs(static_cast<float>(mem_ptr[i]) - static_cast<float>(std::get<0>(ref_data)[i]));
- if (error > tolerance) block_mismatches++;
+ // Print catastrophic error locations with detailed tags
+ static void print_catastrophic_errors(const ov::float16* mem_ptr,
+ const std::vector<ov::float16>& ref_output,
+ size_t num_heads,
+ size_t head_size,
+ int catastrophic_count) {
+ if (catastrophic_count > 0 && catastrophic_count <= 20) {
+ GPU_DEBUG_LOG << "\nCatastrophic error locations (NaN/Inf/error>1.0):" << std::endl;
+ size_t total_elements = ref_output.size();
+ size_t total_tokens = total_elements / (num_heads * head_size);
+
+ GPU_DEBUG_LOG << " Dimensions: tokens=" << total_tokens
+ << " heads=" << num_heads
+ << " head_size=" << head_size
+ << " (total=" << total_elements << ")" << std::endl;
+
+ for (size_t i = 0; i < total_elements; i++) {
+ float actual = static_cast<float>(mem_ptr[i]);
+ float expected = static_cast<float>(ref_output[i]);
+ float error = std::fabs(actual - expected);
+ if (std::isnan(actual) || std::isnan(expected) || std::isinf(actual) || std::isinf(expected) || error > 1.0f) {
+ // Memory layout: [token][head][dim] with innermost dimension first
+ size_t elements_per_token = num_heads * head_size;
+ size_t token = i / elements_per_token;
+ size_t within_token = i % elements_per_token;
+ size_t head = within_token / head_size;
+ size_t dim = within_token % head_size;
+
+ GPU_DEBUG_LOG << " Index[" << i << "]: token=" << token << " head=" << head << " dim=" << dim
+ << " | actual=" << actual << " expected=" << expected << " error=" << error;
+
+ // Tag each type
+ std::vector<std::string> tags;
+ if (std::isnan(actual)) tags.push_back("ACTUAL_NaN");
+ if (std::isnan(expected)) tags.push_back("EXPECTED_NaN");
+ if (std::isinf(actual)) tags.push_back("ACTUAL_INF");
+ if (std::isinf(expected)) tags.push_back("EXPECTED_INF");
+ if (!std::isnan(actual) && !std::isinf(actual) && std::fabs(actual) > 1.0f) tags.push_back("ACTUAL_>1.0");
+ if (!std::isnan(expected) && !std::isinf(expected) && std::fabs(expected) > 1.0f) tags.push_back("EXPECTED_>1.0");
+ if (error > 1.0f) tags.push_back("ERROR_>1.0");
+
+ if (!tags.empty()) {
+ GPU_DEBUG_LOG << " [";
+ for (size_t t = 0; t < tags.size(); t++) {
+ if (t > 0) {
+ GPU_DEBUG_LOG << ", ";
+ }
+ GPU_DEBUG_LOG << tags[t];
+ }
+ GPU_DEBUG_LOG << "]";
}
- std::cout << " Block " << block << " [" << start << "-" << end << "): "
- << block_mismatches << "/" << (end - start)
- << " (" << (100.0 * block_mismatches / (end - start)) << "%)" << std::endl;
+ GPU_DEBUG_LOG << std::endl;
}
- std::cout << "========================================\n" << std::endl;
-#endif
}
+ }
+ }
- EXPECT_LE(mismatch_count, int(data_output_mem->count() * 0.04));
+ // Print error distribution by 1024-element blocks
+ static void print_error_distribution(const ov::float16* mem_ptr,
+ const std::vector<ov::float16>& ref_output,
+ float tolerance) {
+ GPU_DEBUG_LOG << "\nError distribution (by 1024-element blocks):" << std::endl;
+ size_t block_size = 1024;
+ size_t total_elements = ref_output.size();
+ for (size_t block = 0; block < (total_elements + block_size - 1) / block_size && block < 10; block++) {
+ int block_mismatches = 0;
+ size_t start = block * block_size;
+ size_t end = std::min(start + block_size, total_elements);
+ for (size_t i = start; i < end; i++) {
+ float error = std::fabs(static_cast<float>(mem_ptr[i]) - static_cast<float>(ref_output[i]));
+ if (error > tolerance) block_mismatches++;
+ }
+ GPU_DEBUG_LOG << " Block " << block << " [" << start << "-" << end << "): "
+ << block_mismatches << "/" << (end - start)
+ << " (" << (100.0 * block_mismatches / (end - start)) << "%)" << std::endl;
}
+ }
- if (scores_output_mem) {
- ASSERT_EQ(scores_output_mem->count(), std::get<1>(ref_data).size());
- mem_lock<ov::float16, mem_lock_type::read> mem_ptr(scores_output_mem, get_test_stream());
- int mismatch_count = 0;
- for (size_t i = 0; i < scores_output_mem->count(); i++) {
- if (std::fabs(static_cast<float>(mem_ptr[i]) - static_cast<float>(std::get<1>(ref_data)[i])) > tolerance) {
- mismatch_count++;
- }
+ // Print detailed XAttention error analysis
+ static void print_xattention_error_details(const XAttentionErrorStats& stats,
+ const ov::float16* mem_ptr,
+ const std::vector<ov::float16>& ref_output,
+ size_t num_heads,
+ size_t head_size,
+ float tolerance) {
+ auto& engine = get_test_engine();
+ auto arch = engine.get_device_info().arch;
+ std::string arch_name = (arch == gpu_arch::xe2) ? "Xe2" : (arch == gpu_arch::xe3) ? "Xe3" : "Xe1";
+ size_t total_elements = ref_output.size();
+ int allowed_mismatches = int(total_elements * 0.04);
+
+ GPU_DEBUG_LOG << "\n=== XAttention Data Comparison Failed ===" << std::endl;
+ GPU_DEBUG_LOG << "GPU Architecture: " << arch_name << " (arch=" << static_cast<int>(arch) << ")" << std::endl;
+ GPU_DEBUG_LOG << "Total elements: " << total_elements << std::endl;
+ GPU_DEBUG_LOG << "\nError Summary:" << std::endl;
+ GPU_DEBUG_LOG << " Mismatches (> tolerance): " << stats.mismatch_count << " ("
+ << (100.0 * stats.mismatch_count / total_elements) << "%)" << std::endl;
+ GPU_DEBUG_LOG << " Allowed mismatches: " << allowed_mismatches << " (4%)" << std::endl;
+ GPU_DEBUG_LOG << " Large errors (> 0.1): " << stats.large_error_count << " ("
+ << (100.0 * stats.large_error_count / total_elements) << "%)" << std::endl;
+ GPU_DEBUG_LOG << " Catastrophic (NaN/Inf/>1.0): " << stats.catastrophic_count << std::endl;
+
+ GPU_DEBUG_LOG << "\nAbnormal Value Analysis:" << std::endl;
+ GPU_DEBUG_LOG << " Actual output (GPU):" << std::endl;
+ print_abnormal_value_coords("NaN values", stats.actual_nan_coords, stats.actual_nan_count);
+ print_abnormal_value_coords("INF values", stats.actual_inf_coords, stats.actual_inf_count);
+ print_abnormal_value_coords("Values > 1.0", stats.actual_gt1_coords, stats.actual_gt1_count);
+ GPU_DEBUG_LOG << " Expected output (CPU reference):" << std::endl;
+ print_abnormal_value_coords("NaN values", stats.expected_nan_coords, stats.expected_nan_count);
+ print_abnormal_value_coords("INF values", stats.expected_inf_coords, stats.expected_inf_count);
+ print_abnormal_value_coords("Values > 1.0", stats.expected_gt1_coords, stats.expected_gt1_count);
+ GPU_DEBUG_LOG << " Error magnitude:" << std::endl;
+ GPU_DEBUG_LOG << " Errors > 1.0: " << stats.error_gt1_count << std::endl;
+ GPU_DEBUG_LOG << "\nError Magnitudes:" << std::endl;
+ GPU_DEBUG_LOG << " Tolerance threshold: " << tolerance << std::endl;
+ GPU_DEBUG_LOG << " Max error: " << stats.max_error << std::endl;
+ GPU_DEBUG_LOG << " Avg error (all): " << stats.avg_error << std::endl;
+ GPU_DEBUG_LOG << " Avg error (mismatches only): " << stats.avg_mismatch_error << std::endl;
+ GPU_DEBUG_LOG << "First mismatch at index " << stats.first_mismatch_idx << ":" << std::endl;
+ GPU_DEBUG_LOG << " Actual: " << stats.first_mismatch_actual << std::endl;
+ GPU_DEBUG_LOG << " Expected: " << stats.first_mismatch_expected << std::endl;
+ GPU_DEBUG_LOG << " Error: " << std::fabs(stats.first_mismatch_actual - stats.first_mismatch_expected) << std::endl;
+
+ // Sample first 10 mismatches
+ GPU_DEBUG_LOG << "\nFirst 10 mismatches:" << std::endl;
+ int sample_count = 0;
+ for (size_t i = 0; i < total_elements && sample_count < 10; i++) {
+ float actual = static_cast<float>(mem_ptr[i]);
+ float expected = static_cast<float>(ref_output[i]);
+ float error = std::fabs(actual - expected);
+ if (error > tolerance) {
+ GPU_DEBUG_LOG << " [" << i << "] actual=" << actual
+ << " expected=" << expected
+ << " error=" << error << std::endl;
+ sample_count++;
}
- EXPECT_LE(mismatch_count, int(scores_output_mem->count() * 0.04));
}
+
+ print_catastrophic_errors(mem_ptr, ref_output, num_heads, head_size, stats.catastrophic_count);
+
+ // Analyze error type
+ GPU_DEBUG_LOG << "\nError Analysis:" << std::endl;
+ if (stats.catastrophic_count > 0) {
+ GPU_DEBUG_LOG << " ERROR TYPE: CATASTROPHIC - Contains NaN/Inf or very large errors" << std::endl;
+ GPU_DEBUG_LOG << " This indicates a serious bug, not just precision issues." << std::endl;
+ } else if (stats.large_error_count > stats.mismatch_count * 0.5) {
+ GPU_DEBUG_LOG << " ERROR TYPE: LARGE - Most mismatches have error > 0.1" << std::endl;
+ GPU_DEBUG_LOG << " This suggests wrong calculations, not precision drift." << std::endl;
+ } else {
+ GPU_DEBUG_LOG << " ERROR TYPE: PRECISION - Most errors are small" << std::endl;
+ GPU_DEBUG_LOG << " This suggests accumulated floating-point errors." << std::endl;
+ }
+
+ // Comment on tolerance metric
+ GPU_DEBUG_LOG << "\nTolerance Metric Analysis:" << std::endl;
+ GPU_DEBUG_LOG << " Using: Absolute error with threshold " << tolerance << std::endl;
+ GPU_DEBUG_LOG << " Input range: Normal(0, 0.1), typically [-0.3, 0.3]" << std::endl;
+ GPU_DEBUG_LOG << " Relative error at typical values: ~" << (tolerance / 0.1 * 100) << "%" << std::endl;
+ GPU_DEBUG_LOG << " Verdict: Tolerance is reasonable for FP16 attention calculations" << std::endl;
+
+ print_error_distribution(mem_ptr, ref_output, tolerance);
+ GPU_DEBUG_LOG << "========================================\n" << std::endl;
}
+public:
static bool check_cm_available() {
auto& engine = get_test_engine();
ExecutionConfig config = get_test_default_config(engine);
@@ -2589,24 +2833,23 @@ struct paged_attention_test_params {
ov::element::Type kv_cache_precision = ov::element::dynamic;
+
// test query-to-query attention bias
bool has_qq_bias = false;
QueryToQueryAttentionDescriptor qq_bias_config = {};
+ bool run_reference = true;
};
class paged_attention_test : public PagedAttentionTest<paged_attention_test_params> {};
TEST_P(paged_attention_test, basic) {
auto p = GetParam();
- execute(p);
+ execute(p, p.run_reference);
}
class xattention_test : public PagedAttentionTest<paged_attention_test_params> {};
TEST_P(xattention_test, basic) {
auto p = GetParam();
- if (p.subsequences.size() > 1)
- GTEST_SKIP() << "Multi-sequence test cases are not supported yet for xattention!";
-
if (!check_cm_available())
GTEST_SKIP() << "CM JIT support is required for XAttention tests, and the device must be Xe1 or later";
@@ -2629,15 +2872,12 @@ TEST_P(xattention_test, basic) {
}
}
- execute(p);
+ 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();
- if (p.subsequences.size() > 1)
- GTEST_SKIP() << "Multi-sequence test cases are not supported yet for xattention!";
-
if (!check_cm_available())
GTEST_SKIP() << "CM JIT support is required for XAttention tests, and the device must be Xe1 or later";
@@ -2694,6 +2934,11 @@ const auto ENABLE_DIVERSITY = true;
const auto DISABLE_DIVERSITY = false;
const auto ENABLE_QQ_BIAS = QueryToQueryAttentionDescriptor{{{{1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1}}}, {0, 16}};
+static paged_attention_test_params disable_reference_compare(paged_attention_test_params p) {
+ p.run_reference = false;
+ return p;
+}
+
INSTANTIATE_TEST_SUITE_P(smoke_paged_attention, paged_attention_test, ::testing::ValuesIn(std::vector<paged_attention_test_params>{
/* with scores output, use SnapKV */
paged_attention_test_params{ {{10, 0}}, 2, 2, 64, 64, 16, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES_SNAPKV, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, false }, // 1st token
@@ -2947,29 +3192,116 @@ INSTANTIATE_TEST_SUITE_P(smoke_cm_xattention, xattention_test, ::testing::Values
paged_attention_test_params{ {{1, 1023}}, 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>{0.9f}, std::vector<int>{128} }, // 2nd token [basic/62]
paged_attention_test_params{ {{1, 1024}}, 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>{0.9f}, std::vector<int>{128} }, // 2nd token [basic/63]
- //////////////////////////////////////////////////////////////////////////////// multi-seq ////////////////////////////////////////////////////////////////////////
- // multi-seq prefill
- paged_attention_test_params{ {{10, 0}, {30, 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.f, 100.f}, std::vector<int>{128, 128} }, // multi-subsequence prefill [basic/64]
- paged_attention_test_params{ {{10, 0}, {30, 0}}, 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.f, 100.f}, std::vector<int>{128, 128} }, // multi-subsequence prefill [basic/65]
- paged_attention_test_params{ {{10, 0}, {30, 0}}, 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.f, 100.f}, std::vector<int>{128, 128} }, // multi-subsequence prefill [basic/66]
+ //////////////////////////////////////////////////////////////////////////////// diversary head_size and head_ratio + bypass xattention ////////////////////////////////////////////////////////////////////////
+ /////////////////// head_size 96 as phi-3-mini-128k-instruct //////////////////////////////
+ // single-seq prefill + uncompressed cache
+ paged_attention_test_params{ {{32, 0}}, 4, 2, 96, 96, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128} }, // 1st token [basic/64]
+ // single-seq generate + uncompressed cache
+ paged_attention_test_params{ {{1, 31}}, 2, 2, 96, 96, 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} }, // 2nd token [basic/65]
- // multi-seq generate
- paged_attention_test_params{ {{1, 34}, {1, 515}}, 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.f, 100.f}, std::vector<int>{128, 128} }, // multi-subsequence generate [basic/67]
- paged_attention_test_params{ {{1, 34}, {1, 515}}, 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.f, 100.f}, std::vector<int>{128, 128} }, // multi-subsequence generate [basic/68]
- paged_attention_test_params{ {{1, 34}, {1, 515}}, 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.f, 100.f}, std::vector<int>{128, 128} }, // multi-subsequence generate [basic/69]
+ // single-seq prefill + by_token i8 cache
+ paged_attention_test_params{ {{32, 0}}, 2, 2, 96, 96, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128} }, // 1st token [basic/66]
+ // single-seq generate + by_token i8 cache
+ paged_attention_test_params{ {{1, 31}}, 2, 2, 96, 96, 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} }, // 2nd token [basic/67]
+
+ // single-seq prefill + by_channel i8 cache
+ paged_attention_test_params{ {{32, 0}}, 4, 2, 96, 96, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128} }, // 1st token [basic/68]
+ // single-seq generate + by_channel i8 cache
+ paged_attention_test_params{ {{1, 31}}, 2, 2, 96, 96, 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} }, // 2nd token [basic/69]
- paged_attention_test_params{ {{1, 34}, {25, 0}, {10, 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.f, 100.f, 100.f}, std::vector<int>{128, 128, 128} }, // multi-subsequence mixed [basic/70]
- paged_attention_test_params{ {{1, 34}, {25, 0}, {10, 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.f, 100.f, 100.f}, std::vector<int>{128, 128, 128} }, // multi-subsequence mixed [basic/71]
- paged_attention_test_params{ {{1, 34}, {25, 0}, {10, 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.f, 100.f, 100.f}, std::vector<int>{128, 128, 128} }, // multi-subsequence mixed [basic/72]
+ /////////////////// head_ratio 16:1 as minicpm4 //////////////////////////////
+ // single-seq prefill + uncompressed cache
+ paged_attention_test_params{ {{32, 0}}, 32, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128} }, // 1st token [basic/70]
+ // single-seq generate + uncompressed cache
+ paged_attention_test_params{ {{1, 31}}, 32, 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} }, // 2nd token [basic/71]
+
+ // single-seq prefill + by_token i8 cache
+ paged_attention_test_params{ {{32, 0}}, 32, 2, 64, 64, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128} }, // 1st token [basic/72]
+ // single-seq generate + by_token i8 cache
+ paged_attention_test_params{ {{1, 31}}, 32, 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} }, // 2nd token [basic/73]
+
+ // single-seq prefill + by_channel i8 cache
+ paged_attention_test_params{ {{32, 0}}, 32, 2, 64, 64, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{128} }, // 1st token [basic/74]
+ // single-seq generate + by_channel i8 cache
+ paged_attention_test_params{ {{1, 31}}, 32, 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} }, // 2nd token [basic/75]
+
+ //////////////////////////////////////////////////////////////////////////////// diversary head_size and head_ratio + enable xattention ////////////////////////////////////////////////////////////////////////
+ /////////////////// head_size 96 as phi-3-mini-128k-instruct //////////////////////////////
+ // single-seq prefill + uncompressed cache
+ paged_attention_test_params{ {{32, 0}}, 4, 2, 96, 96, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{0.9f}, std::vector<int>{128} }, // 1st token [basic/76]
+ // single-seq generate + uncompressed cache
+ paged_attention_test_params{ {{1, 31}}, 2, 2, 96, 96, 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>{0.9f}, std::vector<int>{128} }, // 2nd token [basic/77]
+
+ // single-seq prefill + by_token i8 cache
+ paged_attention_test_params{ {{32, 0}}, 2, 2, 96, 96, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{0.9f}, std::vector<int>{128} }, // 1st token [basic/78]
+ // single-seq generate + by_token i8 cache
+ paged_attention_test_params{ {{1, 31}}, 2, 2, 96, 96, 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>{0.9f}, std::vector<int>{128} }, // 2nd token [basic/79]
+
+ // single-seq prefill + by_channel i8 cache
+ paged_attention_test_params{ {{32, 0}}, 4, 2, 96, 96, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{0.9f}, std::vector<int>{128} }, // 1st token [basic/80]
+ // single-seq generate + by_channel i8 cache
+ paged_attention_test_params{ {{1, 31}}, 2, 2, 96, 96, 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>{0.9f}, std::vector<int>{128} }, // 2nd token [basic/81]
+
+ /////////////////// head_ratio 16:1 as minicpm4 //////////////////////////////
+ // single-seq prefill + uncompressed cache
+ paged_attention_test_params{ {{32, 0}}, 32, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{0.9f}, std::vector<int>{128} }, // 1st token [basic/82]
+ // single-seq generate + uncompressed cache
+ paged_attention_test_params{ {{1, 31}}, 32, 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>{0.9f}, std::vector<int>{128} }, // 2nd token [basic/83]
+
+ // single-seq prefill + by_token i8 cache
+ paged_attention_test_params{ {{32, 0}}, 32, 2, 64, 64, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{0.9f}, std::vector<int>{128} }, // 1st token [basic/84]
+ // single-seq generate + by_token i8 cache
+ paged_attention_test_params{ {{1, 31}}, 32, 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>{0.9f}, std::vector<int>{128} }, // 2nd token [basic/85]
+
+ // single-seq prefill + by_channel i8 cache
+ paged_attention_test_params{ {{32, 0}}, 32, 2, 64, 64, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{0.9f}, std::vector<int>{128} }, // 1st token [basic/86]
+ // single-seq generate + by_channel i8 cache
+ paged_attention_test_params{ {{1, 31}}, 32, 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>{0.9f}, std::vector<int>{128} }, // 2nd token [basic/87]
+
+ //////////////////////////////////////////////////////////////////////////////// multi-seq + bypass xattention ////////////////////////////////////////////////////////////////////////
+ // multi-seq prefill-only
+ paged_attention_test_params{ {{10, 0}, {30, 0}}, 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.f, 100.f}, std::vector<int>{128, 128} }, // multi-subsequence prefill [basic/88]
+ paged_attention_test_params{ {{10, 0}, {30, 0}}, 4, 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.f, 100.f}, std::vector<int>{128, 128} }, // multi-subsequence prefill [basic/89]
+ paged_attention_test_params{ {{10, 0}, {30, 0}}, 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.f, 100.f}, std::vector<int>{128, 128} }, // multi-subsequence prefill [basic/90]
+
+ // multi-seq generate-only
+ paged_attention_test_params{ {{1, 34}, {1, 515}}, 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.f, 100.f}, std::vector<int>{128, 128} }, // multi-subsequence generate [basic/91]
+ paged_attention_test_params{ {{1, 34}, {1, 515}}, 4, 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.f, 100.f}, std::vector<int>{128, 128} }, // multi-subsequence generate [basic/92]
+ paged_attention_test_params{ {{1, 34}, {1, 515}}, 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.f, 100.f}, std::vector<int>{128, 128} }, // multi-subsequence generate [basic/93]
// multi-seq mixed
- paged_attention_test_params{ {{1, 34}, {25, 0}, {10, 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.f, 100.f, 100.f}, std::vector<int>{128, 128, 128} }, // multi-subsequence mixed [basic/73]
- paged_attention_test_params{ {{1, 34}, {25, 0}, {10, 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.f, 100.f, 100.f}, std::vector<int>{128, 128, 128} }, // multi-subsequence mixed [basic/74]
- paged_attention_test_params{ {{1, 34}, {25, 0}, {10, 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.f, 100.f, 100.f}, std::vector<int>{128, 128, 128} }, // multi-subsequence mixed [basic/75]
+ paged_attention_test_params{ {{1, 34}, {25, 0}, {10, 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.f, 100.f, 100.f}, std::vector<int>{128, 128, 128} }, // multi-subsequence mixed [basic/94]
+ paged_attention_test_params{ {{1, 34}, {25, 0}, {10, 34}}, 4, 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.f, 100.f, 100.f}, std::vector<int>{128, 128, 128} }, // multi-subsequence mixed [basic/95]
+ paged_attention_test_params{ {{1, 34}, {25, 0}, {10, 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.f, 100.f, 100.f}, std::vector<int>{128, 128, 128} }, // multi-subsequence mixed [basic/96]
+
+ paged_attention_test_params{ {{1, 1024 + 34}, {25, 0}, {10, 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.f, 100.f, 100.f}, std::vector<int>{128, 128, 128} }, // multi-subsequence mixed [basic/97]
+ paged_attention_test_params{ {{1, 1024 + 34}, {25, 0}, {10, 34}}, 4, 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.f, 100.f, 100.f}, std::vector<int>{128, 128, 128} }, // multi-subsequence mixed [basic/98]
+ paged_attention_test_params{ {{1, 1024 + 34}, {25, 0}, {10, 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.f, 100.f, 100.f}, std::vector<int>{128, 128, 128} }, // multi-subsequence mixed [basic/99]
+
+ //////////////////////////////////////////////////////////////////////////////// multi-seq + enable xattention ////////////////////////////////////////////////////////////////////////
+ // multi-seq prefill
+ paged_attention_test_params{ {{10, 0}, {30, 0}}, 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>{0.9f, 0.9f}, std::vector<int>{128, 128} }, // multi-subsequence generate [basic/100]
+ paged_attention_test_params{ {{10, 0}, {30, 0}}, 4, 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>{0.9f, 0.9f}, std::vector<int>{128, 128} }, // multi-subsequence generate [basic/101]
+ paged_attention_test_params{ {{10, 0}, {30, 0}}, 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>{0.9f, 0.9f}, std::vector<int>{128, 128} }, // multi-subsequence generate [basic/102]
+
+ // multi-seq generate
+ paged_attention_test_params{ {{1, 34}, {1, 515}}, 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>{0.9f, 0.9f}, std::vector<int>{128, 128} }, // multi-subsequence mixed [basic/103]
+ paged_attention_test_params{ {{1, 34}, {1, 515}}, 4, 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>{0.9f, 0.9f}, std::vector<int>{128, 128} }, // multi-subsequence mixed [basic/104]
+ paged_attention_test_params{ {{1, 34}, {1, 515}}, 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>{0.9f, 0.9f}, std::vector<int>{128, 128} }, // multi-subsequence mixed [basic/105]
- paged_attention_test_params{ {{1, 34}, {25, 0}, {10, 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.f, 100.f, 100.f}, std::vector<int>{128, 128, 128} }, // multi-subsequence mixed [basic/76]
- paged_attention_test_params{ {{1, 34}, {25, 0}, {10, 34}}, 4, 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.f, 100.f, 100.f}, std::vector<int>{128, 128, 128} }, // multi-subsequence mixed [basic/77]
- paged_attention_test_params{ {{1, 34}, {25, 0}, {10, 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.f, 100.f, 100.f}, std::vector<int>{128, 128, 128} }, // multi-subsequence mixed [basic/78]
+ // multi-seq mixed
+ paged_attention_test_params{ {{1, 34}, {25, 0}, {10, 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>{0.9f, 0.9f, 0.9f}, std::vector<int>{128, 128, 128} }, // multi-subsequence mixed [basic/106]
+ paged_attention_test_params{ {{1, 34}, {25, 0}, {10, 34}}, 4, 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>{0.9f, 0.9f, 0.9f}, std::vector<int>{128, 128, 128} }, // multi-subsequence mixed [basic/107]
+ paged_attention_test_params{ {{1, 34}, {25, 0}, {10, 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>{0.9f, 0.9f, 0.9f}, std::vector<int>{128, 128, 128} }, // multi-subsequence mixed [basic/108]
+
+ paged_attention_test_params{ {{1, 1024 + 34}, {25, 0}, {10, 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>{0.9f, 0.9f, 0.9f}, std::vector<int>{128, 128, 128} }, // multi-subsequence mixed [basic/109]
+ paged_attention_test_params{ {{1, 1024 + 34}, {25, 0}, {10, 34}}, 4, 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>{0.9f, 0.9f, 0.9f}, std::vector<int>{128, 128, 128} }, // multi-subsequence mixed [basic/110]
+ paged_attention_test_params{ {{1, 1024 + 34}, {25, 0}, {10, 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>{0.9f, 0.9f, 0.9f}, std::vector<int>{128, 128, 128} }, // multi-subsequence mixed [basic/111]
+
+ // Option B: maximally-divergent past_tail to expose by-channel dispatch under-count (basic/112)
+ // past_len=3 => past_tail=3%16=3; cur_tokens 5,7,9 => sub-blocks ceil((3+5)/16)=1, ceil((3+7)/16)=1, ceil((3+9)/16)=1 = 3 sub-blocks
+ // Simple ceil_div(total_tokens=21, 16) would give 2, under-dispatching by 1 sub-block
+ paged_attention_test_params{ {{5, 3}, {7, 3}, {9, 3}}, 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>{0.9f, 0.9f, 0.9f}, std::vector<int>{128, 128, 128} }, // multi-subsequence by-channel divergent [basic/112]
}));
INSTANTIATE_TEST_SUITE_P(smoke_cm_xattention_block_size, xattention_test, ::testing::ValuesIn(std::vector<paged_attention_test_params>{
@@ -2985,6 +3317,8 @@ INSTANTIATE_TEST_SUITE_P(smoke_cm_xattention_block_size_invalid, xattention_inva
paged_attention_test_params{ {{1024, 0}}, 2, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{0.9f}, std::nullopt },
// Abnormal: user provides empty xattention_block_size tensor
paged_attention_test_params{ {{1024, 0}}, 2, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{0.9f}, std::vector<int>{} },
+ // Abnormal: user provides invalid number of block sizes (should be 1 or equal to batch size)
+ paged_attention_test_params{ {{16, 0}, {16, 0}, {16, 0}}, 2, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{0.9f}, std::vector<int>{128, 128} },
}));
INSTANTIATE_TEST_SUITE_P(smoke_cm_xattention_threshold_invalid, xattention_invalid_test, ::testing::ValuesIn(std::vector<paged_attention_test_params>{
@@ -2992,6 +3326,8 @@ INSTANTIATE_TEST_SUITE_P(smoke_cm_xattention_threshold_invalid, xattention_inval
paged_attention_test_params{ {{1024, 0}}, 2, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::nullopt, std::vector<int>{128} },
// Abnormal: user provides empty xattention_threshold tensor
paged_attention_test_params{ {{1024, 0}}, 2, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{}, std::vector<int>{128} },
+ // Abnormal: user provides invalid number of threshold values (should be 1 or equal to batch size)
+ paged_attention_test_params{ {{16, 0}, {16, 0}, {16, 0}}, 2, 2, 64, 64, 256, 0, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{0.9f, 0.9f}, std::vector<int>{128, 128, 128} },
}));
INSTANTIATE_TEST_SUITE_P(smoke_adaptive_rkv, adaptive_rkv_diversity_test, ::testing::ValuesIn(std::vector<paged_attention_test_params>{
@@ -3051,4 +3387,44 @@ INSTANTIATE_TEST_SUITE_P(smoke_qq_bias, qq_bias_test, ::testing::ValuesIn(std::v
// multi sequence with different qq bias patterns
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}} },
-}));
\ No newline at end of file
+}));
+
+// 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>{
+ // prefill-only
+ disable_reference_compare(paged_attention_test_params{ {{4096, 0}}, 32, 8, 128, 128, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false }),
+ disable_reference_compare(paged_attention_test_params{ {{4096, 4*1024}}, 32, 8, 128, 128, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false }),
+ disable_reference_compare(paged_attention_test_params{ {{4096, 7*1024}}, 32, 8, 128, 128, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false }),
+ disable_reference_compare(paged_attention_test_params{ {{4096, 15*1024}}, 32, 8, 128, 128, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false }),
+ disable_reference_compare(paged_attention_test_params{ {{4096, 23*1024}}, 32, 8, 128, 128, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false }),
+ disable_reference_compare(paged_attention_test_params{ {{4096, 31*1024}}, 32, 8, 128, 128, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false }),
+
+ // generate-only
+ disable_reference_compare(paged_attention_test_params{ {{1, 4096}}, 32, 8, 128, 128, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false }),
+ disable_reference_compare(paged_attention_test_params{ {{1, 4*4096}}, 32, 8, 128, 128, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false }),
+ disable_reference_compare(paged_attention_test_params{ {{1, 8*4096}}, 32, 8, 128, 128, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false }),
+ disable_reference_compare(paged_attention_test_params{ {{1, 16*4096}}, 32, 8, 128, 128, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false }),
+
+ // mixed prefill+generate
+ disable_reference_compare(paged_attention_test_params{ {{1, 1*4096}, {1, 1*1024}, {4096, 1024}}, 32, 8, 128, 128, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false }),
+}));
+
+INSTANTIATE_TEST_SUITE_P(DISABLED_smoke_paged_attention_perf_cm, xattention_test, ::testing::ValuesIn(std::vector<paged_attention_test_params>{
+ // prefill-only
+ disable_reference_compare(paged_attention_test_params{ {{4096, 0}}, 32, 8, 128, 128, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{256} }),
+ disable_reference_compare(paged_attention_test_params{ {{4096, 4*1024}}, 32, 8, 128, 128, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{256} }),
+ disable_reference_compare(paged_attention_test_params{ {{4096, 7*1024}}, 32, 8, 128, 128, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{256} }),
+ disable_reference_compare(paged_attention_test_params{ {{4096, 15*1024}}, 32, 8, 128, 128, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{256} }),
+ disable_reference_compare(paged_attention_test_params{ {{4096, 23*1024}}, 32, 8, 128, 128, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{256} }),
+ disable_reference_compare(paged_attention_test_params{ {{4096, 31*1024}}, 32, 8, 128, 128, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{256} }),
+
+ // generate-only
+ disable_reference_compare(paged_attention_test_params{ {{1, 4096}}, 32, 8, 128, 128, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{256} }),
+ disable_reference_compare(paged_attention_test_params{ {{1, 4*4096}}, 32, 8, 128, 128, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{256} }),
+ disable_reference_compare(paged_attention_test_params{ {{1, 8*4096}}, 32, 8, 128, 128, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{256} }),
+ disable_reference_compare(paged_attention_test_params{ {{1, 16*4096}}, 32, 8, 128, 128, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f}, std::vector<int>{256} }),
+
+ // mixed prefill+generate
+ disable_reference_compare(paged_attention_test_params{ {{1, 1*4096}, {1, 1*1024}, {4096, 1024}}, 32, 8, 128, 128, 256, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, ENABLE_FA_V2, false, 0, {}, true, std::vector<float>{100.0f, 100.0f, 100.0f}, std::vector<int>{256, 256, 256} }),
+}));