Skip to content

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

Enable sdpa micro 4bit kv cache (#35231)

Min, Byungil4433099da25d
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl/kv_cache.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl/kv_cache.cpp
index 164b901bf57..0f411c4b965 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl/kv_cache.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl/kv_cache.cpp
@@ -514,6 +514,14 @@ struct kv_cache_impl : multi_stage_primitive<kv_cache> {
params.combine_scales_and_zp =
primitive->quantization_attributes.output_storage_type != ov::op::internal::DynamicQuantize::OutputStorageType::Planar;
+ // 4-bit KV-cache: the dynamic quantize kernel packs two u4 values into one i8 byte,
+ // halving the physical innermost dimension (head_size). This also forces unsigned
+ // asymmetric quantization (u4 range 0..15) regardless of the original quantization mode.
+ const auto kv_cache_dt = impl_param.get_program().get_config().get_kv_cache_precision();
+ params.is_int4_compressed = ov::element::Type(kv_cache_dt).bitwidth() == 4;
+ if (params.is_int4_compressed)
+ params.use_asymmetric_quantization = true;
+
const auto& past_kv_cache_shape = impl_param.input_layouts[0].get_partial_shape();
params.axis_offset = past_kv_cache_shape[primitive->concat_axis].is_static() ? past_kv_cache_shape[primitive->concat_axis].get_length() : 0;
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_kv_cache_update_ref.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_kv_cache_update_ref.cl
index 9bb27521f04..2918fadc781 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_kv_cache_update_ref.cl
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/pa_kv_cache_update_ref.cl
@@ -48,13 +48,49 @@ inline void FUNC(quantize_and_save_per_token)(__global const INPUT0_TYPE* in_dat
#undef ACCUMULATOR_TYPE
#if IS_INT4_COMPRESSED
- char2 res_vec = 0;
- uint packed_offset[((K_HEAD_SIZE+V_HEAD_SIZE) / SUBGROUP_SIZE) / U4_ELEMS_PER_BYTE] = {0, };
- unroll_for (uint i = 0; i < num_groups; i+=U4_ELEMS_PER_BYTE) {
- res_vec.s0 = convert_char_rte(input_data[i] * scale + zp);
- res_vec.s1 = (i+1 < num_groups) ? convert_char_rte(input_data[i+1] * scale + zp) : 0;
- uint packed_output_offset = out_data_offset + ((i / U4_ELEMS_PER_BYTE) * SUBGROUP_SIZE + sglid) * out_data_pitch;
- out_data[packed_output_offset] = cvt_int8x2_to_uint4x2(res_vec);
+ // Quantize all groups first (clamp to [0, UINT4_RANGE] before packing)
+ char quant_data[(K_HEAD_SIZE+V_HEAD_SIZE) / SUBGROUP_SIZE];
+ unroll_for (uint i = 0; i < num_groups; i++) {
+ quant_data[i] = (char)clamp(convert_int_rte((float)(input_data[i] * scale + zp)), 0, UINT4_RANGE);
+ }
+ // Adjacent packing: packed byte n = pack(head[2n], head[2n+1])
+ // Each packed group of 16 bytes covers 2 input groups (32 head elements)
+ // Use out_data_pitch: key (pitch=block_size) → head-major, value (pitch=1) → token-major
+ unroll_for (uint pp = 0; pp < num_groups / U4_ELEMS_PER_BYTE; pp++) {
+ uint src_lane = (sglid % 8) * 2;
+ char lo_even = intel_sub_group_shuffle(quant_data[2 * pp], src_lane);
+ char hi_even = intel_sub_group_shuffle(quant_data[2 * pp], src_lane + 1);
+ char lo_odd = intel_sub_group_shuffle(quant_data[2 * pp + 1], src_lane);
+ char hi_odd = intel_sub_group_shuffle(quant_data[2 * pp + 1], src_lane + 1);
+ char2 res_vec;
+ res_vec.s0 = (sglid < 8) ? lo_even : lo_odd;
+ res_vec.s1 = (sglid < 8) ? hi_even : hi_odd;
+ out_data[out_data_offset + (pp * SUBGROUP_SIZE + sglid) * out_data_pitch] = cvt_int8x2_to_uint4x2(res_vec);
+ }
+ // Handle remaining group when num_groups is odd (e.g., head_size=80 → 5 groups)
+ if (num_groups % U4_ELEMS_PER_BYTE != 0) {
+ uint last_grp = num_groups - 1;
+ uint pp = num_groups / U4_ELEMS_PER_BYTE;
+ uint src_lane = (sglid % 8) * 2;
+ char lo = intel_sub_group_shuffle(quant_data[last_grp], src_lane);
+ char hi = intel_sub_group_shuffle(quant_data[last_grp], src_lane + 1);
+ char2 res_vec = {lo, hi};
+ if (sglid < 8) {
+ out_data[out_data_offset + (pp * SUBGROUP_SIZE + sglid) * out_data_pitch] = cvt_int8x2_to_uint4x2(res_vec);
+ }
+ }
+ // Scale/zp storage depends on layout:
+ // head-major (pitch>1, key BY_TOKEN): per-token indexed at block end, like INT8
+ // token-major (pitch=1, value): embedded per-token at comp_offset
+ INPUT0_TYPE* comp_ptr = (INPUT0_TYPE*)(out_data + comp_offset);
+ if (sglid == 0) {
+ if (out_data_pitch > 1) {
+ comp_ptr[token_pos_in_block] = 1.0 / scale;
+ comp_ptr[PAGED_ATTENTION_BLOCK_SIZE + token_pos_in_block] = zp;
+ } else {
+ comp_ptr[0] = 1.0 / scale;
+ comp_ptr[1] = zp;
+ }
}
#else // !IS_INT4_COMPRESSED
unroll_for (uint i = 0; i < num_groups; i++) {
@@ -63,17 +99,22 @@ inline void FUNC(quantize_and_save_per_token)(__global const INPUT0_TYPE* in_dat
uint offset = out_data_offset + (i * SUBGROUP_SIZE + sglid) * out_data_pitch;
out_data[offset] = res;
}
- #endif // !IS_INT4_COMPRESSED
- INPUT0_TYPE* comp_ptr = out_data + comp_offset;
- if (sglid == 0) {
- comp_ptr[token_pos_in_block] = 1.0 / scale;
- comp_ptr[PAGED_ATTENTION_BLOCK_SIZE + token_pos_in_block] = zp;
- }
+ INPUT0_TYPE* comp_ptr = out_data + comp_offset;
+ if (sglid == 0) {
+ comp_ptr[token_pos_in_block] = 1.0 / scale;
+ comp_ptr[PAGED_ATTENTION_BLOCK_SIZE + token_pos_in_block] = zp;
+ }
+ #endif // !IS_INT4_COMPRESSED
}
#ifdef IS_KEY_BY_CHANNEL
+#if IS_INT4_COMPRESSED
+// INT4 BY_CHANNEL: packed_block_size = block_size / 2 = 8 bytes of packed u4 data per column
+#define COMP_K_OFFSET (PAGED_ATTENTION_BLOCK_SIZE / U4_ELEMS_PER_BYTE)
+#else
#define COMP_K_OFFSET PAGED_ATTENTION_BLOCK_SIZE
+#endif
#define NUM_HEAD_SIZE_GROUPS K_HEAD_SIZE / SUBGROUP_SIZE
inline void FUNC(quantize_and_save_by_channel_block_with_requantize)(__global const INPUT0_TYPE* in_data,
const uint in_data_offset,
@@ -158,141 +199,73 @@ inline void FUNC(quantize_and_save_by_channel_block_with_requantize_int4)(__glob
const uint new_tokens_num,
const uint sglid,
const uint is_prefill_stage) {
- int head_size_offset = SUBGROUP_SIZE * get_group_id(2) * U4_ELEMS_PER_BYTE;
+ // INT4 BY_CHANNEL with token-axis packing:
+ // Each column (head dim) stores packed TOKEN pairs within bytes.
+ // Column layout: [packed_tokens (8 bytes)] [scale (f16)] [zp (f16)] = 12 bytes
+ // Byte t/2 in column h: lo nibble = token t, hi nibble = token t+1
+ // Each lane (sglid) processes one head dim per iteration.
+ int head_size_offset = SUBGROUP_SIZE * get_group_id(2);
int num_head_size_groups;
if (is_prefill_stage) {
num_head_size_groups = NUM_HEAD_SIZE_GROUPS;
} else {
- // But INT4 work groups process U4_ELEMS_PER_BYTE partitions at a time, so multiply by U4_ELEMS_PER_BYTE
- num_head_size_groups = (NUM_HEAD_SIZE_GROUPS / NUM_K_HEAD_SIZE_PARTITIONS) * U4_ELEMS_PER_BYTE;
- if ((NUM_K_HEAD_SIZE_PARTITIONS % 2) != 0 && NUM_K_HEAD_SIZE_PARTITIONS > 1 &&
- get_group_id(2) == get_num_groups(2) - 1) {
- num_head_size_groups -= 1;
- }
+ num_head_size_groups = NUM_HEAD_SIZE_GROUPS / NUM_K_HEAD_SIZE_PARTITIONS;
}
- int packed_head_size_offset = SUBGROUP_SIZE * (get_group_id(2));
-
- INPUT0_TYPE orig_scale[U4_ELEMS_PER_BYTE] = {0, };
- INPUT0_TYPE orig_zp[U4_ELEMS_PER_BYTE] = {0, };
- OUTPUT_TYPE orig_cache[ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE] = {0, };
-
- INPUT0_TYPE scale[U4_ELEMS_PER_BYTE];
- INPUT0_TYPE zp[U4_ELEMS_PER_BYTE];
- OUTPUT_TYPE buffer[ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE] = {0, };
-
- MAKE_VECTOR_TYPE(INPUT0_TYPE, 16) cache_data_vec_decompressed[NUM_HEAD_SIZE_GROUPS] = {0, };
-
- INPUT0_TYPE* prev_comp_ptr;
for (int h_sub = 0; h_sub < num_head_size_groups; h_sub++) {
const int hidden_idx = head_size_offset + h_sub * SUBGROUP_SIZE + sglid;
-
- // cache
- const uint order_in_packed = (h_sub % U4_ELEMS_PER_BYTE);
- const int packed_hidden_idx = packed_head_size_offset + (h_sub/U4_ELEMS_PER_BYTE) * SUBGROUP_SIZE + sglid;
- const uint packed_out_offset_per_wi = out_data_offset + packed_hidden_idx * out_data_pitch;
+ const uint col_base = out_data_offset + hidden_idx * out_data_pitch;
// Read original scale and zp
- if (order_in_packed == 0) {
- INPUT0_TYPE* comp_ptr = (INPUT0_TYPE*) (&out_data[packed_out_offset_per_wi + COMP_K_OFFSET]);
- orig_scale[0] = comp_ptr[0];
- orig_zp[0] = comp_ptr[1];
- orig_scale[1] = comp_ptr[2];
- orig_zp[1] = comp_ptr[3];
- }
+ INPUT0_TYPE* comp_ptr = (INPUT0_TYPE*)(&out_data[col_base + COMP_K_OFFSET]);
+ INPUT0_TYPE orig_scale = comp_ptr[0];
+ INPUT0_TYPE orig_zp = comp_ptr[1];
+
INPUT0_TYPE max_value = INPUT0_VAL_MIN;
INPUT0_TYPE min_value = INPUT0_VAL_MAX;
- // Read new input
- #define READ_SIZE 16
- #define OUT_DATA_VEC MAKE_VECTOR_TYPE(OUTPUT_TYPE, READ_SIZE)
- #define IN_DATA_VEC MAKE_VECTOR_TYPE(INPUT0_TYPE, READ_SIZE)
- #define VLOAD CAT(vload, READ_SIZE)
-
- for (int j = 0; j < new_tokens_num; ++j) {
- INPUT0_TYPE new_token = BLOCK_READN(INPUT0_TYPE, 1, in_data, in_data_offset + j * K_HEAD_SIZE * KV_HEADS_NUM + hidden_idx);
-
- cache_data_vec_decompressed[order_in_packed][token_pos_in_block + j] = new_token;
-
- max_value = fmax(max_value, new_token);
- min_value = fmin(min_value, new_token);
- }
-
- {
- // Read a hidden dim of the previously quantized cache => decompress
- // TODO : current block size is 16 (same as PA block size),
- // but when the block size becomes different, this part should be updated as well
- OUT_DATA_VEC prev_cache_data_vec;
- if (order_in_packed == 0)
- prev_cache_data_vec = VLOAD(0, out_data + packed_out_offset_per_wi);
- #undef READ_SIZE
- #undef VLOAD
- #undef DATA_VEC
- for (int j = 0; j < token_pos_in_block + new_tokens_num; ++j) {
- if (j < token_pos_in_block) {
- if (order_in_packed == 0) {
- // Generate cache_data_vec_decompressed[0~token_pos_in_block] from key-cache
- char temp = prev_cache_data_vec[j];
- MAKE_VECTOR_TYPE(char, U4_ELEMS_PER_BYTE) buff = unpack_to_char(*(uint4x2_t *)&temp);
-
- if (h_sub + 1 >= num_head_size_groups) {
- cache_data_vec_decompressed[0][j] = ((INPUT0_TYPE)buff.s0 - orig_zp[0]) * orig_scale[0];
- orig_cache[j] = buff.s1;
- } else {
- cache_data_vec_decompressed[0][j] = ((INPUT0_TYPE)buff.s0 - orig_zp[0]) * orig_scale[0];
- cache_data_vec_decompressed[1][j] = ((INPUT0_TYPE)buff.s1 - orig_zp[1]) * orig_scale[1];
- }
- }
- }
- max_value = fmax(max_value, cache_data_vec_decompressed[order_in_packed][j]);
- min_value = fmin(min_value, cache_data_vec_decompressed[order_in_packed][j]);
+ // Decompress existing tokens and collect new tokens
+ INPUT0_TYPE token_vals[PAGED_ATTENTION_BLOCK_SIZE];
+ for (int j = 0; j < (int)(token_pos_in_block + new_tokens_num); ++j) {
+ if (j < (int)token_pos_in_block) {
+ // Decompress existing packed token from column
+ char packed_byte = out_data[col_base + j / U4_ELEMS_PER_BYTE];
+ MAKE_VECTOR_TYPE(char, U4_ELEMS_PER_BYTE) buff = unpack_to_char(*(uint4x2_t *)&packed_byte);
+ char u4_val = (j % U4_ELEMS_PER_BYTE == 0) ? buff.s0 : buff.s1;
+ token_vals[j] = ((INPUT0_TYPE)u4_val - orig_zp) * orig_scale;
+ } else {
+ // Read new token
+ int new_idx = j - token_pos_in_block;
+ token_vals[j] = BLOCK_READN(INPUT0_TYPE, 1, in_data, in_data_offset + new_idx * in_data_pitch + hidden_idx);
}
+ max_value = fmax(max_value, token_vals[j]);
+ min_value = fmin(min_value, token_vals[j]);
}
- // requantize and store
+ // Requantize and store with token-axis packing
{
#define ACCUMULATOR_TYPE float
ACCUMULATOR_TYPE range = (max_value == min_value) ? (0.001) : (max_value - min_value);
const ACCUMULATOR_TYPE min_range = fabs(max_value * 0.1f);
if (range <= min_range) {
- // When the range is very small, expand the range to avoid zp overflow
range += fmax(1.0f, min_range);
}
-
ACCUMULATOR_TYPE scale_tmp = (ACCUMULATOR_TYPE)((UINT4_RANGE) / range);
ACCUMULATOR_TYPE zp_tmp = (ACCUMULATOR_TYPE)(-min_value * scale_tmp);
- scale[order_in_packed] = (INPUT1_TYPE)(scale_tmp);
- zp[order_in_packed] = (INPUT1_TYPE)(zp_tmp);
#undef ACCUMULATOR_TYPE
- INPUT0_TYPE* comp_ptr = (INPUT0_TYPE*) (&out_data[packed_out_offset_per_wi + COMP_K_OFFSET]);
- // [0,1] 1st scale and zp, [2,3] 2nd scale and zp. It represnets [PACKED_CACHE][Scale][ZP][Scale][ZP]
- comp_ptr[2*order_in_packed] = 1.0/scale[order_in_packed];
- comp_ptr[2*order_in_packed+1] = zp[order_in_packed];
- }
-
- if (order_in_packed == 0 && h_sub + 1 >= num_head_size_groups) {
- // NUM_HEAD_SIZE_GROUPS or number of processing groups of this partition is not aligned by U4_ELEMS_PER_BYTE.
- // This sub is the last and single size.
- for (uint token = 0; token < token_pos_in_block + new_tokens_num; ++token) {
- char2 res_vec = 0;
- res_vec.s0 = convert_char_rte(cache_data_vec_decompressed[0][token] * scale[0] + zp[0]);
- res_vec.s1 = orig_cache[token];
- out_data[packed_out_offset_per_wi + token] = cvt_int8x2_to_uint4x2(res_vec);
+ // Pack adjacent token pairs into bytes
+ uint total_tokens = token_pos_in_block + new_tokens_num;
+ for (uint t = 0; t < total_tokens; t += U4_ELEMS_PER_BYTE) {
+ char q0 = (char)clamp(convert_int_rte((float)(token_vals[t] * scale_tmp + zp_tmp)), 0, UINT4_RANGE);
+ char q1 = (t + 1 < total_tokens) ? (char)clamp(convert_int_rte((float)(token_vals[t + 1] * scale_tmp + zp_tmp)), 0, UINT4_RANGE) : 0;
+ char2 res_vec = {q0, q1};
+ out_data[col_base + t / U4_ELEMS_PER_BYTE] = cvt_int8x2_to_uint4x2(res_vec);
}
- } else {
- // Process aligned size sub-group from num_head_size_groups
- for (uint token = 0; token < token_pos_in_block + new_tokens_num; ++token) {
- if (order_in_packed == (U4_ELEMS_PER_BYTE - 1)) {
- char2 res_vec;
- res_vec.s0 = buffer[token];
- res_vec.s1 = convert_char_rte(cache_data_vec_decompressed[1][token] * scale[1] + zp[1]);
- out_data[packed_out_offset_per_wi + token] = cvt_int8x2_to_uint4x2(res_vec);
- } else {
- buffer[token] = convert_char_rte(cache_data_vec_decompressed[0][token] * scale[0] + zp[0]);
- }
- }
+ // Store scale/zp
+ comp_ptr[0] = 1.0 / (INPUT0_TYPE)scale_tmp;
+ comp_ptr[1] = (INPUT0_TYPE)zp_tmp;
}
}
}
@@ -306,10 +279,6 @@ inline void FUNC(quantize_and_save_by_channel_prefill)(__global const INPUT0_TYP
//const uint token_start_pos_key,
const uint sglid) {
uint out_offset = out_data_offset;
- #if IS_INT4_COMPRESSED
- // store the rest of the pair
- OUTPUT_TYPE buffer[PAGED_ATTENTION_BLOCK_SIZE] = {0, };
- #endif
for (uint i = 0; i < NUM_HEAD_SIZE_GROUPS; i++) {
uint key_in_offset_tmp = in_data_offset + i * SUBGROUP_SIZE;
INPUT0_TYPE input_data[PAGED_ATTENTION_BLOCK_SIZE];
@@ -347,47 +316,25 @@ inline void FUNC(quantize_and_save_by_channel_prefill)(__global const INPUT0_TYP
INPUT0_TYPE* comp_ptr = (INPUT0_TYPE*) (&out_data[out_offset_per_wi + COMP_K_OFFSET]);
#if IS_INT4_COMPRESSED
- const uint order_in_packed = i % U4_ELEMS_PER_BYTE;
- comp_ptr[2 * order_in_packed] = 1.0 / scale;
- comp_ptr[2 * order_in_packed + 1] = zp;
- #else
+ // Token-axis packing: one scale/zp per column (head dim)
comp_ptr[0] = 1.0 / scale;
comp_ptr[1] = zp;
- #endif
-
- // Store quantized key
- #if IS_INT4_COMPRESSED
- for (uint token_num = 0; token_num < tokens_num; token_num++) {
- if (order_in_packed == (U4_ELEMS_PER_BYTE - 1)) {
- char2 res_vec = 0;
- res_vec.s0 = buffer[token_num];
- res_vec.s1 = convert_char_rte(input_data[token_num] * scale + zp);
- out_data[out_offset_per_wi] = cvt_int8x2_to_uint4x2(res_vec);
- out_offset_per_wi++;
- } else {
- buffer[token_num] = convert_char_rte(input_data[token_num] * scale + zp);
-
- if (i + 1 >= NUM_HEAD_SIZE_GROUPS) {
- char2 res_vec = 0;
- res_vec.s0 = buffer[token_num];
- res_vec.s1 = 0;
-
- out_data[out_offset_per_wi] = cvt_int8x2_to_uint4x2(res_vec);
- out_offset_per_wi++;
- }
- }
- }
-
- if (order_in_packed == (U4_ELEMS_PER_BYTE - 1)) {
- out_offset += (ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE * SUBGROUP_SIZE);
+ // Pack adjacent token pairs into bytes within this column
+ for (uint token_num = 0; token_num < tokens_num; token_num += U4_ELEMS_PER_BYTE) {
+ char q0 = (char)clamp(convert_int_rte((float)(input_data[token_num] * scale + zp)), 0, UINT4_RANGE);
+ char q1 = (token_num + 1 < tokens_num) ? (char)clamp(convert_int_rte((float)(input_data[token_num + 1] * scale + zp)), 0, UINT4_RANGE) : 0;
+ char2 res_vec = {q0, q1};
+ out_data[out_offset_per_wi + token_num / U4_ELEMS_PER_BYTE] = cvt_int8x2_to_uint4x2(res_vec);
}
+ out_offset += (ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE * SUBGROUP_SIZE);
#else
+ comp_ptr[0] = 1.0 / scale;
+ comp_ptr[1] = zp;
+
for (uint token_num = 0; token_num < tokens_num; token_num++) {
OUTPUT_TYPE res = convert_char_rte(input_data[token_num] * scale + zp);
- out_data[out_offset_per_wi] = res;
-
- out_offset_per_wi++;
+ out_data[out_offset_per_wi + token_num] = res;
}
out_offset += ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE * SUBGROUP_SIZE;
#endif
@@ -421,9 +368,11 @@ KERNEL(pa_kv_cache_update)(
#endif
#if IS_INT4_COMPRESSED
- const uint phys_adjusted_k_head_size = PACKED_ADJUSTED_K_HEAD_SIZE;
+ // INT4 BY_CHANNEL K: head_size is outer dim (not packed), block is inner (packed)
+ const uint phys_adjusted_k_head_size = PACKED_ADJUSTED_K_HEAD_SIZE; // = K_HEAD_SIZE for BY_CHANNEL
+ const uint phys_k_head_size = PACKED_K_HEAD_SIZE; // = K_HEAD_SIZE for BY_CHANNEL
+ // INT4 V: per-token, head_size is inner dim (packed)
const uint phys_adjusted_v_head_size = PACKED_ADJUSTED_V_HEAD_SIZE;
- const uint phys_k_head_size = PACKED_K_HEAD_SIZE;
const uint phys_v_head_size = PACKED_V_HEAD_SIZE;
#else
const uint phys_adjusted_k_head_size = ADJUSTED_K_HEAD_SIZE;
@@ -452,8 +401,13 @@ KERNEL(pa_kv_cache_update)(
uint block_k_base_offset = block_idx * KV_HEADS_NUM * phys_adjusted_k_head_size * PAGED_ATTENTION_BLOCK_SIZE + head_idx * phys_adjusted_k_head_size * PAGED_ATTENTION_BLOCK_SIZE;
#endif
uint block_v_base_offset = block_idx * KV_HEADS_NUM * phys_adjusted_v_head_size * PAGED_ATTENTION_BLOCK_SIZE + head_idx * phys_adjusted_v_head_size * PAGED_ATTENTION_BLOCK_SIZE;
+ // Key: head-major for both INT4 and INT8 BY_TOKEN (token pos = offset within stride)
uint key_out_offset = block_k_base_offset + current_token_pos_in_block;
+#if IS_INT4_COMPRESSED
+ uint value_out_offset = block_v_base_offset + current_token_pos_in_block * phys_adjusted_v_head_size;
+#else
uint value_out_offset = block_v_base_offset + current_token_pos_in_block * phys_v_head_size;
+#endif
#if !IS_KV_COMPRESSED
#define READ_K_BLOCK_SIZE GENERATE_STAGE_K_BLOCK_SIZE
@@ -494,10 +448,19 @@ KERNEL(pa_kv_cache_update)(
// key by channel
{
#if IS_INT4_COMPRESSED
+ // INT4 BY_CHANNEL K: requantize existing block with new token
FUNC_CALL(quantize_and_save_by_channel_block_with_requantize_int4)(key_data,
+ key_in_offset,
+ KEY_IN_STRIDE,
+ key_cache_data,
+ block_k_base_offset,
+ k_hidden_stride,
+ current_token_pos_in_block,
+ 1,
+ sglid,
+ 0);
#else
FUNC_CALL(quantize_and_save_by_channel_block_with_requantize)(key_data,
- #endif
key_in_offset,
KEY_IN_STRIDE,
key_cache_data,
@@ -507,11 +470,16 @@ KERNEL(pa_kv_cache_update)(
1,
sglid,
0);
+ #endif
}
// value per token
if (get_group_id(2) == 0) {
+ #if IS_INT4_COMPRESSED
+ const uint comp_v_offset = value_out_offset + phys_v_head_size;
+ #else
const uint comp_v_offset = block_v_base_offset + phys_v_head_size * PAGED_ATTENTION_BLOCK_SIZE;
+ #endif
INPUT0_TYPE input_data[V_HEAD_SIZE / SUBGROUP_SIZE];
FUNC_CALL(quantize_and_save_per_token)(value_data, value_in_offset, value_cache_data, value_out_offset, 1, comp_v_offset,
current_token_pos_in_block, sglid, V_HEAD_SIZE / SUBGROUP_SIZE, &input_data[0]);
@@ -525,7 +493,11 @@ KERNEL(pa_kv_cache_update)(
FUNC_CALL(quantize_and_save_per_token)(key_data, key_in_offset, key_cache_data, key_out_offset, PAGED_ATTENTION_BLOCK_SIZE, comp_k_offset,
current_token_pos_in_block, sglid, K_HEAD_SIZE / SUBGROUP_SIZE, &input_k_data[0]);
+#if IS_INT4_COMPRESSED
+ const uint comp_v_offset = value_out_offset + phys_v_head_size;
+#else
const uint comp_v_offset = block_v_base_offset + phys_v_head_size * PAGED_ATTENTION_BLOCK_SIZE;
+#endif
INPUT0_TYPE input_v_data[V_HEAD_SIZE / SUBGROUP_SIZE];
FUNC_CALL(quantize_and_save_per_token)(value_data, value_in_offset, value_cache_data, value_out_offset, 1, comp_v_offset,
current_token_pos_in_block, sglid, V_HEAD_SIZE / SUBGROUP_SIZE, &input_v_data[0]);
@@ -570,21 +542,58 @@ KERNEL(pa_kv_cache_update)(
uint block_v_base_offset = block_indices[block_offset] * KV_HEADS_NUM * phys_adjusted_v_head_size * PAGED_ATTENTION_BLOCK_SIZE +
head_idx * phys_adjusted_v_head_size * PAGED_ATTENTION_BLOCK_SIZE;
+#if IS_INT4_COMPRESSED
+ uint value_out_offset = block_v_base_offset;
+ value_out_offset += token_start_pos_val * phys_adjusted_v_head_size;
+ const uint comp_v_offset = value_out_offset + phys_v_head_size;
+#else
const uint comp_v_offset = block_v_base_offset + phys_v_head_size * PAGED_ATTENTION_BLOCK_SIZE;
uint value_out_offset = block_v_base_offset;
value_out_offset += token_start_pos_val * phys_v_head_size;
+#endif
if (tokens_num == PAGED_ATTENTION_BLOCK_SIZE) {
// block is full
#if defined(IS_KV_COMPRESSED) && defined(IS_KEY_BY_CHANNEL)
+ #if IS_INT4_COMPRESSED
+ // INT4 BY_CHANNEL: use by-channel prefill or requantize (same as INT8 BY_CHANNEL)
+ {
+ if (token_start_pos_key != 0) {
+ // mixed mode: need requantize with previous tokens
+ FUNC_CALL(quantize_and_save_by_channel_block_with_requantize_int4)(key_data,
+ key_in_offset,
+ KEY_IN_STRIDE,
+ key_cache_data,
+ block_k_base_offset,
+ k_hidden_stride,
+ token_start_pos_key,
+ tokens_num,
+ sglid,
+ 1);
+ } else {
+ FUNC_CALL(quantize_and_save_by_channel_prefill)(key_data,
+ key_in_offset,
+ KEY_IN_STRIDE,
+ key_cache_data,
+ key_out_offset,
+ tokens_num,
+ sglid);
+ }
+ }
+ // Value per token
+ for (uint token_num = 0; token_num < tokens_num; token_num++) {
+ INPUT0_TYPE input_data[V_HEAD_SIZE / SUBGROUP_SIZE];
+ const uint comp_v = value_out_offset + phys_v_head_size;
+ FUNC_CALL(quantize_and_save_per_token)(value_data, value_in_offset, value_cache_data, value_out_offset, 1,
+ comp_v, token_start_pos_val + token_num, sglid, V_HEAD_SIZE / SUBGROUP_SIZE, &input_data[0]);
+ value_in_offset += (KV_HEADS_NUM * V_HEAD_SIZE + INPUT1_PAD_AFTER_FEATURE_NUM + INPUT1_PAD_BEFORE_FEATURE_NUM);
+ value_out_offset += phys_adjusted_v_head_size;
+ }
+ #else
// Key by channel
if (token_start_pos_key != 0) {
// mixed mode => need requantize with prev tokens
- #if IS_INT4_COMPRESSED
- FUNC_CALL(quantize_and_save_by_channel_block_with_requantize_int4)(key_data,
- #else
FUNC_CALL(quantize_and_save_by_channel_block_with_requantize)(key_data,
- #endif
key_in_offset,
KEY_IN_STRIDE,
key_cache_data,
@@ -611,6 +620,7 @@ KERNEL(pa_kv_cache_update)(
value_in_offset += (KV_HEADS_NUM * V_HEAD_SIZE + INPUT1_PAD_AFTER_FEATURE_NUM + INPUT1_PAD_BEFORE_FEATURE_NUM);
value_out_offset += phys_v_head_size;
}
+ #endif
#else // !(defined(IS_KV_COMPRESSED) && defined(IS_KEY_BY_CHANNEL))
unroll_for (uint token_num = 0; token_num < PAGED_ATTENTION_BLOCK_SIZE; token_num++) {
#if !IS_KV_COMPRESSED
@@ -735,26 +745,67 @@ KERNEL(pa_kv_cache_update)(
// Value per token
INPUT0_TYPE input_v_data[V_HEAD_SIZE / SUBGROUP_SIZE];
+#if IS_INT4_COMPRESSED
+ const uint cur_comp_v = value_out_offset + phys_v_head_size;
+ FUNC_CALL(quantize_and_save_per_token)(value_data, value_in_offset, value_cache_data, value_out_offset, 1,
+ cur_comp_v, token_num, sglid, V_HEAD_SIZE / SUBGROUP_SIZE, &input_v_data[0]);
+#else
FUNC_CALL(quantize_and_save_per_token)(value_data, value_in_offset, value_cache_data, value_out_offset, 1,
comp_v_offset, token_num, sglid, V_HEAD_SIZE / SUBGROUP_SIZE, &input_v_data[0]);
+#endif
}
#endif // IS_KV_COMPRESSED
key_in_offset += (KV_HEADS_NUM * K_HEAD_SIZE + INPUT0_PAD_AFTER_FEATURE_NUM + INPUT0_PAD_BEFORE_FEATURE_NUM);
key_out_offset += 1;
value_in_offset += (KV_HEADS_NUM * V_HEAD_SIZE + INPUT1_PAD_AFTER_FEATURE_NUM + INPUT1_PAD_BEFORE_FEATURE_NUM);
+#if IS_INT4_COMPRESSED
+ value_out_offset += phys_adjusted_v_head_size;
+#else
value_out_offset += phys_v_head_size;
+#endif
}
#endif // !(defined(IS_KV_COMPRESSED) && defined(IS_KEY_BY_CHANNEL))
} else {
#if defined(IS_KV_COMPRESSED) && defined(IS_KEY_BY_CHANNEL)
+ #if IS_INT4_COMPRESSED
+ // INT4 BY_CHANNEL: use by-channel requantize (same as INT8 BY_CHANNEL path)
+ {
+ if (token_start_pos_key != 0) {
+ FUNC_CALL(quantize_and_save_by_channel_block_with_requantize_int4)(key_data,
+ key_in_offset,
+ KEY_IN_STRIDE,
+ key_cache_data,
+ block_k_base_offset,
+ k_hidden_stride,
+ token_start_pos_key,
+ tokens_num,
+ sglid,
+ 1);
+ } else {
+ FUNC_CALL(quantize_and_save_by_channel_prefill)(key_data,
+ key_in_offset,
+ KEY_IN_STRIDE,
+ key_cache_data,
+ key_out_offset,
+ tokens_num,
+ sglid);
+ }
+ }
+
+ // value processing per token
+ for (uint token_num = 0; token_num < tokens_num; token_num++) {
+ INPUT0_TYPE input_data[V_HEAD_SIZE / SUBGROUP_SIZE];
+ const uint comp_v = value_out_offset + phys_v_head_size;
+ FUNC_CALL(quantize_and_save_per_token)(value_data, value_in_offset, value_cache_data, value_out_offset, 1,
+ comp_v, token_start_pos_val + token_num, sglid, V_HEAD_SIZE / SUBGROUP_SIZE, &input_data[0]);
+ value_in_offset += (KV_HEADS_NUM * V_HEAD_SIZE + INPUT1_PAD_AFTER_FEATURE_NUM + INPUT1_PAD_BEFORE_FEATURE_NUM);
+ value_out_offset += phys_adjusted_v_head_size;
+ }
+ #else
// key processing by channel
if (token_start_pos_key != 0) {
// mixed mode => need requantize with prev tokens
- #if IS_INT4_COMPRESSED
- FUNC_CALL(quantize_and_save_by_channel_block_with_requantize_int4)(key_data,
- #else
FUNC_CALL(quantize_and_save_by_channel_block_with_requantize)(key_data,
- #endif
key_in_offset,
KEY_IN_STRIDE,
key_cache_data,
@@ -782,6 +833,7 @@ KERNEL(pa_kv_cache_update)(
value_in_offset += (KV_HEADS_NUM * V_HEAD_SIZE + INPUT1_PAD_AFTER_FEATURE_NUM + INPUT1_PAD_BEFORE_FEATURE_NUM);
value_out_offset += phys_v_head_size;
}
+ #endif
#else // defined(IS_KV_COMPRESSED) && defined(IS_KEY_BY_CHANNEL)
for (uint token_num = 0; token_num < tokens_num; token_num++) {
uint head_idx_index = 0;
@@ -817,14 +869,24 @@ KERNEL(pa_kv_cache_update)(
// value processing
INPUT0_TYPE input_v_data[V_HEAD_SIZE / SUBGROUP_SIZE];
+#if IS_INT4_COMPRESSED
+ const uint cur_comp_v = value_out_offset + phys_v_head_size;
+ FUNC_CALL(quantize_and_save_per_token)(value_data, value_in_offset, value_cache_data, value_out_offset, 1,
+ cur_comp_v, token_start_pos_val + token_num, sglid, V_HEAD_SIZE / SUBGROUP_SIZE, &input_v_data[0]);
+#else
FUNC_CALL(quantize_and_save_per_token)(value_data, value_in_offset, value_cache_data, value_out_offset, 1,
comp_v_offset, token_start_pos_val + token_num, sglid, V_HEAD_SIZE / SUBGROUP_SIZE, &input_v_data[0]);
+#endif
}
#endif // IS_KV_COMPRESSED
key_in_offset += (KV_HEADS_NUM * K_HEAD_SIZE + INPUT0_PAD_AFTER_FEATURE_NUM + INPUT0_PAD_BEFORE_FEATURE_NUM);
key_out_offset += 1;
value_in_offset += (KV_HEADS_NUM * V_HEAD_SIZE + INPUT1_PAD_AFTER_FEATURE_NUM + INPUT1_PAD_BEFORE_FEATURE_NUM);
+#if IS_INT4_COMPRESSED
+ value_out_offset += phys_adjusted_v_head_size;
+#else
value_out_offset += phys_v_head_size;
+#endif
}
#endif // defined(IS_KV_COMPRESSED) && defined(IS_KEY_BY_CHANNEL)
}
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/paged_attention_opt.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/paged_attention_opt.cl
index eba9d5437c8..78617fddeb9 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/paged_attention_opt.cl
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/paged_attention_opt.cl
@@ -269,47 +269,39 @@ KERNEL(pa_sdpa_opt)(
#endif
// Loop for qk_index
-#if IS_KV_COMPRESSED && IS_INT4_COMPRESSED
+#if IS_KV_COMPRESSED && IS_INT4_COMPRESSED && defined(IS_KEY_BY_CHANNEL)
+ // INT4 BY_CHANNEL: dim order {0,1,3,2}: [blocks, heads, head_size, packed_block+scales]
+ // Each column (head dim) = COMP_K_OFFSET packed bytes + 4 bytes scale/zp.
+ // Token sglid's u4 value is at packed byte sglid/2, nibble sglid%2.
+ // Lane sglid represents token sglid, reads its nibble from each column.
MAKE_VECTOR_TYPE(INPUT0_TYPE, KEY_VEC_SIZE) k_vals[K_HEAD_SIZE / KEY_VEC_SIZE];
-
- unroll_for (uint qk_idx = 0; qk_idx < (K_HEAD_SIZE / KEY_VEC_SIZE); qk_idx+=U4_ELEMS_PER_BYTE) {
- #ifdef IS_KEY_BY_CHANNEL
- INPUT0_TYPE comp_scale[U4_ELEMS_PER_BYTE] = {0, };
- INPUT0_TYPE comp_zp[U4_ELEMS_PER_BYTE] = {0, };
-
- uint key_comp_offset = key_block_offset + (qk_idx / U4_ELEMS_PER_BYTE) * SUBGROUP_SIZE * hidden_stride + sglid * hidden_stride + PAGED_ATTENTION_BLOCK_SIZE;
- INPUT0_TYPE* key_comp_ptr = key_cache + key_comp_offset;
- comp_scale[0] = key_comp_ptr[0];
- comp_zp[0] = key_comp_ptr[1];
- comp_scale[1] = key_comp_ptr[2];
- comp_zp[1] = key_comp_ptr[3];
- #endif
-
- uint init_index = key_block_offset + 0 * hidden_stride * KEY_VEC_SIZE;
- unroll_for (uint i = 0; i < KEY_VEC_SIZE; i++) {
- uint index = key_block_offset + (qk_idx/U4_ELEMS_PER_BYTE) * hidden_stride * KEY_VEC_SIZE + i * hidden_stride;
-
- char packed_cache = BLOCK_READN(INPUT1_TYPE, 1, key_cache, index);
- MAKE_VECTOR_TYPE(char, U4_ELEMS_PER_BYTE) buff = unpack_to_char(*(uint4x2_t *)&packed_cache);
-
- char key_orig = buff.s0;
- #ifdef IS_KEY_BY_CHANNEL
- INPUT0_TYPE first_scale = sub_group_shuffle(comp_scale[0], i);
- INPUT0_TYPE second_scale = sub_group_shuffle(comp_scale[1], i);
- INPUT0_TYPE first_zp = sub_group_shuffle(comp_zp[0], i);
- INPUT0_TYPE second_zp = sub_group_shuffle(comp_zp[1], i);
- k_vals[qk_idx][i] = ((INPUT0_TYPE)key_orig - first_zp) * first_scale;
- if (qk_idx + 1 < (K_HEAD_SIZE / KEY_VEC_SIZE)) {
- key_orig = buff.s1;
- k_vals[qk_idx+1][i] = ((INPUT0_TYPE)key_orig - second_zp) * second_scale;
- }
- #else
- k_vals[qk_idx][i] = ((INPUT0_TYPE)key_orig - comp_zp) * comp_scale;
- if (qk_idx + 1 < (K_HEAD_SIZE / KEY_VEC_SIZE)) {
- key_orig = buff.s1;
- k_vals[qk_idx+1][i] = ((INPUT0_TYPE)key_orig - comp_zp) * comp_scale;
- }
- #endif
+ {
+ unroll_for (uint qk_idx = 0; qk_idx < K_HEAD_SIZE / KEY_VEC_SIZE; qk_idx++) {
+ // Pre-read scale/zp: lane sglid reads scale for head dim (qk_idx*16 + sglid)
+ const uint comp_head_dim = qk_idx * KEY_VEC_SIZE + sglid;
+ const uint comp_col_base = key_block_offset + comp_head_dim * hidden_stride;
+ INPUT0_TYPE* comp_ptr = (INPUT0_TYPE*)(key_cache + comp_col_base + PACKED_K_BLOCK_SIZE);
+ INPUT0_TYPE comp_scale = comp_ptr[0];
+ INPUT0_TYPE comp_zp = comp_ptr[1];
+
+ // Optimized: process 2 adjacent head dims per iteration to halve memory reads
+ // and eliminate redundant unpack + branch operations.
+ const uint sglid_byte_offset = sglid / U4_ELEMS_PER_BYTE;
+ const uint is_odd_lane = sglid % U4_ELEMS_PER_BYTE;
+ unroll_for (uint i = 0; i < KEY_VEC_SIZE; i += 2) {
+ const uint head_dim0 = qk_idx * KEY_VEC_SIZE + i;
+ const uint head_dim1 = head_dim0 + 1;
+
+ const uint col_base0 = key_block_offset + head_dim0 * hidden_stride;
+ const uint col_base1 = key_block_offset + head_dim1 * hidden_stride;
+ char packed0 = key_cache[col_base0 + sglid_byte_offset];
+ char packed1 = key_cache[col_base1 + sglid_byte_offset];
+ char u4_val0 = is_odd_lane ? ((uchar)packed0 >> 4) : (packed0 & 0x0F);
+ char u4_val1 = is_odd_lane ? ((uchar)packed1 >> 4) : (packed1 & 0x0F);
+
+ k_vals[qk_idx][i] = ((INPUT0_TYPE)u4_val0 - _sub_group_shuffle(comp_zp, i)) * _sub_group_shuffle(comp_scale, i);
+ k_vals[qk_idx][i + 1] = ((INPUT0_TYPE)u4_val1 - _sub_group_shuffle(comp_zp, i + 1)) * _sub_group_shuffle(comp_scale, i + 1);
+ }
}
}
@@ -332,7 +324,7 @@ KERNEL(pa_sdpa_opt)(
}
#endif
-#else // !(IS_KV_COMPRESSED && IS_INT4_COMPRESSED)
+#else // !(IS_KV_COMPRESSED && IS_INT4_COMPRESSED && defined(IS_KEY_BY_CHANNEL))
#define KEY_BLOCK_UNCOMPRESSED MAKE_VECTOR_TYPE(INPUT0_TYPE, KEY_VEC_SIZE)
#ifdef DISABLE_QK_LOOP_UNROLL
for (uint qk_idx = 0; qk_idx < K_HEAD_SIZE / KEY_VEC_SIZE; qk_idx++) {
@@ -341,15 +333,29 @@ KERNEL(pa_sdpa_opt)(
#endif
#if IS_KV_COMPRESSED
- #ifdef IS_KEY_BY_CHANNEL
- const uint key_comp_offset = key_block_offset + qk_idx * SUBGROUP_SIZE * hidden_stride + sglid * hidden_stride + PAGED_ATTENTION_BLOCK_SIZE;
- INPUT0_TYPE* key_comp_ptr = key_cache + key_comp_offset;
- INPUT0_TYPE comp_scale = key_comp_ptr[0];
- INPUT0_TYPE comp_zp = key_comp_ptr[1];
- #endif
-
+ #if IS_INT4_COMPRESSED
+ // INT4 BY_TOKEN head-major: [blocks, heads, packed_head_size * block_size, scales, zps]
+ // Each byte packs 2 adjacent head dims (lo nibble, hi nibble)
+ // Use scalar reads (not BLOCK_READN) to avoid subgroup block read issues with byte types
+ KEY_BLOCK_UNCOMPRESSED k_vals;
+ unroll_for (uint i = 0; i < KEY_VEC_SIZE / 2; i++) {
+ uint packed_h = qk_idx * (KEY_VEC_SIZE / 2) + i;
+ INPUT1_TYPE packed_byte = key_cache[key_block_offset + packed_h * hidden_stride + sglid];
+ MAKE_VECTOR_TYPE(char, U4_ELEMS_PER_BYTE) buff = unpack_to_char(*(uint4x2_t *)&packed_byte);
+ k_vals[2 * i] = ((INPUT0_TYPE)(char)buff.s0 - comp_zp) * comp_scale;
+ k_vals[2 * i + 1] = ((INPUT0_TYPE)(char)buff.s1 - comp_zp) * comp_scale;
+ }
+ #else
KEY_BLOCK_UNCOMPRESSED k_vals;
uint init_index = key_block_offset + 0 * hidden_stride * KEY_VEC_SIZE;
+ #ifdef IS_KEY_BY_CHANNEL
+ // Per-channel scale/zp for i8 BY_CHANNEL: each column has PAGED_ATTENTION_BLOCK_SIZE data bytes + scale(fp16) + zp(fp16)
+ const uint comp_head_dim = qk_idx * KEY_VEC_SIZE + sglid;
+ const uint comp_col_base = key_block_offset + comp_head_dim * hidden_stride;
+ INPUT0_TYPE* comp_ptr = (INPUT0_TYPE*)(key_cache + comp_col_base + PAGED_ATTENTION_BLOCK_SIZE);
+ INPUT0_TYPE comp_scale = comp_ptr[0];
+ INPUT0_TYPE comp_zp = comp_ptr[1];
+ #endif
unroll_for (uint i = 0; i < KEY_VEC_SIZE; i++) {
k_vals[i] = BLOCK_READN(INPUT1_TYPE, 1, key_cache, key_block_offset + qk_idx * hidden_stride * KEY_VEC_SIZE + i * hidden_stride);
#ifdef IS_KEY_BY_CHANNEL
@@ -358,6 +364,7 @@ KERNEL(pa_sdpa_opt)(
k_vals[i] = (k_vals[i] - comp_zp) * comp_scale;
#endif
}
+ #endif // IS_INT4_COMPRESSED
#else // !IS_KV_COMPRESSED
KEY_BLOCK k_vals = 0;
unroll_for (uint i = 0; i < KEY_VEC_SIZE; i++) {
@@ -647,12 +654,17 @@ KERNEL(pa_sdpa_opt)(
#if IS_KV_COMPRESSED
const uint packed_block_offset = block_indices[start_block_idx + block_num] * KV_HEADS_NUM * phys_adjusted_v_head_size * PAGED_ATTENTION_BLOCK_SIZE
+ head_idx * phys_adjusted_v_head_size * PAGED_ATTENTION_BLOCK_SIZE;
- const uint head_size_offset = ((head_size_idx / SUBGROUP_SIZE) / U4_ELEMS_PER_BYTE) * SUBGROUP_SIZE + (head_size_idx % SUBGROUP_SIZE);
- const uint packed_value_offset = packed_block_offset + head_size_offset;
+#if IS_INT4_COMPRESSED
+ // INT4: per-token embedded scales at end of each token's row
+ INPUT0_TYPE* my_token_comp_ptr = (INPUT0_TYPE*)(value_cache + packed_block_offset + sglid * phys_adjusted_v_head_size + phys_v_head_size);
+ INPUT0_TYPE comp_scale = my_token_comp_ptr[0];
+ INPUT0_TYPE comp_zp = my_token_comp_ptr[1];
+#else
const uint value_comp_offset = packed_block_offset + phys_v_head_size * PAGED_ATTENTION_BLOCK_SIZE;
INPUT0_TYPE* value_comp_ptr = value_cache + value_comp_offset;
INPUT0_TYPE comp_scale = value_comp_ptr[0 + sglid];
INPUT0_TYPE comp_zp = value_comp_ptr[PAGED_ATTENTION_BLOCK_SIZE + sglid];
+#endif
#endif
@@ -664,20 +676,18 @@ KERNEL(pa_sdpa_opt)(
#if IS_KV_COMPRESSED && IS_INT4_COMPRESSED
- // INT4 compression for value-cache
- const uint idx_packed = (head_size_idx / SUBGROUP_SIZE) % U4_ELEMS_PER_BYTE;
+ // INT4 adjacent packing: V layout [blocks, heads, block_size, packed_head+scales=68]
+ // packed_byte = head_size_idx/2, nibble = head_size_idx%2
+ // Token stride = phys_adjusted_v_head_size (68)
+ const uint packed_byte_idx = head_size_idx / 2;
+ const uint nibble_sel = head_size_idx & 1;
VALUE_BLOCK v_vals_packed;
unroll_for (uint i = 0; i < VALUE_VEC_SIZE; i++) {
- uint index = packed_value_offset + i * phys_v_head_size;
- char packed_value = BLOCK_READN(INPUT2_TYPE, 1, value_cache, index);
- MAKE_VECTOR_TYPE(char, U4_ELEMS_PER_BYTE) buff = unpack_to_char(*(uint4x2_t *)&packed_value);
-
- if (idx_packed == 0) {
- v_vals_packed[i] = buff.s0;
- } else {
- v_vals_packed[i] = buff.s1;
- }
+ uint token_offset = packed_block_offset + i * phys_adjusted_v_head_size + packed_byte_idx;
+ char packed_val = value_cache[token_offset];
+ MAKE_VECTOR_TYPE(char, U4_ELEMS_PER_BYTE) buff = unpack_to_char(*(uint4x2_t *)&packed_val);
+ v_vals_packed[i] = (nibble_sel == 0) ? buff.s0 : buff.s1;
}
#else // !(IS_KV_COMPRESSED && IS_INT4_COMPRESSED)
@@ -717,13 +727,11 @@ KERNEL(pa_sdpa_opt)(
#if IS_KV_COMPRESSED && IS_INT4_COMPRESSED
const uint packed_block_offset = block_indices[last_block_idx] * KV_HEADS_NUM * phys_adjusted_v_head_size * PAGED_ATTENTION_BLOCK_SIZE
+ head_idx * phys_adjusted_v_head_size * PAGED_ATTENTION_BLOCK_SIZE;
- const uint head_size_offset = ((head_size_idx / SUBGROUP_SIZE) / U4_ELEMS_PER_BYTE) * SUBGROUP_SIZE + (head_size_idx % SUBGROUP_SIZE);
- const uint packed_value_offset = packed_block_offset + head_size_offset;
- const uint value_comp_offset = packed_block_offset + phys_v_head_size * PAGED_ATTENTION_BLOCK_SIZE;
- INPUT0_TYPE* value_comp_ptr = value_cache + value_comp_offset;
- INPUT0_TYPE comp_scale = value_comp_ptr[0 + sglid];
- INPUT0_TYPE comp_zp = value_comp_ptr[PAGED_ATTENTION_BLOCK_SIZE + sglid];
+ // INT4: per-token embedded scales
+ INPUT0_TYPE* my_token_comp_ptr = (INPUT0_TYPE*)(value_cache + packed_block_offset + sglid * phys_adjusted_v_head_size + phys_v_head_size);
+ INPUT0_TYPE comp_scale = my_token_comp_ptr[0];
+ INPUT0_TYPE comp_zp = my_token_comp_ptr[1];
#elif IS_KV_COMPRESSED && !IS_INT4_COMPRESSED
const uint value_comp_offset = block_offset + V_HEAD_SIZE * PAGED_ATTENTION_BLOCK_SIZE;
INPUT0_TYPE* value_comp_ptr = value_cache + value_comp_offset;
@@ -731,26 +739,19 @@ KERNEL(pa_sdpa_opt)(
INPUT0_TYPE comp_zp = value_comp_ptr[PAGED_ATTENTION_BLOCK_SIZE + sglid];
#endif
-#if IS_KV_COMPRESSED && IS_INT4_COMPRESSED
- const uint idx_packed = (head_size_idx / SUBGROUP_SIZE) % U4_ELEMS_PER_BYTE;
-#endif
-
MAKE_VECTOR_TYPE(OUTPUT_TYPE, QUERIES_PER_WI) qk_val;
unroll_for (uint q_idx = 0; q_idx < QUERIES_PER_WI; q_idx++) {
GET_VECTOR_ELEMENT(qk_val, q_idx) = slm_qk_vals[q_idx * SEQ_LEN_PARTITION_SIZE + blocks_num_per_partition * PAGED_ATTENTION_BLOCK_SIZE + sglid];
}
for (uint i = 0; i < leftovers; i++) {
#if IS_KV_COMPRESSED && IS_INT4_COMPRESSED
- INPUT2_TYPE value_packed = 0;
- uint index = packed_value_offset + i * phys_v_head_size;
- char packed_value = BLOCK_READN(INPUT2_TYPE, 1, value_cache, index);
+ // INT4 adjacent packing: scalar read of packed byte + nibble selection
+ const uint packed_byte_idx = head_size_idx / 2;
+ const uint nibble_sel = head_size_idx & 1;
+ uint token_offset = packed_block_offset + i * phys_adjusted_v_head_size + packed_byte_idx;
+ char packed_value = value_cache[token_offset];
MAKE_VECTOR_TYPE(char, U4_ELEMS_PER_BYTE) buff = unpack_to_char(*(uint4x2_t *)&packed_value);
-
- if (idx_packed == 0) {
- value_packed = buff.s0;
- } else {
- value_packed = buff.s1;
- }
+ INPUT2_TYPE value_packed = (nibble_sel == 0) ? buff.s0 : buff.s1;
#else // !(IS_KV_COMPRESSED && IS_INT4_COMPRESSED)
INPUT2_TYPE value_packed = BLOCK_READN(INPUT2_TYPE, 1, value_cache, value_offset + i * V_HEAD_SIZE);
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 edeb58396c8..3b1a146d0dc 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
@@ -51,7 +51,7 @@ static size_t get_pa_sg_number_scale_factor(const device_info& info, size_t head
if (is_kv_compressed) {
const size_t optimal_scale_factor = 2;
if (kernel_type == SDPAStage::SINGLE_TOKEN || kernel_type == SDPAStage::MULTI_TOKENS) {
- if (head_size * optimal_scale_factor <= info.max_work_group_size) {
+ if (head_size * optimal_scale_factor < info.max_work_group_size) {
return optimal_scale_factor;
}
}
@@ -242,21 +242,27 @@ JitConstants make_uint4_kv_cache_jit_constants(const kernel_impl_params& params)
ov::intel_gpu::JitConstants jit;
const auto desc = params.typed_desc<paged_attention>();
const auto kv_cache_dt = params.get_program().get_config().get_kv_cache_precision();
- const auto is_key_by_channel = desc->is_key_by_channel;
auto& kv_dt = params.input_layouts[PagedAttentionInputIdx::KEY].data_type;
if (data_type_traits::is_i4_u4(kv_cache_dt)) {
- // INT4 compression is packing elements along groups in head which has different scalea and zp
- const auto scales_zp_size = get_element_size(kv_dt) * 4;
+ const auto scales_zp_size = get_element_size(kv_dt) * 2; // fp16 scale + fp16 zp = 4 bytes
+ const auto is_key_by_channel = desc->is_key_by_channel;
jit.make("IS_INT4_COMPRESSED", true);
- jit.make("PACKED_K_HEAD_SIZE", kernel_selector::Align(desc->k_head_size / u4_elems_per_byte, subgroup_size));
- jit.make("PACKED_ADJUSTED_V_HEAD_SIZE", (kernel_selector::Align(desc->v_head_size / u4_elems_per_byte, subgroup_size)) + scales_zp_size);
- jit.make("PACKED_V_HEAD_SIZE", (kernel_selector::Align(desc->v_head_size / u4_elems_per_byte, subgroup_size)));
if (is_key_by_channel) {
- jit.make("PACKED_ADJUSTED_K_HEAD_SIZE", (kernel_selector::Align(desc->k_head_size / u4_elems_per_byte, subgroup_size)));
+ // K BY_CHANNEL: head_size is NOT packed (outer dim), block_size IS packed (inner dim)
+ jit.make("PACKED_K_HEAD_SIZE", desc->k_head_size);
+ jit.make("PACKED_ADJUSTED_K_HEAD_SIZE", desc->k_head_size);
+ jit.make("PACKED_K_BLOCK_SIZE", paged_attention_block_size / u4_elems_per_byte);
} else {
- jit.make("PACKED_ADJUSTED_K_HEAD_SIZE", (kernel_selector::Align(desc->k_head_size / u4_elems_per_byte, subgroup_size)) + scales_zp_size);
+ // K BY_TOKEN: head_size IS packed (inner dim), block_size is NOT packed
+ const auto packed_k_head_size = kernel_selector::Align(desc->k_head_size / u4_elems_per_byte, subgroup_size);
+ jit.make("PACKED_K_HEAD_SIZE", packed_k_head_size);
+ jit.make("PACKED_ADJUSTED_K_HEAD_SIZE", packed_k_head_size + scales_zp_size);
+ jit.make("PACKED_K_BLOCK_SIZE", paged_attention_block_size);
}
+ // V per-token: head_size IS packed (inner dim)
+ jit.make("PACKED_V_HEAD_SIZE", (kernel_selector::Align(desc->v_head_size / u4_elems_per_byte, subgroup_size)));
+ jit.make("PACKED_ADJUSTED_V_HEAD_SIZE", (kernel_selector::Align(desc->v_head_size / u4_elems_per_byte, subgroup_size)) + scales_zp_size);
} else {
jit.make("IS_INT4_COMPRESSED", false);
}
@@ -292,21 +298,32 @@ public:
if (is_kv_compressed) {
auto& kv_dt = params.input_layouts[PagedAttentionInputIdx::KEY].data_type;
auto scales_zp_size = get_element_size(kv_dt) * 2; // scale + zp
- if (data_type_traits::is_i4_u4(kv_cache_dt))
- scales_zp_size = get_element_size(kv_dt) * 4;
jit.make("SCALE_ZP_SIZE_PER_TOKEN", scales_zp_size);
jit.add(make_uint4_kv_cache_jit_constants(params));
- if (is_key_by_channel) {
+ if (data_type_traits::is_i4_u4(kv_cache_dt)) {
+ if (is_key_by_channel) {
+ // INT4 BY_CHANNEL: K dim order {0,1,3,2}, block_size packed in innermost dim
+ jit.make("IS_KEY_BY_CHANNEL", 1);
+ jit.make("ADJUSTED_K_HEAD_SIZE", desc->k_head_size);
+ jit.make("ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE", paged_attention_block_size / u4_elems_per_byte + scales_zp_size);
+ } else {
+ // INT4 BY_TOKEN: K dim order {0,1,2,3}, head_size packed
+ jit.make("ADJUSTED_K_HEAD_SIZE", desc->k_head_size + scales_zp_size);
+ jit.make("ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE", paged_attention_block_size);
+ }
+ jit.make("ADJUSTED_V_HEAD_SIZE", desc->v_head_size + scales_zp_size);
+ } else if (is_key_by_channel) {
jit.make("IS_KEY_BY_CHANNEL", 1);
jit.make("ADJUSTED_K_HEAD_SIZE", desc->k_head_size);
jit.make("ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE", paged_attention_block_size + scales_zp_size);
+ jit.make("ADJUSTED_V_HEAD_SIZE", desc->v_head_size + scales_zp_size);
} else {
jit.make("ADJUSTED_K_HEAD_SIZE", desc->k_head_size + scales_zp_size);
jit.make("ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE", paged_attention_block_size);
+ jit.make("ADJUSTED_V_HEAD_SIZE", desc->v_head_size + scales_zp_size);
}
- jit.make("ADJUSTED_V_HEAD_SIZE", desc->v_head_size + scales_zp_size);
} else {
jit.make("ADJUSTED_K_HEAD_SIZE", desc->k_head_size);
jit.make("ADJUSTED_V_HEAD_SIZE", desc->v_head_size);
@@ -949,13 +966,24 @@ protected:
if (is_kv_compressed) {
auto data_type = params.input_layouts[PagedAttentionInputIdx::KEY].data_type; // key tensor data size
auto scales_zp_size = get_element_size(data_type) * 2; // scale + zp
- if (data_type_traits::is_i4_u4(kv_cache_dt))
- scales_zp_size = get_element_size(data_type) * 4;
jit.make("SCALE_ZP_SIZE_PER_TOKEN", scales_zp_size);
jit.add(make_uint4_kv_cache_jit_constants(params));
- if (is_key_by_channel) {
+ if (data_type_traits::is_i4_u4(kv_cache_dt)) {
+ if (is_key_by_channel) {
+ // INT4 BY_CHANNEL: K dim order {0,1,3,2}, block_size packed in innermost dim
+ jit.make("IS_KEY_BY_CHANNEL", 1);
+ jit.make("ADJUSTED_K_HEAD_SIZE", desc->k_head_size);
+ jit.make("ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE", paged_attention_block_size / u4_elems_per_byte + scales_zp_size);
+ } else {
+ // INT4 BY_TOKEN: K dim order {0,1,2,3}, head_size packed
+ jit.make("ADJUSTED_K_HEAD_SIZE", desc->k_head_size + scales_zp_size);
+ jit.make("ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE", paged_attention_block_size);
+ }
+ jit.make("NUM_K_HEAD_SIZE_PARTITIONS", get_num_k_head_size_partitions(desc->is_key_by_channel, desc->k_head_size));
+ jit.make("ADJUSTED_V_HEAD_SIZE", desc->v_head_size + scales_zp_size);
+ } else if (is_key_by_channel) {
jit.make("IS_KEY_BY_CHANNEL", 1);
jit.make("ADJUSTED_K_HEAD_SIZE", desc->k_head_size);
jit.make("ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE", paged_attention_block_size + scales_zp_size);
@@ -1023,13 +1051,7 @@ protected:
const auto& key_input = params.input_layouts[0];
const auto sequences_number = key_input.get_partial_shape()[0].get_length();
size_t head_size_partition = get_num_k_head_size_partitions(desc->is_key_by_channel, desc->k_head_size);
- const auto kv_cache_dt = params.get_program().get_config().get_kv_cache_precision();
- if (data_type_traits::is_i4_u4(kv_cache_dt) && head_size_partition > 1)
- wgs.global = {static_cast<size_t>(sequences_number),
- heads_number,
- kernel_selector::Align(subgroup_size * head_size_partition / u4_elems_per_byte, subgroup_size)};
- else
- wgs.global = {static_cast<size_t>(sequences_number), heads_number, subgroup_size * head_size_partition};
+ wgs.global = {static_cast<size_t>(sequences_number), heads_number, subgroup_size * head_size_partition};
wgs.local = {1, 1, subgroup_size};
}
@@ -1077,12 +1099,16 @@ protected:
jit.add(make_uint4_kv_cache_jit_constants(params));
auto scales_zp_size = get_element_size(original_cache_dt) * 2; // scale + zp;
const auto kv_cache_dt = params.get_program().get_config().get_kv_cache_precision();
- if (data_type_traits::is_i4_u4(kv_cache_dt)) {
- scales_zp_size = get_element_size(original_cache_dt) * 4;
- }
jit.make("SCALE_ZP_SIZE_PER_TOKEN", scales_zp_size);
- if (is_key_by_channel) {
+ if (data_type_traits::is_i4_u4(kv_cache_dt)) {
+ // INT4 BY_CHANNEL: dim order {0,1,2,3}, scales embedded per-token in head dim
+ jit.make("IS_KEY_BY_CHANNEL", 1);
+ jit.make("ADJUSTED_HEAD_SIZE", desc->k_head_size);
+ jit.make("ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE", paged_attention_block_size);
+ jit.make("NUM_K_HEAD_SIZE_PARTITIONS", get_num_k_head_size_partitions(desc->is_key_by_channel, desc->k_head_size));
+ jit.make("ADJUSTED_V_HEAD_SIZE", desc->v_head_size + scales_zp_size);
+ } else if (is_key_by_channel) {
jit.make("ADJUSTED_HEAD_SIZE", desc->k_head_size);
jit.make("ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE", paged_attention_block_size + scales_zp_size);
} else {
@@ -1359,15 +1385,9 @@ public:
return false;
}
- // micro_sdpa does not support 4-bit (u4/i4) KV-cache quantization.
- // In MIXED stage, the prefill and generate iterations share the same kernel path;
- // because the generate iteration must read the already-quantized KV-cache that was
- // written during prefill, every kernel in this stage must be able to dequantize 4-bit
- // entries. micro_sdpa currently lacks this dequantization logic, so we fall back to
- // the standard paged-attention kernel (pa_multi_tokens / pa_single_token) which does
- // support INT4 KV-cache.
- if (data_type_traits::is_i4_u4(params.get_program().get_config().get_kv_cache_precision()) &&
- get_paged_attention_stage(params) == PagedAttentionStage::MIXED) {
+ // Disable micro SDPA for INT4 BY_TOKEN due to accuracy issues
+ const auto kv_cache_dt = params.get_program().get_config().get_kv_cache_precision();
+ if (data_type_traits::is_i4_u4(kv_cache_dt) && !desc->is_key_by_channel) {
return false;
}
@@ -1611,11 +1631,6 @@ public:
can_use_micro_sdpa = has_stage(pa_sdpa_micro) && valid_micro_stage(stage);
if (stage == PagedAttentionStage::GENERATE && (rt_params == nullptr || (rt_params != nullptr && rt_params->use_gqa_kernel == false)))
can_use_micro_sdpa = false;
-
- if (data_type_traits::is_i4_u4(params.get_program().get_config().get_kv_cache_precision()) &&
- get_paged_attention_stage(params) == PagedAttentionStage::MIXED) {
- can_use_micro_sdpa = false;
- }
#endif
GPU_DEBUG_TRACE_DETAIL << "get_internal_buffer_descs: stage = " << static_cast<size_t>(stage) << std::endl;
int64_t paged_attention_aligned_seq_len = -1;
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_base.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_base.cpp
index 814f76db252..07416445805 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_base.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_base.cpp
@@ -74,6 +74,14 @@ size_t get_beam_table_id(const std::shared_ptr<const scaled_dot_product_attentio
} // namespace
+// 4-bit KV-cache packs two u4 values into one i8 byte, halving the physical
+// innermost dimension (head_size) of K/V layouts. Any code that reads head_size
+// from K/V layouts must use the logical (un-halved) size from the query layout.
+bool SDPABase::is_int4_kv_cache(const kernel_impl_params& params) {
+ const auto kv_cache_dt = params.get_program().get_config().get_kv_cache_precision();
+ return ov::element::Type(kv_cache_dt).bitwidth() == 4;
+}
+
std::pair<int64_t, int64_t> SDPABase::get_gqa_params(const kernel_impl_params& params) const {
if (params.is_type<scaled_dot_product_attention>()) {
auto desc = params.typed_desc<scaled_dot_product_attention>();
@@ -157,6 +165,14 @@ sdpa_configuration SDPABase::get_sdpa_configuration(const kernel_impl_params& im
if (value_shape[value_shape.size() - 1].is_static())
config.v_head_size = value_shape[value_shape.size() - 1].get_length();
+ // 4-bit KV-cache: physical V layout has head_size/2 due to u4 packing.
+ // Use logical head size from query to get the correct un-halved value.
+ if (desc->is_kv_compressed && SDPABase::is_int4_kv_cache(impl_param)) {
+ if (query_shape[query_shape.size() - 1].is_static()) {
+ config.v_head_size = query_shape[query_shape.size() - 1].get_length();
+ }
+ }
+
config.is_causal = desc->is_causal;
if (desc->scale_val.has_value()) {
@@ -212,6 +228,7 @@ JitConstants SDPABase::get_jit_constants(const kernel_impl_params& params) const
jit.make("HAS_SINK_INPUT", 1);
}
jit.make("IS_KV_COMPRESSED", desc->is_kv_compressed);
+ jit.make("IS_INT4_COMPRESSED", desc->is_kv_compressed && SDPABase::is_int4_kv_cache(params));
GPU_DEBUG_TRACE_DETAIL << "desc->is_kv_compressed = " << desc->is_kv_compressed << std::endl;
const auto& in_offsets_map = params.in_port_to_shape_info_offset;
@@ -295,9 +312,19 @@ JitConstants SDPABase::get_jit_constants(const kernel_impl_params& params) const
const auto q_head_size = get_head_size(params.get_input_layout(0), extended_input_q_transpose_order);
const auto q_num_head = get_num_heads(params.get_input_layout(0), extended_input_q_transpose_order);
- const auto k_head_size = get_head_size(params.get_input_layout(1), extended_input_k_transpose_order);
+ auto k_head_size = get_head_size(params.get_input_layout(1), extended_input_k_transpose_order);
const auto k_num_head = get_num_heads(params.get_input_layout(1), extended_input_k_transpose_order);
- const auto v_head_size = get_head_size(params.get_input_layout(2), extended_input_v_transpose_order);
+ auto v_head_size = get_head_size(params.get_input_layout(2), extended_input_v_transpose_order);
+
+ // 4-bit KV-cache: K/V layouts have head_size/2 due to u4→i8 packing.
+ // Override with logical head size from query (which is not packed).
+ {
+ if (desc->is_kv_compressed && SDPABase::is_int4_kv_cache(params)) {
+ k_head_size = q_head_size;
+ v_head_size = q_head_size;
+ }
+ }
+
jit.make("HEAD_SIZE", q_head_size);
jit.make("NUM_HEADS", q_num_head);
jit.make("K_HEAD_SIZE", k_head_size);
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_base.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_base.hpp
index 6334d4dbb06..78e445906b6 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_base.hpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_base.hpp
@@ -64,6 +64,7 @@ struct SDPABase : public KernelGenerator {
const std::vector<int64_t>& input_k_transpose_order,
const std::vector<int64_t>& input_v_transpose_order);
+ static bool is_int4_kv_cache(const kernel_impl_params& params);
static bool requires_shape_canonicalization(const kernel_impl_params& impl_params);
static kernel_impl_params static_canonicalize_shapes(const kernel_impl_params& impl_params);
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_micro.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_micro.cpp
index 7f8ae476e56..cc54ba9ccf0 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_micro.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_micro.cpp
@@ -55,6 +55,10 @@ micro::Type convert_type(ov::element::Type t) {
return micro::Type::u8;
case ov::element::i32:
return micro::Type::s32;
+ case ov::element::u4:
+ return micro::Type::u4;
+ case ov::element::i4:
+ return micro::Type::s4;
default:
break;
}
@@ -1149,16 +1153,32 @@ JitConstants SDPAMicroGenerator::get_jit_constants(const kernel_impl_params& par
auto pa_desc = params.typed_desc<paged_attention>();
jit.make("IS_KV_COMPRESSED_PA", true);
+ const auto kv_precision = params.get_program().get_config().get_kv_cache_precision();
+ const bool is_int4_logical = data_type_traits::is_i4_u4(kv_precision);
+
auto scales_zp_size = 4; // scale + zp
- if (pa_desc->is_key_by_channel) {
+ if (is_int4_logical) {
+ // INT4 KV cache with BY_CHANNEL K quantization:
+ // K: dim order {0,1,3,2} (col-major), packed block_size in innermost dim
+ // physical: [blocks, heads, head_size, packed_block + scales] u8
+ // packed_block = block_size/2 bytes, scales = 4 bytes
+ // V: dim order {0,1,2,3} (row-major), packed head_size in innermost dim
+ // physical: [blocks, heads, block_size, packed_head + scales] u8
+ jit.make("IS_INT4_KV_CACHE", 1);
+ jit.make("IS_KEY_BY_CHANNEL", 1);
+ jit.make("ADJUSTED_K_HEAD_SIZE", k_head_size);
+ jit.make("ADJUSTED_V_HEAD_SIZE", v_head_size / 2 + scales_zp_size);
+ jit.make("ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE", config.paged_attention_block_size / 2 + scales_zp_size);
+ } else if (pa_desc->is_key_by_channel) {
jit.make("IS_KEY_BY_CHANNEL", 1);
jit.make("ADJUSTED_K_HEAD_SIZE", k_head_size);
jit.make("ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE", config.paged_attention_block_size + scales_zp_size);
+ jit.make("ADJUSTED_V_HEAD_SIZE", v_head_size + scales_zp_size);
} else {
jit.make("ADJUSTED_K_HEAD_SIZE", k_head_size + scales_zp_size);
jit.make("ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE", config.paged_attention_block_size);
+ jit.make("ADJUSTED_V_HEAD_SIZE", v_head_size + scales_zp_size);
}
- jit.make("ADJUSTED_V_HEAD_SIZE", v_head_size + scales_zp_size);
} else if (config.is_paged_attention) {
jit.make("ADJUSTED_K_HEAD_SIZE", k_head_size);
jit.make("ADJUSTED_V_HEAD_SIZE", v_head_size);
@@ -1536,11 +1556,21 @@ void SDPAMicroGenerator::init_microkernels(const kernel_impl_params& params,
problem.Ta_ext = convert_type(K.data_type);
problem.Tb_ext = convert_type(Q.data_type);
+ // Detect INT4 KV cache: stored as u8 but logical precision is u4/i4
+ const auto kv_cache_precision = is_paged_attention ? params.get_program().get_config().get_kv_cache_precision() : ov::element::dynamic;
+ const bool is_int4_kv_cache = data_type_traits::is_i4_u4(kv_cache_precision);
+
+ // For INT4 PA generate: override Ta_ext to u4/i4 so micro-kernel handles u4 unpacking
+ if (is_int4_kv_cache && is_paged_attention && !is_prefill) {
+ problem.Ta_ext = convert_type(kv_cache_precision);
+ }
+
problem.Ta = problem.Tb = micro::Type::f16;
problem.Tc = problem.Tc_ext = micro::Type::f32;
problem.Ts = problem.Tc;
auto problem_kq = problem;
+ // Both INT4 and INT8 K cache use dim order {0,1,3,2} (column-major / Layout::N).
problem_kq.A.layout = (is_paged_attention && !is_prefill) ? micro::MatrixLayout::N : micro::MatrixLayout::T;
/* Set up microkernel options */
@@ -1551,7 +1581,9 @@ void SDPAMicroGenerator::init_microkernels(const kernel_impl_params& params,
const bool use_asymmetric_quantization = configuration.use_asymmetric_quantization;
if (is_paged_attention && !is_prefill && is_quantized) {
- problem.Ta = micro::Type::s8;
+ if (!is_int4_kv_cache) {
+ problem.Ta = micro::Type::s8;
+ }
const auto scale_dt = convert_type(ov::element::f16);
problem_kq.Ta_scale = scale_dt;
@@ -1567,7 +1599,13 @@ void SDPAMicroGenerator::init_microkernels(const kernel_impl_params& params,
problem_kq.aOffset = micro::ABOffset::Calc;
auto pa_desc = params.typed_desc<paged_attention>();
- if (pa_desc->is_key_by_channel) {
+ if (is_int4_kv_cache) {
+ // INT4 BY_CHANNEL: per-channel quantization (one scale/zp per head dim for all tokens in block)
+ // Same quantization grouping as INT8 BY_CHANNEL.
+ problem_kq.aqGroupM = config->unroll_m_kq * config->wg_m_kq;
+ problem_kq.aqGroupK = 1;
+ // BY_CHANNEL scales: Layout::N (stride-1 between rows, ldkq stride between columns)
+ } else if (pa_desc->is_key_by_channel) {
problem_kq.aqGroupM = config->unroll_m_kq * config->wg_m_kq;
problem_kq.aqGroupK = 1;
} else {
@@ -1614,9 +1652,15 @@ void SDPAMicroGenerator::init_microkernels(const kernel_impl_params& params,
if (is_paged_attention && !is_prefill) {
auto pa_desc = params.typed_desc<paged_attention>();
const auto paged_attention_block_size = static_cast<int>(paged_attention::block_size);
- problem_kq.A.setAlignment(paged_attention_block_size * problem.Ta);
- if (is_quantized && pa_desc->is_key_by_channel) {
- problem_kq.A.setAlignment(paged_attention_block_size * problem.Ta + 4); // scale - 2 bytes, zp - 2 bytes
+ if (is_int4_kv_cache) {
+ // INT4 BY_CHANNEL Layout::N: lda = packed_block_bytes + scales
+ // = block_size * u4 + 4 = 16 * 0.5 + 4 = 12 bytes
+ problem_kq.A.setAlignment(paged_attention_block_size * problem.Ta_ext + 4);
+ } else {
+ problem_kq.A.setAlignment(paged_attention_block_size * problem.Ta);
+ if (is_quantized && pa_desc->is_key_by_channel) {
+ problem_kq.A.setAlignment(paged_attention_block_size * problem.Ta + 4); // scale - 2 bytes, zp - 2 bytes
+ }
}
}
problem_kq.B.setAlignment(64); // Q is packed in VNNI format in SLM
@@ -1685,6 +1729,10 @@ void SDPAMicroGenerator::init_microkernels(const kernel_impl_params& params,
/* Update for second GEMM: V*S */
auto problem_vs = problem;
problem_vs.Ta_ext = convert_type(V.data_type);
+ // For INT4 V: override Ta_ext to u4/i4
+ if (is_int4_kv_cache && is_paged_attention && !is_prefill) {
+ problem_vs.Ta_ext = convert_type(kv_cache_precision);
+ }
problem_vs.A.layout = micro::MatrixLayout::N;
if (is_paged_attention && !is_prefill && is_quantized) {
@@ -1704,6 +1752,13 @@ void SDPAMicroGenerator::init_microkernels(const kernel_impl_params& params,
problem_vs.aqGroupM = static_cast<int>(v_head_size);
problem_vs.aqGroupK = 1;
+ // NOTE: V*S scale Layout stays ::N (the default set above), which is correct.
+ // V*S A = V[m=head_dim, k=tokens], so per-token scales form a [1, tokens] matrix.
+ // With Layout::N: scale(0, token) = base + token * ldvq = 68-byte stride. Correct.
+ // (Layout::T would give stride-1 = 2-byte intervals, which is wrong.)
+ // This differs from K*Q where A = K[m=tokens, k=head_dim], scale is [tokens, 1],
+ // and Layout::T is needed to get the token stride via ldkq.
+
opts_vs.scaleA = true;
opts_vs.offsetA = true;
} else {
@@ -1739,7 +1794,14 @@ void SDPAMicroGenerator::init_microkernels(const kernel_impl_params& params,
problem_vs.B.layout = micro::MatrixLayout::Pr;
problem_vs.C.layout = micro::MatrixLayout::N;
- problem_vs.A.setAlignment(micro::alignment_for_ld(static_cast<int>(v_head_size * problem.Ta)));
+
+ if (is_int4_kv_cache && is_paged_attention && !is_prefill) {
+ // INT4 V: ldv = packed_head_bytes + scales = v_head_size * u4 + 4 = 68
+ problem_vs.A.setAlignment(static_cast<int>(v_head_size * problem_vs.Ta_ext) + 4);
+ } else {
+ problem_vs.A.setAlignment(micro::alignment_for_ld(static_cast<int>(v_head_size * problem.Ta)));
+ }
+
problem_vs.B.setAlignment(64); // S is packed in SLM
problem_vs.B.crosspack = 16;
sizes.m = n_values.is_dynamic() ? -1 : n_values.get_length();
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_opt.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_opt.cpp
index cd1ce1a145e..826ffbd0d28 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_opt.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_opt.cpp
@@ -63,6 +63,18 @@ JitConstants SDPAOptGeneratorBase::get_jit_constants_base(const kernel_impl_para
auto extended_input_v_transpose_order = extend_order_in_num_heads_dim(desc->input_v_transpose_order);
k_head_size = get_head_size(k_layout, extended_input_k_transpose_order);
v_head_size = get_head_size(v_layout, extended_input_v_transpose_order);
+
+ // 4-bit KV-cache: K/V layouts have head_size/2 due to u4→i8 packing.
+ // Override with logical head size from query (which is not packed).
+ {
+ if (desc->is_kv_compressed && SDPABase::is_int4_kv_cache(params)) {
+ auto extended_input_q_transpose_order = extend_order_in_num_heads_dim(desc->input_q_transpose_order);
+ auto q_head_size = get_head_size(params.get_input_layout(0), extended_input_q_transpose_order);
+ k_head_size = q_head_size;
+ v_head_size = q_head_size;
+ }
+ }
+
GPU_DEBUG_TRACE_DETAIL << "k_head_size = " << k_head_size << ", v_head_size = " << v_head_size << "\n";
size_t data_inputs_num = get_data_inputs_num(*desc);
@@ -188,7 +200,14 @@ DispatchDataFunc SDPAOptGeneratorSingleToken::get_dispatch_data_func() const {
const size_t target_seq_len = get_seq_length(params.get_input_layout(0), extended_input_q_transpose_order);
const size_t heads_num = get_num_heads(params.get_output_layout(0), extended_output_transpose_order);
const size_t num_of_partitions = get_partitions_num(params, SDPAStage::SINGLE_TOKEN);
- const auto head_size = get_head_size(params.get_input_layout(2), extended_input_v_transpose_order);
+ auto head_size = get_head_size(params.get_input_layout(2), extended_input_v_transpose_order);
+
+ // 4-bit KV-cache: V layout has head_size/2 due to u4→i8 packing.
+ // Use logical head size from query for work-group dispatch.
+ if (desc->is_kv_compressed && SDPABase::is_int4_kv_cache(params)) {
+ head_size = get_head_size(params.get_input_layout(0), extended_input_q_transpose_order);
+ }
+
const size_t sg_num_scale = get_sg_number_scale_factor(params.get_device_info(), head_size, SDPAStage::SINGLE_TOKEN);
GPU_DEBUG_TRACE_DETAIL << "batch_size = " << batch_size << ", target_seq_len = " << target_seq_len << ", heads_num = " << heads_num << "\n";
GPU_DEBUG_TRACE_DETAIL << "head_size = " << head_size << ", num_of_partitions = " << num_of_partitions << "\n";
@@ -227,7 +246,14 @@ DispatchDataFunc SDPAOptGeneratorMultiToken::get_dispatch_data_func() const {
const size_t target_seq_len = get_seq_length(params.get_input_layout(0), extended_input_q_transpose_order);
const size_t heads_num = get_num_heads(params.get_output_layout(0), extended_output_transpose_order);
const size_t target_seq_len_block_size = get_target_seq_len_block_size();
- const size_t head_size = get_head_size(params.get_input_layout(2), extended_input_v_transpose_order);
+ auto head_size = get_head_size(params.get_input_layout(2), extended_input_v_transpose_order);
+
+ // 4-bit KV-cache: V layout has head_size/2 due to u4→i8 packing.
+ // Use logical head size from query for work-group dispatch.
+ if (desc->is_kv_compressed && SDPABase::is_int4_kv_cache(params)) {
+ head_size = get_head_size(params.get_input_layout(0), extended_input_q_transpose_order);
+ }
+
const size_t sg_num_scale = get_sg_number_scale_factor(params.get_device_info(), head_size, SDPAStage::MULTI_TOKENS);
GPU_DEBUG_TRACE_DETAIL << "batch_size = " << batch_size << ", target_seq_len = " << target_seq_len << ", heads_num = " << heads_num << "\n";
@@ -270,13 +296,19 @@ DispatchDataFunc SDPAOptGeneratorFinalization::get_dispatch_data_func() const {
const size_t target_seq_len = get_seq_length(params.get_input_layout(0), extended_input_q_transpose_order);
const size_t heads_num = get_num_heads(params.get_output_layout(0), extended_output_transpose_order);
const size_t num_of_partitions = get_partitions_num(params, SDPAStage::FINALIZATION);
- const size_t head_size = get_head_size(params.get_input_layout(2), extended_input_v_transpose_order);
+ auto head_size = get_head_size(params.get_input_layout(2), extended_input_v_transpose_order);
+
+ // 4-bit KV-cache: V layout has head_size/2 due to u4→i8 packing.
+ // Use logical head size from query for finalization dispatch.
+ if (desc->is_kv_compressed && SDPABase::is_int4_kv_cache(params)) {
+ head_size = get_head_size(params.get_input_layout(0), extended_input_q_transpose_order);
+ }
GPU_DEBUG_TRACE_DETAIL << "batch_size = " << batch_size << ", target_seq_len = " << target_seq_len << ", heads_num = " << heads_num << "\n";
GPU_DEBUG_TRACE_DETAIL << "head_size = " << head_size << ", num_of_partitions = " << num_of_partitions << "\n";
- wgs.global = {batch_size * heads_num, target_seq_len, head_size};
- wgs.local = {1, 1, head_size};
+ wgs.global = {batch_size * heads_num, target_seq_len, static_cast<size_t>(head_size)};
+ wgs.local = {1, 1, static_cast<size_t>(head_size)};
num_of_partitions_scalar.v.u32 = static_cast<uint32_t>(num_of_partitions);
scalars.push_back(num_of_partitions_scalar);
}
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_opt.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_opt.cpp
index a9c28c2a52f..4969912528c 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_opt.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_opt.cpp
@@ -113,9 +113,15 @@ public:
bool is_indirect = need_indirect_load(static_cast<scaled_dot_product_attention_inst&>(instance));
GPU_DEBUG_TRACE_DETAIL << "execute indirect = " << is_indirect << ", prefill = " << is_prefill << "\n";
update_rt_params(instance);
+
kernel_dump_info.clear_entries();
+
+ // Check if INT4 KV cache is in use (micro kernel doesn't support INT4 for non-PA SDPA)
+ const auto kv_cache_dt = new_params.get_program().get_config().get_kv_cache_precision();
+ const bool is_int4_kv = ov::element::Type(kv_cache_dt).bitwidth() == 4;
+
#ifdef ENABLE_ONEDNN_FOR_GPU
- if (has_stage(regular_micro_multi_tokens) && is_prefill && !is_indirect) {
+ if (has_stage(regular_micro_multi_tokens) && is_prefill && !is_indirect && !is_int4_kv) {
GPU_DEBUG_TRACE_DETAIL << "execute regular_micro_multi_tokens for prefill \n";
return execute_stage(events, instance, regular_micro_multi_tokens);
}
@@ -129,7 +135,7 @@ public:
return execute_stage(events, instance, is_indirect ? indirect_multi_tokens : regular_multi_tokens);
}
#ifdef ENABLE_ONEDNN_FOR_GPU
- if (has_stage(regular_micro_single_token) && !is_indirect) {
+ if (has_stage(regular_micro_single_token) && !is_indirect && !is_int4_kv) {
return execute_stage(events, instance, regular_micro_single_token);
}
#endif
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_micro.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_micro.cl
index 8429e49e5e9..b8f8d4f5882 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_micro.cl
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_micro.cl
@@ -231,17 +231,34 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG
uint ldk = HEAD_SIZE * KV_HEADS_NUM + INPUT1_PAD_BEFORE_FEATURE_NUM + INPUT1_PAD_AFTER_FEATURE_NUM;
uint ldv = HEAD_SIZE * KV_HEADS_NUM + INPUT2_PAD_BEFORE_FEATURE_NUM + INPUT2_PAD_AFTER_FEATURE_NUM;
#else
+ #if IS_INT4_KV_CACHE
+ // INT4 K BY_CHANNEL Layout::N: ldk = column stride in u4 elements.
+ // ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE is in bytes (packed_block + scale = 12).
+ // Multiply by 2 for u4: 12 * 2 = 24 u4 elements → 12 byte stride.
+ uint ldk = ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE * 2;
+ // INT4 V per-token Layout::N: ldv = row stride in u4 elements.
+ // ADJUSTED_V_HEAD_SIZE is in bytes (packed_head + scale = 68).
+ // Multiply by 2 for u4: 68 * 2 = 136 u4 elements → 68 byte stride.
+ uint ldv = ADJUSTED_V_HEAD_SIZE * 2;
+ #else
uint ldk = ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE;
uint ldv = HEAD_SIZE;
+ #endif
uint ldkc = HEAD_SIZE * KV_HEADS_NUM + INPUT1_PAD_BEFORE_FEATURE_NUM + INPUT1_PAD_AFTER_FEATURE_NUM;
uint ldvc = HEAD_SIZE * KV_HEADS_NUM + INPUT2_PAD_BEFORE_FEATURE_NUM + INPUT2_PAD_AFTER_FEATURE_NUM;
#if IS_KV_COMPRESSED_PA
- #if IS_KEY_BY_CHANNEL
+ #if IS_INT4_KV_CACHE
+ // INT4 K BY_CHANNEL: scale stride = ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE bytes / 2 in f16 elements
uint ldkq = ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE / 2;
+ // INT4 V per-token: scale stride = ADJUSTED_V_HEAD_SIZE bytes / 2 in f16 elements
+ uint ldvq = ADJUSTED_V_HEAD_SIZE / 2;
+ #elif IS_KEY_BY_CHANNEL
+ uint ldkq = ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE / 2;
+ uint ldvq = 1;
#else
uint ldkq = 1;
+ uint ldvq = 1;
#endif
- uint ldvq = 1;
#endif
#endif
#else
@@ -523,10 +540,22 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG
for (;k0 < past_lens[gws_mapping];) {
#endif
int k_block_num = k0 / PAGED_ATTENTION_BLOCK_SIZE + sg_i_kq;
- global KEY_DATA_T *K0 = K + KV_HEADS_NUM * ADJUSTED_K_HEAD_SIZE * ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE * block_indices[base_block_index + k_block_num]
- - PAGED_ATTENTION_BLOCK_SIZE * sg_i_kq;
+ #if IS_INT4_KV_CACHE
+ // INT4 BY_CHANNEL Layout::N: micro-kernel adds sg_i_kq * tile_sg_m * sizeof(u4)
+ // = sg_i_kq * PAGED_ATTENTION_BLOCK_SIZE / 2 bytes
+ global KEY_DATA_T *K0 = K + KV_HEADS_NUM * ADJUSTED_K_HEAD_SIZE * ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE * block_indices[base_block_index + k_block_num]
+ - (uint)(PAGED_ATTENTION_BLOCK_SIZE / 2) * sg_i_kq;
+ #else
+ global KEY_DATA_T *K0 = K + KV_HEADS_NUM * ADJUSTED_K_HEAD_SIZE * ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE * block_indices[base_block_index + k_block_num]
+ - PAGED_ATTENTION_BLOCK_SIZE * sg_i_kq;
+ #endif
#if IS_KV_COMPRESSED_PA
- #if IS_KEY_BY_CHANNEL
+ #if IS_INT4_KV_CACHE
+ // INT4 BY_CHANNEL: scales at packed_block_size offset within each column
+ // packed_block_size = PAGED_ATTENTION_BLOCK_SIZE / 2 = 8 bytes
+ global KEY_DATA_T *K0_scales = K0 + (PAGED_ATTENTION_BLOCK_SIZE / 2) * (sg_i_kq + 1);
+ global KEY_DATA_T *K0_zp = K0_scales + 2;
+ #elif IS_KEY_BY_CHANNEL
global KEY_DATA_T *K0_scales = K0 + PAGED_ATTENTION_BLOCK_SIZE * (sg_i_kq + 1);
global KEY_DATA_T *K0_zp = K0_scales + 2;
#else
@@ -905,8 +934,14 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG
global VAL_DATA_T *Vb0 = V + KV_HEADS_NUM * ADJUSTED_V_HEAD_SIZE * PAGED_ATTENTION_BLOCK_SIZE * block_indices[base_block_index + v_block_num];
int kb_chunk = min(k - k0 - kb0, PAGED_ATTENTION_BLOCK_SIZE);
#if IS_KV_COMPRESSED_PA
+ #if IS_INT4_KV_CACHE
+ // INT4: scales embedded at HEAD_SIZE/2 offset within each token row
+ global VAL_DATA_T *Vb0_scales = Vb0 + HEAD_SIZE / 2;
+ global VAL_DATA_T *Vb0_zp = Vb0_scales + 2;
+ #else
global VAL_DATA_T *Vb0_scales = Vb0 + HEAD_SIZE * PAGED_ATTENTION_BLOCK_SIZE;
global VAL_DATA_T *Vb0_zp = Vb0_scales + PAGED_ATTENTION_BLOCK_SIZE * 2;
+ #endif
#endif
a_tile_type A_tile1 = ugemm_vs(
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_opt.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_opt.cl
index 496c38a651d..df0735b0dce 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_opt.cl
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_opt.cl
@@ -4,6 +4,7 @@
#include "include/batch_headers/fetch_data.cl"
#include "include/batch_headers/common.cl"
+#include "include/batch_headers/int4_utils.cl"
#include "include/batch_headers/sub_group_block_read.cl"
#include "include/batch_headers/sub_group_block_write.cl"
#include "include/batch_headers/sub_group_shuffle.cl"
@@ -115,7 +116,11 @@ inline uint FUNC(get_bt_index_value)(OPTIONAL_SHAPE_INFO_ARG uint b, uint f, uin
#define OUTPUT_BLOCK_READ(ptr, offset) BLOCK_READN(OUTPUT_TYPE, 1, ptr, offset)
#define OUTPUT_BLOCK_WRITE(ptr, offset, val) BLOCK_WRITEN(OUTPUT_TYPE, 1, ptr, offset, val)
+#if IS_INT4_COMPRESSED
+#define VALUE_BLOCK_READ(ptr, offset) ((ptr)[(offset) + sglid])
+#else
#define VALUE_BLOCK_READ(ptr, offset) BLOCK_READN(INPUT2_TYPE, 1, ptr, offset)
+#endif
#define SUBGROUPS_PER_WG CEIL_DIV(V_HEAD_SIZE * SG_SCALE_FACTOR, SUBGROUP_SIZE)
#if IS_KV_COMPRESSED
@@ -271,6 +276,15 @@ KERNEL(sdpa_opt)(
// Main Gemm1 calculation loop
// Each SG performs element-wise multiplications of Q[HEAD_SIZE]xK[HEAD_SIZE] values
// HEAD_SIZE / SUBGROUPS_PER_WG times in the loop and saves the result to the qk_local SLM buffer
+#if IS_INT4_COMPRESSED && !defined(BEAM_TABLE_TYPE)
+ #ifdef INPUT1_DIMS_ORDER
+ const uint key_base_p0 = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 0, 0);
+ const uint key_packed_pitch_p0 = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 1, 0) - key_base_p0;
+ #else
+ const uint key_base_p0 = INPUT1_GET_INDEX(b0_idx, b1_idx, 0, 0);
+ const uint key_packed_pitch_p0 = INPUT1_SIZE_X;
+ #endif
+#endif
for (uint seq_len = sgid; seq_len < partition_seq_len; seq_len += SUBGROUPS_PER_WG) {
#ifdef BEAM_TABLE_TYPE
const uint b_idx = beam_table[FUNC_CALL(get_bt_index_key)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, start_partition_idx + seq_len, 0)];
@@ -278,7 +292,9 @@ KERNEL(sdpa_opt)(
const uint b_idx = b0_idx;
#endif
-#ifdef INPUT1_DIMS_ORDER
+#if IS_INT4_COMPRESSED && !defined(BEAM_TABLE_TYPE)
+ uint key_offset = key_base_p0 + (start_partition_idx + seq_len) * key_packed_pitch_p0;
+#elif defined(INPUT1_DIMS_ORDER)
uint key_offset = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + seq_len, 0);
#else
uint key_offset = INPUT1_GET_INDEX(b_idx, b1_idx, start_partition_idx + seq_len, 0);
@@ -293,6 +309,58 @@ KERNEL(sdpa_opt)(
KEY_COMPRESSION_SCALE_TYPE comp_zp = GET_ZP(key_zp, key_scale, comp_offset);
#endif
#endif
+
+#if IS_KV_COMPRESSED && IS_INT4_COMPRESSED
+ // INT4 adjacent packing: each byte holds 2 head dims (lo/hi nibble).
+ for (uint head_idx_index = 0; head_idx_index + 2 * SUBGROUP_SIZE <= K_HEAD_SIZE; head_idx_index += 2 * SUBGROUP_SIZE) {
+ #define KEY_BLOCK_READ_1(ptr, offset) ((ptr)[(offset) + sglid])
+ INPUT1_TYPE packed_byte = KEY_BLOCK_READ_1(key_input, key_offset + head_idx_index / 2);
+ char2 unpacked = unpack_to_char(*(uint4x2_t*)&packed_byte);
+
+ KEY_COMPRESSION_SCALE_TYPE key_val0 = (CAT(convert_, KEY_COMPRESSION_SCALE_TYPE)(unpacked.s0) - comp_zp) * comp_scale;
+ KEY_COMPRESSION_SCALE_TYPE key_val1 = (CAT(convert_, KEY_COMPRESSION_SCALE_TYPE)(unpacked.s1) - comp_zp) * comp_scale;
+
+ unroll_for (uint seq_idx = 0; seq_idx < TARGET_SEQ_LEN_BLOCK_SIZE; seq_idx++) {
+ uint query_offset = seq_idx * K_HEAD_SIZE + head_idx_index;
+ INPUT0_TYPE q_val0 = query_local[query_offset + 2 * sglid];
+ INPUT0_TYPE q_val1 = query_local[query_offset + 2 * sglid + 1];
+ acc[seq_idx] = mad(TO_SOFTMAX_ACCUMULATOR_TYPE(q_val0), TO_SOFTMAX_ACCUMULATOR_TYPE(key_val0), acc[seq_idx]);
+ acc[seq_idx] = mad(TO_SOFTMAX_ACCUMULATOR_TYPE(q_val1), TO_SOFTMAX_ACCUMULATOR_TYPE(key_val1), acc[seq_idx]);
+ }
+ #undef KEY_BLOCK_READ_1
+ }
+ // Handle leftover chunk when K_HEAD_SIZE is not a multiple of 2*SUBGROUP_SIZE
+#if (K_HEAD_SIZE % (2 * SUBGROUP_SIZE)) != 0
+ {
+ const uint head_idx_index = (K_HEAD_SIZE / (2 * SUBGROUP_SIZE)) * (2 * SUBGROUP_SIZE);
+ #define KEY_BLOCK_READ_1(ptr, offset) ((ptr)[(offset) + sglid])
+ INPUT1_TYPE packed_byte = (head_idx_index / 2 + sglid < K_HEAD_SIZE / 2)
+ ? KEY_BLOCK_READ_1(key_input, key_offset + head_idx_index / 2) : (INPUT1_TYPE)0;
+ char2 unpacked = unpack_to_char(*(uint4x2_t*)&packed_byte);
+
+ KEY_COMPRESSION_SCALE_TYPE key_val0 = (CAT(convert_, KEY_COMPRESSION_SCALE_TYPE)(unpacked.s0) - comp_zp) * comp_scale;
+ KEY_COMPRESSION_SCALE_TYPE key_val1 = (CAT(convert_, KEY_COMPRESSION_SCALE_TYPE)(unpacked.s1) - comp_zp) * comp_scale;
+ KEY_COMPRESSION_SCALE_TYPE lane_mask = (head_idx_index + 2 * sglid < K_HEAD_SIZE) ? (KEY_COMPRESSION_SCALE_TYPE)1 : (KEY_COMPRESSION_SCALE_TYPE)0;
+ key_val0 *= lane_mask;
+ key_val1 *= lane_mask;
+
+ unroll_for (uint seq_idx = 0; seq_idx < TARGET_SEQ_LEN_BLOCK_SIZE; seq_idx++) {
+ uint query_offset = seq_idx * K_HEAD_SIZE + head_idx_index;
+ INPUT0_TYPE q_val0 = query_local[query_offset + 2 * sglid];
+ INPUT0_TYPE q_val1 = query_local[query_offset + 2 * sglid + 1];
+ acc[seq_idx] = mad(TO_SOFTMAX_ACCUMULATOR_TYPE(q_val0), TO_SOFTMAX_ACCUMULATOR_TYPE(key_val0), acc[seq_idx]);
+ acc[seq_idx] = mad(TO_SOFTMAX_ACCUMULATOR_TYPE(q_val1), TO_SOFTMAX_ACCUMULATOR_TYPE(key_val1), acc[seq_idx]);
+ }
+ #undef KEY_BLOCK_READ_1
+ }
+#endif
+
+ // Sum up all accumulators accross SG and save result to SLM
+ unroll_for (uint seq_idx = 0; seq_idx < TARGET_SEQ_LEN_BLOCK_SIZE; seq_idx++) {
+ acc[seq_idx] = sub_group_reduce_add(acc[seq_idx]);
+ qk_local[seq_idx * SEQ_LEN_PARTITION_SIZE + seq_len] = acc[seq_idx];
+ }
+#else // !(IS_KV_COMPRESSED && IS_INT4_COMPRESSED) — original INT8 path
uint head_idx_index = 0;
#define KEY_BLOCK_SIZE 8
for (; head_idx_index + (KEY_BLOCK_SIZE * SUBGROUP_SIZE) <= K_HEAD_SIZE; head_idx_index += SUBGROUP_SIZE * KEY_BLOCK_SIZE) {
@@ -424,6 +492,7 @@ KERNEL(sdpa_opt)(
acc[seq_idx] = sub_group_reduce_add(acc[seq_idx]);
qk_local[seq_idx * SEQ_LEN_PARTITION_SIZE + seq_len] = acc[seq_idx];
}
+#endif // IS_KV_COMPRESSED && IS_INT4_COMPRESSED
}
{
@@ -641,10 +710,34 @@ KERNEL(sdpa_opt)(
#ifdef INPUT2_DIMS_ORDER
uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 0, 0);
uint value_offset_next_seq = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 1, 0);
+ #if IS_INT4_COMPRESSED
+ const uint value_pitch = value_offset_next_seq - value_offset;
+ #else
const uint value_pitch = value_offset_next_seq - value_offset;
+ #endif
#else
+ #if IS_INT4_COMPRESSED
+ const uint value_pitch = INPUT2_SIZE_X;
+ #else
const uint value_pitch = V_HEAD_SIZE;
+ #endif
+#endif
#endif
+
+#if IS_INT4_COMPRESSED
+ // Adjacent head packing: byte = head_size_idx/2, nibble = head_size_idx%2
+ // val_packed_x: base byte offset for BLOCK_READ (aligned to SUBGROUP_SIZE)
+ const uint val_packed_x = (head_size_idx / (2 * SUBGROUP_SIZE)) * SUBGROUP_SIZE;
+ // Shuffle source: which lane holds the byte containing our head element
+ const uint shuffle_src_p0 = (head_size_idx & (2 * SUBGROUP_SIZE - 1)) >> 1;
+ const uint nibble_sel_p0 = sglid & 1;
+ #ifndef BEAM_TABLE_TYPE
+ #ifdef INPUT2_DIMS_ORDER
+ const uint value_base_p0 = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 0, val_packed_x);
+ #else
+ const uint value_base_p0 = INPUT2_GET_INDEX(b0_idx, b1_idx, 0, val_packed_x);
+ #endif
+ #endif // !BEAM_TABLE_TYPE
#endif
#if SG_SCALE_FACTOR > 1
@@ -657,15 +750,22 @@ KERNEL(sdpa_opt)(
for (uint seq_len = seq_len_start; seq_len < seq_len_end; seq_len++) {
#ifdef BEAM_TABLE_TYPE
+ #if IS_INT4_COMPRESSED
+ const uint b_idx = beam_table[FUNC_CALL(get_bt_index_value)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, start_partition_idx + (seq_len * SUBGROUP_SIZE) + sglid, val_packed_x)];
+ uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + (seq_len * SUBGROUP_SIZE) + sglid, val_packed_x);
+ #else
const uint b_idx = beam_table[FUNC_CALL(get_bt_index_value)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, start_partition_idx + (seq_len * SUBGROUP_SIZE) + sglid, sgid * SUBGROUP_SIZE)];
uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + (seq_len * SUBGROUP_SIZE) + sglid, sgid * SUBGROUP_SIZE);
+ #endif
#else
const uint b_idx = b0_idx;
-#ifdef INPUT2_DIMS_ORDER
- uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + (seq_len * SUBGROUP_SIZE), head_size_idx);
-#else
- uint value_offset = INPUT2_GET_INDEX(b_idx, b1_idx, start_partition_idx + (seq_len * SUBGROUP_SIZE), head_size_idx);
-#endif
+ #if IS_INT4_COMPRESSED
+ uint value_offset = value_base_p0 + (start_partition_idx + (seq_len * SUBGROUP_SIZE)) * value_pitch;
+ #elif defined(INPUT2_DIMS_ORDER)
+ uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + (seq_len * SUBGROUP_SIZE), head_size_idx);
+ #else
+ uint value_offset = INPUT2_GET_INDEX(b_idx, b1_idx, start_partition_idx + (seq_len * SUBGROUP_SIZE), head_size_idx);
+ #endif
#endif
#if IS_KV_COMPRESSED
@@ -683,12 +783,25 @@ KERNEL(sdpa_opt)(
unroll_for (uint i = 0; i < SUBGROUP_SIZE; i++) {
#ifdef BEAM_TABLE_TYPE
+ #if IS_INT4_COMPRESSED
+ const INPUT2_TYPE value_packed = (val_packed_x + sglid < K_HEAD_SIZE / 2)
+ ? VALUE_BLOCK_READ(value_input, sub_group_broadcast(value_offset, i)) : (INPUT2_TYPE)0;
+ #else
const INPUT2_TYPE value_packed = VALUE_BLOCK_READ(value_input, sub_group_broadcast(value_offset, i));
+ #endif
#else
const INPUT2_TYPE value_packed = VALUE_BLOCK_READ(value_input, value_offset);
#endif
-#if IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATION
+#if IS_KV_COMPRESSED && IS_INT4_COMPRESSED
+ // INT4 adjacent packing: shuffle to get correct byte, select nibble by lane parity
+ INPUT2_TYPE needed_byte = intel_sub_group_shuffle(value_packed, shuffle_src_p0);
+ char2 v_unpacked = unpack_to_char(*(uint4x2_t*)&needed_byte);
+ VALUE_COMPRESSION_SCALE_TYPE value_val = (nibble_sel_p0 == 0 ?
+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(v_unpacked.s0) :
+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(v_unpacked.s1));
+ value_val = (value_val - sub_group_broadcast(comp_zp, i)) * sub_group_broadcast(comp_scale, i);
+#elif IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATION
VALUE_COMPRESSION_SCALE_TYPE value_val = (value_packed - sub_group_broadcast(comp_zp, i)) * sub_group_broadcast(comp_scale, i);
#elif IS_KV_COMPRESSED
VALUE_COMPRESSION_SCALE_TYPE value_val = (value_packed * sub_group_broadcast(comp_scale, i));
@@ -717,7 +830,17 @@ KERNEL(sdpa_opt)(
const uint b_idx = b0_idx;
#endif
-#ifdef INPUT2_DIMS_ORDER
+#if IS_INT4_COMPRESSED
+ #ifdef BEAM_TABLE_TYPE
+ #ifdef INPUT2_DIMS_ORDER
+ const uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + seq_len, val_packed_x);
+ #else
+ const uint value_offset = INPUT2_GET_INDEX(b_idx, b1_idx, start_partition_idx + seq_len, val_packed_x);
+ #endif
+ #else
+ const uint value_offset = value_base_p0 + (start_partition_idx + seq_len) * value_pitch;
+ #endif
+#elif defined(INPUT2_DIMS_ORDER)
const uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + seq_len, head_size_idx);
#else
const uint value_offset = INPUT2_GET_INDEX(b_idx, b1_idx, start_partition_idx + seq_len, head_size_idx);
@@ -736,8 +859,21 @@ KERNEL(sdpa_opt)(
qk_val[seq_idx] = qk_local[seq_idx * SEQ_LEN_PARTITION_SIZE + seq_len];
}
+#if IS_INT4_COMPRESSED
+ const INPUT2_TYPE value_packed = (val_packed_x + sglid < K_HEAD_SIZE / 2)
+ ? VALUE_BLOCK_READ(value_input, value_offset) : (INPUT2_TYPE)0;
+#else
const INPUT2_TYPE value_packed = VALUE_BLOCK_READ(value_input, value_offset);
-#if IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATION
+#endif
+#if IS_KV_COMPRESSED && IS_INT4_COMPRESSED
+ // INT4 adjacent packing: shuffle to get correct byte, select nibble by lane parity
+ INPUT2_TYPE needed_byte = intel_sub_group_shuffle(value_packed, shuffle_src_p0);
+ char2 v_rem_unpacked = unpack_to_char(*(uint4x2_t*)&needed_byte);
+ VALUE_COMPRESSION_SCALE_TYPE value_val = (nibble_sel_p0 == 0 ?
+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(v_rem_unpacked.s0) :
+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(v_rem_unpacked.s1));
+ value_val = (value_val - comp_zp) * comp_scale;
+#elif IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATION
const VALUE_COMPRESSION_SCALE_TYPE value_val = (value_packed - comp_zp) * comp_scale;
#elif IS_KV_COMPRESSED
const VALUE_COMPRESSION_SCALE_TYPE value_val = (value_packed * comp_scale);
@@ -1274,6 +1410,16 @@ KERNEL(sdpa_opt)(
// Q*K calculation loop
MAKE_VECTOR_TYPE(OUTPUT_TYPE, TARGET_SEQ_LEN_BLOCK_SIZE) output_acc = OUTPUT_VAL_ZERO;
+#if IS_INT4_COMPRESSED && !defined(BEAM_TABLE_TYPE)
+ #ifdef INPUT1_DIMS_ORDER
+ const uint key_base_s1 = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 0, 0);
+ const uint key_packed_pitch_s1 = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 1, 0) - key_base_s1;
+ #else
+ const uint key_base_s1 = INPUT1_GET_INDEX(b0_idx, b1_idx, 0, 0);
+ const uint key_packed_pitch_s1 = INPUT1_SIZE_X;
+ #endif
+#endif
+
__attribute__((opencl_unroll_hint(1)))
for (uint start_partition_idx = 0; start_partition_idx < SOURCE_SEQ_LEN; start_partition_idx += SEQ_LEN_PARTITION_SIZE) {
const uint seq_len = start_partition_idx + sgid * SUBGROUP_SIZE;
@@ -1294,18 +1440,27 @@ KERNEL(sdpa_opt)(
const uint heads_dim = num_heads_dim;
#endif
#define KEY_SEQ_OFFSET subsequence_begins[gws_seq_indexes_correspondence[target_seq_dim]]
+#if IS_INT4_COMPRESSED && !defined(BEAM_TABLE_TYPE)
+ // INT4 adjacent packing: use physical pitch from tensor layout
+ uint key_offset = key_base_s1 + seq_len * key_packed_pitch_s1;
+ const uint key_pitch = key_packed_pitch_s1;
+#else
const uint key_pitch = (K_HEAD_SIZE * NUM_KV_HEADS + INPUT1_PAD_BEFORE_FEATURE_NUM + INPUT1_PAD_AFTER_FEATURE_NUM);
uint key_offset = INPUT1_OFFSET +
KEY_SEQ_OFFSET * key_pitch +
heads_dim * K_HEAD_SIZE +
seq_len * key_pitch;
+#endif
#else // !IS_PAGED_ATTENTION
#ifdef BEAM_TABLE_TYPE
const uint b_idx = beam_table[FUNC_CALL(get_bt_index_key)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, seq_len + sglid, 0)];
const uint key_offset = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, seq_len + sglid, 0);
#else
const uint b_idx = b0_idx;
- #ifdef INPUT1_DIMS_ORDER
+ #if IS_INT4_COMPRESSED
+ uint key_offset = key_base_s1 + seq_len * key_packed_pitch_s1;
+ const uint key_pitch = key_packed_pitch_s1;
+ #elif defined(INPUT1_DIMS_ORDER)
uint key_offset = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, seq_len, 0);
uint key_offset_next_seq = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, seq_len + 1, 0);
const uint key_pitch = key_offset_next_seq - key_offset;
@@ -1336,6 +1491,71 @@ KERNEL(sdpa_opt)(
KEY_COMPRESSION_SCALE_TYPE comp_zp = GET_ZP(key_zp, key_scale, comp_offset);
#endif
#endif
+#if IS_KV_COMPRESSED && IS_INT4_COMPRESSED
+ {
+ // INT4 adjacent packing: scalar read gives 16 head-dim bytes per lane.
+ // Lane i holds key at head dims (hi + 2*i) and (hi + 2*i + 1).
+ // Load query values matching adjacent-packed head dims.
+ #define KEY_BLOCK_READ(ptr, offset) ((ptr)[(offset) + sglid])
+ #define QUERY_VEC MAKE_VECTOR_TYPE(INPUT0_TYPE, TARGET_SEQ_LEN_BLOCK_SIZE)
+ for (uint hi = 0; hi + 2 * SUBGROUP_SIZE <= K_HEAD_SIZE; hi += 2 * SUBGROUP_SIZE) {
+ QUERY_VEC qvec_lo, qvec_hi;
+ // qvec_lo[i] = query at head dim (hi + 2*i) for target token sglid
+ // qvec_hi[i] = query at head dim (hi + 2*i + 1) for target token sglid
+ unroll_for (uint i = 0; i < SUBGROUP_SIZE; i++) {
+ qvec_lo[i] = slm_query[(hi + 2 * i) * TARGET_SEQ_LEN_BLOCK_SIZE + sglid];
+ qvec_hi[i] = slm_query[(hi + 2 * i + 1) * TARGET_SEQ_LEN_BLOCK_SIZE + sglid];
+ }
+ unroll_for (uint key_row_idx = 0; key_row_idx < TARGET_SEQ_LEN_BLOCK_SIZE; key_row_idx++) {
+#ifdef BEAM_TABLE_TYPE
+ const INPUT1_TYPE packed_byte = KEY_BLOCK_READ(key_input, sub_group_broadcast(key_offset, key_row_idx) + hi / 2);
+#else
+ const INPUT1_TYPE packed_byte = KEY_BLOCK_READ(key_input, key_offset + key_row_idx * key_pitch + hi / 2);
+#endif
+ char2 unpacked = unpack_to_char(*(uint4x2_t*)&packed_byte);
+ KEY_COMPRESSION_SCALE_TYPE key_lo = (TO_KEY_COMPRESSION_SCALE_TYPE(unpacked.s0) - sub_group_broadcast(comp_zp, key_row_idx)) * sub_group_broadcast(comp_scale, key_row_idx);
+ KEY_COMPRESSION_SCALE_TYPE key_hi = (TO_KEY_COMPRESSION_SCALE_TYPE(unpacked.s1) - sub_group_broadcast(comp_zp, key_row_idx)) * sub_group_broadcast(comp_scale, key_row_idx);
+ unroll_for (uint i = 0; i < SUBGROUP_SIZE; i++) {
+ qk_acc[key_row_idx] = mad(sub_group_broadcast(key_lo, i), qvec_lo[i], qk_acc[key_row_idx]);
+ qk_acc[key_row_idx] = mad(sub_group_broadcast(key_hi, i), qvec_hi[i], qk_acc[key_row_idx]);
+ }
+ }
+ }
+ // Handle leftover chunk when K_HEAD_SIZE is not a multiple of 2*SUBGROUP_SIZE
+#if (K_HEAD_SIZE % (2 * SUBGROUP_SIZE)) != 0
+ {
+ const uint hi = (K_HEAD_SIZE / (2 * SUBGROUP_SIZE)) * (2 * SUBGROUP_SIZE);
+ QUERY_VEC qvec_lo, qvec_hi;
+ unroll_for (uint i = 0; i < SUBGROUP_SIZE; i++) {
+ qvec_lo[i] = (hi + 2 * i < K_HEAD_SIZE) ?
+ slm_query[(hi + 2 * i) * TARGET_SEQ_LEN_BLOCK_SIZE + sglid] : (INPUT0_TYPE)0;
+ qvec_hi[i] = (hi + 2 * i + 1 < K_HEAD_SIZE) ?
+ slm_query[(hi + 2 * i + 1) * TARGET_SEQ_LEN_BLOCK_SIZE + sglid] : (INPUT0_TYPE)0;
+ }
+ unroll_for (uint key_row_idx = 0; key_row_idx < TARGET_SEQ_LEN_BLOCK_SIZE; key_row_idx++) {
+#ifdef BEAM_TABLE_TYPE
+ const INPUT1_TYPE packed_byte = (hi / 2 + sglid < K_HEAD_SIZE / 2)
+ ? KEY_BLOCK_READ(key_input, sub_group_broadcast(key_offset, key_row_idx) + hi / 2) : (INPUT1_TYPE)0;
+#else
+ const INPUT1_TYPE packed_byte = (hi / 2 + sglid < K_HEAD_SIZE / 2)
+ ? KEY_BLOCK_READ(key_input, key_offset + key_row_idx * key_pitch + hi / 2) : (INPUT1_TYPE)0;
+#endif
+ char2 unpacked = unpack_to_char(*(uint4x2_t*)&packed_byte);
+ KEY_COMPRESSION_SCALE_TYPE key_lo = (TO_KEY_COMPRESSION_SCALE_TYPE(unpacked.s0) - sub_group_broadcast(comp_zp, key_row_idx)) * sub_group_broadcast(comp_scale, key_row_idx);
+ KEY_COMPRESSION_SCALE_TYPE key_hi = (TO_KEY_COMPRESSION_SCALE_TYPE(unpacked.s1) - sub_group_broadcast(comp_zp, key_row_idx)) * sub_group_broadcast(comp_scale, key_row_idx);
+ KEY_COMPRESSION_SCALE_TYPE lo_mask = (hi + 2 * sglid < K_HEAD_SIZE) ? (KEY_COMPRESSION_SCALE_TYPE)1 : (KEY_COMPRESSION_SCALE_TYPE)0;
+ KEY_COMPRESSION_SCALE_TYPE hi_mask = (hi + 2 * sglid + 1 < K_HEAD_SIZE) ? (KEY_COMPRESSION_SCALE_TYPE)1 : (KEY_COMPRESSION_SCALE_TYPE)0;
+ key_lo *= lo_mask;
+ key_hi *= hi_mask;
+ unroll_for (uint i = 0; i < SUBGROUP_SIZE; i++) {
+ qk_acc[key_row_idx] = mad(sub_group_broadcast(key_lo, i), qvec_lo[i], qk_acc[key_row_idx]);
+ qk_acc[key_row_idx] = mad(sub_group_broadcast(key_hi, i), qvec_hi[i], qk_acc[key_row_idx]);
+ }
+ }
+ }
+#endif
+ }
+#else // !IS_INT4_COMPRESSED
uint head_idx_index = 0;
__attribute__((opencl_unroll_hint(1)))
for (; head_idx_index + SUBGROUP_SIZE <= K_HEAD_SIZE; head_idx_index += SUBGROUP_SIZE) {
@@ -1383,7 +1603,7 @@ KERNEL(sdpa_opt)(
INPUT1_TYPE key_packed = (sglid < K_HEAD_SIZE_LEFTOVER) ? key_input[key_offset + key_row_idx * key_pitch + head_idx_index + sglid] : INPUT1_VAL_ZERO;
#endif
#if IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATION
- KEY_COMPRESSION_SCALE_TYPE key_vals = (TO_KEY_COMPRESSION_SCALE_TYPE(key_packed) - sub_group_broadcast(comp_zp, key_row_idx)) * sub_group_broadcast(comp_scale, key_row_idx);j
+ KEY_COMPRESSION_SCALE_TYPE key_vals = (TO_KEY_COMPRESSION_SCALE_TYPE(key_packed) - sub_group_broadcast(comp_zp, key_row_idx)) * sub_group_broadcast(comp_scale, key_row_idx);
#elif IS_KV_COMPRESSED
KEY_COMPRESSION_SCALE_TYPE key_vals = (TO_KEY_COMPRESSION_SCALE_TYPE(key_packed) * sub_group_broadcast(comp_scale, key_row_idx));
#else
@@ -1394,15 +1614,85 @@ KERNEL(sdpa_opt)(
}
}
#endif
+#endif // !IS_INT4_COMPRESSED
} else if (seq_len_calc_size > 0) {
#if IS_KV_COMPRESSED
const uint comp_offset = GET_COMPRESSION_INDEX(KEY_COMPRESSION_SCALE, b_idx, b1_idx / BROADCAST_GROUP_SIZE, seq_len + min(sglid, (uint)seq_len_calc_size - 1), 0);
- // const uint comp_offset = GET_COMPRESSION_INDEX(KEY_COMPRESSION_SCALE, b_idx, b1_idx / BROADCAST_GROUP_SIZE, seq_len + sglid, 0);
KEY_COMPRESSION_SCALE_TYPE comp_scale = GET_SCALE(key_zp, key_scale, comp_offset);
#if USE_ASYMMETRIC_QUANTIZATION
KEY_COMPRESSION_SCALE_TYPE comp_zp = GET_ZP(key_zp, key_scale, comp_offset);
#endif
#endif
+#if IS_KV_COMPRESSED && IS_INT4_COMPRESSED
+ {
+ // INT4 partial block: process 2*SUBGROUP_SIZE logical head dims per iteration
+ #define KEY_BLOCK_READ(ptr, offset) ((ptr)[(offset) + sglid])
+ #define QUERY_VEC_TYPE MAKE_VECTOR_TYPE(INPUT0_TYPE, TARGET_SEQ_LEN_BLOCK_SIZE)
+ const uint key_pitch_int4 = INPUT1_SIZE_X;
+ for (uint hi = 0; hi + 2 * SUBGROUP_SIZE <= K_HEAD_SIZE; hi += 2 * SUBGROUP_SIZE) {
+ QUERY_VEC_TYPE qvec_lo, qvec_hi;
+ unroll_for (uint i = 0; i < SUBGROUP_SIZE; i++) {
+ qvec_lo[i] = slm_query[(hi + 2 * i) * TARGET_SEQ_LEN_BLOCK_SIZE + sglid];
+ qvec_hi[i] = slm_query[(hi + 2 * i + 1) * TARGET_SEQ_LEN_BLOCK_SIZE + sglid];
+ }
+ unroll_for (uint key_row_idx = 0; key_row_idx < TARGET_SEQ_LEN_BLOCK_SIZE; key_row_idx++) {
+ KEY_COMPRESSION_SCALE_TYPE key_lo = 0;
+ KEY_COMPRESSION_SCALE_TYPE key_hi = 0;
+ if (key_row_idx < seq_len_calc_size) {
+#ifdef BEAM_TABLE_TYPE
+ const INPUT1_TYPE packed_byte = KEY_BLOCK_READ(key_input, sub_group_broadcast(key_offset, key_row_idx) + hi / 2);
+#else
+ const INPUT1_TYPE packed_byte = KEY_BLOCK_READ(key_input, key_offset + key_row_idx * key_pitch_int4 + hi / 2);
+#endif
+ char2 unpacked = unpack_to_char(*(uint4x2_t*)&packed_byte);
+ key_lo = (TO_KEY_COMPRESSION_SCALE_TYPE(unpacked.s0) - sub_group_broadcast(comp_zp, key_row_idx)) * sub_group_broadcast(comp_scale, key_row_idx);
+ key_hi = (TO_KEY_COMPRESSION_SCALE_TYPE(unpacked.s1) - sub_group_broadcast(comp_zp, key_row_idx)) * sub_group_broadcast(comp_scale, key_row_idx);
+ }
+ unroll_for (uint i = 0; i < SUBGROUP_SIZE; i++) {
+ qk_acc[key_row_idx] = mad(sub_group_broadcast(key_lo, i), qvec_lo[i], qk_acc[key_row_idx]);
+ qk_acc[key_row_idx] = mad(sub_group_broadcast(key_hi, i), qvec_hi[i], qk_acc[key_row_idx]);
+ }
+ }
+ }
+ // Handle leftover chunk when K_HEAD_SIZE is not a multiple of 2*SUBGROUP_SIZE
+#if (K_HEAD_SIZE % (2 * SUBGROUP_SIZE)) != 0
+ {
+ const uint hi = (K_HEAD_SIZE / (2 * SUBGROUP_SIZE)) * (2 * SUBGROUP_SIZE);
+ QUERY_VEC_TYPE qvec_lo, qvec_hi;
+ unroll_for (uint i = 0; i < SUBGROUP_SIZE; i++) {
+ qvec_lo[i] = (hi + 2 * i < K_HEAD_SIZE) ?
+ slm_query[(hi + 2 * i) * TARGET_SEQ_LEN_BLOCK_SIZE + sglid] : (INPUT0_TYPE)0;
+ qvec_hi[i] = (hi + 2 * i + 1 < K_HEAD_SIZE) ?
+ slm_query[(hi + 2 * i + 1) * TARGET_SEQ_LEN_BLOCK_SIZE + sglid] : (INPUT0_TYPE)0;
+ }
+ unroll_for (uint key_row_idx = 0; key_row_idx < TARGET_SEQ_LEN_BLOCK_SIZE; key_row_idx++) {
+ KEY_COMPRESSION_SCALE_TYPE key_lo = 0;
+ KEY_COMPRESSION_SCALE_TYPE key_hi = 0;
+ if (key_row_idx < seq_len_calc_size) {
+#ifdef BEAM_TABLE_TYPE
+ const INPUT1_TYPE packed_byte = (hi / 2 + sglid < K_HEAD_SIZE / 2)
+ ? KEY_BLOCK_READ(key_input, sub_group_broadcast(key_offset, key_row_idx) + hi / 2) : (INPUT1_TYPE)0;
+#else
+ const INPUT1_TYPE packed_byte = (hi / 2 + sglid < K_HEAD_SIZE / 2)
+ ? KEY_BLOCK_READ(key_input, key_offset + key_row_idx * key_pitch_int4 + hi / 2) : (INPUT1_TYPE)0;
+#endif
+ char2 unpacked = unpack_to_char(*(uint4x2_t*)&packed_byte);
+ key_lo = (TO_KEY_COMPRESSION_SCALE_TYPE(unpacked.s0) - sub_group_broadcast(comp_zp, key_row_idx)) * sub_group_broadcast(comp_scale, key_row_idx);
+ key_hi = (TO_KEY_COMPRESSION_SCALE_TYPE(unpacked.s1) - sub_group_broadcast(comp_zp, key_row_idx)) * sub_group_broadcast(comp_scale, key_row_idx);
+ }
+ KEY_COMPRESSION_SCALE_TYPE lo_mask = (hi + 2 * sglid < K_HEAD_SIZE) ? (KEY_COMPRESSION_SCALE_TYPE)1 : (KEY_COMPRESSION_SCALE_TYPE)0;
+ KEY_COMPRESSION_SCALE_TYPE hi_mask = (hi + 2 * sglid + 1 < K_HEAD_SIZE) ? (KEY_COMPRESSION_SCALE_TYPE)1 : (KEY_COMPRESSION_SCALE_TYPE)0;
+ key_lo *= lo_mask;
+ key_hi *= hi_mask;
+ unroll_for (uint i = 0; i < SUBGROUP_SIZE; i++) {
+ qk_acc[key_row_idx] = mad(sub_group_broadcast(key_lo, i), qvec_lo[i], qk_acc[key_row_idx]);
+ qk_acc[key_row_idx] = mad(sub_group_broadcast(key_hi, i), qvec_hi[i], qk_acc[key_row_idx]);
+ }
+ }
+ }
+#endif
+ }
+#else // !IS_INT4_COMPRESSED
uint head_idx_index = 0;
__attribute__((opencl_unroll_hint(1)))
for (; head_idx_index + SUBGROUP_SIZE <= K_HEAD_SIZE; head_idx_index += SUBGROUP_SIZE) {
@@ -1479,7 +1769,7 @@ KERNEL(sdpa_opt)(
const INPUT1_TYPE key_packed = (sglid < K_HEAD_SIZE_LEFTOVER) ? key_input[key_offset + key_row_idx * key_pitch + head_idx_index + sglid] : INPUT1_VAL_ZERO;
#endif
#if IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATION
- KEY_COMPRESSION_SCALE_TYPE key_val = (TO_KEY_COMPRESSION_SCALE_TYPE(key_packed) - sub_group_broadcast(comp_zp, key_row_idx)) * sub_group_broadcast(comp_scale, key_row_idx);j
+ KEY_COMPRESSION_SCALE_TYPE key_val = (TO_KEY_COMPRESSION_SCALE_TYPE(key_packed) - sub_group_broadcast(comp_zp, key_row_idx)) * sub_group_broadcast(comp_scale, key_row_idx);
#elif IS_KV_COMPRESSED
KEY_COMPRESSION_SCALE_TYPE key_val = (TO_KEY_COMPRESSION_SCALE_TYPE(key_packed) * sub_group_broadcast(comp_scale, key_row_idx));
#else
@@ -1490,6 +1780,7 @@ KERNEL(sdpa_opt)(
}
}
#endif // K_HEAD_SIZE_LEFTOVER
+#endif // !IS_INT4_COMPRESSED
}
// softmax_scale
@@ -1759,10 +2050,32 @@ KERNEL(sdpa_opt)(
#ifdef INPUT2_DIMS_ORDER
uint value_offset_base = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 0, 0);
uint value_offset_next_seq = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 1, 0);
+ #if IS_INT4_COMPRESSED
const uint value_pitch = value_offset_next_seq - value_offset_base;
+ #else
+ const uint value_pitch = value_offset_next_seq - value_offset_base;
+ #endif
#else
+ #if IS_INT4_COMPRESSED
+ const uint value_pitch = INPUT2_SIZE_X;
+ #else
const uint value_pitch = V_HEAD_SIZE;
+ #endif
+#endif
#endif
+
+#if IS_INT4_COMPRESSED && !defined(IS_PAGED_ATTENTION)
+ const uint val_packed_x_s1 = (head_size_idx / (2 * SUBGROUP_SIZE)) * SUBGROUP_SIZE;
+ // Adjacent head packing: shuffle to get correct byte, select nibble by lane parity
+ const uint shuffle_src_s1 = (head_size_idx & (2 * SUBGROUP_SIZE - 1)) >> 1;
+ const uint nibble_sel_s1 = sglid & 1;
+ #ifndef BEAM_TABLE_TYPE
+ #ifdef INPUT2_DIMS_ORDER
+ const uint value_base_s1 = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 0, val_packed_x_s1);
+ #else
+ const uint value_base_s1 = INPUT2_GET_INDEX(b0_idx, b1_idx, 0, val_packed_x_s1);
+ #endif
+ #endif // !BEAM_TABLE_TYPE
#endif
if (partition_seq_len == SEQ_LEN_PARTITION_SIZE) {
@@ -1781,11 +2094,18 @@ KERNEL(sdpa_opt)(
(start_partition_idx + (seq_len)) * value_pitch + head_size_idx;
#else
#ifdef BEAM_TABLE_TYPE
+ #if IS_INT4_COMPRESSED
+ const uint b_idx = beam_table[FUNC_CALL(get_bt_index_value)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, start_partition_idx + (seq_len) + sglid, val_packed_x_s1)];
+ const uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + (seq_len) + sglid, val_packed_x_s1);
+ #else
const uint b_idx = beam_table[FUNC_CALL(get_bt_index_value)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, start_partition_idx + (seq_len) + sglid, sgid * SUBGROUP_SIZE)];
const uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + (seq_len) + sglid, sgid * SUBGROUP_SIZE);
+ #endif
#else
const uint b_idx = b0_idx;
- #ifdef INPUT2_DIMS_ORDER
+ #if IS_INT4_COMPRESSED
+ uint value_offset = value_base_s1 + (start_partition_idx + (seq_len)) * value_pitch;
+ #elif defined(INPUT2_DIMS_ORDER)
uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, start_partition_idx + (seq_len), head_size_idx);
#else
uint value_offset = INPUT2_GET_INDEX(b0_idx, b1_idx, start_partition_idx + (seq_len), head_size_idx);
@@ -1815,7 +2135,14 @@ KERNEL(sdpa_opt)(
const INPUT2_TYPE value_packed = VALUE_BLOCK_READ(value_input, value_offset);
#endif
- #if IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATION
+ #if IS_KV_COMPRESSED && IS_INT4_COMPRESSED
+ INPUT2_TYPE needed_byte = intel_sub_group_shuffle(value_packed, shuffle_src_s1);
+ char2 v_unpacked = unpack_to_char(*(uint4x2_t*)&needed_byte);
+ VALUE_COMPRESSION_SCALE_TYPE value_val = (nibble_sel_s1 == 0 ?
+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(v_unpacked.s0) :
+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(v_unpacked.s1));
+ value_val = (value_val - sub_group_broadcast(comp_zp, i)) * sub_group_broadcast(comp_scale, i);
+ #elif IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATION
VALUE_COMPRESSION_SCALE_TYPE value_val = (value_packed - sub_group_broadcast(comp_zp, i)) * sub_group_broadcast(comp_scale, i);
#elif IS_KV_COMPRESSED
VALUE_COMPRESSION_SCALE_TYPE value_val = (value_packed * sub_group_broadcast(comp_scale, i));
@@ -1838,7 +2165,14 @@ KERNEL(sdpa_opt)(
#else
const INPUT2_TYPE value_packed = value_input[value_offset];
#endif
- #if IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATION
+ #if IS_KV_COMPRESSED && IS_INT4_COMPRESSED
+ INPUT2_TYPE needed_byte_elt = intel_sub_group_shuffle(value_packed, shuffle_src_s1);
+ char2 v_unpacked_elt = unpack_to_char(*(uint4x2_t*)&needed_byte_elt);
+ VALUE_COMPRESSION_SCALE_TYPE value_val = (nibble_sel_s1 == 0 ?
+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(v_unpacked_elt.s0) :
+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(v_unpacked_elt.s1));
+ value_val = (value_val - sub_group_broadcast(comp_zp, i)) * sub_group_broadcast(comp_scale, i);
+ #elif IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATION
VALUE_COMPRESSION_SCALE_TYPE value_val = (value_packed - sub_group_broadcast(comp_zp, i)) * sub_group_broadcast(comp_scale, i);
#elif IS_KV_COMPRESSED
VALUE_COMPRESSION_SCALE_TYPE value_val = (value_packed * sub_group_broadcast(comp_scale, i));
@@ -1874,11 +2208,18 @@ KERNEL(sdpa_opt)(
(start_partition_idx + (seq_len * SUBGROUP_SIZE)) * value_pitch + head_size_idx;
#else // !IS_PAGED_ATTENTION
#ifdef BEAM_TABLE_TYPE
+ #if IS_INT4_COMPRESSED
+ const uint b_idx = beam_table[FUNC_CALL(get_bt_index_value)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, start_partition_idx + (seq_len * SUBGROUP_SIZE) + sglid, val_packed_x_s1)];
+ uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + (seq_len * SUBGROUP_SIZE) + sglid, val_packed_x_s1);
+ #else
const uint b_idx = beam_table[FUNC_CALL(get_bt_index_value)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, start_partition_idx + (seq_len * SUBGROUP_SIZE) + sglid, sgid * SUBGROUP_SIZE)];
uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + (seq_len * SUBGROUP_SIZE) + sglid, sgid * SUBGROUP_SIZE);
+ #endif
#else
const uint b_idx = b0_idx;
- #ifdef INPUT2_DIMS_ORDER
+ #if IS_INT4_COMPRESSED
+ uint value_offset = value_base_s1 + (start_partition_idx + (seq_len * SUBGROUP_SIZE)) * value_pitch;
+ #elif defined(INPUT2_DIMS_ORDER)
uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, start_partition_idx + (seq_len * SUBGROUP_SIZE), head_size_idx);
#else
uint value_offset = INPUT2_GET_INDEX(b0_idx, b1_idx, start_partition_idx + (seq_len * SUBGROUP_SIZE), head_size_idx);
@@ -1910,7 +2251,14 @@ KERNEL(sdpa_opt)(
const INPUT2_TYPE value_packed = VALUE_BLOCK_READ(value_input, value_offset);
#endif
- #if IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATION
+ #if IS_KV_COMPRESSED && IS_INT4_COMPRESSED
+ INPUT2_TYPE needed_byte = intel_sub_group_shuffle(value_packed, shuffle_src_s1);
+ char2 v_unpacked = unpack_to_char(*(uint4x2_t*)&needed_byte);
+ VALUE_COMPRESSION_SCALE_TYPE value_val = (nibble_sel_s1 == 0 ?
+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(v_unpacked.s0) :
+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(v_unpacked.s1));
+ value_val = (value_val - sub_group_broadcast(comp_zp, i)) * sub_group_broadcast(comp_scale, i);
+ #elif IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATION
VALUE_COMPRESSION_SCALE_TYPE value_val = (value_packed - sub_group_broadcast(comp_zp, i)) * sub_group_broadcast(comp_scale, i);
#elif IS_KV_COMPRESSED
VALUE_COMPRESSION_SCALE_TYPE value_val = (value_packed * sub_group_broadcast(comp_scale, i));
@@ -1933,7 +2281,14 @@ KERNEL(sdpa_opt)(
#else
const INPUT2_TYPE value_packed = value_input[value_offset];
#endif
- #if IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATION
+ #if IS_KV_COMPRESSED && IS_INT4_COMPRESSED
+ INPUT2_TYPE needed_byte_elt = intel_sub_group_shuffle(value_packed, shuffle_src_s1);
+ char2 v_unpacked_elt = unpack_to_char(*(uint4x2_t*)&needed_byte_elt);
+ VALUE_COMPRESSION_SCALE_TYPE value_val = (nibble_sel_s1 == 0 ?
+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(v_unpacked_elt.s0) :
+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(v_unpacked_elt.s1));
+ value_val = (value_val - sub_group_broadcast(comp_zp, i)) * sub_group_broadcast(comp_scale, i);
+ #elif IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATION
VALUE_COMPRESSION_SCALE_TYPE value_val = (value_packed - sub_group_broadcast(comp_zp, i)) * sub_group_broadcast(comp_scale, i);
#elif IS_KV_COMPRESSED
VALUE_COMPRESSION_SCALE_TYPE value_val = (value_packed * sub_group_broadcast(comp_scale, i));
@@ -1972,11 +2327,18 @@ KERNEL(sdpa_opt)(
#else // !IS_PAGED_ATTENTION
#ifdef BEAM_TABLE_TYPE
+ #if IS_INT4_COMPRESSED
+ const uint b_idx = beam_table[FUNC_CALL(get_bt_index_value)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, start_partition_idx + seq_len_leftovers_start + sglid, val_packed_x_s1)];
+ const uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + seq_len_leftovers_start + sglid, val_packed_x_s1);
+ #else
const uint b_idx = beam_table[FUNC_CALL(get_bt_index_value)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, start_partition_idx + seq_len_leftovers_start + sglid, sgid * SUBGROUP_SIZE)];
const uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + seq_len_leftovers_start + sglid, sgid * SUBGROUP_SIZE);
+ #endif
#else
const uint b_idx = b0_idx;
- #ifdef INPUT2_DIMS_ORDER
+ #if IS_INT4_COMPRESSED
+ uint value_offset = value_base_s1 + (start_partition_idx + seq_len_leftovers_start) * value_pitch;
+ #elif defined(INPUT2_DIMS_ORDER)
uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, start_partition_idx + seq_len_leftovers_start, head_size_idx);
#else
uint value_offset = INPUT2_GET_INDEX(b0_idx, b1_idx, start_partition_idx + seq_len_leftovers_start, head_size_idx);
@@ -1986,7 +2348,6 @@ KERNEL(sdpa_opt)(
#if IS_KV_COMPRESSED
const uint comp_offset = GET_COMPRESSION_INDEX(VALUE_COMPRESSION_SCALE, b_idx, b1_idx / BROADCAST_GROUP_SIZE, start_partition_idx + min(seq_len_leftovers_start + sglid, seq_len_end - 1), 0);
- // const uint comp_offset = GET_COMPRESSION_INDEX(VALUE_COMPRESSION_SCALE, b_idx, b1_idx / BROADCAST_GROUP_SIZE, start_partition_idx + seq_len_leftovers_start + sglid, 0);
VALUE_COMPRESSION_SCALE_TYPE comp_scale = GET_SCALE(val_zp, val_scale, comp_offset);
#if USE_ASYMMETRIC_QUANTIZATION
VALUE_COMPRESSION_SCALE_TYPE comp_zp = GET_ZP(val_zp, val_scale, comp_offset);
@@ -2014,7 +2375,14 @@ KERNEL(sdpa_opt)(
#endif
#endif // V_HEAD_SIZE_LEFTOVER
-#if IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATION
+#if IS_KV_COMPRESSED && IS_INT4_COMPRESSED
+ INPUT2_TYPE needed_byte = intel_sub_group_shuffle(value_packed, shuffle_src_s1);
+ char2 v_left_unpacked = unpack_to_char(*(uint4x2_t*)&needed_byte);
+ VALUE_COMPRESSION_SCALE_TYPE value_val = (nibble_sel_s1 == 0 ?
+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(v_left_unpacked.s0) :
+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(v_left_unpacked.s1));
+ value_val = (value_val - sub_group_broadcast(comp_zp, seq_len_idx)) * sub_group_broadcast(comp_scale, seq_len_idx);
+#elif IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATION
VALUE_COMPRESSION_SCALE_TYPE value_val = (value_packed - sub_group_broadcast(comp_zp, seq_len_idx)) * sub_group_broadcast(comp_scale, seq_len_idx);
#elif IS_KV_COMPRESSED
VALUE_COMPRESSION_SCALE_TYPE value_val = (value_packed * sub_group_broadcast(comp_scale, seq_len_idx));
diff --git a/src/plugins/intel_gpu/src/graph/kv_cache.cpp b/src/plugins/intel_gpu/src/graph/kv_cache.cpp
index a4c2ed3fbd5..4e9cb52ca07 100644
--- a/src/plugins/intel_gpu/src/graph/kv_cache.cpp
+++ b/src/plugins/intel_gpu/src/graph/kv_cache.cpp
@@ -103,6 +103,15 @@ std::vector<layout> kv_cache_inst::calc_output_layouts(kv_cache_node const& /*no
static const std::map<size_t, size_t> ports_map = {{0, 0}, {1, 2}, {2, 3}, {3, 4}};
+ // For INT4 KV-cache, pack two values per byte (halve inner dim)
+ if (desc->compressed) {
+ const auto kv_cache_dt = impl_param.get_program().get_config().get_kv_cache_precision();
+ if (ov::element::Type(kv_cache_dt).bitwidth() == 4 && output_shapes[0].size() > 0) {
+ auto inner_dim_idx = output_shapes[0].size() - 1;
+ output_shapes[0][inner_dim_idx] = output_shapes[0][inner_dim_idx] / 2;
+ }
+ }
+
std::vector<layout> out_layouts;
for (size_t i = 0; i < desc->num_outputs; i++) {
auto out_type = desc->output_data_types[i].value_or(impl_param.get_input_layout(ports_map.at(i)).data_type);
diff --git a/src/plugins/intel_gpu/src/graph/paged_attention.cpp b/src/plugins/intel_gpu/src/graph/paged_attention.cpp
index ecb69870299..61121b209bb 100644
--- a/src/plugins/intel_gpu/src/graph/paged_attention.cpp
+++ b/src/plugins/intel_gpu/src/graph/paged_attention.cpp
@@ -44,9 +44,12 @@ std::vector<layout> paged_attention_inst::calc_output_layouts(paged_attention_no
impl_param.get_input_layout(key_cache_idx).data_type == ov::element::u8 ||
data_type_traits::is_i4_u4(key_cache_dt);
auto expected_block_size = desc->has_xattention ? paged_attention::block_size_xattn : paged_attention::block_size;
+ // Both INT4 and INT8 BY_CHANNEL use dim order {0,1,3,2} with block_size at dim[3].
+ const bool is_int4 = data_type_traits::is_i4_u4(key_cache_dt);
if (key_cache_compressed && key_cache_quant_mode == ov::internal::CacheQuantMode::BY_CHANNEL) {
- if (data_type_traits::is_i4_u4(key_cache_dt)) {
- expected_block_size += 8;
+ if (is_int4) {
+ // INT4 BY_CHANNEL: block_size dim is packed (u4→u8) + scale/zp = block_size/2 + sizeof(fp16)*2
+ expected_block_size = expected_block_size / 2 + 4;
} else {
constexpr size_t kv_sub_block_size = 16;
OPENVINO_ASSERT(expected_block_size % kv_sub_block_size == 0,
@@ -62,6 +65,7 @@ std::vector<layout> paged_attention_inst::calc_output_layouts(paged_attention_no
"[GPU] Paged Attention key cache quantization mode mismatch: prim.is_key_by_channel : ",
desc->is_key_by_channel, " but exec_config : ", impl_param.get_program().get_config().get_key_cache_quant_mode());
+ // Both INT4 and INT8 BY_CHANNEL use {0,1,3,2} dim order (block_size at dim[3]).
const auto block_size_idx = desc->has_xattention ? 2 : 3;
bool valid_block_size = key_cache_ps.is_dynamic() ||
(key_cache_ps[block_size_idx].get_length() == static_cast<ov::Dimension::value_type>(expected_block_size));
diff --git a/src/plugins/intel_gpu/src/graph/scaled_dot_product_attention.cpp b/src/plugins/intel_gpu/src/graph/scaled_dot_product_attention.cpp
index ec35eb76e79..828ddff651b 100644
--- a/src/plugins/intel_gpu/src/graph/scaled_dot_product_attention.cpp
+++ b/src/plugins/intel_gpu/src/graph/scaled_dot_product_attention.cpp
@@ -70,6 +70,16 @@ std::vector<layout> scaled_dot_product_attention_inst::calc_output_layouts(scale
input_shapes.push_back(impl_param.get_input_layout(i).get<ShapeType>());
}
+ // For INT4 KV-cache, restore logical head size from query for shape inference
+ if (prim->is_kv_compressed) {
+ const auto kv_cache_dt = impl_param.get_program().get_config().get_kv_cache_precision();
+ if (ov::element::Type(kv_cache_dt).bitwidth() == 4 && input_shapes.size() >= 3) {
+ auto q_last = input_shapes[0][input_shapes[0].size() - 1];
+ input_shapes[1][input_shapes[1].size() - 1] = q_last;
+ input_shapes[2][input_shapes[2].size() - 1] = q_last;
+ }
+ }
+
std::vector<ShapeType> output_shapes = ov::intel_gpu::op::shape_infer(&op,
input_shapes,
prim->input_q_transpose_order,
diff --git a/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/dynamic_quantize_gpu_kv_cache.cl b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/dynamic_quantize_gpu_kv_cache.cl
index 8351266528e..22e68ba1dd5 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/dynamic_quantize_gpu_kv_cache.cl
+++ b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/dynamic_quantize_gpu_kv_cache.cl
@@ -2,14 +2,16 @@
// SPDX-License-Identifier: Apache-2.0
//
-#include "include/batch_headers/fetch_data.cl"
#include "include/batch_headers/fetch_data.cl"
#include "include/batch_headers/common.cl"
+#include "include/batch_headers/int4_utils.cl"
#include "include/batch_headers/sub_group_block_read.cl"
#include "include/batch_headers/sub_group_block_write.cl"
#include "include/batch_headers/sub_group_shuffle.cl"
+#define UINT4_RANGE 15
+
#if OUTPUT_DIMS != 4
#error "dynamic_quantize_gpu_kv_cache.cl: Unsupported output dimension"
#endif
@@ -84,6 +86,70 @@ KERNEL(dynamic_quantize_gpu_kv_cache)(
max_value = fmax(max_value, grp_max);
#endif
+#ifdef APPEND_MODE
+ APPEND_AXIS_NAME += axis_offset;
+#endif
+
+#if IS_INT4_COMPRESSED
+ // 4-bit unsigned asymmetric quantization with adjacent head packing
+ min_value = work_group_reduce_min(min_value);
+ max_value = work_group_reduce_max(max_value);
+
+ ACCUMULATOR_TYPE diff_value = max_value == min_value ? (ACCUMULATOR_TYPE)(grp_max)
+ : (ACCUMULATOR_TYPE)(max_value - min_value);
+ ACCUMULATOR_TYPE scale_tmp = (ACCUMULATOR_TYPE)((UINT4_RANGE) / diff_value);
+ ACCUMULATOR_TYPE zp_tmp = (ACCUMULATOR_TYPE)(-min_value * scale_tmp);
+
+ // Quantize all values to u4 range
+ uchar qval[INNERMOST_DIM_VALUE / SUBGROUP_SIZE];
+ unroll_for (uint i = 0; i < INNERMOST_DIM_VALUE / SUBGROUP_SIZE; i++) {
+ qval[i] = (uchar)clamp(convert_int_rte((float)val[i] * scale_tmp + zp_tmp), 0, UINT4_RANGE);
+ }
+
+ // Pack adjacent head dimensions
+ const uint output_offset = OUTPUT_GET_INDEX(b, f, y, x);
+#define NUM_SUBGROUP_CHUNKS (INNERMOST_DIM_VALUE / SUBGROUP_SIZE)
+#define NUM_OUTPUT_ITERS (NUM_SUBGROUP_CHUNKS / 2)
+ unroll_for (uint i = 0; i < NUM_OUTPUT_ITERS; i++) {
+ uint pair_lane = 2 * (sglid % 8);
+ uchar lo_even = intel_sub_group_shuffle(qval[2 * i], pair_lane);
+ uchar hi_even = intel_sub_group_shuffle(qval[2 * i], pair_lane + 1);
+ uchar lo_odd = intel_sub_group_shuffle(qval[2 * i + 1], pair_lane);
+ uchar hi_odd = intel_sub_group_shuffle(qval[2 * i + 1], pair_lane + 1);
+ uchar q_lo = (sglid < 8) ? lo_even : lo_odd;
+ uchar q_hi = (sglid < 8) ? hi_even : hi_odd;
+ char packed = cvt_uint8x2_to_uint4x2((uchar2)(q_lo, q_hi));
+ output[output_offset + i * SUBGROUP_SIZE + sglid] = packed;
+ }
+#if (NUM_SUBGROUP_CHUNKS % 2) != 0
+ {
+ uint pair_lane = 2 * (sglid % 8);
+ uchar q_lo = intel_sub_group_shuffle(qval[NUM_SUBGROUP_CHUNKS - 1], pair_lane);
+ uchar q_hi = intel_sub_group_shuffle(qval[NUM_SUBGROUP_CHUNKS - 1], pair_lane + 1);
+ char packed = cvt_uint8x2_to_uint4x2((uchar2)(q_lo, q_hi));
+ if (sglid < SUBGROUP_SIZE / 2)
+ output[output_offset + NUM_OUTPUT_ITERS * SUBGROUP_SIZE + sglid] = packed;
+ }
+#endif
+#undef NUM_SUBGROUP_CHUNKS
+#undef NUM_OUTPUT_ITERS
+
+ const uint scale_idx = FUNC_CALL(get_scales_offset)(OPTIONAL_SHAPE_INFO_TENSOR b, f, y, x);
+ if (grouped_indexes == 0 && sglid == 0) {
+ output_scale[scale_idx] = (OUTPUT1_TYPE)(1.0f / scale_tmp); // dequant scale
+#if ASYMMETRIC_QUANTIZATION && !GROUP_SCALES_WITH_ZP
+ #if OUTPUT2_IS_FP
+ output_zp[scale_idx] = (OUTPUT2_TYPE)(zp_tmp);
+ #else
+ output_zp[scale_idx] = convert_char_rte(zp_tmp);
+ #endif
+#else
+ output_scale[scale_idx + 1] = (OUTPUT1_TYPE)(zp_tmp); // zero-point (interleaved)
+#endif
+ }
+
+#else // !IS_INT4_COMPRESSED — original INT8 path
+
#if ASYMMETRIC_QUANTIZATION
min_value = work_group_reduce_min(min_value);
max_value = work_group_reduce_max(max_value);
@@ -100,10 +166,6 @@ KERNEL(dynamic_quantize_gpu_kv_cache)(
OUTPUT1_TYPE scale = 127.0h / max_value;
#endif
-#ifdef APPEND_MODE
- APPEND_AXIS_NAME += axis_offset;
-#endif
-
const uint output_offset = OUTPUT_GET_INDEX(b, f, y, x);
unroll_for (uint i = 0; i < INNERMOST_DIM_VALUE / SUBGROUP_SIZE; i++) {
#if ASYMMETRIC_QUANTIZATION
@@ -134,4 +196,6 @@ KERNEL(dynamic_quantize_gpu_kv_cache)(
output_scale[scale_idx] = 1.0h / scale;
#endif
}
+
+#endif // IS_INT4_COMPRESSED
}
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/dynamic_quantize/dynamic_quantize_kernel_opt_kv_cache.cpp b/src/plugins/intel_gpu/src/kernel_selector/kernels/dynamic_quantize/dynamic_quantize_kernel_opt_kv_cache.cpp
index ec4c40affa8..c0a47c23dc2 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/kernels/dynamic_quantize/dynamic_quantize_kernel_opt_kv_cache.cpp
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/dynamic_quantize/dynamic_quantize_kernel_opt_kv_cache.cpp
@@ -88,6 +88,9 @@ ParamsKey DynamicQuantizeKernelKVCache::GetSupportedKey() const {
ParamsKey k;
k.EnableInputDataType(Datatype::F16);
k.EnableOutputDataType(Datatype::INT8);
+ k.EnableOutputDataType(Datatype::UINT8);
+ k.EnableOutputDataType(Datatype::INT4);
+ k.EnableOutputDataType(Datatype::UINT4);
k.EnableDifferentTypes();
k.EnableAllInputLayout();
k.EnableAllOutputLayout();
@@ -141,6 +144,7 @@ JitConstants DynamicQuantizeKernelKVCache::GetJitConstants(const dynamic_quantiz
jit.AddConstant(MakeJitConstant("ITERATIONS_NUMBER", iterations_number));
jit.AddConstant(MakeJitConstant("ASYMMETRIC_QUANTIZATION", params.use_asymmetric_quantization));
jit.AddConstant(MakeJitConstant("GROUP_SCALES_WITH_ZP", params.combine_scales_and_zp));
+ jit.AddConstant(MakeJitConstant("IS_INT4_COMPRESSED", params.is_int4_compressed));
// Use FP32 accumulator type for scale/zp calculation
jit.Merge(MakeTypeJitConstants(Datatype::F32, "ACCUMULATOR"));
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/dynamic_quantize/dynamic_quantize_kernel_ref.h b/src/plugins/intel_gpu/src/kernel_selector/kernels/dynamic_quantize/dynamic_quantize_kernel_ref.h
index c44e8dcaaed..6b7985aef25 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/kernels/dynamic_quantize/dynamic_quantize_kernel_ref.h
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/dynamic_quantize/dynamic_quantize_kernel_ref.h
@@ -21,6 +21,7 @@ struct dynamic_quantize_params : public base_params {
bool use_asymmetric_quantization = false;
bool combine_scales_and_zp = false;
bool generate_precomputed_reduction = false;
+ bool is_int4_compressed = false;
};
class DynamicQuantizeKernelRef : public KernelBaseOpenCL {
diff --git a/src/plugins/intel_gpu/src/plugin/multi_tensor_variable_state.cpp b/src/plugins/intel_gpu/src/plugin/multi_tensor_variable_state.cpp
index 971c025235a..55d92fdb961 100644
--- a/src/plugins/intel_gpu/src/plugin/multi_tensor_variable_state.cpp
+++ b/src/plugins/intel_gpu/src/plugin/multi_tensor_variable_state.cpp
@@ -165,7 +165,7 @@ VariableStateIndirectKVCacheCompressed::VariableStateIndirectKVCacheCompressed(
const std::vector<cldnn::layout>& output_layouts,
size_t beam_idx,
size_t concat_idx,
- bool has_zp_state = false)
+ bool has_zp_state)
: VariableStateIndirectKVCache(info, context, shape_predictor, beam_idx, concat_idx),
m_has_zp_state(has_zp_state) {
OPENVINO_ASSERT((has_zp_state && output_layouts.size() == 3) ||
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/kv_cache_compression.cpp b/src/plugins/intel_gpu/src/plugin/transformations/kv_cache_compression.cpp
index b99bb2b1274..ea0a733fb18 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations/kv_cache_compression.cpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations/kv_cache_compression.cpp
@@ -232,8 +232,14 @@ KVCacheCompressionMatcher::KVCacheCompressionMatcher(ov::element::Type compressi
config.scales_zp_output_order = get_scales_output_order(sdpa_node->get_input1_transpose_order());
config.output_storage_type = output_storage_type;
- if (config.quantization_type == ov::op::internal::DynamicQuantize::QuantizationType::Asymmetric)
- config.zp_dt = supports_immad ? element::i8 : query_node->get_output_element_type(0);
+ if (config.quantization_type == ov::op::internal::DynamicQuantize::QuantizationType::Asymmetric) {
+ // For INT4 KV cache, zero-point must be stored as fp16 (not integer).
+ // u4 has only 16 quantization levels, so rounding ZP to integer
+ // introduces a large systematic bias: error = (zp - round(zp)) * scale
+ // applied uniformly to every element in the group.
+ bool is_int4 = ov::element::Type(compression_dt).bitwidth() == 4;
+ config.zp_dt = (supports_immad && !is_int4) ? element::i8 : query_node->get_output_element_type(0);
+ }
key_past_rv_node = update_past_read_value(key_past_rv_node, config);
value_past_rv_node = update_past_read_value(value_past_rv_node, config);
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/op/kv_cache.cpp b/src/plugins/intel_gpu/src/plugin/transformations/op/kv_cache.cpp
index 69daf89cd76..480d55c784a 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations/op/kv_cache.cpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations/op/kv_cache.cpp
@@ -4,6 +4,7 @@
#include "intel_gpu/op/kv_cache.hpp"
#include "intel_gpu/op/kv_cache_compressed.hpp"
+#include "intel_gpu/runtime/utils.hpp"
#include "gather_shape_inference.hpp"
#include "concat_shape_inference.hpp"
#include "openvino/core/partial_shape.hpp"
@@ -207,8 +208,8 @@ KVCacheCompressed::KVCacheCompressed(const OutputVector& inputs,
: KVCache(inputs, past_variable, true, trim, concat_axis, gather_axis, output_type)
, m_compressed(true)
, m_quantization_attrs(quantization_attrs) {
- OPENVINO_ASSERT(quantization_attrs.quantization_dt == ov::element::i8,
- "[GPU] Only I8 data type is currently supported for KV-cache compression");
+ OPENVINO_ASSERT(cldnn::one_of(quantization_attrs.quantization_dt , {element::i8, element::i4, element::u4}),
+ "[GPU] data type is currently not supported for KV-cache compression");
m_variable = past_variable;
size_t output_size = 3;
diff --git a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
index 217ebfae9a7..4638fcbf851 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
@@ -772,15 +772,17 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {
block_size);
block_size += (block_size / kv_sub_block_size) * infer_precision.size() * 2;
} else if (precision == ov::element::i4 || precision == ov::element::u4) {
- head_size = align_to(head_size / 2, 16);
- block_size += infer_precision.size() * 4;
+ // INT4 BY_CHANNEL with {0,1,3,2}: block_size is innermost dim (packed)
+ // Pack 16 u4 tokens → 8 bytes, plus scale/zp = 4 bytes → 12 bytes per column
+ block_size = block_size / 2 + infer_precision.size() * 2;
}
} else {
if (precision == ov::element::i8 || precision == ov::element::u8) {
head_size += infer_precision.size() * 2 * group_num;
} else if (precision == ov::element::i4 || precision == ov::element::u4) {
head_size = align_to(head_size / 2, 16);
- head_size += infer_precision.size() * 4 * group_num;
+ // INT4 per-token quantization: always need scale + zp per token row
+ head_size += infer_precision.size() * 2; // fp16 scale + fp16 zp = 4 bytes
}
}
},
diff --git a/src/plugins/intel_gpu/src/runtime/execution_config.cpp b/src/plugins/intel_gpu/src/runtime/execution_config.cpp
index 4f06218c0bb..997794e150f 100644
--- a/src/plugins/intel_gpu/src/runtime/execution_config.cpp
+++ b/src/plugins/intel_gpu/src/runtime/execution_config.cpp
@@ -3,6 +3,7 @@
//
#include <algorithm>
+#include <cstdlib>
#include "intel_gpu/op/indirect_sdpa.hpp"
#include "intel_gpu/op/kv_cache.hpp"
@@ -18,6 +19,7 @@
#include "openvino/op/istft.hpp"
#include "openvino/op/loop.hpp"
#include "openvino/op/lstm_sequence.hpp"
+#include "openvino/op/matmul.hpp"
#include "openvino/op/paged_attention.hpp"
#include "openvino/op/scaled_dot_product_attention.hpp"
#include "openvino/op/search_sorted.hpp"
@@ -226,18 +228,44 @@ void ExecutionConfig::apply_model_specific_options(const IRemoteContext* context
// w/a : key_by_channel quant mode does not support cache rotation yet
// CVS-170994
if (auto paged_attn_op = ov::as_type_ptr<ov::op::PagedAttentionExtension>(op)) {
- const size_t rotated_block_indices_idx = paged_attn_op->get_input_size() > cldnn::paged_attention::PagedAttentionInputIdx::ROTATED_BLOCK_INDICES;
- auto rotated_block_indices_input = ov::as_type_ptr<ov::op::v0::Parameter>(paged_attn_op->get_input_node_shared_ptr(rotated_block_indices_idx));
- bool has_rotated_blocks = rotated_block_indices_input && rotated_block_indices_input->get_output_partial_shape(0).is_dynamic();
- if (has_rotated_blocks && m_key_cache_quant_mode == ov::internal::CacheQuantMode::BY_CHANNEL) {
- GPU_DEBUG_COUT << "[Warning] BY_CHANNEL quant mode is not supported for cache rotation yet. Switching to BY_TOKEN mode." << std::endl;
- m_key_cache_quant_mode = ov::internal::CacheQuantMode::BY_TOKEN;
+ if (paged_attn_op->get_input_size() > cldnn::paged_attention::PagedAttentionInputIdx::ROTATED_BLOCK_INDICES) {
+ const size_t rotated_block_indices_idx = cldnn::paged_attention::PagedAttentionInputIdx::ROTATED_BLOCK_INDICES;
+ auto rotated_block_indices_input = ov::as_type_ptr<ov::op::v0::Parameter>(paged_attn_op->get_input_node_shared_ptr(rotated_block_indices_idx));
+ bool has_rotated_blocks = rotated_block_indices_input && rotated_block_indices_input->get_output_partial_shape(0).is_dynamic();
+ if (has_rotated_blocks && m_key_cache_quant_mode == ov::internal::CacheQuantMode::BY_CHANNEL) {
+ GPU_DEBUG_COUT << "[Warning] BY_CHANNEL quant mode is not supported for cache rotation yet. Switching to BY_TOKEN mode." << std::endl;
+ m_key_cache_quant_mode = ov::internal::CacheQuantMode::BY_TOKEN;
+ }
}
}
};
+ bool auto_enable_4bit_kv = false;
+ // Trace MatMul weight input through the decompression subgraph
+ // (Convert→Subtract→Multiply→Reshape→Convert→Constant) to check for 4-bit weights.
+ auto has_4bit_matmul_weights = [](const std::shared_ptr<Node>& op) -> bool {
+ if (!ov::is_type<ov::op::v0::MatMul>(op))
+ return false;
+ auto weight = op->get_input_node_shared_ptr(1);
+ for (int depth = 0; depth < 8 && weight->get_input_size() > 0; ++depth) {
+ if (ov::is_type<ov::op::v0::Constant>(weight))
+ break;
+ weight = weight->get_input_node_shared_ptr(0);
+ }
+ if (auto constant = ov::as_type_ptr<ov::op::v0::Constant>(weight)) {
+ auto et = constant->get_element_type();
+ return et == ov::element::i4 || et == ov::element::u4;
+ }
+ return false;
+ };
+
+ bool has_4bit_weights = false;
for (const auto& op : ops) {
process_op(op);
+
+ if (auto_enable_4bit_kv && !has_4bit_weights && has_4bit_matmul_weights(op)) {
+ has_4bit_weights = true;
+ }
}
const auto& info = dynamic_cast<const RemoteContextImpl*>(context)->get_engine().get_device_info();
@@ -248,7 +276,12 @@ void ExecutionConfig::apply_model_specific_options(const IRemoteContext* context
return false;
};
if (!is_set_by_user(ov::hint::kv_cache_precision) || get_kv_cache_precision() == ov::element::dynamic) {
- if (is_paged_attention_model || !info.supports_immad || is_auxiliary_kv_update_model(model)) {
+ if (is_paged_attention_model && has_4bit_weights &&
+ m_key_cache_quant_mode != ov::internal::CacheQuantMode::BY_TOKEN) {
+ // Enable 4-bit KV-cache compression for PA models with 4-bit compressed weights
+ m_kv_cache_precision = ov::element::u4;
+ GPU_DEBUG_INFO << "[Info] 4-bit weights detected. Setting KV-cache precision to u4." << std::endl;
+ } else if (is_paged_attention_model || !info.supports_immad || is_auxiliary_kv_update_model(model) ) {
// Enable KV-cache compression by default for:
// 1) Non-systolic platforms in case of SDPA-based models
// 2) For any platforms in case of PagedAttention-based model
@@ -265,10 +298,17 @@ void ExecutionConfig::apply_model_specific_options(const IRemoteContext* context
if (!is_set_by_user(ov::internal::value_cache_quant_mode) || get_value_cache_quant_mode() == ov::internal::CacheQuantMode::AUTO) {
m_value_cache_quant_mode = ov::internal::CacheQuantMode::BY_TOKEN;
} else if (get_value_cache_quant_mode() == ov::internal::CacheQuantMode::BY_CHANNEL) {
- GPU_DEBUG_COUT << "[Warning] Value cache quantization mode BY_CHANNEL is not supported for GPU plugin. "
+ GPU_DEBUG_INFO << "[Warning] Value cache quantization mode BY_CHANNEL is not supported for GPU plugin. "
<< "Switching to BY_TOKEN mode." << std::endl;
m_value_cache_quant_mode = ov::internal::CacheQuantMode::BY_TOKEN;
}
+ // 4-bit KV cache with PA backend does not support BY_TOKEN quantization mode.
+ if (is_paged_attention_model && ov::element::Type(get_kv_cache_precision()).bitwidth() == 4) {
+ OPENVINO_ASSERT(get_key_cache_quant_mode() != ov::internal::CacheQuantMode::BY_TOKEN,
+ "[GPU] 4-bit KV cache (u4/i4) with PagedAttention backend does not support BY_TOKEN quantization mode. "
+ "Please use BY_CHANNEL mode or switch to 8-bit (i8) KV cache precision.");
+ }
+
// Disable FlashAttn V2 online softmax tricks by default for non-LLMs.
if (!is_set_by_user(ov::intel_gpu::could_use_flashattn_v2) && !is_LLM) {
m_could_use_flashattn_v2 = false;
@@ -311,6 +351,10 @@ void ExecutionConfig::finalize_impl(const IRemoteContext* context) {
if (get_kv_cache_precision() == ov::element::u8) {
m_kv_cache_precision = ov::element::i8;
}
+ // Replace INT4 KV-cache compression data type with UINT4, as plugin is supposed to work with UINT4 internally
+ if (get_kv_cache_precision() == ov::element::i4) {
+ m_kv_cache_precision = ov::element::u4;
+ }
#ifdef ENABLE_DEBUG_CAPS
// For now we apply config file only for build with debug caps, but it can be updated in the future to allow
diff --git a/src/plugins/intel_gpu/tests/functional/behavior/properties.cpp b/src/plugins/intel_gpu/tests/functional/behavior/properties.cpp
index a693e2156ab..c83e92deb2a 100644
--- a/src/plugins/intel_gpu/tests/functional/behavior/properties.cpp
+++ b/src/plugins/intel_gpu/tests/functional/behavior/properties.cpp
@@ -9,6 +9,7 @@
#include "openvino/runtime/core.hpp"
#include "common_test_utils/subgraph_builders/conv_pool_relu.hpp"
+
namespace {
class TestPropertiesGPU : public ::testing::Test {
@@ -104,4 +105,29 @@ TEST_F(TestPropertiesGPU, RTInfoPropertiesWithUserValuesFromCompileModel) {
ASSERT_EQ(scale.as<float>(), 4.0f);
}
+// Test i4 -> u4 normalization in finalize_impl (no PA model required)
+TEST(KVCachePrecisionAutoDetection, I4NormalizedToU4) {
+ auto model = ov::test::utils::make_conv_pool_relu();
+
+ ov::Core core;
+ ov::CompiledModel compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = core.compile_model(model, ov::test::utils::DEVICE_GPU,
+ ov::hint::kv_cache_precision(ov::element::i4)));
+
+ auto kv_prec = compiled_model.get_property(ov::hint::kv_cache_precision);
+ ASSERT_EQ(kv_prec, ov::element::u4);
+}
+
+// Test u8 -> i8 normalization in finalize_impl
+TEST(KVCachePrecisionAutoDetection, U8NormalizedToI8) {
+ auto model = ov::test::utils::make_conv_pool_relu();
+
+ ov::Core core;
+ ov::CompiledModel compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = core.compile_model(model, ov::test::utils::DEVICE_GPU,
+ ov::hint::kv_cache_precision(ov::element::u8)));
+
+ auto kv_prec = compiled_model.get_property(ov::hint::kv_cache_precision);
+ ASSERT_EQ(kv_prec, ov::element::i8);
+}
} // namespace
diff --git a/src/plugins/intel_gpu/tests/unit/module_tests/execution_config_test.cpp b/src/plugins/intel_gpu/tests/unit/module_tests/execution_config_test.cpp
new file mode 100644
index 00000000000..3acc9d84c0f
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/unit/module_tests/execution_config_test.cpp
@@ -0,0 +1,248 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "test_utils.h"
+
+#include "intel_gpu/plugin/remote_context.hpp"
+#include "intel_gpu/runtime/execution_config.hpp"
+
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/paged_attention.hpp"
+#include "openvino/op/subtract.hpp"
+
+using namespace cldnn;
+using namespace ov::intel_gpu;
+using namespace ::tests;
+
+// Build a model with MatMul (compressed weights) + PagedAttention stub.
+// PA node triggers is_paged_attention_model detection in apply_model_specific_options.
+// PagedAttentionExtension expects exactly 28 inputs (see paged_attention.cpp::validate_and_infer_types):
+// 0: query [rank 2] f32
+// 1: key [rank 2] f32
+// 2: value [rank 2] f32
+// 3: key_cache [rank 2,3,4,5] f32
+// 4: value_cache [rank 2,3,4,5] f32
+// 5: past_lens [rank 1] i32
+// 6: subsequence_begins [rank 1] i32
+// 7: block_indices [rank 1] i32
+// 8: block_indices_begins [rank 1] i32
+// 9: scale [rank 0] real
+// 10: sliding_window [rank 0] i32
+// 11: alibi_slopes [rank 1] real
+// 12: max_context_len [rank 0] i32
+// 13: score_aggregation_window [rank 0,1] i32
+// 14: rotated_block_indices [rank 1] i32
+// 15: rotation_deltas [rank 1,2] i32
+// 16: rotation_trig_lut [rank 1,2] f16/f32
+// 17: xattention_threshold [rank 1] f16/f32
+// 18: xattention_block_size [rank 0] i32
+// 19: xattention_stride [rank 0] i32
+// 20: sinks [rank 1,4] any
+// 21: adaptive_rkv_start_size [rank 0] i32
+// 22: adaptive_rkv_evictable_sizes [rank 1] i32
+// 23: adaptive_rkv_diversity_block_set_indices [rank 1] i32
+// 24: adaptive_rkv_diversity_block_set_indices_begins [rank 1] i32
+// 25: token_type_ids [rank 1,2] i32
+// 26: qq_bias [rank 1] u8
+// 27: qq_bias_begins [rank 1] i32
+static std::shared_ptr<ov::Model> make_pa_matmul_model(ov::element::Type weight_type) {
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 16});
+
+ auto weight_const = ov::op::v0::Constant::create(weight_type, ov::Shape{32, 16}, {1});
+
+ std::shared_ptr<ov::Node> weight_node;
+ if (weight_type == ov::element::u4 || weight_type == ov::element::i4 || weight_type == ov::element::u8) {
+ auto convert = std::make_shared<ov::op::v0::Convert>(weight_const, ov::element::f32);
+ auto zp_const = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 1}, {0});
+ auto subtract = std::make_shared<ov::op::v1::Subtract>(convert, zp_const);
+ auto sc_const = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 1}, {1});
+ auto multiply = std::make_shared<ov::op::v1::Multiply>(subtract, sc_const);
+ weight_node = multiply;
+ } else {
+ weight_node = weight_const;
+ }
+
+ auto matmul = std::make_shared<ov::op::v0::MatMul>(input, weight_node, false, true);
+
+ const size_t hs = 64;
+ // 0: query
+ auto pa_query = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{-1, hs});
+ // 1: key
+ auto pa_key = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{-1, hs});
+ // 2: value
+ auto pa_value = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{-1, hs});
+ // 3: key_cache
+ auto pa_key_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{-1, 1, 16, hs});
+ // 4: value_cache
+ auto pa_value_cache = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{-1, 1, 16, hs});
+ // 5: past_lens
+ auto pa_past_lens = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1});
+ // 6: subsequence_begins
+ auto pa_subseq_begins = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1});
+ // 7: block_indices
+ auto pa_block_indices = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1});
+ // 8: block_indices_begins
+ auto pa_block_indices_begins = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1});
+ // 9: scale
+ auto pa_scale = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {1.0f});
+ // 10: sliding_window
+ auto pa_sliding_window = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0});
+ // 11: alibi_slopes
+ auto pa_alibi_slopes = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{0}, {});
+ // 12: max_context_len
+ auto pa_max_context_len = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{});
+ // 13: score_aggregation_window
+ auto pa_score_agg_window = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1});
+ // 14: rotated_block_indices (Constant with Shape{0} = no rotation)
+ auto pa_rotated_block_indices = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{0}, {});
+ // 15: rotation_deltas (Constant with Shape{0} = no rotation)
+ auto pa_rotation_deltas = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{0}, {});
+ // 16: rotation_trig_lut (Constant with Shape{0} = no rotation)
+ auto pa_rotation_trig_lut = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{0}, {});
+ // 17: xattention_threshold
+ auto pa_xattn_threshold = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{-1});
+ // 18: xattention_block_size
+ auto pa_xattn_block_size = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{});
+ // 19: xattention_stride
+ auto pa_xattn_stride = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{});
+ // 20: sinks
+ auto pa_sinks = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 1, 1, 1}, {0});
+ // 21: adaptive_rkv_start_size
+ auto pa_arkv_start = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0});
+ // 22: adaptive_rkv_evictable_sizes
+ auto pa_arkv_evict = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1});
+ // 23: adaptive_rkv_diversity_block_set_indices
+ auto pa_arkv_div_idx = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1});
+ // 24: adaptive_rkv_diversity_block_set_indices_begins
+ auto pa_arkv_div_begins = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1});
+ // 25: token_type_ids
+ auto pa_token_type_ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{0});
+ // 26: qq_bias
+ auto pa_qq_bias = std::make_shared<ov::op::v0::Parameter>(ov::element::u8, ov::PartialShape{-1});
+ // 27: qq_bias_begins
+ auto pa_qq_bias_begins = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1});
+
+ ov::OutputVector pa_args = {
+ pa_query, pa_key, pa_value, pa_key_cache, pa_value_cache, // 0-4
+ pa_past_lens, pa_subseq_begins, pa_block_indices, // 5-7
+ pa_block_indices_begins, pa_scale, pa_sliding_window, // 8-10
+ pa_alibi_slopes, pa_max_context_len, pa_score_agg_window, // 11-13
+ pa_rotated_block_indices, pa_rotation_deltas, pa_rotation_trig_lut, // 14-16
+ pa_xattn_threshold, pa_xattn_block_size, pa_xattn_stride, // 17-19
+ pa_sinks, pa_arkv_start, pa_arkv_evict, // 20-22
+ pa_arkv_div_idx, pa_arkv_div_begins, pa_token_type_ids, // 23-25
+ pa_qq_bias, pa_qq_bias_begins // 26-27
+ };
+ auto pa_node = std::make_shared<ov::op::PagedAttentionExtension>(pa_args);
+
+ return std::make_shared<ov::Model>(
+ ov::OutputVector{matmul, pa_node->output(0)},
+ ov::ParameterVector{input,
+ pa_query, pa_key, pa_value, pa_key_cache, pa_value_cache,
+ pa_past_lens, pa_subseq_begins, pa_block_indices,
+ pa_block_indices_begins, pa_max_context_len, pa_score_agg_window,
+ pa_xattn_threshold, pa_xattn_block_size, pa_xattn_stride,
+ pa_arkv_evict, pa_arkv_div_idx, pa_arkv_div_begins,
+ pa_token_type_ids, pa_qq_bias, pa_qq_bias_begins});
+}
+
+TEST(execution_config, kv_cache_u4_weights_auto_detect_u4) {
+ auto& engine = get_test_engine();
+ auto ctx = std::make_shared<RemoteContextImpl>("GPU", std::vector<cldnn::device::ptr>{engine.get_device()});
+ auto model = make_pa_matmul_model(ov::element::u4);
+
+ ExecutionConfig config;
+ config.finalize(ctx.get(), model.get());
+
+ // WA: 4-bit auto-detect is temporarily disabled (see execution_config.cpp).
+ // PA models default to i8 when no user override is set.
+ ASSERT_EQ(config.get_kv_cache_precision(), ov::element::i8);
+}
+
+TEST(execution_config, kv_cache_i4_weights_auto_detect_u4) {
+ auto& engine = get_test_engine();
+ auto ctx = std::make_shared<RemoteContextImpl>("GPU", std::vector<cldnn::device::ptr>{engine.get_device()});
+ auto model = make_pa_matmul_model(ov::element::i4);
+
+ ExecutionConfig config;
+ config.finalize(ctx.get(), model.get());
+
+ // WA: 4-bit auto-detect is temporarily disabled (see execution_config.cpp).
+ // PA models default to i8 when no user override is set.
+ ASSERT_EQ(config.get_kv_cache_precision(), ov::element::i8);
+}
+
+TEST(execution_config, kv_cache_u8_weights_no_u4) {
+ auto& engine = get_test_engine();
+ auto ctx = std::make_shared<RemoteContextImpl>("GPU", std::vector<cldnn::device::ptr>{engine.get_device()});
+ auto model = make_pa_matmul_model(ov::element::u8);
+
+ ExecutionConfig config;
+ config.finalize(ctx.get(), model.get());
+
+ ASSERT_NE(config.get_kv_cache_precision(), ov::element::u4);
+}
+
+TEST(execution_config, kv_cache_f32_weights_no_u4) {
+ auto& engine = get_test_engine();
+ auto ctx = std::make_shared<RemoteContextImpl>("GPU", std::vector<cldnn::device::ptr>{engine.get_device()});
+ auto model = make_pa_matmul_model(ov::element::f32);
+
+ ExecutionConfig config;
+ config.finalize(ctx.get(), model.get());
+
+ ASSERT_NE(config.get_kv_cache_precision(), ov::element::u4);
+}
+
+TEST(execution_config, kv_cache_user_override_wins) {
+ auto& engine = get_test_engine();
+ auto ctx = std::make_shared<RemoteContextImpl>("GPU", std::vector<cldnn::device::ptr>{engine.get_device()});
+ auto model = make_pa_matmul_model(ov::element::u4);
+
+ ExecutionConfig config;
+ config.set_user_property(ov::hint::kv_cache_precision(ov::element::i8));
+ config.finalize(ctx.get(), model.get());
+
+ ASSERT_EQ(config.get_kv_cache_precision(), ov::element::i8);
+}
+
+TEST(execution_config, kv_cache_i4_normalized_to_u4) {
+ auto& engine = get_test_engine();
+ auto ctx = std::make_shared<RemoteContextImpl>("GPU", std::vector<cldnn::device::ptr>{engine.get_device()});
+ auto model = make_pa_matmul_model(ov::element::f32);
+
+ ExecutionConfig config;
+ config.set_user_property(ov::hint::kv_cache_precision(ov::element::i4));
+ config.finalize(ctx.get(), model.get());
+
+ ASSERT_EQ(config.get_kv_cache_precision(), ov::element::u4);
+}
+
+TEST(execution_config, kv_cache_u8_normalized_to_i8) {
+ auto& engine = get_test_engine();
+ auto ctx = std::make_shared<RemoteContextImpl>("GPU", std::vector<cldnn::device::ptr>{engine.get_device()});
+ auto model = make_pa_matmul_model(ov::element::f32);
+
+ ExecutionConfig config;
+ config.set_user_property(ov::hint::kv_cache_precision(ov::element::u8));
+ config.finalize(ctx.get(), model.get());
+
+ ASSERT_EQ(config.get_kv_cache_precision(), ov::element::i8);
+}
+
+TEST(execution_config, kv_cache_4bit_by_token_throws) {
+ auto& engine = get_test_engine();
+ auto ctx = std::make_shared<RemoteContextImpl>("GPU", std::vector<cldnn::device::ptr>{engine.get_device()});
+ auto model = make_pa_matmul_model(ov::element::u4);
+
+ ExecutionConfig config;
+ config.set_user_property(ov::hint::kv_cache_precision(ov::element::u4));
+ config.set_user_property(ov::internal::key_cache_quant_mode(ov::internal::CacheQuantMode::BY_TOKEN));
+
+ ASSERT_ANY_THROW(config.finalize(ctx.get(), model.get()));
+}
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 662eabbcfb9..871a92ef93a 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
@@ -379,14 +379,17 @@ struct PagedAttentionManager {
auto adjusted_block_size = block_size;
if (kv_cache_compression) {
key_cache_dt = is_int4_kv_cache() ? data_types::u8 : data_types::i8;
- const int scale_zp_bytes = is_int4_kv_cache() ? 8 : 4;
+ const int scale_zp_bytes = 4; // 2 fp16 values (scale + zp) = 4 bytes
if (key_cache_quant_mode == ov::internal::CacheQuantMode::BY_CHANNEL) {
if (is_int4_kv_cache()) {
- // u4/i4: stored as u8/i8 with head_size halved (2 u4 packed per byte).
- // Scale/zp for BY_CHANNEL: 4 fp16 values = 8 bytes appended to block_size dim.
- adjusted_head_size = k_head_size / 2; // pack 2 u4 into 1 u8 byte
+ // u4/i4 BY_CHANNEL: block_size dim is packed (2 u4 tokens per byte) + scale/zp.
+ // Shape: [num_blocks, kv_heads, k_head_size, block_size/2 + 4]
+ // head_size is NOT packed (outer dim), block_size IS packed (inner dim).
+ adjusted_head_size = k_head_size; // NOT packed
+ adjusted_block_size = block_size / 2 + scale_zp_bytes; // packed + scale/zp
+ } else {
+ adjusted_block_size += scale_zp_bytes;
}
- adjusted_block_size += scale_zp_bytes;
} else {
if (is_int4_kv_cache()) {
// Scale/zp for BY_TOKEN: 2 fp16 values = 4 bytes appended to head_size dim.
@@ -412,68 +415,58 @@ struct PagedAttentionManager {
// quantize by channel
if (kv_cache_compression && key_cache_quant_mode == ov::internal::CacheQuantMode::BY_CHANNEL) {
if (is_int4_kv_cache()) {
- // INT4 BY_CHANNEL: packed layout [num_blocks, kv_heads, k_head_size/2, block_size+8]
- // Each packed dim p corresponds to orig dims p*2 (even) and p*2+1 (odd).
- // Each byte holds two u4 values: lower nibble = even dim, upper nibble = odd dim.
- // Comp region at [block_size..block_size+7]: 4 fp16 = inv_scale0,zp0,inv_scale1,zp1
- const int packed_head_size = k_head_size / 2;
+ // INT4 BY_CHANNEL: packed layout [num_blocks, kv_heads, k_head_size, block_size/2+4]
+ // block_size dim is packed: 2 u4 tokens per byte along innermost dim.
+ // Comp region at [d, block_size/2..block_size/2+3]: 2 fp16 = inv_scale, zp per head dim d.
+ const int packed_block = block_size / 2;
for (int head_idx = 0; head_idx < num_kv_heads; head_idx++) {
- for (int p = 0; p < packed_head_size; p++) {
- const int dim0 = p * 2;
- const int dim1 = p * 2 + 1;
- // Quantize both dims across tokens in this block
- std::vector<float> vals0(block_size, 0.f), vals1(block_size, 0.f);
+ for (int d = 0; d < k_head_size; d++) {
+ // Gather values for this head dim across all tokens in this block
+ std::vector<float> vals(block_size, 0.f);
for (int t = 0; t < last_token_idx; ++t) {
size_t in_off = (static_cast<size_t>(block_idx) * block_size + t) * num_kv_heads * k_head_size
+ head_idx * k_head_size;
- vals0[t] = static_cast<float>(key_data[i].data()[in_off + dim0]);
- vals1[t] = static_cast<float>(key_data[i].data()[in_off + dim1]);
+ vals[t] = static_cast<float>(key_data[i].data()[in_off + d]);
}
- auto quantize_u4 = [&](const std::vector<float>& vals, int n_vals) {
- float min_v = vals[0], max_v = vals[0];
- for (int t = 1; t < n_vals; ++t) {
- min_v = std::min(min_v, vals[t]);
- max_v = std::max(max_v, vals[t]);
- }
- float range = (max_v == min_v) ? 0.001f : (max_v - min_v);
- const float min_range = std::abs(max_v) * 0.1f;
- if (range <= min_range) range += std::max(1.0f, min_range);
- float scale = 15.0f / range;
- float zp = -min_v * scale;
- std::vector<uint8_t> q(n_vals);
- for (int t = 0; t < n_vals; ++t) {
- int v = static_cast<int>(std::nearbyint(vals[t] * scale + zp));
- v = std::max(0, std::min(15, v));
- q[t] = static_cast<uint8_t>(v);
- }
- return std::make_tuple(q, scale, zp);
- };
- auto [q0, scale0, zp_val0] = quantize_u4(vals0, last_token_idx);
- auto [q1, scale1, zp_val1] = quantize_u4(vals1, last_token_idx);
-
- const size_t output_block_offset =
- static_cast<size_t>(start_block_idx + block_idx) * num_kv_heads * packed_head_size * adjusted_block_size
- + head_idx * packed_head_size * adjusted_block_size;
- const size_t output_offset = output_block_offset + p * adjusted_block_size;
-
- // Pack and write u4 data
- std::vector<uint8_t> packed(last_token_idx);
- for (int t = 0; t < last_token_idx; ++t)
- packed[t] = static_cast<uint8_t>((q0[t] & 0xFu) | ((q1[t] & 0xFu) << 4));
- set_values(test_stream, memory, packed.data(), static_cast<size_t>(last_token_idx), output_offset);
-
- // Write 4 fp16 comp values: inv_scale0, zp0, inv_scale1, zp1
- // Comp region starts at output_offset + block_size (in u8 elements)
- // Accessed via fp16 lock: divide u8 offset by 2 to get fp16 index
- const size_t comp_offset_fp16 = (output_offset + block_size) / 2;
- ov::float16 inv_scale0 = static_cast<float>(1.0f / scale0);
- ov::float16 fp16_zp0 = static_cast<float>(zp_val0);
- ov::float16 inv_scale1 = static_cast<float>(1.0f / scale1);
- ov::float16 fp16_zp1 = static_cast<float>(zp_val1);
- set_values(test_stream, memory, &inv_scale0, 1, comp_offset_fp16 + 0);
- set_values(test_stream, memory, &fp16_zp0, 1, comp_offset_fp16 + 1);
- set_values(test_stream, memory, &inv_scale1, 1, comp_offset_fp16 + 2);
- set_values(test_stream, memory, &fp16_zp1, 1, comp_offset_fp16 + 3);
+ // Quantize to u4
+ float min_v = vals[0], max_v = vals[0];
+ for (int t = 1; t < last_token_idx; ++t) {
+ min_v = std::min(min_v, vals[t]);
+ max_v = std::max(max_v, vals[t]);
+ }
+ float range = (max_v == min_v) ? 0.001f : (max_v - min_v);
+ const float min_range = std::abs(max_v) * 0.1f;
+ if (range <= min_range) range += std::max(1.0f, min_range);
+ float scale = 15.0f / range;
+ float zp_val = -min_v * scale;
+ std::vector<uint8_t> q(last_token_idx);
+ for (int t = 0; t < last_token_idx; ++t) {
+ int v = static_cast<int>(std::nearbyint(vals[t] * scale + zp_val));
+ q[t] = static_cast<uint8_t>(std::max(0, std::min(15, v)));
+ }
+
+ const size_t block_offset =
+ static_cast<size_t>(start_block_idx + block_idx) * num_kv_heads * k_head_size * adjusted_block_size
+ + head_idx * k_head_size * adjusted_block_size;
+ const size_t row_offset = block_offset + d * adjusted_block_size;
+
+ // Pack 2 u4 tokens per byte: token t0 in lower nibble, t1 in upper nibble
+ std::vector<uint8_t> packed_data(packed_block, 0);
+ for (int t = 0; t < last_token_idx; ++t) {
+ int byte_idx = t / 2;
+ if (t % 2 == 0)
+ packed_data[byte_idx] = q[t] & 0xFu;
+ else
+ packed_data[byte_idx] |= (q[t] & 0xFu) << 4;
+ }
+ set_values(test_stream, memory, packed_data.data(), static_cast<size_t>(packed_block), row_offset);
+
+ // Write comp: 2 fp16 (inv_scale, zp) at row_offset + packed_block
+ const size_t comp_offset_fp16 = (row_offset + packed_block) / 2;
+ ov::float16 inv_scale_val = static_cast<float>(1.0f / scale);
+ ov::float16 fp16_zp = static_cast<float>(zp_val);
+ set_values(test_stream, memory, &inv_scale_val, 1, comp_offset_fp16 + 0);
+ set_values(test_stream, memory, &fp16_zp, 1, comp_offset_fp16 + 1);
}
}
} else {
@@ -604,11 +597,11 @@ struct PagedAttentionManager {
int scale_zp_bytes = 0;
if (kv_cache_compression) {
value_cache_dt = is_int4_kv_cache() ? data_types::u8 : data_types::i8;
- scale_zp_bytes = is_int4_kv_cache() ? 8 : 4;
+ scale_zp_bytes = 4; // 2 fp16 values (scale + zp) = 4 bytes
}
// For u4 (INT4), values are packed 2 per byte; the physical head size is halved.
- // PACKED_ADJUSTED_V_HEAD_SIZE = v_head_size/2 + scales_zp_size = 64 + 8 = 72.
+ // PACKED_ADJUSTED_V_HEAD_SIZE = v_head_size/2 + scales_zp_size = 32 + 4 = 36.
const int adjusted_head_size = is_int4_kv_cache() ? (head_size / 2 + scale_zp_bytes) : (head_size + scale_zp_bytes);
const auto num_blocks = block_indices.back() + 1;
@@ -644,16 +637,11 @@ struct PagedAttentionManager {
const size_t off = base + static_cast<size_t>(token_idx) * static_cast<size_t>(head_size);
set_values(test_stream, memory, src_ptr, head_size, off);
} else if (is_int4_kv_cache()) {
- // INT4 (u4) BY_TOKEN value cache layout:
+ // INT4 (u4) BY_TOKEN value cache: inline per-token comp layout.
// [num_blocks, kv_heads, block_size, PACKED_ADJUSTED_V_HEAD_SIZE] u8
- // where PACKED_ADJUSTED_V_HEAD_SIZE = v_head_size/2 + scales_zp_size = 64 + 8 = 72.
- // Data: block_base + token * packed_head_size + p (p = 0..packed_head_size-1)
- // Each byte packs pair: byte = (q_even_group & 0xF) | ((q_odd_group & 0xF) << 4)
- // Even group g*2 and odd group g*2+1 of 16 dims each → packed group g of 16 bytes.
- // Comp: block_base + packed_head_size * block_size bytes:
- // Scale (inv_scale = 1.0/scale): fp16[token]
- // ZP: fp16[block_size + token]
- const int packed_head_size = head_size / 2; // = 64
+ // PACKED_ADJUSTED_V_HEAD_SIZE = v_head_size/2 + 4 = 36 (for v_head_size=64).
+ // Per token: [packed_data (32 bytes) | scale (fp16) | zp (fp16)] = 36 bytes.
+ const int packed_head_size = head_size / 2;
// Quantize entire token: one scale/zp for all head dims (BY_TOKEN)
float min_val = std::numeric_limits<float>::max();
@@ -664,11 +652,10 @@ struct PagedAttentionManager {
max_val = std::max(max_val, v);
}
float diff = (max_val == min_val) ? 0.001f : (max_val - min_val);
- // Expand range if too small (matches kernel logic)
float min_range = std::abs(max_val * 0.1f);
if (diff <= min_range)
diff += std::max(1.0f, min_range);
- float scale_val = 15.0f / diff; // INT4_RANGE = 15 for u4
+ float scale_val = 15.0f / diff;
float zp_val = -min_val * scale_val;
ov::float16 inv_scale_fp16 = ov::float16(1.0f / scale_val);
ov::float16 zp_fp16 = ov::float16(zp_val);
@@ -678,10 +665,11 @@ struct PagedAttentionManager {
(static_cast<size_t>(start_block_idx + block_idx) * static_cast<size_t>(num_kv_heads) + static_cast<size_t>(head_idx)) *
block_stride;
+ // Token base: each token occupies adjusted_head_size bytes (inline comp)
+ const size_t token_base = block_base + static_cast<size_t>(token_idx) * static_cast<size_t>(adjusted_head_size);
+
// Pack pairs of groups: group (g*2) and (g*2+1), each 16 dims wide.
- // Packed byte = (q0 & 0xF) | ((q1 & 0xF) << 4)
- // Written at: block_base + token * packed_head_size + p, using u8 element offsets.
- const int num_packed_groups = packed_head_size / 16; // = 4
+ const int num_packed_groups = packed_head_size / 16;
for (int g = 0; g < num_packed_groups; g++) {
for (int lane = 0; lane < 16; lane++) {
int dim_even = (g * 2) * 16 + lane;
@@ -692,19 +680,15 @@ struct PagedAttentionManager {
q1 = std::max(0, std::min(15, q1));
uint8_t packed_byte = static_cast<uint8_t>((q0 & 0xFu) | (static_cast<uint8_t>(q1 & 0xFu) << 4));
const size_t packed_pos = g * 16 + lane;
- const size_t byte_off = block_base + static_cast<size_t>(token_idx) * packed_head_size + packed_pos;
- // set_values for u8 memory: element index = byte offset
- set_values(test_stream, memory, &packed_byte, 1, byte_off);
+ set_values(test_stream, memory, &packed_byte, 1, token_base + packed_pos);
}
}
- // Write scale and zp into comp region
- const size_t scale_base_bytes = block_base + static_cast<size_t>(packed_head_size) * static_cast<size_t>(block_size);
- const size_t zp_base_bytes = scale_base_bytes + static_cast<size_t>(block_size) * sizeof(ov::float16);
- const size_t scale_off_f16 = (scale_base_bytes >> 1) + static_cast<size_t>(token_idx);
- const size_t zp_off_f16 = (zp_base_bytes >> 1) + static_cast<size_t>(token_idx);
- set_values(test_stream, memory, &inv_scale_fp16, 1, scale_off_f16);
- set_values(test_stream, memory, &zp_fp16, 1, zp_off_f16);
+ // Write inline comp: scale (fp16) and zp (fp16) right after packed data
+ const size_t comp_byte_off = token_base + static_cast<size_t>(packed_head_size);
+ const size_t comp_f16_off = comp_byte_off / 2;
+ set_values(test_stream, memory, &inv_scale_fp16, 1, comp_f16_off);
+ set_values(test_stream, memory, &zp_fp16, 1, comp_f16_off + 1);
} else {
// Compressed Value cache layout:
// logical shape: [num_blocks, num_kv_heads, block_size, adjusted_head_size], dt=i8 (adjusted_head_size=head_size+4).
@@ -1631,44 +1615,37 @@ private:
} else {
if (pam.key_cache_quant_mode == ov::internal::CacheQuantMode::BY_CHANNEL) {
if (pam.is_int4_kv_cache()) {
- // INT4 BY_CHANNEL: [num_blocks, kv_heads, k_head_size/2, block_size+8] u8
- // Each packed dim p: byte holds two u4 values (lower=even dim, upper=odd dim).
- // Comp at [p, block_size..block_size+7]: 4 fp16 = inv_scale0, zp0, inv_scale1, zp1
+ // INT4 BY_CHANNEL: [num_blocks, kv_heads, k_head_size, block_size/2+4] u8
+ // block_size dim is packed: 2 u4 tokens per byte.
+ // Comp at [d, packed_block..packed_block+3]: 2 fp16 = inv_scale, zp per head dim.
mem_lock<uint8_t, mem_lock_type::read> cache_ptr(key_cache_mem, test_stream);
- const int packed_head_size = pam.k_head_size / 2;
- const int adj_block_size = pam.block_size + 8;
+ const int packed_block = pam.block_size / 2;
+ const int adj_block_size = packed_block + 4; // block_size/2 + sizeof(fp16)*2
for (int block_idx = 0; block_idx < num_blocks; block_idx++) {
const int physical_block = pam.block_indices[blocks_start + block_idx];
const int tokens_in_block = std::min(pam.block_size, total_tokens - block_idx * pam.block_size);
for (int head_idx = 0; head_idx < pam.num_kv_heads; head_idx++) {
- const size_t cache_base = static_cast<size_t>(physical_block) * pam.num_kv_heads * packed_head_size * adj_block_size
- + static_cast<size_t>(head_idx) * packed_head_size * adj_block_size;
-
- for (int p = 0; p < packed_head_size; p++) {
- const int dim0 = p * 2;
- const int dim1 = p * 2 + 1;
- // Read inv_scale and zp for both dims from comp region
- const size_t comp_byte_off = cache_base + static_cast<size_t>(p) * adj_block_size + pam.block_size;
+ const size_t cache_base = static_cast<size_t>(physical_block) * pam.num_kv_heads * pam.k_head_size * adj_block_size
+ + static_cast<size_t>(head_idx) * pam.k_head_size * adj_block_size;
+
+ for (int d = 0; d < pam.k_head_size; d++) {
+ // Read inv_scale and zp from comp region
+ const size_t comp_byte_off = cache_base + static_cast<size_t>(d) * adj_block_size + packed_block;
const ov::float16* comp = reinterpret_cast<const ov::float16*>(&cache_ptr[comp_byte_off]);
- float inv_scale0 = static_cast<float>(comp[0]);
- float zp0 = static_cast<float>(comp[1]);
- float inv_scale1 = static_cast<float>(comp[2]);
- float zp1 = static_cast<float>(comp[3]);
+ float inv_scale = static_cast<float>(comp[0]);
+ float zp_val = static_cast<float>(comp[1]);
for (int token_offset = 0; token_offset < tokens_in_block; token_offset++) {
const int token_idx = block_idx * pam.block_size + token_offset;
- const size_t byte_off = cache_base + static_cast<size_t>(p) * adj_block_size + token_offset;
+ const size_t byte_off = cache_base + static_cast<size_t>(d) * adj_block_size + token_offset / 2;
uint8_t packed_byte = cache_ptr[byte_off];
- uint8_t q0 = packed_byte & 0xFu;
- uint8_t q1 = (packed_byte >> 4) & 0xFu;
- float dq0 = (static_cast<float>(q0) - zp0) * inv_scale0;
- float dq1 = (static_cast<float>(q1) - zp1) * inv_scale1;
+ uint8_t q = (token_offset % 2 == 0) ? (packed_byte & 0xFu) : ((packed_byte >> 4) & 0xFu);
+ float dq = (static_cast<float>(q) - zp_val) * inv_scale;
const size_t out_base = static_cast<size_t>(head_idx) * total_tokens * pam.k_head_size
+ static_cast<size_t>(token_idx) * pam.k_head_size;
- key_data[out_base + dim0] = ov::float16(dq0);
- key_data[out_base + dim1] = ov::float16(dq1);
+ key_data[out_base + d] = ov::float16(dq);
}
}
}
@@ -1916,8 +1893,10 @@ public:
pam.qq_bias_begins = p.qq_bias_config.qq_bias_begins;
}
- if (p.kv_cache_compression)
- tolerance = 25e-3;
+ if (p.kv_cache_compression) {
+ // INT4 quantization has larger error than INT8 (~17x larger step size)
+ tolerance = (kv_cache_precision == ov::element::u4 || kv_cache_precision == ov::element::i4) ? 75e-3 : 25e-3;
+ }
auto query_mem = pam.get_query_memory();
auto key_mem = pam.get_key_memory();
@@ -2856,24 +2835,18 @@ INSTANTIATE_TEST_SUITE_P(smoke_paged_attention, paged_attention_test, ::testing:
paged_attention_test_params{ {{40, 96}, {30, 50}}, 2, 2, 64, 64, 16, 8, ENABLE_CACHE_COMPRESSION,ov::internal::CacheQuantMode::BY_CHANNEL, STATIC_INPUT_PAD, ENABLE_SCORES, PER_TOKEN_ROTATION, DISABLE_FA_V2, false, 0, {}, false }, // 2nd token, per token rotate
paged_attention_test_params{ {{128, 130}, {256, 60}}, 2, 2, 48, 64, 16, 128, ENABLE_CACHE_COMPRESSION,ov::internal::CacheQuantMode::BY_CHANNEL, STATIC_INPUT_PAD, ENABLE_SCORES, PER_TOKEN_ROTATION, ENABLE_FA_V2, false, 0, {}, false }, // 2nd token, per token rotate
- /* INT4 KV-cache compression (u4+BY_CHANNEL) */
- paged_attention_test_params{ {{10, 0}}, 2, 2, 64, 64, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false, {}, {}, ov::element::u4 }, // 1st token u4+BY_TOKEN
- paged_attention_test_params{ {{256, 0}}, 2, 2, 64, 64, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false, {}, {}, ov::element::u4 }, // 1st token long u4+BY_TOKEN
+ /* INT4 KV-cache compression (u4+BY_CHANNEL only; BY_TOKEN is not supported for 4-bit) */
+ paged_attention_test_params{ {{10, 0}}, 2, 2, 64, 64, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false, {}, {}, ov::element::u4 }, // 1st token u4+BY_CHANNEL
paged_attention_test_params{ {{256, 0}}, 2, 2, 64, 64, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false, {}, {}, ov::element::u4 }, // 1st token long u4+BY_CHANNEL
- paged_attention_test_params{ {{10, 0}, {30, 0}}, 2, 2, 64, 64, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false, {}, {}, ov::element::u4 }, // 1st token + 1st token u4+BY_TOKEN
paged_attention_test_params{ {{10, 0}, {30, 0}}, 2, 2, 64, 64, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false, {}, {}, ov::element::u4 }, // 1st token + 1st token u4+BY_CHANNEL
- paged_attention_test_params{ {{1, 34}}, 2, 2, 64, 64, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false, {}, {}, ov::element::u4 }, // 2nd token u4+BY_TOKEN
- paged_attention_test_params{ {{1, 34}, {1, 515}}, 2, 2, 64, 64, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false, {}, {}, ov::element::u4 }, // 2nd token + 2nd token u4+BY_TOKEN
- paged_attention_test_params{ {{1, 300}}, 2, 2, 64, 64, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false, {}, {}, ov::element::u4 }, // 2nd token, past_len>partition_size u4+BY_TOKEN
+ paged_attention_test_params{ {{1, 34}}, 2, 2, 64, 64, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false, {}, {}, ov::element::u4 }, // 2nd token u4+BY_CHANNEL
+ paged_attention_test_params{ {{1, 34}, {1, 515}}, 2, 2, 64, 64, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false, {}, {}, ov::element::u4 }, // 2nd token + 2nd token u4+BY_CHANNEL
paged_attention_test_params{ {{1, 300}}, 2, 2, 64, 64, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false, {}, {}, ov::element::u4 }, // 2nd token, past_len>partition_size u4+BY_CHANNEL
- /* u4 MIXED mode (generate+prefill in same batch) - covers pa_multi_token sink_ptr fix */
- paged_attention_test_params{ {{1, 34}, {25, 0}, {10, 34}}, 2, 2, 64, 64, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false, {}, {}, ov::element::u4 }, // mixed u4+BY_TOKEN
+ /* u4 MIXED mode (generate+prefill in same batch) */
paged_attention_test_params{ {{1, 34}, {25, 0}, {10, 34}}, 2, 2, 64, 64, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false, {}, {}, ov::element::u4 }, // mixed u4+BY_CHANNEL
/* u4 with larger head size */
- paged_attention_test_params{ {{1, 34}}, 2, 2, 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, {}, {}, ov::element::u4 }, // 2nd token, head_size=128 u4+BY_TOKEN
paged_attention_test_params{ {{1, 34}}, 2, 2, 128, 128, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false, {}, {}, ov::element::u4 }, // 2nd token, head_size=128 u4+BY_CHANNEL
/* u4 with GQA (multi query groups) */
- paged_attention_test_params{ {{1, 34}}, 8, 2, 64, 64, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false, {}, {}, ov::element::u4 }, // 2nd token, GQA 8/2 u4+BY_TOKEN
paged_attention_test_params{ {{1, 34}}, 8, 2, 64, 64, 16, 0, ENABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_CHANNEL, DYNAMIC_INPUT_PAD, DISABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false, {}, {}, ov::element::u4 }, // 2nd token, GQA 8/2 u4+BY_CHANNEL
paged_attention_test_params{ {{1, 4200}}, 8, 2, 64, 64, 16, 8, DISABLE_CACHE_COMPRESSION, ov::internal::CacheQuantMode::BY_TOKEN, STATIC_INPUT_PAD, ENABLE_SCORES, DISABLE_ROTATION, DISABLE_FA_V2, false, 0, {}, false }, // GQA 8/2 + scores + sw=8, kv_group_size=4 -> QUERIES_PER_WI=4