OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[GPU] SDPA to support per channel quantization KV Cache (#37157)
Yaru Du7ca416dd5ef9
diff --git a/src/common/transformations/include/transformations/op_conversions/group_query_attention_decomposition.hpp b/src/common/transformations/include/transformations/op_conversions/group_query_attention_decomposition.hppindex fa42eada8ae..e1cec9f89a4 100644--- a/src/common/transformations/include/transformations/op_conversions/group_query_attention_decomposition.hpp+++ b/src/common/transformations/include/transformations/op_conversions/group_query_attention_decomposition.hpp@@ -4,6 +4,8 @@#pragma once+#include <optional>+#include "openvino/op/group_query_attention.hpp"#include "openvino/op/shape_of.hpp"#include "openvino/pass/matcher_pass.hpp"@@ -23,6 +25,12 @@ public:GroupQueryAttentionDecomposition();protected:+ struct CompressedKV {+ ov::Output<ov::Node> key;+ ov::Output<ov::Node> value;+ ov::OutputVector quantization_inputs;+ };+ov::OutputVector decompose(std::shared_ptr<ov::op::internal::GroupQueryAttention> node);virtual std::shared_ptr<ov::Node> make_sdpa(const ov::Output<ov::Node>& query,const ov::Output<ov::Node>& key,@@ -30,7 +38,16 @@ protected:const ov::Output<ov::Node>& mask,const ov::Output<ov::Node>& scale,const ov::Output<ov::Node>& sink,- bool is_causal);+ bool is_causal,+ const std::optional<CompressedKV>& compressed_kv);+ virtual std::optional<CompressedKV> prepare_compressed_kv(+ const std::shared_ptr<ov::op::internal::GroupQueryAttention>& node,+ const ov::Output<ov::Node>& key,+ const ov::Output<ov::Node>& value,+ const ov::Output<ov::Node>& key_scale,+ const ov::Output<ov::Node>& value_scale) {+ return std::nullopt;+ }std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<op::v3::ShapeOf>& shape,const std::vector<int>& dims);std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::Node>& node, const std::vector<int>& dims);diff --git a/src/common/transformations/src/transformations/op_conversions/group_query_attention_decomposition.cpp b/src/common/transformations/src/transformations/op_conversions/group_query_attention_decomposition.cppindex 503869e4cc4..e15f43f89e6 100644--- a/src/common/transformations/src/transformations/op_conversions/group_query_attention_decomposition.cpp+++ b/src/common/transformations/src/transformations/op_conversions/group_query_attention_decomposition.cpp@@ -298,9 +298,11 @@ ov::OutputVector ov::pass::GroupQueryAttentionDecomposition::decompose(present_v = V;}+ const auto compressed_kv = prepare_compressed_kv(node, K, V, k_scale, v_scale);+// Dequantize the assembled cache to the compute (float) type for the attention math. Everything downstream// (head broadcast, mask, SDPA) then operates in float exactly as in the non-quantized path.- if (kv_quantized) {+ if (kv_quantized && !compressed_kv) {K = dequantize_kv(K, k_scale, kv_num_heads, kv_cache_bit_width, k_quant_type, T);V = dequantize_kv(V, v_scale, kv_num_heads, kv_cache_bit_width, v_quant_type, T);}@@ -310,7 +312,7 @@ ov::OutputVector ov::pass::GroupQueryAttentionDecomposition::decompose(// Broadcast KV if grouped query attentionconst size_t kv_num_heads_factor = num_heads / kv_num_heads;- if (kv_num_heads_factor > 1) {+ if (kv_num_heads_factor > 1 && !compressed_kv) {const auto kv_shape = register_new_node<v3::ShapeOf>(K);const auto kv_shape_prev_2 = get_dimensions(kv_shape, {0, 1});const auto kv_shape_last_2 = get_dimensions(kv_shape, {2, 3});@@ -377,12 +379,12 @@ ov::OutputVector ov::pass::GroupQueryAttentionDecomposition::decompose(const auto neg_half = register_new_node(v0::Constant::create(T, Shape{}, {-0.5f}));scale_node = register_new_node<v0::Squeeze>(register_new_node<ov::op::v1::Power>(head_size_t, neg_half));}- qga_output = make_sdpa(Q, K, V, mask, scale_node, sink, false);+ qga_output = make_sdpa(Q, K, V, mask, scale_node, sink, false, compressed_kv);} else if (scale != 0.0f) {auto scale_node = register_new_node(v0::Constant::create(T, Shape{}, {scale}));- qga_output = make_sdpa(Q, K, V, mask, scale_node, {}, false);+ qga_output = make_sdpa(Q, K, V, mask, scale_node, {}, false, compressed_kv);} else {- qga_output = make_sdpa(Q, K, V, mask, {}, {}, !mask);+ qga_output = make_sdpa(Q, K, V, mask, {}, {}, !mask, compressed_kv);}// transpose the result from (batch_size, num_heads, sequence_length, head_size)@@ -401,7 +403,8 @@ std::shared_ptr<ov::Node> ov::pass::GroupQueryAttentionDecomposition::make_sdpa(const ov::Output<ov::Node>& mask,const ov::Output<ov::Node>& scale,const ov::Output<ov::Node>& sink,- bool is_causal) {+ bool is_causal,+ const std::optional<CompressedKV>&) {if (sink.get_node()) {return register_new_node<v13::ScaledDotProductAttention>(query, key, value, mask, scale, sink, is_causal);}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.cppindex e144d10f927..53bc68127ce 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@@ -78,8 +78,13 @@ size_t get_beam_table_id(const std::shared_ptr<const scaled_dot_product_attentio// 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) {+ if (params.is_type<scaled_dot_product_attention>()) {+ const auto& desc = params.typed_desc<scaled_dot_product_attention>();+ return desc->is_kv_compressed && data_type_traits::is_i4_u4(desc->quantization_attributes.quantization_dt);+ }+const auto kv_cache_dt = params.get_program().get_config().get_kv_cache_precision();- return ov::element::Type(kv_cache_dt).bitwidth() == 4;+ return data_type_traits::is_i4_u4(kv_cache_dt);}std::pair<int64_t, int64_t> SDPABase::get_gqa_params(const kernel_impl_params& params) const {@@ -235,6 +240,7 @@ JitConstants SDPABase::get_jit_constants(const kernel_impl_params& params) const}jit.make("IS_KV_COMPRESSED", desc->is_kv_compressed);jit.make("IS_INT4_COMPRESSED", desc->is_kv_compressed && SDPABase::is_int4_kv_cache(params));+ jit.make("IS_INT4_SIGNED", desc->is_kv_compressed && desc->quantization_attributes.quantization_dt == ov::element::i4);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;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.cppindex f992fe49dfc..59ab8b914bf 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@@ -166,6 +166,11 @@ inline size_t micro_get_head_size(const kernel_impl_params& params, size_t qkv_i}} else {const auto desc = params.typed_desc<scaled_dot_product_attention>();+ if (qkv_idx != 0 && desc->is_kv_compressed && data_type_traits::is_i4_u4(desc->quantization_attributes.quantization_dt)) {+ const auto& order = qkv_idx == 1 ? desc->input_k_transpose_order : desc->input_v_transpose_order;+ return get_head_size(params.input_layouts[qkv_idx], extend_order_in_num_heads_dim(order)) * 2;+ }+switch (qkv_idx) {case 0: {const auto head_size = get_head_size(params.input_layouts[0], extend_order_in_num_heads_dim(desc->input_q_transpose_order));@@ -532,13 +537,14 @@ sdpa_config_t* choose_config_xehpg(int head_size, int seq, bool thin_q, bool qua}if (quantized) {if (thin_q) {- if (seq <= 1) {- return &xehpg_q_h128_2nd;- }- if (seq <= 96) {+ // xehpg_q_h128_2nd (unroll_m_kq = 32) does not fit the Xe HPG register budget once K+ // is integer-typed: the KQ strategy is rejected, micro-kernel generation throws, and+ // SDPA silently falls back to sdpa_opt - which cannot index per-channel scales at+ // all. xehpg_h128_2nd differs only in unroll_m_kq (8) and does fit.+ if (seq <= 96 && seq > 1) {return &xehpg_q_h128_s96_2nd;}- return &xehpg_q_h128_2nd;+ return &xehpg_h128_2nd;}if (seq <= 64) {return &xehpg_q_h128_s64;@@ -1104,6 +1110,52 @@ KernelData SDPAMicroGenerator::get_kernel_data(const kernel_impl_params& params)[[maybe_unused]] const bool vs_common_scales = false;[[maybe_unused]] const bool vs_common_zp = false;+// Per-channel key scales ([b, heads, 1, head_size]) vary along the KQ GEMM's *reduction* axis, so+// gemmstone has to broadcast them across the whole M extent. Describing that through 2D+// A-quantization is both fragile (the group descriptor has to cover every key tile) and expensive:+// with a zero point added on top, the register budget of the pinned KQ strategy is exceeded and+// micro-kernel generation fails outright, silently dropping SDPA onto sdpa_opt. Fold the scales+// into Q instead, which is exact and needs no quantization parameters in the GEMM at all:+// sum_d K_int[m,d] * kscale[d] * Q[n,d] == sum_d K_int[m,d] * (kscale[d] * Q[n,d])+// K then becomes a plain int -> f16 upconvert; see FOLD_KEY_SCALES_INTO_Q in sdpa_micro.cl.+//+// For asymmetric quantization the key zero point is dropped along with the scale instead of being+// applied: -sum_d zp[d] * kscale[d] * Q[n,d] does not depend on the key m, so it shifts every logit+// of a query by the same constant, and softmax over the keys is invariant to such a shift (the+// attention scale and the mask preserve that). A sink logit, however, joins the softmax denominator+// unshifted, so with sinks the shift would survive - don't fold then.+inline bool micro_fold_key_scales_into_q(const kernel_impl_params& params, bool is_kv_compressed, bool use_asymmetric_quantization) {+ if (params.is_type<paged_attention>() || !is_kv_compressed || kq_common_scales)+ return false;+ if (use_asymmetric_quantization && params.typed_desc<scaled_dot_product_attention>()->has_sink_input)+ return false;+ // Per-channel scales have seq == 1 and one entry per channel; per-token scales have seq > 1.+ const auto desc = params.typed_desc<scaled_dot_product_attention>();+ const auto scale_idx = get_data_inputs_num(*desc);+ const auto& ps = params.input_layouts[scale_idx].get_partial_shape();+ return ps[2].get_length() == 1 && ps[3].get_length() > 1;+}++// Per-channel value scales/zero points ([b, heads, 1, head_size]) are constant along the VS GEMM's+// *reduction* axis (the keys), so nothing forces them to be applied inside the k-loop. With+// acc[d,n] = sum_t V_int[d,t] * S[t,n] and l[n] = sum_t S[t,n]+// (l is the softmax denominator the kernel already accumulates in SLM), the dequantized output is+// out[d,n] = vscale[d] * (acc[d,n] / l[n] - vzp[d])+// exactly, for any number of k-chunks: both terms are linear in the chunk contributions, and the+// running-maximum correction rescales acc and l by the same per-query factor. Applying the scales+// once in the epilogue removes the per-element dequantization from the VS k-loop, the scale/zero+// point loads and prefetches, and gemmstone's ABOffset::Calc column-sum bookkeeping. It is also+// slightly more accurate: V enters the GEMM as an exactly representable integer instead of a+// dequantized value rounded to f16. See FOLD_VAL_SCALES_INTO_OUTPUT in sdpa_micro.cl.+inline bool micro_fold_value_scales_into_output(const kernel_impl_params& params, bool is_kv_compressed) {+ if (params.is_type<paged_attention>() || !is_kv_compressed || vs_common_scales || vs_common_zp)+ return false;+ const auto desc = params.typed_desc<scaled_dot_product_attention>();+ const auto scale_idx = get_data_inputs_num(*desc) + 1;+ const auto& ps = params.input_layouts[scale_idx].get_partial_shape();+ return ps[2].get_length() == 1 && ps[3].get_length() > 1;+}+JitConstants SDPAMicroGenerator::get_jit_constants(const kernel_impl_params& params, const micro::Package& gemm_kq, const micro::Package& gemm_vs) const {auto jit = make_base_jit_constants(params);sdpa_configuration config;@@ -1262,8 +1314,32 @@ JitConstants SDPAMicroGenerator::get_jit_constants(const kernel_impl_params& parint vs_scale_mask = (static_cast<int>(config.is_kv_compressed) << 1) | static_cast<int>(vs_common_scales);jit.make("KEY_SCALES", kq_scale_mask);jit.make("VAL_SCALES", vs_scale_mask);- jit.make("KEY_GROUP_SIZE", head_size);- jit.make("VAL_GROUP_SIZE", head_size);++ // Derive group size from the scale tensor shape.+ // Scale shape is [batch, heads, seq, num_groups], where num_groups = head_size / group_size.+ // If seq == 1, the scale is broadcast across all tokens (per-channel quantization).+ const auto key_scale_seq = key_cache_comp_scale.get_partial_shape()[2].get_length();+ const auto key_scale_groups = key_cache_comp_scale.get_partial_shape()[3].get_length();+ const auto key_group_size = head_size / key_scale_groups;+ const auto val_scale_seq = value_cache_comp_scale.get_partial_shape()[2].get_length();+ const auto val_scale_groups = value_cache_comp_scale.get_partial_shape()[3].get_length();+ const auto val_group_size = head_size / val_scale_groups;+ jit.make("KEY_GROUP_SIZE", key_group_size);+ jit.make("VAL_GROUP_SIZE", val_group_size);+ const bool is_key_by_channel = (key_scale_seq == 1 && key_scale_groups > 1);+ const bool is_value_by_channel = (val_scale_seq == 1 && val_scale_groups > 1);+ if (is_key_by_channel)+ jit.make("IS_KEY_BY_CHANNEL", 1);+ if (is_value_by_channel)+ jit.make("IS_VALUE_BY_CHANNEL", 1);+ // Per-channel key scales are folded into Q rather than applied to K in the KQ micro-kernel,+ // and the key zero point is dropped with them; see micro_fold_key_scales_into_q().+ if (is_key_by_channel && micro_fold_key_scales_into_q(params, config.is_kv_compressed, use_asymmetric_quantization))+ jit.make("FOLD_KEY_SCALES_INTO_Q", 1);+ // Per-channel value scales/zero points are applied once in the epilogue rather than to every+ // V element inside the VS k-loop; see micro_fold_value_scales_into_output().+ if (is_value_by_channel && micro_fold_value_scales_into_output(params, config.is_kv_compressed))+ jit.make("FOLD_VAL_SCALES_INTO_OUTPUT", 1);jit.add(make_layout_jit_constants("KEY_SCALE", key_cache_comp_scale, params.in_port_to_shape_info_offset.at(data_inputs_num)));jit.add(make_layout_jit_constants("VAL_SCALE", value_cache_comp_scale, params.in_port_to_shape_info_offset.at(data_inputs_num + 1)));@@ -1326,8 +1402,14 @@ JitConstants SDPAMicroGenerator::get_jit_constants(const kernel_impl_params& parjit.make("ADJUSTED_PAGED_ATTENTION_BLOCK_SIZE", config.paged_attention_block_size);}- jit.make("KEY_ELEMENTS_PER_BYTE", elems_per_byte(params.input_layouts[1].data_type));- jit.make("VAL_ELEMENTS_PER_BYTE", elems_per_byte(params.input_layouts[2].data_type));+ const auto compressed_dt = !config.is_paged_attention && config.is_kv_compressed+ ? params.typed_desc<scaled_dot_product_attention>()->quantization_attributes.quantization_dt+ : ov::element::dynamic;+ const bool is_byte_packed_int4 = !config.is_paged_attention && data_type_traits::is_i4_u4(compressed_dt);+ if (is_byte_packed_int4)+ jit.make("IS_INT4_KV_CACHE", 1);+ jit.make("KEY_ELEMENTS_PER_BYTE", elems_per_byte(compressed_dt.is_dynamic() ? ov::element::Type(K.data_type) : ov::element::Type(compressed_dt)));+ jit.make("VAL_ELEMENTS_PER_BYTE", elems_per_byte(compressed_dt.is_dynamic() ? ov::element::Type(V.data_type) : ov::element::Type(compressed_dt)));int tile_k = gemm_kq.getSetting("wg_tile_m");int tile_q = gemm_kq.getSetting("wg_tile_n");@@ -1380,9 +1462,10 @@ JitConstants SDPAMicroGenerator::get_jit_constants(const kernel_impl_params& parif (device_info.arch >= gpu_arch::xe_hpc) {jit.make("PREFETCH_MASK", 1);- jit.make("PREFETCH_K0", (config.is_paged_attention && !m_is_prefill) ? 0 : 1);- jit.make("PREFETCH_K", (config.is_paged_attention && !m_is_prefill) ? 0 : 1);- jit.make("PREFETCH_V", (config.is_paged_attention && !m_is_prefill) ? 0 : 1);+ const bool enable_kv_prefetch = (!config.is_paged_attention || m_is_prefill) && !is_byte_packed_int4;+ jit.make("PREFETCH_K0", enable_kv_prefetch);+ jit.make("PREFETCH_K", enable_kv_prefetch);+ jit.make("PREFETCH_V", enable_kv_prefetch);bool no_rem = d_full && v_full && k_full;jit.make("PREFETCH_REMAINDER", !no_rem);jit.make("PREFETCH_D_MAX", std::min<int64_t>(d_max, 64));@@ -1720,12 +1803,12 @@ 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;+ // INT4 cache is byte-backed, so use its logical precision rather than the physical layout type.+ const auto kv_cache_precision = is_paged_attention ? params.get_program().get_config().get_kv_cache_precision()+ : params.typed_desc<scaled_dot_product_attention>()->quantization_attributes.quantization_dt;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) {+ if (is_int4_kv_cache && (!is_paged_attention || !is_prefill)) {problem.Ta_ext = convert_type(kv_cache_precision);}@@ -1781,7 +1864,14 @@ void SDPAMicroGenerator::init_microkernels(const kernel_impl_params& params,opts_kq.offsetA = true;} else {const auto key_cache_id = micro_get_key_cache_id(params);- if (configuration.is_kv_compressed && !kq_common_scales) {++ // Per-channel key scales are folded into Q instead of being applied to K, and for asymmetric+ // quantization the key zero point is dropped with them; see micro_fold_key_scales_into_q(),+ // which get_jit_constants() consults as well so the two agree on whether the micro-kernel+ // takes quantization arguments.+ const bool fold_key_scales_into_q = micro_fold_key_scales_into_q(params, configuration.is_kv_compressed, use_asymmetric_quantization);++ if (configuration.is_kv_compressed && !kq_common_scales && !fold_key_scales_into_q) {const auto& key_cache_comp_scale = params.input_layouts[key_cache_id];const auto scale_dt = convert_type(key_cache_comp_scale.data_type);problem_kq.Ta_scale = scale_dt;@@ -1791,7 +1881,7 @@ void SDPAMicroGenerator::init_microkernels(const kernel_impl_params& params,GPU_DEBUG_TRACE_DETAIL << "kq: key_cache_id = " << key_cache_id << std::endl;}- if (configuration.is_kv_compressed && use_asymmetric_quantization) {+ if (configuration.is_kv_compressed && use_asymmetric_quantization && !fold_key_scales_into_q) {const auto& key_cache_comp_zp = params.input_layouts[key_cache_id + 2];const auto zp_dt = convert_type(key_cache_comp_zp.data_type);problem_kq.Tao = zp_dt;@@ -1801,18 +1891,23 @@ void SDPAMicroGenerator::init_microkernels(const kernel_impl_params& params,problem_kq.aOffset = micro::ABOffset::Calc;}- if (configuration.is_kv_compressed) {+ if (configuration.is_kv_compressed && !fold_key_scales_into_q) {+ const auto& key_cache_comp_scale_layout = params.input_layouts[key_cache_id];+ const auto key_scale_groups = key_cache_comp_scale_layout.get_partial_shape()[3].get_length();+ const auto key_group_size = k_head_size / key_scale_groups;+ // KQ GEMM: A=K[M=seq_k, K=head_size]. Per-token scales only (the per-channel case is+ // folded into Q above): each token has its own scale, so aqGroupM = 1.problem_kq.aqGroupM = 1;- problem_kq.aqGroupK = (kq_common_scales || kq_common_zp) ? 1 : static_cast<int>(k_head_size);+ problem_kq.aqGroupK = (kq_common_scales || kq_common_zp) ? 1 : static_cast<int>(key_group_size);}- opts_kq.scaleA = configuration.is_kv_compressed && !kq_common_scales;- opts_kq.offsetA = configuration.is_kv_compressed && use_asymmetric_quantization;+ opts_kq.scaleA = configuration.is_kv_compressed && !kq_common_scales && !fold_key_scales_into_q;+ opts_kq.offsetA = configuration.is_kv_compressed && use_asymmetric_quantization && !fold_key_scales_into_q;}problem_kq.B.layout = micro::MatrixLayout::Pr;problem_kq.C.layout = micro::MatrixLayout::T;- problem_kq.A.setAlignment(micro::alignment_for_ld(static_cast<int>(k_head_size * problem.Ta)));+ problem_kq.A.setAlignment(micro::alignment_for_ld(static_cast<int>(k_head_size * problem_kq.Ta_ext)));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);@@ -1893,8 +1988,7 @@ 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) {+ if (is_int4_kv_cache && (!is_paged_attention || !is_prefill)) {problem_vs.Ta_ext = convert_type(kv_cache_precision);}const bool transpose_v = micro_is_v_transposed(params);@@ -1928,7 +2022,14 @@ void SDPAMicroGenerator::init_microkernels(const kernel_impl_params& params,opts_vs.offsetA = true;} else {const auto value_cache_id = micro_get_value_cache_id(params);- if (configuration.is_kv_compressed && !vs_common_scales) {++ // Per-channel value scales and zero points are applied in the epilogue instead of inside the+ // VS GEMM, which then needs no quantization arguments at all; see+ // micro_fold_value_scales_into_output(), which get_jit_constants() consults as well so the+ // two agree on the micro-kernel's signature.+ const bool fold_value_scales = micro_fold_value_scales_into_output(params, configuration.is_kv_compressed);++ if (configuration.is_kv_compressed && !vs_common_scales && !fold_value_scales) {const auto& value_cache_comp_scale = params.input_layouts[value_cache_id];auto scale_dt = convert_type(value_cache_comp_scale.data_type);problem_vs.Ta_scale = scale_dt;@@ -1938,7 +2039,7 @@ void SDPAMicroGenerator::init_microkernels(const kernel_impl_params& params,GPU_DEBUG_TRACE_DETAIL << "vs: value_cache_id = " << value_cache_id << std::endl;}- if (configuration.is_kv_compressed && use_asymmetric_quantization) {+ if (configuration.is_kv_compressed && use_asymmetric_quantization && !fold_value_scales) {const auto& value_cache_comp_zp = params.input_layouts[value_cache_id + 2];auto zp_dt = convert_type(value_cache_comp_zp.data_type);problem_vs.Tao = zp_dt;@@ -1948,13 +2049,27 @@ void SDPAMicroGenerator::init_microkernels(const kernel_impl_params& params,problem_vs.aOffset = micro::ABOffset::Calc;}- if (configuration.is_kv_compressed) {- problem_vs.aqGroupM = (vs_common_scales || vs_common_zp) ? 1 : static_cast<int>(micro::rnd_up_pow2(v_head_size));- problem_vs.aqGroupK = 1;+ if (configuration.is_kv_compressed && !fold_value_scales) {+ const auto& value_cache_comp_scale_layout = params.input_layouts[value_cache_id];+ const auto val_scale_seq = value_cache_comp_scale_layout.get_partial_shape()[2].get_length();+ const auto val_scale_groups = value_cache_comp_scale_layout.get_partial_shape()[3].get_length();+ const auto val_group_size = v_head_size / val_scale_groups;+ // VS GEMM: A=V[M=head_size, K=seq_k]+ // Per-channel broadcast (seq=1): each head_size row has own scale, all tokens share it+ // -> aqGroupM = group_size, aqGroupK >= k_chunk (bounded by wg_tile_m)+ // Per-token (seq>1): all head_size share one scale per token+ // -> aqGroupM = head_size (don't vary per head_size), aqGroupK = 1 (vary per token)+ if (val_scale_seq == 1) {+ problem_vs.aqGroupM = (vs_common_scales || vs_common_zp) ? 1 : static_cast<int>(val_group_size);+ problem_vs.aqGroupK = config->unroll_m_kq * config->wg_m_kq;+ } else {+ problem_vs.aqGroupM = (vs_common_scales || vs_common_zp) ? 1 : static_cast<int>(micro::rnd_up_pow2(v_head_size));+ problem_vs.aqGroupK = 1;+ }}- opts_vs.scaleA = configuration.is_kv_compressed && !vs_common_scales;- opts_vs.offsetA = configuration.is_kv_compressed && use_asymmetric_quantization;+ opts_vs.scaleA = configuration.is_kv_compressed && !vs_common_scales && !fold_value_scales;+ opts_vs.offsetA = configuration.is_kv_compressed && use_asymmetric_quantization && !fold_value_scales;}problem_vs.B.layout = micro::MatrixLayout::Pr;@@ -1966,7 +2081,7 @@ void SDPAMicroGenerator::init_microkernels(const kernel_impl_params& params,} else if (transpose_v) {problem_vs.A.setAlignment(problem_vs.Ta_ext.size());} else {- problem_vs.A.setAlignment(micro::alignment_for_ld(static_cast<int>(v_head_size * problem.Ta)));+ problem_vs.A.setAlignment(micro::alignment_for_ld(static_cast<int>(v_head_size * problem_vs.Ta_ext)));}problem_vs.B.setAlignment(64); // S is packed in SLMdiff --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.cppindex 369c1f56e1b..1be10207b4d 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@@ -26,6 +26,21 @@ using namespace cldnn;namespace ov::intel_gpu::ocl {+bool SDPAOpt::has_per_channel_compressed_kv(const kernel_impl_params& params) {+ const auto desc = params.typed_desc<scaled_dot_product_attention>();+ if (!desc->is_kv_compressed) {+ return false;+ }++ const auto data_inputs_num = get_data_inputs_num(*desc);+ const auto is_per_channel_scale = [¶ms](size_t scale_idx) {+ const auto& shape = params.input_layouts[scale_idx].get_partial_shape();+ return shape.rank().is_static() && shape.rank().get_length() == 4 && shape[2].is_static() && shape[2].get_length() == 1 && shape[3].is_static() &&+ shape[3].get_length() > 1;+ };+ return is_per_channel_scale(data_inputs_num) || is_per_channel_scale(data_inputs_num + 1);+}+class SDPAOptImpl : public SDPAImplBase {public:DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::ocl::SDPAOptImpl)@@ -80,6 +95,7 @@ public:// Sometimes micro kernel will fail due to "Insufficient registers in requested bundle",// In this case, fallback to opt kernel.if (!has_stage(regular_micro_multi_tokens)) {+ OPENVINO_ASSERT(!SDPAOpt::has_per_channel_compressed_kv(params), "Per-channel compressed KV requires the micro SDPA kernel");GPU_DEBUG_TRACE_DETAIL << "fail to create micro kernel, fallback to regular_multi_tokens for prefill \n";add_stage(regular_multi_tokens, params);}@@ -117,15 +133,13 @@ public:kernel_dump_info.clear_entries();#ifdef ENABLE_ONEDNN_FOR_GPU- // Check if INT4 KV cache is in use (micro kernel doesn't support INT4 for non-PA SDPA)- // Only apply this check when the SDPA node actually uses compressed KV cache (i8/u8/i4/u4 K/V inputs).- // Vision Encoder SDPA nodes have f16 K/V inputs and should not be affected by the global config.const auto k_dt = new_params.input_layouts[1].data_type;const bool is_kv_compressed = data_type_traits::is_i8_u8(k_dt) || data_type_traits::is_i4_u4(k_dt);const auto kv_cache_dt = new_params.get_program().get_config().get_kv_cache_precision();const bool is_int4_kv = is_kv_compressed && ov::element::Type(kv_cache_dt).bitwidth() == 4;+ const bool is_per_channel_kv = SDPAOpt::has_per_channel_compressed_kv(new_params);- if (has_stage(regular_micro_multi_tokens) && is_prefill && !is_indirect && !is_int4_kv) {+ if (has_stage(regular_micro_multi_tokens) && is_prefill && !is_indirect && (!is_int4_kv || is_per_channel_kv)) {GPU_DEBUG_TRACE_DETAIL << "execute regular_micro_multi_tokens for prefill \n";return execute_stage(events, instance, regular_micro_multi_tokens);}@@ -139,7 +153,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 && !is_int4_kv) {+ if (has_stage(regular_micro_single_token) && !is_indirect) {return execute_stage(events, instance, regular_micro_single_token);}#endif@@ -265,4 +279,4 @@ std::unique_ptr<primitive_impl> SDPAOpt::create_impl(const program_node& node, c} // namespace ov::intel_gpu::oclBIND_BINARY_BUFFER_WITH_TYPE(cldnn::scaled_dot_product_attention)-BIND_BINARY_BUFFER_WITH_TYPE(ov::intel_gpu::ocl::SDPAOptImpl)\ No newline at end of file+BIND_BINARY_BUFFER_WITH_TYPE(ov::intel_gpu::ocl::SDPAOptImpl)diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_opt.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_opt.hppindex 9ddb008b7f0..8d997c253e8 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_opt.hpp+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_opt.hpp@@ -29,6 +29,7 @@ struct SDPAOpt : public ImplementationManager {explicit SDPAOpt(shape_types shape_type, ValidateFunc vf = nullptr) : ImplementationManager(impl_types::ocl, shape_type, std::move(vf)) {}[[nodiscard]] std::unique_ptr<primitive_impl> create_impl(const program_node& node, const RuntimeParams& params) const override;[[nodiscard]] static bool supports_micro_sdpa(const kernel_impl_params& params);+ [[nodiscard]] static bool has_per_channel_compressed_kv(const kernel_impl_params& params);[[nodiscard]] bool validate_impl(const program_node& node) const override {const auto desc = node.as<scaled_dot_product_attention>().get_primitive();const auto& supported_precisions = ov::intel_gpu::op::SDPA::get_supported_precisions();@@ -73,6 +74,9 @@ struct SDPAOpt : public ImplementationManager {const bool combine_scales_and_zp = desc->quantization_attributes.output_storage_type != ov::op::internal::DynamicQuantize::OutputStorageType::Planar;auto p = node.get_kernel_impl_params();+ if (has_per_channel_compressed_kv(*p) && !supports_micro_sdpa(*p)) {+ return false;+ }return !use_asymmetric_quantization || combine_scales_and_zp || supports_micro_sdpa(*p);}};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.clindex 2713c8efec0..1ba457b83b6 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@@ -123,6 +123,20 @@ DECLARE_2D_TILE_HREDUCE(a_tile_type, SUBGROUP_SIZE, ugemm_vs_c_type_block0,ugemm_vs_c_type_nblock1, a_scale_tile_type, SUBGROUP_SIZE,ugemm_vs_sg_tile_n, 1, 1, 1)+#if FOLD_VAL_SCALES_INTO_OUTPUT+/* Per-channel value scales/zero points apply to the A tile's rows (head size), unlike the softmax+ * denominator, which applies to its columns (queries) -- hence vbroadcast rather than hbroadcast.+ * Round the tile up to one element per lane; the extra rows are never touched. */+#define v_scale_tile_m MAX(ugemm_vs_sg_tile_m, SUBGROUP_SIZE)++DECLARE_2D_TILE(v_scale_tile_type, float, SUBGROUP_SIZE, v_scale_tile_m, 1, 1, 1)++DECLARE_2D_TILE_VREDUCE(a_tile_type, SUBGROUP_SIZE, ugemm_vs_c_type_block0,+ ugemm_vs_c_type_block1, ugemm_vs_c_type_nblock0,+ ugemm_vs_c_type_nblock1, v_scale_tile_type, SUBGROUP_SIZE,+ v_scale_tile_m, 1, 1, 1)+#endif+#if ugemm_kq_wg_tile_n == ugemm_vs_wg_tile_n \&& (ugemm_kq_sg_tile_n % ugemm_vs_sg_tile_n) == 0DECLARE_2D_TILE_RSELECT(a_scale_tile_type, SUBGROUP_SIZE, ugemm_vs_sg_tile_n, 1,@@ -208,9 +222,13 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG#endif#ifdef KV_COMPRESSED, const global KEY_ATTR_SCALES_DATA_T *K_scales+#if KEY_ZERO_POINTS, const global KEY_ATTR_ZP_DATA_T *K_zp+#endif, const global VAL_ATTR_SCALES_DATA_T *V_scales+#if VAL_ZERO_POINTS, const global VAL_ATTR_ZP_DATA_T *V_zp+#endif#endif) {#if IS_PAGED_ATTENTION@@ -357,19 +375,29 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG#endif#endif#else- uint ldk = TRANSPOSE_K ? KEY_S3 : KEY_S2;+ /* Layout pitches are physical KEY/VAL elements (bytes for packed INT4), while the+ micro-kernel leading dimensions use logical elements (nibbles for i4/u4). */+ uint ldk = (TRANSPOSE_K ? KEY_S3 : KEY_S2) * KEY_ELEMENTS_PER_BYTE;uint ldq = QRY_S2;- uint ldv = TRANSPOSE_V ? VAL_S3 : VAL_S2;+ uint ldv = TRANSPOSE_V ? VAL_S3 * VAL_ELEMENTS_PER_BYTE : VAL_S2 * VAL_ELEMENTS_PER_BYTE;uint lda = DST_S2;#endif#if KEY_SCALES || KEY_ZERO_POINTS- uint ldkq = DIV_UP(d, KEY_GROUP_SIZE);uint num_key_groups = d / KEY_GROUP_SIZE;+ #if IS_KEY_BY_CHANNEL+ uint ldkq = 1;+ #else+ uint ldkq = num_key_groups;+ #endif#endif#if VAL_SCALES || VAL_ZERO_POINTS- uint ldvq = DIV_UP(d, VAL_GROUP_SIZE);uint num_val_groups = d / VAL_GROUP_SIZE;+ #if IS_VALUE_BY_CHANNEL+ uint ldvq = 1;+ #else+ uint ldvq = num_val_groups;+ #endif#endif/* Subgroup IDs for each GEMM */@@ -436,9 +464,10 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG+ b0_kv * HEAD_SIZE + INPUT2_PAD_BEFORE_FEATURE_NUM;#endif#else- K += (KEY_OFF(b1, b0_kv, 0, 0) + INPUT1_OFFSET) / KEY_ELEMENTS_PER_BYTE;+ /* KEY_OFF/VAL_OFF and offsets address the physical byte-backed layouts. */+ K += KEY_OFF(b1, b0_kv, 0, 0) + INPUT1_OFFSET;Q += (QRY_OFF(b1, b0, 0, 0) + INPUT0_OFFSET);- V += (VAL_OFF(b1, b0_kv, 0, 0) + INPUT2_OFFSET) / VAL_ELEMENTS_PER_BYTE;+ V += VAL_OFF(b1, b0_kv, 0, 0) + INPUT2_OFFSET;A += DST_OFF(b1, b0, 0, 0, 0);#if WITH_ATTN_MASKuint ldmsk = MSK_S2;@@ -473,10 +502,10 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG#if SLIDING_WINDOW_SIZE && !(IS_PAGED_ATTENTION && !IS_PREFILL)if (window_k0_begin > 0) {V += (size_t)(TRANSPOSE_V ? window_k0_begin : ldv * window_k0_begin) / VAL_ELEMENTS_PER_BYTE;- #if VAL_SCALES == QUANTIZE_2D+ #if VAL_SCALES == QUANTIZE_2D && !IS_VALUE_BY_CHANNELV_scales += (size_t)ldvq * window_k0_begin;#endif- #if VAL_ZERO_POINTS == QUANTIZE_2D+ #if VAL_ZERO_POINTS == QUANTIZE_2D && !IS_VALUE_BY_CHANNELV_zp += (size_t)ldvq * window_k0_begin / VAL_ZP_ELEMENTS_PER_BYTE;#endif}@@ -495,6 +524,32 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARGtile_load_packed_half(&Q_tile, Q, d, q, ldq, 0, wg_j0 + q0_copy);#endif+#if FOLD_KEY_SCALES_INTO_Q+ /* Fold the per-channel key scales into Q instead of dequantizing K in the KQ micro-kernel:+ * sum_d K_int8[m,d] * kscale[d] * Q[n,d] == sum_d K_int8[m,d] * (kscale[d] * Q[n,d])+ * See sdpa_gen_micro.cpp for why. Q_tile packs pairs of halves along d into uints, spread over+ * the subgroup: tile row i0 (channels 2*i0 and 2*i0+1) lives in lane (i0 % SUBGROUP_SIZE) at+ * slot (i0 / SUBGROUP_SIZE). K_scales is already offset to this head. Channels past d are+ * padding; K is zero there, so leaving them unscaled keeps their contribution zero. */+ {+ const int q_fold_lane = get_sub_group_local_id();+#pragma unroll+ for (int q_fold_t = 0; q_fold_t < (D_MAX / 2) / SUBGROUP_SIZE; q_fold_t++) {+ const int q_fold_i0 = q_fold_t * SUBGROUP_SIZE + q_fold_lane;+ const int q_fold_d0 = 2 * q_fold_i0;+ if (q_fold_d0 >= d)+ continue;+ const half2 q_fold_s = (half2)(K_scales[q_fold_d0 / KEY_GROUP_SIZE],+ (q_fold_d0 + 1 < d) ? K_scales[(q_fold_d0 + 1) / KEY_GROUP_SIZE] : (half)0.0h);+#pragma unroll+ for (int q_fold_j = 0; q_fold_j < q_tile_sg_n; q_fold_j++) {+ Q_tile.x[q_fold_j][q_fold_t]+ = as_uint(as_half2(Q_tile.x[q_fold_j][q_fold_t]) * q_fold_s);+ }+ }+ }+#endif+#if WITH_SCALE/* Load scale */#if INVERT_SCALE@@ -554,7 +609,23 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG/* sg_size */ SUBGROUP_SIZE,/* cache */ LSC_LDCC_L1C_L3C);-#if KEY_SCALES == QUANTIZE_2D+/* Under FOLD_KEY_SCALES_INTO_Q the k-loop never reads the key scales or zero points: the scales were+ consumed once, above, when folding them into the Q tile, and the zero points are dropped. */+#if (KEY_SCALES == QUANTIZE_2D) && !FOLD_KEY_SCALES_INTO_Q+ #if IS_KEY_BY_CHANNEL+ /* Broadcast: prefetch only the single row of scale groups */+ cooperative_prefetch_2d_maybe_rem(+ /* ptr */ K_scales,+ /* r */ 1,+ /* c */ num_key_groups,+ /* rmax */ 1,+ /* cmax */ D_MAX / KEY_GROUP_SIZE,+ /* ld */ ldkq,+ /* sg_id */ sg_ij,+ /* n_sg */ sg_per_wg,+ /* sg_size */ SUBGROUP_SIZE,+ /* cache */ LSC_LDCC_L1C_L3C);+ #elsecooperative_prefetch_2d_maybe_rem(/* ptr */ K_scales + window_k_begin,/* r */ causal_k - window_k_begin,@@ -566,8 +637,22 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG/* n_sg */ sg_per_wg,/* sg_size */ SUBGROUP_SIZE,/* cache */ LSC_LDCC_L1C_L3C);+ #endif#endif-#if KEY_ZERO_POINTS == QUANTIZE_2D+#if (KEY_ZERO_POINTS == QUANTIZE_2D) && !FOLD_KEY_SCALES_INTO_Q+ #if IS_KEY_BY_CHANNEL+ cooperative_prefetch_2d_maybe_rem(+ /* ptr */ K_zp,+ /* r */ 1,+ /* c */ num_key_groups,+ /* rmax */ 1,+ /* cmax */ D_MAX / KEY_GROUP_SIZE,+ /* ld */ ldkq,+ /* sg_id */ sg_ij,+ /* n_sg */ sg_per_wg,+ /* sg_size */ SUBGROUP_SIZE,+ /* cache */ LSC_LDCC_L1C_L3C);+ #elsecooperative_prefetch_2d_maybe_rem(/* ptr */ K_zp + window_k_begin,/* r */ causal_k - window_k_begin,@@ -579,6 +664,7 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG/* n_sg */ sg_per_wg,/* sg_size */ SUBGROUP_SIZE,/* cache */ LSC_LDCC_L1C_L3C);+ #endif#endif#endif@@ -873,15 +959,18 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARGs_tile_type S_tile= ugemm_kq(K, ldk, Q_slm, D_MAX, causal_k, ugemm_kq_wg_tile_n, d, k0,0, 0, sg_i_kq, sg_j_kq, (local char *)ugemm_slm- #if KEY_SCALES == QUANTIZE_2D+ /* When FOLD_KEY_SCALES_INTO_Q, the micro-kernel is generated without A scaling or offsetting+ * (the scales were already folded into Q above, and the zero point cancels in the softmax),+ * so neither quantization argument must be passed. */+ #if (KEY_SCALES == QUANTIZE_2D) && !FOLD_KEY_SCALES_INTO_Q,K_scales#endif- #if KEY_ZERO_POINTS+ #if KEY_ZERO_POINTS && !FOLD_KEY_SCALES_INTO_Q,K_zp#endif- #if (KEY_SCALES == QUANTIZE_2D) || KEY_ZERO_POINTS+ #if ((KEY_SCALES == QUANTIZE_2D) || KEY_ZERO_POINTS) && !FOLD_KEY_SCALES_INTO_Q,ldkq#endif@@ -1156,7 +1245,10 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG/* sg_size */ SUBGROUP_SIZE,/* cache */ LSC_LDCC_L1C_L3C);-#if VAL_SCALES == QUANTIZE_2D+/* Per-channel value scales/zero points are a single [num_val_groups, 1] column, not one entry per+ token, so the per-token geometry below would fetch k_chunk columns that do not exist. They are not+ read in the k-loop at all -- see FOLD_VAL_SCALES_INTO_OUTPUT. */+#if (VAL_SCALES == QUANTIZE_2D) && !IS_VALUE_BY_CHANNEL/* Prefetch V scales. */cooperative_prefetch_2d_maybe_rem(/* ptr */ V_scales + (size_t)ldvq * window_v_pf_begin,@@ -1170,7 +1262,7 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG/* sg_size */ SUBGROUP_SIZE,/* cache */ LSC_LDCC_L1C_L3C);#endif-#if VAL_ZERO_POINTS == QUANTIZE_2D+#if (VAL_ZERO_POINTS == QUANTIZE_2D) && !IS_VALUE_BY_CHANNEL/* Prefetch V zero points. */cooperative_prefetch_2d_maybe_rem(/* ptr */ V_zp + (size_t)ldvq * window_v_pf_begin / VAL_ZP_ELEMENTS_PER_BYTE,@@ -1315,7 +1407,20 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG/* n_sg */ sg_per_wg,/* sg_size */ SUBGROUP_SIZE,/* cache*/ LSC_LDCC_L1C_L3C);-#if KEY_SCALES == QUANTIZE_2D+#if (KEY_SCALES == QUANTIZE_2D) && !FOLD_KEY_SCALES_INTO_Q+ #if IS_KEY_BY_CHANNEL+ cooperative_prefetch_2d_maybe_rem(+ /* ptr */ K_scales,+ /* r */ 1,+ /* c */ num_key_groups,+ /* rmax */ 1,+ /* cmax */ D_MAX / KEY_GROUP_SIZE,+ /* ld */ ldkq,+ /* sg_id */ sg_ij,+ /* n_sg */ sg_per_wg,+ /* sg_size */ SUBGROUP_SIZE,+ /* cache */ LSC_LDCC_L1C_L3C);+ #elsecooperative_prefetch_2d_maybe_rem(/* ptr */ K_scales + (k0 + ugemm_kq_wg_tile_m),/* r */ causal_k - k0 - ugemm_kq_wg_tile_m,@@ -1327,8 +1432,22 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG/* n_sg */ sg_per_wg,/* sg_size */ SUBGROUP_SIZE,/* cache */ LSC_LDCC_L1C_L3C);+ #endif#endif-#if KEY_ZERO_POINTS == QUANTIZE_2D+#if (KEY_ZERO_POINTS == QUANTIZE_2D) && !FOLD_KEY_SCALES_INTO_Q+ #if IS_KEY_BY_CHANNEL+ cooperative_prefetch_2d_maybe_rem(+ /* ptr */ K_zp,+ /* r */ 1,+ /* c */ num_key_groups,+ /* rmax */ 1,+ /* cmax */ D_MAX / KEY_GROUP_SIZE,+ /* ld */ ldkq,+ /* sg_id */ sg_ij,+ /* n_sg */ sg_per_wg,+ /* sg_size */ SUBGROUP_SIZE,+ /* cache */ LSC_LDCC_L1C_L3C);+ #elsecooperative_prefetch_2d_maybe_rem(/* ptr */ K_zp + (k0 + ugemm_kq_wg_tile_m),/* r */ causal_k - k0 - ugemm_kq_wg_tile_m,@@ -1340,6 +1459,7 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG/* n_sg */ sg_per_wg,/* sg_size */ SUBGROUP_SIZE,/* cache */ LSC_LDCC_L1C_L3C);+ #endif#endif}#endif@@ -1481,18 +1601,21 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG}#endif#else+ /* When FOLD_VAL_SCALES_INTO_OUTPUT, the micro-kernel is generated without A scaling or+ offsetting, so it takes no quantization arguments; they are applied in the epilogue. */a_tile_type A_tile1 = ugemm_vs(V, ldv, S_slm, ugemm_kq_wg_tile_m, d, ugemm_kq_wg_tile_n,k_chunk, 0, 0, 0, sg_i_vs, sg_j_vs, (local char *)ugemm_slm-#if VAL_SCALES == QUANTIZE_2D+#if (VAL_SCALES == QUANTIZE_2D) && !FOLD_VAL_SCALES_INTO_OUTPUT,V_scales#endif-#if VAL_ZERO_POINTS+#if VAL_ZERO_POINTS && !FOLD_VAL_SCALES_INTO_OUTPUT,V_zp#endif-#if (VAL_SCALES == QUANTIZE_2D) || VAL_ZERO_POINTS+#if ((VAL_SCALES == QUANTIZE_2D) || VAL_ZERO_POINTS) \+ && !FOLD_VAL_SCALES_INTO_OUTPUT,ldvq#endif@@ -1502,10 +1625,14 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG#endif#if VAL_SCALES == QUANTIZE_2D+ #if !IS_VALUE_BY_CHANNELV_scales += ldvq * ugemm_kq_wg_tile_m;+ #endif#endif#if VAL_ZERO_POINTS == QUANTIZE_2D+ #if !IS_VALUE_BY_CHANNELV_zp += ldvq * ugemm_kq_wg_tile_m / VAL_ZP_ELEMENTS_PER_BYTE;+ #endif#endif#if IS_PAGED_ATTENTION && !IS_PREFILL// already done@@ -1538,6 +1665,36 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARGtile_elementwise(A_scale_tile, native_vrecip);tile_hbroadcast_mul(&A_tile, A_scale_tile);+#if FOLD_VAL_SCALES_INTO_OUTPUT+ /* Apply the per-channel value scales/zero points that were kept out of the VS micro-kernel:+ * out[dd,n] = vscale[dd] * (sum_t V_int[dd,t] * S[t,n] / l[n] - vzp[dd])+ * The division by the column sum l[n] just happened, so A_tile holds the bracketed accumulator.+ * See sdpa_gen_micro.cpp for why this is exact. Tile rows past the head size are never stored;+ * clamp their index so the loads stay inside the scale/zero point buffers. */+ {+ const int v_fold_row = sg_i_vs * ugemm_vs_sg_tile_m+ + get_sub_group_local_id();+ v_scale_tile_type V_scale_tile;+#if VAL_ZERO_POINTS == QUANTIZE_2D+ v_scale_tile_type V_zp_tile;+#endif+#pragma unroll+ for (int i0 = 0; i0 < ugemm_vs_sg_tile_m; i0 += SUBGROUP_SIZE) {+ const int v_fold_g = min(v_fold_row + i0, d - 1) / VAL_GROUP_SIZE;+ tile_access(V_scale_tile, i0, 0, SUBGROUP_SIZE, v_scale_tile_m, 1, 1)+ = convert_float(V_scales[v_fold_g]);+#if VAL_ZERO_POINTS == QUANTIZE_2D+ tile_access(V_zp_tile, i0, 0, SUBGROUP_SIZE, v_scale_tile_m, 1, 1)+ = convert_float(V_zp[v_fold_g]);+#endif+ }+#if VAL_ZERO_POINTS == QUANTIZE_2D+ tile_vbroadcast_sub(&A_tile, V_zp_tile);+#endif+ tile_vbroadcast_mul(&A_tile, V_scale_tile);+ }+#endif+/* Convert and store */a_tile_type_half A_tile_half;#if INPUT0_IS_BF16diff --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.clindex b5027fd66dd..1e92e5b788f 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@@ -134,6 +134,11 @@ inline uint FUNC(get_bt_index_value)(OPTIONAL_SHAPE_INFO_ARG uint b, uint f, uin#endif#define SUBGROUPS_PER_WG CEIL_DIV(V_HEAD_SIZE * SG_SCALE_FACTOR, SUBGROUP_SIZE)+#if IS_INT4_SIGNED+#define DECODE_INT4_NIBBLE(value) (((value) >= 8) ? ((value) - 16) : (value))+#else+#define DECODE_INT4_NIBBLE(value) (value)+#endif#if IS_KV_COMPRESSED#if COMPRESSED_PER_HEAD#define GET_COMPRESSION_INDEX(INPUT, b, f, y, x) GET_DATA_INDEX(INPUT, (b), (f), (y), (0));@@ -147,6 +152,11 @@ inline uint FUNC(get_bt_index_value)(OPTIONAL_SHAPE_INFO_ARG uint b, uint f, uin#else#define GET_ZP(zp, scale, comp_offset) ((scale)[(comp_offset) + 1])#endif+#if USE_ASYMMETRIC_QUANTIZATION+ #define DEQUANTIZE_KV(value, zp, scale) (((value) - (zp)) * (scale))+#else+ #define DEQUANTIZE_KV(value, zp, scale) ((value) * (scale))+#endif#endif#ifdef SDPA_STAGE_0@@ -328,8 +338,8 @@ KERNEL(sdpa_opt)(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;+ KEY_COMPRESSION_SCALE_TYPE key_val0 = DEQUANTIZE_KV(CAT(convert_, KEY_COMPRESSION_SCALE_TYPE)(DECODE_INT4_NIBBLE(unpacked.s0)), comp_zp, comp_scale);+ KEY_COMPRESSION_SCALE_TYPE key_val1 = DEQUANTIZE_KV(CAT(convert_, KEY_COMPRESSION_SCALE_TYPE)(DECODE_INT4_NIBBLE(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;@@ -349,8 +359,8 @@ KERNEL(sdpa_opt)(? 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 key_val0 = DEQUANTIZE_KV(CAT(convert_, KEY_COMPRESSION_SCALE_TYPE)(DECODE_INT4_NIBBLE(unpacked.s0)), comp_zp, comp_scale);+ KEY_COMPRESSION_SCALE_TYPE key_val1 = DEQUANTIZE_KV(CAT(convert_, KEY_COMPRESSION_SCALE_TYPE)(DECODE_INT4_NIBBLE(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;@@ -823,9 +833,9 @@ KERNEL(sdpa_opt)(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);+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(DECODE_INT4_NIBBLE(v_unpacked.s0)) :+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(DECODE_INT4_NIBBLE(v_unpacked.s1)));+ value_val = DEQUANTIZE_KV(value_val, sub_group_broadcast(comp_zp, i), sub_group_broadcast(comp_scale, i));#elif IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATIONVALUE_COMPRESSION_SCALE_TYPE value_val = (value_packed - sub_group_broadcast(comp_zp, i)) * sub_group_broadcast(comp_scale, i);#elif IS_KV_COMPRESSED@@ -895,9 +905,9 @@ KERNEL(sdpa_opt)(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;+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(DECODE_INT4_NIBBLE(v_rem_unpacked.s0)) :+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(DECODE_INT4_NIBBLE(v_rem_unpacked.s1)));+ value_val = DEQUANTIZE_KV(value_val, comp_zp, comp_scale);#elif IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATIONconst VALUE_COMPRESSION_SCALE_TYPE value_val = (value_packed - comp_zp) * comp_scale;#elif IS_KV_COMPRESSED@@ -1670,8 +1680,8 @@ KERNEL(sdpa_opt)(const INPUT1_TYPE packed_byte = KEY_BLOCK_READ(key_input, key_offset + key_row_idx * key_pitch + hi / 2);#endifchar2 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 key_lo = DEQUANTIZE_KV(TO_KEY_COMPRESSION_SCALE_TYPE(DECODE_INT4_NIBBLE(unpacked.s0)), sub_group_broadcast(comp_zp, key_row_idx), sub_group_broadcast(comp_scale, key_row_idx));+ KEY_COMPRESSION_SCALE_TYPE key_hi = DEQUANTIZE_KV(TO_KEY_COMPRESSION_SCALE_TYPE(DECODE_INT4_NIBBLE(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]);@@ -1698,8 +1708,8 @@ KERNEL(sdpa_opt)(? KEY_BLOCK_READ(key_input, key_offset + key_row_idx * key_pitch + hi / 2) : (INPUT1_TYPE)0;#endifchar2 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 key_lo = DEQUANTIZE_KV(TO_KEY_COMPRESSION_SCALE_TYPE(DECODE_INT4_NIBBLE(unpacked.s0)), sub_group_broadcast(comp_zp, key_row_idx), sub_group_broadcast(comp_scale, key_row_idx));+ KEY_COMPRESSION_SCALE_TYPE key_hi = DEQUANTIZE_KV(TO_KEY_COMPRESSION_SCALE_TYPE(DECODE_INT4_NIBBLE(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;@@ -1802,8 +1812,8 @@ KERNEL(sdpa_opt)(const INPUT1_TYPE packed_byte = KEY_BLOCK_READ(key_input, key_offset + key_row_idx * key_pitch_int4 + hi / 2);#endifchar2 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_lo = DEQUANTIZE_KV(TO_KEY_COMPRESSION_SCALE_TYPE(DECODE_INT4_NIBBLE(unpacked.s0)), sub_group_broadcast(comp_zp, key_row_idx), sub_group_broadcast(comp_scale, key_row_idx));+ key_hi = DEQUANTIZE_KV(TO_KEY_COMPRESSION_SCALE_TYPE(DECODE_INT4_NIBBLE(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]);@@ -1834,8 +1844,8 @@ KERNEL(sdpa_opt)(? KEY_BLOCK_READ(key_input, key_offset + key_row_idx * key_pitch_int4 + hi / 2) : (INPUT1_TYPE)0;#endifchar2 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_lo = DEQUANTIZE_KV(TO_KEY_COMPRESSION_SCALE_TYPE(DECODE_INT4_NIBBLE(unpacked.s0)), sub_group_broadcast(comp_zp, key_row_idx), sub_group_broadcast(comp_scale, key_row_idx));+ key_hi = DEQUANTIZE_KV(TO_KEY_COMPRESSION_SCALE_TYPE(DECODE_INT4_NIBBLE(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;@@ -2296,9 +2306,9 @@ KERNEL(sdpa_opt)(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);+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(DECODE_INT4_NIBBLE(v_unpacked.s0)) :+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(DECODE_INT4_NIBBLE(v_unpacked.s1)));+ value_val = DEQUANTIZE_KV(value_val, sub_group_broadcast(comp_zp, i), sub_group_broadcast(comp_scale, i));#elif IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATIONVALUE_COMPRESSION_SCALE_TYPE value_val = (value_packed - sub_group_broadcast(comp_zp, i)) * sub_group_broadcast(comp_scale, i);#elif IS_KV_COMPRESSED@@ -2326,9 +2336,9 @@ KERNEL(sdpa_opt)(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);+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(DECODE_INT4_NIBBLE(v_unpacked_elt.s0)) :+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(DECODE_INT4_NIBBLE(v_unpacked_elt.s1)));+ value_val = DEQUANTIZE_KV(value_val, sub_group_broadcast(comp_zp, i), sub_group_broadcast(comp_scale, i));#elif IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATIONVALUE_COMPRESSION_SCALE_TYPE value_val = (value_packed - sub_group_broadcast(comp_zp, i)) * sub_group_broadcast(comp_scale, i);#elif IS_KV_COMPRESSED@@ -2412,9 +2422,9 @@ KERNEL(sdpa_opt)(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);+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(DECODE_INT4_NIBBLE(v_unpacked.s0)) :+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(DECODE_INT4_NIBBLE(v_unpacked.s1)));+ value_val = DEQUANTIZE_KV(value_val, sub_group_broadcast(comp_zp, i), sub_group_broadcast(comp_scale, i));#elif IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATIONVALUE_COMPRESSION_SCALE_TYPE value_val = (value_packed - sub_group_broadcast(comp_zp, i)) * sub_group_broadcast(comp_scale, i);#elif IS_KV_COMPRESSED@@ -2442,9 +2452,9 @@ KERNEL(sdpa_opt)(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);+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(DECODE_INT4_NIBBLE(v_unpacked_elt.s0)) :+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(DECODE_INT4_NIBBLE(v_unpacked_elt.s1)));+ value_val = DEQUANTIZE_KV(value_val, sub_group_broadcast(comp_zp, i), sub_group_broadcast(comp_scale, i));#elif IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATIONVALUE_COMPRESSION_SCALE_TYPE value_val = (value_packed - sub_group_broadcast(comp_zp, i)) * sub_group_broadcast(comp_scale, i);#elif IS_KV_COMPRESSED@@ -2536,9 +2546,9 @@ KERNEL(sdpa_opt)(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);+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(DECODE_INT4_NIBBLE(v_left_unpacked.s0)) :+ CAT(convert_, VALUE_COMPRESSION_SCALE_TYPE)(DECODE_INT4_NIBBLE(v_left_unpacked.s1)));+ value_val = DEQUANTIZE_KV(value_val, sub_group_broadcast(comp_zp, seq_len_idx), sub_group_broadcast(comp_scale, seq_len_idx));#elif IS_KV_COMPRESSED && USE_ASYMMETRIC_QUANTIZATIONVALUE_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_COMPRESSEDdiff --git a/src/plugins/intel_gpu/src/plugin/ops/scaled_dot_product_attention.cpp b/src/plugins/intel_gpu/src/plugin/ops/scaled_dot_product_attention.cppindex a72723bdde7..bebfe344d9c 100644--- a/src/plugins/intel_gpu/src/plugin/ops/scaled_dot_product_attention.cpp+++ b/src/plugins/intel_gpu/src/plugin/ops/scaled_dot_product_attention.cpp@@ -116,7 +116,6 @@ static void CreateScaledDotProductAttentionOp(ProgramBuilder& p, const std::shar}static void CreateSDPAOp(ProgramBuilder& p, const std::shared_ptr<ov::op::internal::SDPA>& op) {- validate_inputs_count(op, {cnt_inputs_with_qkv, cnt_inputs_with_mask, cnt_inputs_with_scale, cnt_inputs_with_sink});auto inputs = p.GetInputInfo(op);auto layerName = layer_type_name_ID(op);@@ -131,6 +130,16 @@ static void CreateSDPAOp(ProgramBuilder& p, const std::shared_ptr<ov::op::internbool is_causal = op->get_causal();int64_t indirect_axis = -1;+ // When the KV cache is compressed (int8/int4), the op carries extra scale (and, for asymmetric+ // quantization, zero-point) inputs after the data inputs. Account for them in the input-count+ // validation and forward the quantization attributes to the primitive so the kernel dequantizes+ // the cache on the fly. get_compression_inputs_num() is 0 for the non-compressed path.+ const auto compression_inputs = op->get_compression_inputs_num();+ validate_inputs_count(op, {cnt_inputs_with_qkv + compression_inputs,+ cnt_inputs_with_mask + compression_inputs,+ cnt_inputs_with_scale + compression_inputs,+ cnt_inputs_with_sink + compression_inputs});+auto sdpa_prim = cldnn::scaled_dot_product_attention(layerName,inputs,is_causal,diff --git a/src/plugins/intel_gpu/src/plugin/transformations/group_query_attention_decomposition.cpp b/src/plugins/intel_gpu/src/plugin/transformations/group_query_attention_decomposition.cppindex cc0f150a5f6..d140bef1156 100644--- a/src/plugins/intel_gpu/src/plugin/transformations/group_query_attention_decomposition.cpp+++ b/src/plugins/intel_gpu/src/plugin/transformations/group_query_attention_decomposition.cpp@@ -4,18 +4,104 @@#include "group_query_attention_decomposition.hpp"+#include <limits>+#include <utility>+#include "intel_gpu/op/sdpa.hpp"+#include "openvino/op/broadcast.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/group_query_attention.hpp"+#include "openvino/op/shape_of.hpp"++namespace {++bool is_supported_compressed_kv_type(const ov::element::Type& type) {+ return type == ov::element::i8 || type == ov::element::u8 || type == ov::element::i4 || type == ov::element::u4;+}++std::vector<uint64_t> compute_kv_group_sizes(const ov::PartialShape& data_shape, const ov::PartialShape& scale_shape) {+ if (data_shape.rank().is_dynamic())+ return {};++ const size_t rank = data_shape.rank().get_length();+ std::vector<uint64_t> group_sizes(rank, 1);+ if (scale_shape.rank().is_static() && static_cast<size_t>(scale_shape.rank().get_length()) == rank) {+ for (size_t i = 0; i < rank; ++i) {+ const bool scale_is_one = scale_shape[i].is_static() && scale_shape[i].get_length() == 1;+ const bool data_is_one = data_shape[i].is_static() && data_shape[i].get_length() == 1;+ if (scale_is_one && !data_is_one)+ group_sizes[i] = std::numeric_limits<uint64_t>::max();+ }+ } else if (rank > 0) {+ group_sizes[rank - 1] = std::numeric_limits<uint64_t>::max();+ }+ return group_sizes;+}++} // namespacenamespace ov::intel_gpu {+std::optional<GroupQueryAttentionDecomposition::CompressedKV> GroupQueryAttentionDecomposition::prepare_compressed_kv(+ const std::shared_ptr<ov::op::internal::GroupQueryAttention>& node,+ const ov::Output<ov::Node>& key,+ const ov::Output<ov::Node>& value,+ const ov::Output<ov::Node>& key_scale,+ const ov::Output<ov::Node>& value_scale) {+ using GQAInputs = ov::op::internal::GroupQueryAttentionInputs;+ using GQAQuantType = ov::op::internal::GroupQueryAttentionQuantType;++ const auto kv_cache_bit_width = node->get_kv_cache_bit_width();+ const auto key_quant_type = node->get_k_quant_type();+ const auto value_quant_type = node->get_v_quant_type();+ if (!node->is_kv_quantized() || (kv_cache_bit_width != 8 && kv_cache_bit_width != 4) || key.get_element_type() != value.get_element_type() ||+ !is_supported_compressed_kv_type(key.get_element_type()) || key_quant_type == GQAQuantType::PER_TENSOR ||+ value_quant_type == GQAQuantType::PER_TENSOR)+ return std::nullopt;++ ov::Output<ov::Node> prepared_key_scale =+ make_kv_scale(node->input_value(static_cast<size_t>(GQAInputs::K_SCALE)), node->get_kv_num_heads(), key_quant_type);+ ov::Output<ov::Node> prepared_value_scale =+ make_kv_scale(node->input_value(static_cast<size_t>(GQAInputs::V_SCALE)), node->get_kv_num_heads(), value_quant_type);++ if (prepared_key_scale.get_element_type() != ov::element::f16)+ prepared_key_scale = register_new_node<ov::op::v0::Convert>(prepared_key_scale, ov::element::f16);+ if (prepared_value_scale.get_element_type() != ov::element::f16)+ prepared_value_scale = register_new_node<ov::op::v0::Convert>(prepared_value_scale, ov::element::f16);++ const bool is_int4 = kv_cache_bit_width == 4;+ m_quantization_attrs.quantization_type = is_int4 ? ov::op::internal::DynamicQuantize::QuantizationType::Asymmetric+ : ov::op::internal::DynamicQuantize::QuantizationType::Symmetric;+ m_quantization_attrs.output_storage_type = ov::op::internal::DynamicQuantize::OutputStorageType::Planar;+ // GQA stores signed INT4 values as unsigned nibbles biased by +8. Describe that physical encoding to SDPA+ // as asymmetric u4 with a fixed zero point instead of i4, whose nibbles use two's-complement encoding.+ m_quantization_attrs.quantization_dt = is_int4 ? ov::element::u4 : key.get_element_type();+ m_quantization_attrs.scale_dt = ov::element::f16;+ ov::OutputVector quantization_inputs{prepared_key_scale, prepared_value_scale};+ if (is_int4) {+ m_quantization_attrs.zp_dt = ov::element::f16;+ const auto storage_zp = register_new_node<ov::op::v0::Constant>(ov::element::f16, ov::Shape{}, 8.0f);+ const auto key_scale_shape = register_new_node<ov::op::v3::ShapeOf>(prepared_key_scale, ov::element::i64);+ const auto value_scale_shape = register_new_node<ov::op::v3::ShapeOf>(prepared_value_scale, ov::element::i64);+ quantization_inputs.push_back(register_new_node<ov::op::v3::Broadcast>(storage_zp, key_scale_shape));+ quantization_inputs.push_back(register_new_node<ov::op::v3::Broadcast>(storage_zp, value_scale_shape));+ }+ m_quantization_attrs.group_sizes = compute_kv_group_sizes(key.get_partial_shape(), prepared_key_scale.get_partial_shape());+ m_quantization_attrs.scales_zp_output_order = {0, 1, 2, 3};+ return CompressedKV{key, value, std::move(quantization_inputs)};+}+std::shared_ptr<ov::Node> GroupQueryAttentionDecomposition::make_sdpa(const ov::Output<ov::Node>& query,const ov::Output<ov::Node>& key,const ov::Output<ov::Node>& value,const ov::Output<ov::Node>& mask,const ov::Output<ov::Node>& scale,const ov::Output<ov::Node>& sink,- bool is_causal) {- ov::OutputVector inputs{query, key, value};+ bool is_causal,+ const std::optional<CompressedKV>& compressed_kv) {+ ov::OutputVector inputs{query,+ compressed_kv ? compressed_kv->key : key,+ compressed_kv ? compressed_kv->value : value};if (mask.get_node()) {inputs.push_back(mask);}@@ -25,16 +111,21 @@ std::shared_ptr<ov::Node> GroupQueryAttentionDecomposition::make_sdpa(const ov::if (sink.get_node()) {inputs.push_back(sink);}+ if (compressed_kv) {+ inputs.insert(inputs.end(),+ compressed_kv->quantization_inputs.begin(),+ compressed_kv->quantization_inputs.end());+ }const auto order = op::SDPA::default_order(query.get_partial_shape().rank().get_length());- return register_new_node<op::SDPA>(inputs,- is_causal,- order,- order,- order,- order,- ov::element::dynamic,- is_causal ? op::SDPA::CausalMaskAlignment::LOWER_RIGHT : op::SDPA::CausalMaskAlignment::UPPER_LEFT);+ const auto alignment = is_causal ? op::SDPA::CausalMaskAlignment::LOWER_RIGHT : op::SDPA::CausalMaskAlignment::UPPER_LEFT;+ std::shared_ptr<op::SDPA> sdpa;+ if (compressed_kv) {+ sdpa = register_new_node<op::SDPA>(inputs, is_causal, order, order, order, order, m_quantization_attrs, ov::element::dynamic, alignment);+ } else {+ sdpa = register_new_node<op::SDPA>(inputs, is_causal, order, order, order, order, ov::element::dynamic, alignment);+ }+ return sdpa;}std::shared_ptr<ov::Node> GroupQueryAttentionDecomposition::make_attention_mask(const ov::Output<ov::Node>& curr_seqlen_scalar,@@ -67,4 +158,4 @@ std::shared_ptr<ov::Node> GroupQueryAttentionDecomposition::make_attention_mask(has_sink);}-} // namespace ov::intel_gpu\ No newline at end of file+} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/plugin/transformations/group_query_attention_decomposition.hpp b/src/plugins/intel_gpu/src/plugin/transformations/group_query_attention_decomposition.hppindex 43938cac40a..eb1ee47d391 100644--- a/src/plugins/intel_gpu/src/plugin/transformations/group_query_attention_decomposition.hpp+++ b/src/plugins/intel_gpu/src/plugin/transformations/group_query_attention_decomposition.hpp@@ -4,6 +4,7 @@#pragma once+#include "intel_gpu/op/sdpa.hpp"#include "transformations/op_conversions/group_query_attention_decomposition.hpp"namespace ov::intel_gpu {@@ -20,7 +21,8 @@ protected:const ov::Output<ov::Node>& mask,const ov::Output<ov::Node>& scale,const ov::Output<ov::Node>& sink,- bool is_causal) override;+ bool is_causal,+ const std::optional<CompressedKV>& compressed_kv) override;std::shared_ptr<ov::Node> make_attention_mask(const ov::Output<ov::Node>& curr_seqlen_scalar,const ov::Output<ov::Node>& kv_len_scalar,const ov::Output<ov::Node>& kv_len_1d,@@ -33,6 +35,14 @@ protected:bool sliding_window_cache,float scale,bool has_sink) override;+ std::optional<CompressedKV> prepare_compressed_kv(+ const std::shared_ptr<ov::op::internal::GroupQueryAttention>& node,+ const ov::Output<ov::Node>& key,+ const ov::Output<ov::Node>& value,+ const ov::Output<ov::Node>& key_scale,+ const ov::Output<ov::Node>& value_scale) override;++ op::SDPA::QuantizationAttribute m_quantization_attrs;};-} // namespace ov::intel_gpu\ No newline at end of file+} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/plugin/transformations/op/sdpa.cpp b/src/plugins/intel_gpu/src/plugin/transformations/op/sdpa.cppindex 99deb96520e..c312b2c5a21 100644--- a/src/plugins/intel_gpu/src/plugin/transformations/op/sdpa.cpp+++ b/src/plugins/intel_gpu/src/plugin/transformations/op/sdpa.cpp@@ -177,6 +177,16 @@ std::vector<ov::PartialShape> shape_infer(const SDPA* op,}std::vector<ov::PartialShape> transposed_input_shapes{ shape_q_t, shape_k_t, shape_v_t };++ // INT4 KV data is stored as packed bytes, so its physical head dimension+ // is half the logical dimension used by SDPA shape inference.+ if (op->get_kv_compressed() && ov::element::Type(op->get_quantization_attrs().quantization_dt).bitwidth() == 4) {+ shape_k_t[shape_k_t.rank().get_length() - 1] *= 2;+ shape_v_t[shape_v_t.rank().get_length() - 1] *= 2;+ transposed_input_shapes[1] = shape_k_t;+ transposed_input_shapes[2] = shape_v_t;+ }+for (size_t i = 3; i < transposed_input_shapes.size(); i++) {transposed_input_shapes.push_back(input_shapes[i]);}diff --git a/src/plugins/intel_gpu/src/plugin/transformations/transpose_fusion.cpp b/src/plugins/intel_gpu/src/plugin/transformations/transpose_fusion.cppindex 7582ca6476f..f99ff0d4d7d 100644--- a/src/plugins/intel_gpu/src/plugin/transformations/transpose_fusion.cpp+++ b/src/plugins/intel_gpu/src/plugin/transformations/transpose_fusion.cpp@@ -615,4 +615,4 @@ TransposeSplitMatcher::TransposeSplitMatcher() {this->register_matcher(matcher, callback);}-} // namespace ov::intel_gpu+} // namespace ov::intel_gpu\ No newline at end of filediff --git a/src/plugins/intel_gpu/tests/unit/test_cases/sdpa_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/sdpa_gpu_test.cppindex a9ce33cba60..e606f49af3b 100644--- a/src/plugins/intel_gpu/tests/unit/test_cases/sdpa_gpu_test.cpp+++ b/src/plugins/intel_gpu/tests/unit/test_cases/sdpa_gpu_test.cpp@@ -35,6 +35,7 @@ namespace {struct sdpa_test_params {int head_size;int num_heads;+ int kv_num_heads;int sequence_length_q;int sequence_length_kv;int batch;@@ -43,22 +44,30 @@ struct sdpa_test_params {float scale_val;bool use_scalar_attn_mask;float attn_mask_val;+ int bit_width;+ bool asymmetric;data_types dt;// Constructor for basic tests (backward compatibility)sdpa_test_params(int h_size, int n_heads, int seq_q, int seq_kv, int b,bool dynamic_shape, data_types dt = data_types::f16)- : head_size(h_size), num_heads(n_heads), sequence_length_q(seq_q),+ : head_size(h_size), num_heads(n_heads), kv_num_heads(n_heads), sequence_length_q(seq_q),sequence_length_kv(seq_kv), batch(b), dynamic(dynamic_shape),use_scalar_scale_val(false), scale_val(1.0f), use_scalar_attn_mask(false),- attn_mask_val(0.0f), dt(dt) {}+ attn_mask_val(0.0f), bit_width(0), asymmetric(false), dt(dt) {}// Constructor for advanced caching testssdpa_test_params(int h_size, int n_heads, int seq_q, int seq_kv, int b,bool use_scale, float scale, bool use_mask, float mask, data_types dt = data_types::f16)- : head_size(h_size), num_heads(n_heads), sequence_length_q(seq_q), sequence_length_kv(seq_kv),+ : head_size(h_size), num_heads(n_heads), kv_num_heads(n_heads), sequence_length_q(seq_q), sequence_length_kv(seq_kv),batch(b), dynamic(true), use_scalar_scale_val(use_scale),- scale_val(scale), use_scalar_attn_mask(use_mask), attn_mask_val(mask), dt(dt) {}+ scale_val(scale), use_scalar_attn_mask(use_mask), attn_mask_val(mask), bit_width(0), asymmetric(false), dt(dt){}++ // constructor for quantization tests+ sdpa_test_params(int h_size, int q_heads, int kv_heads, int seq_q, int seq_kv, int b, int bits, bool asym, data_types dt = data_types::f16)+ : head_size(h_size), num_heads(q_heads), kv_num_heads(kv_heads), sequence_length_q(seq_q),+ sequence_length_kv(seq_kv), batch(b), dynamic(false), use_scalar_scale_val(false), scale_val(1.0f),+ use_scalar_attn_mask(false), attn_mask_val(0.0f), bit_width(bits), asymmetric(asym), dt(dt) {}};struct sdpa_gpu_test : public ::testing::TestWithParam<sdpa_test_params> {@@ -794,6 +803,628 @@ TEST(sdpa_gpu_micro, transposed_v_matches_non_transposed_v_multi_tile) {}}++// ---------------------------------------------------------------------------+// Compressed (int8 / int4) KV-cache SDPA tests.+//+// The optimized SDPA kernel (sdpa_opt) dequantizes the KV cache on read using+// the asymmetric formula `deq = (q - zp) * scale`, where a single (scale, zp)+// pair is shared by all head_size channels of a given (batch, head, token) and+// stored interleaved as [scale, zp] (InterleavedScalesZP) in fp16. INT4 packs+// two unsigned nibbles per byte: low nibble -> even head dim, high nibble -> odd+// head dim.+//+// These tests build a `scaled_dot_product_attention` primitive with+// is_kv_compressed=true directly and feed host-quantized KV plus the matching+// scale/zp buffers to the forced `sdpa_opt` path. The golden reference is an+// independent float attention (uncompressed, forced `sdpa_ref`) fed the exact+// host-dequantized KV, so the two networks operate on identical effective KV+// and any divergence isolates the kernel's dequant + attention math.+// ---------------------------------------------------------------------------+struct kv_quant_result {+ std::vector<int8_t> packed; // quantized (INT4: two nibbles per byte)+ std::vector<ov::float16> dequantized; // (q - zp) * scale, full head_size+ std::vector<ov::float16> scales;+ std::vector<ov::float16> zero_points;+};++enum class kv_quant_granularity {+ per_channel,+ per_token,+};++// Per-(batch, head, token) quantization over the whole head_size dim.+// Layout of `src` is bfyx {batch, seq, heads, head_size} (matches transpose {0,2,1,3}).+// Load a raw little-endian binary dump into a typed vector (no header parsing).+template <typename T>+static std::vector<T> load_bin_as(const std::string& path) {+ const auto bytes = ov::util::load_binary(path);+ OPENVINO_ASSERT(!bytes.empty(), "Failed to load (missing/empty) binary file: ", path);+ OPENVINO_ASSERT(bytes.size() % sizeof(T) == 0, "Binary file size is not a multiple of element size: ", path);+ std::vector<T> out(bytes.size() / sizeof(T));+ std::memcpy(out.data(), bytes.data(), bytes.size());+ return out;+}++// Per-token KV quantization: one (scale, zp) per (batch, head, token), covering the+// whole head dimension. When seq_major is true the source is laid out+// [batch, seq, heads, head_size]; when false it is [batch, heads, seq, head_size]. The produced+// scales / zero_points buffers are always laid out [batch, heads, seq].+//+// Two quantization strategies are supported:+// * Symmetric (symmetric=true): signed codes centered on zero, deq = q * scale (no+// zero-point). The per-token scale is max_abs / q_max over the head dimension.+// * Asymmetric (symmetric=false): unsigned codes with a zero-point, deq = (q - zp) * scale.+// The per-token scale/zp are derived from the [min, max] range over the head dimension+// positions: scale = (max - min) / (q_max - q_min), zp = q_min - min / scale.+// In both cases the derived scale is multiplied by a per-token random factor (see below).+// provided_scale, when non-null, supplies the per-token scales ([batch, heads, seq])+// instead of deriving (and randomizing) them; the zero-point is still derived for the asymmetric+// case so it matches the given scale.+static kv_quant_result quantize_kv_per_token(const std::vector<ov::float16>& src,+ int batch,+ int seq,+ int heads,+ int head_size,+ int bit_width,+ bool seq_major = true,+ const std::vector<ov::float16>* provided_scale = nullptr,+ bool symmetric = false) {+ // Symmetric uses a signed range centered on zero (no zero-point); asymmetric int4 uses+ // unsigned nibbles [0, 15] with a zero-point.+ const int q_min = symmetric ? -(bit_width == 4 ? 7 : 127) : (bit_width == 4 ? 0 : -128);+ const int q_max = symmetric ? (bit_width == 4 ? 7 : 127) : (bit_width == 4 ? 15 : 127);+ const int packed_hs = bit_width == 4 ? head_size / 2 : head_size;+ const size_t token_count = static_cast<size_t>(batch) * heads * seq;++ kv_quant_result r;+ r.packed.assign(static_cast<size_t>(batch) * seq * heads * packed_hs, 0);+ r.dequantized.assign(static_cast<size_t>(batch) * seq * heads * head_size, ov::float16(0.0f));+ r.scales.assign(token_count, ov::float16(0.0f));+ if (!symmetric)+ r.zero_points.assign(token_count, ov::float16(0.0f));++ const auto elem_base = [&](int b, int s, int h) -> size_t {+ return seq_major ? ((static_cast<size_t>(b) * seq + s) * heads + h) * head_size : ((static_cast<size_t>(b) * heads + h) * seq + s) * head_size;+ };+ const auto packed_base_of = [&](int b, int s, int h) -> size_t {+ return seq_major ? ((static_cast<size_t>(b) * seq + s) * heads + h) * packed_hs : ((static_cast<size_t>(b) * heads + h) * seq + s) * packed_hs;+ };+ const auto pack_value = [&](size_t packed_base, int d, int q) {+ if (bit_width == 4) {+ // low nibble = even head dim, high nibble = odd head dim+ auto& byte = r.packed[packed_base + d / 2];+ if (d % 2 == 0)+ byte = static_cast<int8_t>((byte & 0xF0) | (q & 0x0F));+ else+ byte = static_cast<int8_t>((byte & 0x0F) | ((q & 0x0F) << 4));+ } else {+ r.packed[packed_base + d] = static_cast<int8_t>(q);+ }+ };++ // Random per-token multiplier applied on top of the derived scale, generated the same way as+ // the tests' random inputs (1/8-resolution values in [1, 2]). Neighbouring tokens therefore+ // get clearly different scales, so a kernel that mis-indexes the scale buffer diverges from the+ // host dequantization instead of silently agreeing; staying >= 1 keeps every value inside the+ // quantized range. The fixed seed keeps the test reproducible.+ tests::random_generator scale_rg("quantize_kv_per_token_scale");+ const auto scale_mul = scale_rg.generate_random_1d<float>(token_count, 1, 2, 8);++ // Derive (or take) one scale and zero-point per (batch, head, token) from the values of+ // that token across the whole head.+ for (int b = 0; b < batch; ++b) {+ for (int h = 0; h < heads; ++h) {+ for (int s = 0; s < seq; ++s) {+ const size_t token = (static_cast<size_t>(b) * heads + h) * seq + s;+ float min_v = std::numeric_limits<float>::max();+ float max_v = std::numeric_limits<float>::lowest();+ for (int d = 0; d < head_size; ++d) {+ const float v = static_cast<float>(src[elem_base(b, s, h) + d]);+ min_v = std::min(min_v, v);+ max_v = std::max(max_v, v);+ }+ float scale = 0.0f;+ if (provided_scale != nullptr) {+ scale = static_cast<float>((*provided_scale)[token]);+ } else if (symmetric) {+ scale = std::max(std::abs(min_v), std::abs(max_v)) / static_cast<float>(q_max) * scale_mul[token];+ } else {+ scale = (max_v - min_v) / static_cast<float>(q_max - q_min) * scale_mul[token];+ }+ if (scale == 0.0f)+ scale = 1.0f; // degenerate (constant) token: avoid div-by-zero+ r.scales[token] = ov::float16(scale);+ if (!symmetric) {+ // deq = (q - zp) * scale, so min_v maps to q_min: zp = q_min - min_v / scale.+ r.zero_points[token] = ov::float16(std::round(static_cast<float>(q_min) - min_v / scale));+ }+ }+ }+ }++ for (int b = 0; b < batch; ++b) {+ for (int s = 0; s < seq; ++s) {+ for (int h = 0; h < heads; ++h) {+ const size_t base = elem_base(b, s, h);+ const size_t packed_base = packed_base_of(b, s, h);+ const size_t scale_base = (static_cast<size_t>(b) * heads + h) * seq + s;+ for (int d = 0; d < head_size; ++d) {+ // Quantize through the fp16-rounded scale/zp so the host dequantization+ // matches exactly what the kernel reads from the scale/zp buffers.+ const float scale = static_cast<float>(r.scales[scale_base]);+ const float zp = symmetric ? 0.0f : static_cast<float>(r.zero_points[scale_base]);+ const float v = static_cast<float>(src[base + d]);+ int q = static_cast<int>(std::lround(v / scale + zp));+ q = std::max(q_min, std::min(q_max, q));+ r.dequantized[base + d] = ov::float16((static_cast<float>(q) - zp) * scale);+ pack_value(packed_base, d, q);+ }+ }+ }+ }+ return r;+}++// Per-channel KV quantization: one scale/zp per (batch, head, channel), shared by all tokens.+// The compression buffers are laid out as [batch, heads, 1, head_size].+static kv_quant_result quantize_kv_per_channel(const std::vector<ov::float16>& src,+ int batch,+ int seq,+ int heads,+ int head_size,+ int bit_width,+ bool seq_major = true,+ const std::vector<ov::float16>* provided_scale = nullptr,+ bool symmetric = false) {+ const int q_min = symmetric ? -(bit_width == 4 ? 7 : 127) : (bit_width == 4 ? 0 : -128);+ const int q_max = symmetric ? (bit_width == 4 ? 7 : 127) : (bit_width == 4 ? 15 : 127);+ const int packed_hs = bit_width == 4 ? head_size / 2 : head_size;+ const size_t channel_count = static_cast<size_t>(batch) * heads * head_size;++ kv_quant_result r;+ r.packed.assign(static_cast<size_t>(batch) * seq * heads * packed_hs, 0);+ r.dequantized.assign(static_cast<size_t>(batch) * seq * heads * head_size, ov::float16(0.0f));+ r.scales.assign(channel_count, ov::float16(0.0f));+ if (!symmetric)+ r.zero_points.assign(channel_count, ov::float16(0.0f));++ const auto elem_base = [&](int b, int s, int h) -> size_t {+ return seq_major ? ((static_cast<size_t>(b) * seq + s) * heads + h) * head_size+ : ((static_cast<size_t>(b) * heads + h) * seq + s) * head_size;+ };+ const auto packed_base_of = [&](int b, int s, int h) -> size_t {+ return seq_major ? ((static_cast<size_t>(b) * seq + s) * heads + h) * packed_hs+ : ((static_cast<size_t>(b) * heads + h) * seq + s) * packed_hs;+ };+ const auto pack_value = [&](size_t packed_base, int d, int q) {+ if (bit_width == 4) {+ auto& byte = r.packed[packed_base + d / 2];+ if (d % 2 == 0)+ byte = static_cast<int8_t>((byte & 0xF0) | (q & 0x0F));+ else+ byte = static_cast<int8_t>((byte & 0x0F) | ((q & 0x0F) << 4));+ } else {+ r.packed[packed_base + d] = static_cast<int8_t>(q);+ }+ };++ tests::random_generator scale_rg("quantize_kv_per_channel_scale");+ const auto scale_mul = scale_rg.generate_random_1d<float>(channel_count, 1, 2, 8);++ for (int b = 0; b < batch; ++b) {+ for (int h = 0; h < heads; ++h) {+ for (int d = 0; d < head_size; ++d) {+ const size_t channel = (static_cast<size_t>(b) * heads + h) * head_size + d;+ float min_v = std::numeric_limits<float>::max();+ float max_v = std::numeric_limits<float>::lowest();+ for (int s = 0; s < seq; ++s) {+ const float v = static_cast<float>(src[elem_base(b, s, h) + d]);+ min_v = std::min(min_v, v);+ max_v = std::max(max_v, v);+ }++ float scale = 0.0f;+ if (provided_scale != nullptr) {+ scale = static_cast<float>((*provided_scale)[channel]);+ } else if (symmetric) {+ scale = std::max(std::abs(min_v), std::abs(max_v)) / static_cast<float>(q_max) *+ scale_mul[channel];+ } else {+ scale = (max_v - min_v) / static_cast<float>(q_max - q_min) * scale_mul[channel];+ }+ if (scale == 0.0f)+ scale = 1.0f;++ r.scales[channel] = ov::float16(scale);+ if (!symmetric)+ r.zero_points[channel] =+ ov::float16(std::round(static_cast<float>(q_min) - min_v / scale));+ }+ }+ }++ for (int b = 0; b < batch; ++b) {+ for (int s = 0; s < seq; ++s) {+ for (int h = 0; h < heads; ++h) {+ const size_t base = elem_base(b, s, h);+ const size_t packed_base = packed_base_of(b, s, h);+ const size_t scale_base = (static_cast<size_t>(b) * heads + h) * head_size;+ for (int d = 0; d < head_size; ++d) {+ const float scale = static_cast<float>(r.scales[scale_base + d]);+ const float zp = symmetric ? 0.0f : static_cast<float>(r.zero_points[scale_base + d]);+ const float v = static_cast<float>(src[base + d]);+ int q = static_cast<int>(std::lround(v / scale + zp));+ q = std::max(q_min, std::min(q_max, q));+ r.dequantized[base + d] = ov::float16((static_cast<float>(q) - zp) * scale);+ pack_value(packed_base, d, q);+ }+ }+ }+ }++ return r;+}++// Per-channel symmetric quantization that reproduces the GQA decomposition's write path.+// INT4 values use a +8 storage bias and are exposed to SDPA as asymmetric u4 with zero point 8.+// INT8 values retain their signed representation and are exposed as symmetric i8.+static kv_quant_result quantize_kv_per_channel_gqa_decomp(const std::vector<ov::float16>& src,+ int batch,+ int seq,+ int heads,+ int head_size,+ int bit_width,+ bool seq_major = true,+ const std::vector<ov::float16>* provided_scale = nullptr,+ bool symmetric = false) {+ OPENVINO_ASSERT(bit_width == 4 || bit_width == 8, "GQA decomposition supports only INT4 and INT8 KV caches");+ OPENVINO_ASSERT(symmetric, "GQA decomposition uses symmetric KV quantization");+ OPENVINO_ASSERT(bit_width != 4 || head_size % 2 == 0, "INT4 KV packing requires an even head size");+ const int q_min = bit_width == 4 ? -8 : -128;+ const int q_max = bit_width == 4 ? 7 : 127;+ const int packed_hs = bit_width == 4 ? head_size / 2 : head_size;+ const size_t channel_count = static_cast<size_t>(batch) * heads * head_size;++ kv_quant_result r;+ r.packed.assign(static_cast<size_t>(batch) * seq * heads * packed_hs, 0);+ r.dequantized.assign(static_cast<size_t>(batch) * seq * heads * head_size, ov::float16(0.0f));+ r.scales.assign(channel_count, ov::float16(0.0f));+ if (bit_width == 4)+ r.zero_points.assign(channel_count, ov::float16(8.0f));++ const auto elem_base = [&](int b, int s, int h) -> size_t {+ return seq_major ? ((static_cast<size_t>(b) * seq + s) * heads + h) * head_size+ : ((static_cast<size_t>(b) * heads + h) * seq + s) * head_size;+ };+ const auto packed_base_of = [&](int b, int s, int h) -> size_t {+ return seq_major ? ((static_cast<size_t>(b) * seq + s) * heads + h) * packed_hs+ : ((static_cast<size_t>(b) * heads + h) * seq + s) * packed_hs;+ };++ tests::random_generator scale_rg("quantize_kv_per_channel_gqa_decomp_scale");+ const auto scale_mul = scale_rg.generate_random_1d<float>(channel_count, 1, 2, 8);++ for (int b = 0; b < batch; ++b) {+ for (int h = 0; h < heads; ++h) {+ for (int d = 0; d < head_size; ++d) {+ const size_t channel = (static_cast<size_t>(b) * heads + h) * head_size + d;+ float min_v = std::numeric_limits<float>::max();+ float max_v = std::numeric_limits<float>::lowest();+ for (int s = 0; s < seq; ++s) {+ const float v = static_cast<float>(src[elem_base(b, s, h) + d]);+ min_v = std::min(min_v, v);+ max_v = std::max(max_v, v);+ }++ float scale = 0.0f;+ if (provided_scale != nullptr) {+ scale = static_cast<float>((*provided_scale)[channel]);+ } else {+ scale = std::max(std::abs(min_v), std::abs(max_v)) / static_cast<float>(q_max) * scale_mul[channel];+ }+ if (scale == 0.0f)+ scale = 1.0f;++ r.scales[channel] = ov::float16(scale);+ }+ }+ }++ for (int b = 0; b < batch; ++b) {+ for (int s = 0; s < seq; ++s) {+ for (int h = 0; h < heads; ++h) {+ const size_t base = elem_base(b, s, h);+ const size_t packed_base = packed_base_of(b, s, h);+ const size_t scale_base = (static_cast<size_t>(b) * heads + h) * head_size;+ for (int d = 0; d < head_size; ++d) {+ const float scale = static_cast<float>(r.scales[scale_base + d]);+ const float v = static_cast<float>(src[base + d]);+ int q = static_cast<int>(std::nearbyint(v / scale));+ q = std::max(q_min, std::min(q_max, q));+ r.dequantized[base + d] = ov::float16(static_cast<float>(q) * scale);+ if (bit_width == 4) {+ const int nibble = q + 8;+ auto& byte = r.packed[packed_base + d / 2];+ if (d % 2 == 0)+ byte = static_cast<int8_t>((byte & 0xF0) | (nibble & 0x0F));+ else+ byte = static_cast<int8_t>((byte & 0x0F) | ((nibble & 0x0F) << 4));+ } else {+ r.packed[packed_base + d] = static_cast<int8_t>(q);+ }+ }+ }+ }+ }++ return r;+}++static void run_compressed_kv_sdpa_test(const sdpa_test_params& params,+ kv_quant_granularity granularity,+ bool gqa_decomp = false) {+ tests::random_generator rg;+ rg.set_seed(GET_SUITE_NAME);+ auto& engine = get_test_engine();++ if (granularity == kv_quant_granularity::per_channel) {+ const auto& device_info = engine.get_device_info();+ if (!device_info.supports_immad || device_info.arch < gpu_arch::xe_hpg) {+ GTEST_SKIP() << "Per-channel compressed KV is supported by micro SDPA only";+ }+ }++ const int bit_width = params.bit_width;+ const bool asymmetric = params.asymmetric;+ const bool has_storage_zero_point = asymmetric || (gqa_decomp && bit_width == 4);+ const int batch = params.batch;+ const int q_num_heads = params.num_heads;+ const int kv_num_heads = params.kv_num_heads;+ const int seq_q = params.sequence_length_q;+ const int seq_kv = params.sequence_length_kv;+ const int head_size = params.head_size;++ OPENVINO_ASSERT(bit_width != 4 || head_size % 2 == 0, "INT4 KV packing requires an even head size");+ const int packed_head_size = bit_width == 4 ? head_size / 2 : head_size;++ // Q and original float K/V use [batch, heads, sequence, head_size].+ auto q_data = rg.generate_random_1d<ov::float16>(static_cast<size_t>(batch) * seq_q * q_num_heads * head_size, -1.0f, 1.0f);+ auto k_orig = rg.generate_random_1d<ov::float16>(static_cast<size_t>(batch) * seq_kv * kv_num_heads * head_size, -1.0f, 1.0f);+ auto v_orig = rg.generate_random_1d<ov::float16>(static_cast<size_t>(batch) * seq_kv * kv_num_heads * head_size, -1.0f, 1.0f);++ const auto quantize_kv = [&]() {+ if (gqa_decomp) {+ OPENVINO_ASSERT(granularity == kv_quant_granularity::per_channel && !asymmetric,+ "GQA decomposition requires symmetric per-channel quantization");+ return &quantize_kv_per_channel_gqa_decomp;+ }+ return granularity == kv_quant_granularity::per_channel ? quantize_kv_per_channel+ : quantize_kv_per_token;+ }();+ auto k_q = quantize_kv(k_orig,+ batch,+ seq_kv,+ kv_num_heads,+ head_size,+ bit_width,+ /*seq_major=*/false,+ nullptr,+ /*symmetric=*/!asymmetric);+ auto v_q = quantize_kv(v_orig,+ batch,+ seq_kv,+ kv_num_heads,+ head_size,+ bit_width,+ /*seq_major=*/false,+ nullptr,+ /*symmetric=*/!asymmetric);++ const layout q_layout({batch, q_num_heads, seq_q, head_size}, data_types::f16, format::bfyx);+ const layout kv_deq_layout({batch, kv_num_heads, seq_kv, head_size}, data_types::f16, format::bfyx);+ // INT4 stores two adjacent head-dimension values in each byte: [B, H, S, D/2].+ const layout kv_packed_layout({batch, kv_num_heads, seq_kv, packed_head_size}, data_types::i8, format::bfyx);+ const layout comp_layout(granularity == kv_quant_granularity::per_channel+ ? ov::PartialShape{batch, kv_num_heads, 1, head_size}+ : ov::PartialShape{batch, kv_num_heads, seq_kv, 1},+ data_types::f16,+ format::bfyx);++ const ov::Shape expected_packed_shape = {static_cast<size_t>(batch),+ static_cast<size_t>(kv_num_heads),+ static_cast<size_t>(seq_kv),+ static_cast<size_t>(packed_head_size)};+ ASSERT_EQ(kv_packed_layout.get_shape(), expected_packed_shape);+ ASSERT_EQ(k_q.packed.size(), ov::shape_size(expected_packed_shape));+ ASSERT_EQ(v_q.packed.size(), ov::shape_size(expected_packed_shape));++ auto q_mem = engine.allocate_memory(q_layout);+ set_values(q_mem, q_data);++ // --- Golden reference: uncompressed float attention on host-dequantized KV (sdpa_ref) ---+ auto make_ref_output = [&]() {+ auto k_mem = engine.allocate_memory(kv_deq_layout);+ auto v_mem = engine.allocate_memory(kv_deq_layout);+ set_values(k_mem, k_q.dequantized);+ set_values(v_mem, v_q.dequantized);++ topology topo;+ topo.add(input_layout("q", q_layout));+ topo.add(input_layout("k", kv_deq_layout));+ topo.add(input_layout("v", kv_deq_layout));+ auto prim = scaled_dot_product_attention("sdpa",+ {input_info("q"), input_info("k"), input_info("v")},+ true,+ -1,+ {0, 1, 2, 3},+ {0, 1, 2, 3},+ {0, 1, 2, 3},+ {0, 1, 2, 3},+ {},+ false);+ topo.add(prim);+ topo.add(reorder("result", input_info("sdpa"), format::bfyx, data_types::f16));++ ExecutionConfig cfg = get_test_default_config(engine);+ cfg.set_property(ov::intel_gpu::allow_new_shape_infer(true));++ auto net = get_network(engine, topo, cfg, get_test_stream_ptr(), false);+ net->set_input_data("q", q_mem);+ net->set_input_data("k", k_mem);+ net->set_input_data("v", v_mem);+ return net->execute().at("result").get_memory();+ };++ // --- Compressed path: quantized KV + interleaved scale/zp on the optimized kernel (sdpa_opt) ---+ auto make_opt_output = [&]() {+ auto k_mem = engine.allocate_memory(kv_packed_layout);+ auto v_mem = engine.allocate_memory(kv_packed_layout);+ auto k_comp_mem = engine.allocate_memory(comp_layout);+ auto v_comp_mem = engine.allocate_memory(comp_layout);+ auto k_zp_mem = has_storage_zero_point ? engine.allocate_memory(comp_layout) : nullptr;+ auto v_zp_mem = has_storage_zero_point ? engine.allocate_memory(comp_layout) : nullptr;+ set_values(k_mem, k_q.packed);+ set_values(v_mem, v_q.packed);+ set_values(k_comp_mem, k_q.scales);+ set_values(v_comp_mem, v_q.scales);+ if (has_storage_zero_point) {+ set_values(k_zp_mem, k_q.zero_points);+ set_values(v_zp_mem, v_q.zero_points);+ }++ scaled_dot_product_attention::QuantizationAttributes qa;+ qa.quantization_type = has_storage_zero_point ? ov::op::internal::DynamicQuantize::QuantizationType::Asymmetric+ : ov::op::internal::DynamicQuantize::QuantizationType::Symmetric;+ qa.quantization_dt = bit_width == 4 ? (has_storage_zero_point ? ov::element::u4 : ov::element::i4) : ov::element::i8;+ qa.scale_dt = ov::element::f16;+ qa.zp_dt = ov::element::f16;+ qa.group_sizes = granularity == kv_quant_granularity::per_channel+ ? std::vector<uint64_t>{1, 1, UINT64_MAX, 1}+ : std::vector<uint64_t>{1, 1, 1, UINT64_MAX};+ qa.scales_zp_output_order = {0, 1, 2, 3};+ qa.output_storage_type = ov::op::internal::DynamicQuantize::OutputStorageType::Planar;++ topology topo;+ topo.add(input_layout("q", q_layout));+ topo.add(input_layout("k", kv_packed_layout));+ topo.add(input_layout("v", kv_packed_layout));+ topo.add(input_layout("k_scale", comp_layout));+ topo.add(input_layout("v_scale", comp_layout));+ std::vector<input_info> inputs = {input_info("q"), input_info("k"), input_info("v"), input_info("k_scale"), input_info("v_scale")};+ if (has_storage_zero_point) {+ topo.add(input_layout("k_zp", comp_layout));+ topo.add(input_layout("v_zp", comp_layout));+ inputs.emplace_back("k_zp");+ inputs.emplace_back("v_zp");+ }++ auto prim = scaled_dot_product_attention("sdpa", inputs, true, -1, {0, 1, 2, 3}, {0, 1, 2, 3}, {0, 1, 2, 3}, {0, 1, 2, 3}, qa, true);+ topo.add(prim);+ topo.add(reorder("result", input_info("sdpa"), format::bfyx, data_types::f16));++ ExecutionConfig cfg = get_test_default_config(engine);+ cfg.set_property(ov::intel_gpu::allow_new_shape_infer(true));+ cfg.set_property(ov::hint::kv_cache_precision(bit_width == 4 ? ov::element::i4 : ov::element::i8));+ cfg.set_property(ov::intel_gpu::force_implementations(ov::intel_gpu::ImplForcingMap{{"sdpa", {format::type::bfyx, "sdpa_opt"}}}));++ auto net = get_network(engine, topo, cfg, get_test_stream_ptr(), false);+ net->set_input_data("q", q_mem);+ net->set_input_data("k", k_mem);+ net->set_input_data("v", v_mem);+ net->set_input_data("k_scale", k_comp_mem);+ net->set_input_data("v_scale", v_comp_mem);+ if (has_storage_zero_point) {+ net->set_input_data("k_zp", k_zp_mem);+ net->set_input_data("v_zp", v_zp_mem);+ }+ return net->execute().at("result").get_memory();+ };++ auto ref_mem = make_ref_output();+ auto opt_mem = make_opt_output();++ cldnn::mem_lock<ov::float16, mem_lock_type::read> ref_ptr(ref_mem, get_test_stream());+ cldnn::mem_lock<ov::float16, mem_lock_type::read> opt_ptr(opt_mem, get_test_stream());++ ASSERT_EQ(ref_ptr.size(), opt_ptr.size());+ for (size_t i = 0; i < opt_ptr.size(); ++i) {+ ASSERT_FALSE(std::isnan(static_cast<float>(opt_ptr[i]))) << "NaN in compressed output at index " << i;+ }+ const float sim = cosineSimilarity(ref_ptr, opt_ptr);+ ASSERT_GE(sim, 0.999f) << "bit_width=" << bit_width << ", asymmetric=" << asymmetric << " cosine similarity too low: " << sim;+}++struct sdpa_gpu_compressed_kv_test_base : public ::testing::TestWithParam<sdpa_test_params> {+ static std::string PrintToStringParamName(const testing::TestParamInfo<sdpa_test_params>& info) {+ const auto& p = info.param;+ return std::string("int") + std::to_string(p.bit_width) + (p.asymmetric ? "_asymmetric_" : "_symmetric_") ++ (p.num_heads == p.kv_num_heads ? "mha_" : "gqa_") + (p.sequence_length_q == 1 ? "decode" : "prefill");+ }+};++struct sdpa_gpu_compressed_kv_per_channel_test : public sdpa_gpu_compressed_kv_test_base {};++TEST_P(sdpa_gpu_compressed_kv_per_channel_test, compare_with_gpu_dequantized_reference) {+ run_compressed_kv_sdpa_test(GetParam(), kv_quant_granularity::per_channel);+}++struct sdpa_gpu_compressed_kv_per_token_test : public sdpa_gpu_compressed_kv_test_base {};++TEST_P(sdpa_gpu_compressed_kv_per_token_test, compare_with_gpu_dequantized_reference) {+ run_compressed_kv_sdpa_test(GetParam(), kv_quant_granularity::per_token);+}++// Verify the INT4 and INT8 cache encodings produced by the GQA decomposition.+struct sdpa_gpu_gqa_decomp_test : public sdpa_gpu_compressed_kv_test_base {};++TEST_P(sdpa_gpu_gqa_decomp_test, compare_with_gpu_dequantized_reference) {+ run_compressed_kv_sdpa_test(GetParam(), kv_quant_granularity::per_channel, /*gqa_decomp=*/true);+}++INSTANTIATE_TEST_SUITE_P(smoke_sdpa_gpu_compressed_kv_per_channel,+ sdpa_gpu_compressed_kv_per_channel_test,+ ::testing::Values(sdpa_test_params{128, 40, 10, 512, 512, 1, 4, false},+ sdpa_test_params{128, 40, 10, 1, 512, 1, 4, false},+ sdpa_test_params{128, 40, 40, 512, 512, 1, 4, false},+ sdpa_test_params{128, 40, 40, 1, 512, 1, 4, false},+ sdpa_test_params{128, 40, 10, 512, 512, 1, 4, true},+ sdpa_test_params{128, 40, 10, 1, 512, 1, 4, true},+ sdpa_test_params{128, 40, 40, 512, 512, 1, 4, true},+ sdpa_test_params{128, 40, 40, 1, 512, 1, 4, true},+ sdpa_test_params{128, 40, 10, 512, 512, 1, 8, false},+ sdpa_test_params{128, 40, 10, 1, 512, 1, 8, false},+ sdpa_test_params{128, 40, 40, 512, 512, 1, 8, false},+ sdpa_test_params{128, 40, 40, 1, 512, 1, 8, false},+ sdpa_test_params{128, 40, 10, 512, 512, 1, 8, true},+ sdpa_test_params{128, 40, 10, 1, 512, 1, 8, true},+ sdpa_test_params{128, 40, 40, 512, 512, 1, 8, true},+ sdpa_test_params{128, 40, 40, 1, 512, 1, 8, true}),+ sdpa_gpu_compressed_kv_per_channel_test::PrintToStringParamName);++INSTANTIATE_TEST_SUITE_P(smoke_sdpa_gpu_compressed_kv_per_token,+ sdpa_gpu_compressed_kv_per_token_test,+ ::testing::Values(sdpa_test_params{128, 40, 10, 512, 512, 1, 8, false},+ sdpa_test_params{128, 40, 10, 1, 512, 1, 8, false},+ sdpa_test_params{128, 40, 40, 512, 512, 1, 8, false},+ sdpa_test_params{128, 40, 40, 1, 512, 1, 8, false},+ sdpa_test_params{128, 40, 10, 512, 512, 1, 8, true},+ sdpa_test_params{128, 40, 10, 1, 512, 1, 8, true},+ sdpa_test_params{128, 40, 40, 512, 512, 1, 8, true},+ sdpa_test_params{128, 40, 40, 1, 512, 1, 8, true}),+ sdpa_gpu_compressed_kv_per_token_test::PrintToStringParamName);++INSTANTIATE_TEST_SUITE_P(smoke_sdpa_gpu_gqa_decomp,+ sdpa_gpu_gqa_decomp_test,+ ::testing::Values(sdpa_test_params{128, 40, 10, 512, 512, 1, 4, false},+ sdpa_test_params{128, 40, 10, 1, 512, 1, 4, false},+ sdpa_test_params{128, 40, 40, 512, 512, 1, 4, false},+ sdpa_test_params{128, 40, 40, 1, 512, 1, 4, false},+ sdpa_test_params{128, 40, 10, 512, 512, 1, 8, false},+ sdpa_test_params{128, 40, 10, 1, 512, 1, 8, false},+ sdpa_test_params{128, 40, 40, 512, 512, 1, 8, false},+ sdpa_test_params{128, 40, 40, 1, 512, 1, 8, false}),+ sdpa_gpu_gqa_decomp_test::PrintToStringParamName);#endifTEST(sdpa_gpu_custom, dynamic_mismatched_v_head_size) {diff --git a/src/plugins/intel_gpu/tests/unit/transformations/group_query_attention_decomposition_test.cpp b/src/plugins/intel_gpu/tests/unit/transformations/group_query_attention_decomposition_test.cppindex d59bb4bd104..71b813486db 100644--- a/src/plugins/intel_gpu/tests/unit/transformations/group_query_attention_decomposition_test.cpp+++ b/src/plugins/intel_gpu/tests/unit/transformations/group_query_attention_decomposition_test.cpp@@ -7,14 +7,15 @@#include <gtest/gtest.h>#include "intel_gpu/op/sdpa.hpp"+#include "openvino/op/broadcast.hpp"#include "openvino/core/model.hpp"+#include "openvino/op/concat.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/group_query_attention.hpp"#include "openvino/op/parameter.hpp"#include "openvino/op/result.hpp"#include "openvino/pass/manager.hpp"-namespace ov::test::intel_gpu {namespace {@@ -33,13 +34,18 @@ struct GQAConfig {float scale = 0.0f; // 0.0f == "use 1/sqrt(head_size)"bool flag_a = false; // do_rotarybool flag_b = false; // rotary_interleaved- int64_t softcap = 0;+ int64_t kv_cache_bit_width = 0;QuantType kv_quant = QuantType::NONE;QuantType out_quant = QuantType::NONE;+ ov::element::Type cache_type = ov::element::i8;int64_t local_window_size = -1; // >= 1 enables sliding window attentionbool sliding_window_cache = false;bool smooth_softmax = false; // adds an extra logit -> sink branch+ bool attention_bias = false;+ bool head_sink = false;bool causal = true;+ ov::PartialShape key_scale_shape{1};+ ov::PartialShape value_scale_shape{1};};std::shared_ptr<ov::Model> make_gqa_model(const GQAConfig& cfg) {@@ -49,12 +55,44 @@ std::shared_ptr<ov::Model> make_gqa_model(const GQAConfig& cfg) {auto query = std::make_shared<ov::op::v0::Parameter>(f32, ov::PartialShape{1, num_heads, 1, head_size});auto key = std::make_shared<ov::op::v0::Parameter>(f32, ov::PartialShape{1, kv_num_heads, 1, head_size});auto value = std::make_shared<ov::op::v0::Parameter>(f32, ov::PartialShape{1, kv_num_heads, 1, head_size});- auto past_key = std::make_shared<ov::op::v0::Parameter>(f32, ov::PartialShape{1, kv_num_heads, past_len, head_size});- auto past_value = std::make_shared<ov::op::v0::Parameter>(f32, ov::PartialShape{1, kv_num_heads, past_len, head_size});+ const auto cache_type = cfg.kv_cache_bit_width ? cfg.cache_type : f32;+ const auto cache_head_size = cfg.kv_cache_bit_width == 4 ? head_size / 2 : head_size;+ auto past_key = std::make_shared<ov::op::v0::Parameter>(cache_type, ov::PartialShape{1, kv_num_heads, past_len, cache_head_size});+ auto past_value = std::make_shared<ov::op::v0::Parameter>(cache_type, ov::PartialShape{1, kv_num_heads, past_len, cache_head_size});auto seqlens_k = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{1});auto total_sequence_length = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{});- ov::OutputVector inputs{query, key, value, past_key, past_value, seqlens_k, total_sequence_length};+ ov::OutputVector inputs(14);+ inputs[0] = query;+ inputs[1] = key;+ inputs[2] = value;+ inputs[3] = past_key;+ inputs[4] = past_value;+ inputs[5] = seqlens_k;+ inputs[6] = total_sequence_length;+ for (size_t i = 7; i <= 13; ++i) {+ inputs[i] = ov::op::v0::Constant::create(f32, ov::Shape{0}, {});+ }+ ov::ParameterVector parameters{query, key, value, past_key, past_value, seqlens_k, total_sequence_length};++ if (cfg.attention_bias) {+ auto attention_bias = std::make_shared<ov::op::v0::Parameter>(f32, ov::PartialShape{1, 1, 1, past_len});+ inputs[10] = attention_bias;+ parameters.push_back(attention_bias);+ }+ if (cfg.head_sink) {+ auto head_sink = std::make_shared<ov::op::v0::Parameter>(f32, ov::PartialShape{num_heads});+ inputs[11] = head_sink;+ parameters.push_back(head_sink);+ }+ if (cfg.kv_cache_bit_width) {+ auto key_scale = std::make_shared<ov::op::v0::Parameter>(f32, cfg.key_scale_shape);+ auto value_scale = std::make_shared<ov::op::v0::Parameter>(f32, cfg.value_scale_shape);+ inputs[12] = key_scale;+ inputs[13] = value_scale;+ parameters.push_back(key_scale);+ parameters.push_back(value_scale);+ }auto gqa = std::make_shared<ov::op::internal::GroupQueryAttention>(inputs,num_heads,@@ -62,7 +100,7 @@ std::shared_ptr<ov::Model> make_gqa_model(const GQAConfig& cfg) {cfg.scale,cfg.flag_a,cfg.flag_b,- cfg.softcap,+ cfg.kv_cache_bit_width,cfg.kv_quant,cfg.out_quant,cfg.local_window_size,@@ -74,7 +112,7 @@ std::shared_ptr<ov::Model> make_gqa_model(const GQAConfig& cfg) {for (const auto& output : gqa->outputs()) {results.push_back(std::make_shared<ov::op::v0::Result>(output));}- return std::make_shared<ov::Model>(results, ov::ParameterVector{query, key, value, past_key, past_value, seqlens_k, total_sequence_length});+ return std::make_shared<ov::Model>(results, parameters);}std::shared_ptr<ov::intel_gpu::op::SDPA> decompose_and_get_sdpa(const GQAConfig& cfg) {@@ -105,10 +143,20 @@ std::shared_ptr<ov::intel_gpu::op::SDPA> decompose_and_get_sdpa(const GQAConfig&return ::testing::AssertionSuccess();}+void expect_fixed_int4_zero_point(const ov::Output<ov::Node>& zero_point) {+ EXPECT_EQ(zero_point.get_element_type(), ov::element::f16);+ EXPECT_EQ(zero_point.get_partial_shape(), ov::PartialShape({1, kv_num_heads, 1, head_size}));+ const auto broadcast = ov::as_type_ptr<ov::op::v3::Broadcast>(zero_point.get_node_shared_ptr());+ ASSERT_NE(broadcast, nullptr);+ const auto value = ov::as_type_ptr<ov::op::v0::Constant>(broadcast->input_value(0).get_node_shared_ptr());+ ASSERT_NE(value, nullptr);+ EXPECT_EQ(value->cast_vector<float>(), std::vector<float>{8.0f});+}+// Verify that GQAConfig maps sliding_window_cache and smooth_softmax// to the intended constructor arguments. Re-checks this at runtime so a future ctor change// cannot silently invalidate the rest of the suite.-TEST(GroupQueryAttentionDecompositionTest, control_field_mapping_sanity) {+TEST(GQADecompositionTest, maps_control_fields) {{GQAConfig cfg;cfg.sliding_window_cache = true;@@ -125,7 +173,7 @@ TEST(GroupQueryAttentionDecompositionTest, control_field_mapping_sanity) {}// Plain causal attention uses lower-right masking without an explicit mask.-TEST(GroupQueryAttentionDecompositionTest, control_plain_causal_uses_lower_right_without_mask) {+TEST(GQADecompositionTest, causal_uses_lower_right_without_mask) {GQAConfig cfg;const auto sdpa = decompose_and_get_sdpa(cfg);@@ -135,8 +183,119 @@ TEST(GroupQueryAttentionDecompositionTest, control_plain_causal_uses_lower_rightEXPECT_EQ(sdpa->get_causal_mask_alignment(), ov::intel_gpu::op::SDPA::CausalMaskAlignment::LOWER_RIGHT);}+TEST(GQADecompositionTest, per_tensor_kv_uses_decompressed_sdpa) {+ GQAConfig cfg;+ cfg.kv_cache_bit_width = 8;+ cfg.kv_quant = QuantType::PER_TENSOR;+ cfg.out_quant = QuantType::PER_TENSOR;++ const auto sdpa = decompose_and_get_sdpa(cfg);++ ASSERT_NE(sdpa, nullptr);+ EXPECT_FALSE(sdpa->get_kv_compressed());+ ASSERT_EQ(sdpa->get_input_size(), 3u) << "Q, dequantized K, dequantized V";+ EXPECT_EQ(sdpa->input_value(1).get_element_type(), ov::element::f32);+ EXPECT_EQ(sdpa->input_value(2).get_element_type(), ov::element::f32);+}++TEST(GQADecompositionTest, per_channel_kv_uses_compressed_sdpa) {+ GQAConfig cfg;+ cfg.kv_cache_bit_width = 8;+ cfg.kv_quant = QuantType::PER_CHANNEL;+ cfg.out_quant = QuantType::PER_CHANNEL;+ cfg.key_scale_shape = ov::PartialShape{kv_num_heads * head_size};+ cfg.value_scale_shape = ov::PartialShape{kv_num_heads * head_size};++ const auto sdpa = decompose_and_get_sdpa(cfg);++ ASSERT_NE(sdpa, nullptr);+ ASSERT_TRUE(sdpa->get_kv_compressed());+ ASSERT_EQ(sdpa->get_input_size(), 5u) << "Q, K, V, K scale, V scale";+ EXPECT_EQ(sdpa->get_quantization_attrs().quantization_dt, ov::element::i8);+ EXPECT_EQ(sdpa->get_quantization_attrs().scale_dt, ov::element::f16);+ EXPECT_EQ(sdpa->get_quantization_attrs().group_sizes,+ (std::vector<uint64_t>{1, 1, std::numeric_limits<uint64_t>::max(), 1}));+ EXPECT_EQ(sdpa->input_value(1).get_element_type(), ov::element::i8);+ EXPECT_EQ(sdpa->input_value(2).get_element_type(), ov::element::i8);+ EXPECT_TRUE(ov::is_type<ov::op::v0::Concat>(sdpa->input_value(1).get_node_shared_ptr()));+ EXPECT_TRUE(ov::is_type<ov::op::v0::Concat>(sdpa->input_value(2).get_node_shared_ptr()));+ const size_t num_data_inputs = sdpa->get_input_size() - sdpa->get_compression_inputs_num();+ EXPECT_EQ(sdpa->input_value(num_data_inputs).get_element_type(), ov::element::f16);+ EXPECT_EQ(sdpa->input_value(num_data_inputs + 1).get_element_type(), ov::element::f16);+ EXPECT_EQ(sdpa->input_value(num_data_inputs).get_partial_shape(), ov::PartialShape({1, kv_num_heads, 1, head_size}));+ EXPECT_EQ(sdpa->input_value(num_data_inputs + 1).get_partial_shape(), ov::PartialShape({1, kv_num_heads, 1, head_size}));+}++TEST(GQADecompositionTest, compressed_kv_preserves_optional_inputs) {+ GQAConfig cfg;+ cfg.kv_cache_bit_width = 8;+ cfg.kv_quant = QuantType::PER_CHANNEL;+ cfg.out_quant = QuantType::PER_CHANNEL;+ cfg.key_scale_shape = ov::PartialShape{kv_num_heads * head_size};+ cfg.value_scale_shape = ov::PartialShape{kv_num_heads * head_size};+ cfg.scale = 0.125f;+ cfg.attention_bias = true;+ cfg.head_sink = true;++ const auto sdpa = decompose_and_get_sdpa(cfg);++ ASSERT_NE(sdpa, nullptr);+ ASSERT_TRUE(sdpa->get_kv_compressed());+ ASSERT_EQ(sdpa->get_input_size(), 8u) << "Q, K, V, mask, scale, sink, K scale, V scale";+ EXPECT_TRUE(slot_holds_a_mask(sdpa->input_value(3)));+ EXPECT_EQ(sdpa->input_value(4).get_element_type(), ov::element::f32);+ EXPECT_EQ(sdpa->input_value(5).get_element_type(), ov::element::f32);+ EXPECT_EQ(sdpa->input_value(6).get_element_type(), ov::element::f16);+ EXPECT_EQ(sdpa->input_value(7).get_element_type(), ov::element::f16);+}++TEST(GQADecompositionTest, int4_i8_cache_uses_u4_zp8) {+ GQAConfig cfg;+ cfg.kv_cache_bit_width = 4;+ cfg.kv_quant = QuantType::PER_CHANNEL;+ cfg.out_quant = QuantType::PER_CHANNEL;+ cfg.key_scale_shape = ov::PartialShape{kv_num_heads * head_size};+ cfg.value_scale_shape = ov::PartialShape{kv_num_heads * head_size};++ const auto sdpa = decompose_and_get_sdpa(cfg);++ ASSERT_NE(sdpa, nullptr);+ ASSERT_TRUE(sdpa->get_kv_compressed());+ ASSERT_EQ(sdpa->get_input_size(), 7u) << "Q, K, V, K scale, V scale, K zero point, V zero point";+ EXPECT_EQ(sdpa->get_quantization_attrs().quantization_type,+ ov::op::internal::DynamicQuantize::QuantizationType::Asymmetric);+ EXPECT_EQ(sdpa->get_quantization_attrs().quantization_dt, ov::element::u4);+ EXPECT_EQ(sdpa->input_value(1).get_element_type(), ov::element::i8);+ EXPECT_EQ(sdpa->input_value(2).get_element_type(), ov::element::i8);+ expect_fixed_int4_zero_point(sdpa->input_value(5));+ expect_fixed_int4_zero_point(sdpa->input_value(6));+}++TEST(GQADecompositionTest, int4_u8_cache_uses_u4_zp8) {+ GQAConfig cfg;+ cfg.kv_cache_bit_width = 4;+ cfg.kv_quant = QuantType::PER_CHANNEL;+ cfg.out_quant = QuantType::PER_CHANNEL;+ cfg.key_scale_shape = ov::PartialShape{kv_num_heads * head_size};+ cfg.value_scale_shape = ov::PartialShape{kv_num_heads * head_size};+ cfg.cache_type = ov::element::u8;++ const auto sdpa = decompose_and_get_sdpa(cfg);++ ASSERT_NE(sdpa, nullptr);+ ASSERT_TRUE(sdpa->get_kv_compressed());+ ASSERT_EQ(sdpa->get_input_size(), 7u) << "Q, K, V, K scale, V scale, K zero point, V zero point";+ EXPECT_EQ(sdpa->get_quantization_attrs().quantization_type,+ ov::op::internal::DynamicQuantize::QuantizationType::Asymmetric);+ EXPECT_EQ(sdpa->get_quantization_attrs().quantization_dt, ov::element::u4);+ EXPECT_EQ(sdpa->input_value(1).get_element_type(), ov::element::u8);+ EXPECT_EQ(sdpa->input_value(2).get_element_type(), ov::element::u8);+ expect_fixed_int4_zero_point(sdpa->input_value(5));+ expect_fixed_int4_zero_point(sdpa->input_value(6));+}+// A sliding-window cache retains the explicit attention mask.-TEST(GroupQueryAttentionDecompositionTest, explicit_mask_for_sliding_window_cache) {+TEST(GQADecompositionTest, sliding_window_keeps_mask) {GQAConfig cfg;cfg.local_window_size = 128;cfg.sliding_window_cache = true;@@ -148,7 +307,7 @@ TEST(GroupQueryAttentionDecompositionTest, explicit_mask_for_sliding_window_cach}// Causal smooth softmax retains the explicit mask.-TEST(GroupQueryAttentionDecompositionTest, explicit_mask_for_causal_smooth_softmax) {+TEST(GQADecompositionTest, smooth_softmax_keeps_mask) {GQAConfig cfg;cfg.smooth_softmax = true;cfg.causal = true;@@ -171,7 +330,7 @@ TEST(GroupQueryAttentionDecompositionTest, explicit_mask_for_causal_smooth_softm}// An explicit scale and smooth_softmax retains the explicit mask.-TEST(GroupQueryAttentionDecompositionTest, explicit_mask_for_causal_smooth_softmax_with_scale) {+TEST(GQADecompositionTest, smooth_softmax_with_scale_keeps_mask) {GQAConfig cfg;cfg.smooth_softmax = true;cfg.causal = true;@@ -184,7 +343,7 @@ TEST(GroupQueryAttentionDecompositionTest, explicit_mask_for_causal_smooth_softm}// A local window with a plain KV cache retains the explicit mask.-TEST(GroupQueryAttentionDecompositionTest, explicit_mask_for_local_window) {+TEST(GQADecompositionTest, local_window_keeps_mask) {GQAConfig cfg;cfg.causal = true;cfg.local_window_size = 128;@@ -199,7 +358,7 @@ TEST(GroupQueryAttentionDecompositionTest, explicit_mask_for_local_window) {}// Combining a local window and sink retains the explicit mask.-TEST(GroupQueryAttentionDecompositionTest, explicit_mask_for_local_window_with_sink) {+TEST(GQADecompositionTest, local_window_with_sink_keeps_mask) {GQAConfig cfg;cfg.causal = true;cfg.smooth_softmax = true;@@ -215,4 +374,4 @@ TEST(GroupQueryAttentionDecompositionTest, explicit_mask_for_local_window_with_s}} // namespace-} // namespace ov::test::intel_gpu\ No newline at end of file+} // namespace ov::test::intel_gpu