Skip to content

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

[GPU] Directly construct StatelessKV during GQA decomposition (#38578)

ZackyLakeacf20bfdd66c
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.hpp
index 17f45415db4..8ed8b04e575 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,8 +4,6 @@
#pragma once
-#include <optional>
-
#include "openvino/op/group_query_attention.hpp"
#include "openvino/op/shape_of.hpp"
#include "openvino/pass/matcher_pass.hpp"
@@ -25,13 +23,43 @@ public:
GroupQueryAttentionDecomposition();
protected:
- struct CompressedKV {
- ov::Output<ov::Node> key;
- ov::Output<ov::Node> value;
- ov::OutputVector quantization_inputs;
+ struct KVCacheMetadata {
+ ov::Output<ov::Node> k_scale;
+ ov::Output<ov::Node> v_scale;
+ bool should_quantize_kv = false;
+ bool should_dequantize_kv = false;
+ bool should_broadcast_kv = true;
+ virtual ~KVCacheMetadata() = default;
+ };
+ struct KVCacheOutputs {
+ ov::Output<ov::Node> present_key;
+ ov::Output<ov::Node> present_value;
+ ov::Output<ov::Node> sdpa_key;
+ ov::Output<ov::Node> sdpa_value;
+ ov::Output<ov::Node> mask_past_seqlen;
+ ov::Output<ov::Node> bias_col_offset;
};
ov::OutputVector decompose(std::shared_ptr<ov::op::internal::GroupQueryAttention> node);
+ virtual std::unique_ptr<KVCacheMetadata> create_metadata();
+ virtual KVCacheOutputs construct_kvcache(const std::shared_ptr<ov::op::internal::GroupQueryAttention>& node,
+ const ov::Output<ov::Node>& past_key,
+ const ov::Output<ov::Node>& past_value,
+ const ov::Output<ov::Node>& key,
+ const ov::Output<ov::Node>& value,
+ const ov::Output<ov::Node>& seqlens_1d,
+ const std::shared_ptr<ov::Node>& kv_seqlen,
+ const std::shared_ptr<ov::Node>& past_seqlen,
+ const ov::Output<ov::Node>& current_seqlen_scalar,
+ KVCacheMetadata& metadata);
+ virtual KVCacheOutputs construct_batched_kvcache(const std::shared_ptr<ov::op::internal::GroupQueryAttention>& node,
+ const ov::Output<ov::Node>& past_key,
+ const ov::Output<ov::Node>& past_value,
+ const ov::Output<ov::Node>& key,
+ const ov::Output<ov::Node>& value,
+ const std::shared_ptr<ov::Node>& kv_past_b,
+ const std::shared_ptr<ov::Node>& kv_rows,
+ KVCacheMetadata& metadata);
virtual std::shared_ptr<ov::Node> make_sdpa(const ov::Output<ov::Node>& query,
const ov::Output<ov::Node>& key,
const ov::Output<ov::Node>& value,
@@ -39,8 +67,8 @@ protected:
const ov::Output<ov::Node>& scale,
const ov::Output<ov::Node>& sink,
bool is_causal,
- int64_t local_window_size = -1,
- const std::optional<CompressedKV>& compressed_kv = std::nullopt);
+ int64_t local_window_size,
+ const KVCacheMetadata& metadata);
// Explicit attention for softcap > 0 or a qk_output request (SDPA can neither soft-cap nor expose the scores):
// softmax(cap(scale * Q * K^T) + mask [, sink]) * V, cap(x) = softcap * tanh(x / softcap) or x when softcap is 0.
// key/value keep kv_num_heads heads; query heads are grouped onto them by MatMul broadcasting, so the KV cache is
@@ -65,17 +93,9 @@ protected:
const ov::Output<ov::Node>& weight,
float epsilon);
- 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);
+ std::shared_ptr<ov::Node> get_dimensions(const ov::Output<ov::Node>& output, const std::vector<int>& dims);
std::shared_ptr<ov::Node> rotaryEmbedding(ov::Output<ov::Node> input,
ov::Output<ov::Node> cos,
ov::Output<ov::Node> sin,
@@ -104,7 +124,8 @@ protected:
const ov::Output<ov::Node>& bias_col_offset,
bool sliding_window_cache,
float scale,
- bool has_sink);
+ bool has_sink,
+ const KVCacheMetadata& metadata);
// Additive [B, 1, S, kv_len] mask for a batch with per-batch lengths (batch not statically 1). total and past
// are [B, 1, 1] (total = seqlens_k + 1, past = causal offset of the first query). Keys at or beyond a batch's
// total are masked (right-padded prompts), then the causal / sliding-window rules apply per batch, matching
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.cpp
index 8450abbbf7b..1e1450f8daf 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
@@ -57,6 +57,8 @@
using ov::pass::pattern::Matcher;
+using GQAInputs = ov::op::internal::GroupQueryAttentionInputs;
+
namespace v0 = ov::op::v0;
namespace v1 = ov::op::v1;
namespace v3 = ov::op::v3;
@@ -98,10 +100,13 @@ ov::pass::GroupQueryAttentionDecomposition::GroupQueryAttentionDecomposition() {
register_matcher(m, callback);
}
+std::unique_ptr<ov::pass::GroupQueryAttentionDecomposition::KVCacheMetadata>
+ov::pass::GroupQueryAttentionDecomposition::create_metadata() {
+ return std::make_unique<KVCacheMetadata>();
+}
+
ov::OutputVector ov::pass::GroupQueryAttentionDecomposition::decompose(
std::shared_ptr<ov::op::internal::GroupQueryAttention> node) {
- using GQAInputs = ov::op::internal::GroupQueryAttentionInputs;
-
const auto num_heads = node->get_num_heads();
const auto kv_num_heads = node->get_kv_num_heads();
const auto scale = node->get_scale();
@@ -135,6 +140,8 @@ ov::OutputVector ov::pass::GroupQueryAttentionDecomposition::decompose(
auto past_value = get_input(GQAInputs::PAST_VALUE);
auto seqlens_k = get_input(GQAInputs::SEQLENS_K);
+ const auto metadata = create_metadata();
+
// Quantized KV cache (com.microsoft spec): past/present KV are i8/u8/f8e4m3 and are dequantized before the
// attention math and (re)quantized when appended to the cache. Scales live at ONNX K_SCALE / V_SCALE positions.
const bool kv_quantized = node->is_kv_quantized();
@@ -142,14 +149,15 @@ ov::OutputVector ov::pass::GroupQueryAttentionDecomposition::decompose(
const auto k_quant_type = node->get_k_quant_type();
const auto v_quant_type = node->get_v_quant_type();
const auto kv_cache_type = past_key.get_element_type();
- ov::Output<ov::Node> k_scale, v_scale;
// Get k_scale and v_scale from their actual input indices.
// Note: validate_and_infer_types() already verified these indices are valid when kv_quantized is true,
// so we skip redundant bounds checks here.
if (kv_quantized) {
- k_scale = get_input(GQAInputs::K_SCALE);
- v_scale = get_input(GQAInputs::V_SCALE);
+ metadata->k_scale = get_input(GQAInputs::K_SCALE);
+ metadata->v_scale = get_input(GQAInputs::V_SCALE);
+ metadata->should_quantize_kv = true;
+ metadata->should_dequantize_kv = true;
}
// The length of all tokens (past + current) is `seqlens_k` + 1.
@@ -164,7 +172,6 @@ ov::OutputVector ov::pass::GroupQueryAttentionDecomposition::decompose(
const auto zero_without_shape = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{}, {0}));
const auto one = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{1}, {1}));
const auto one_without_shape = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{}, {1}));
- const auto two = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{1}, {2}));
const bool shared_kv = node->is_shared_kv();
// A separate key/value with a dynamic length may resolve to 0 at runtime (ORT shared KV), so its own length
// drives the cache arithmetic: the past keeps total - S_kv rows while the causal offset stays total - S_q.
@@ -255,17 +262,13 @@ ov::OutputVector ov::pass::GroupQueryAttentionDecomposition::decompose(
K = rotaryEmbedding(K, cos, sin, rotary_interleaved);
}
}
- // A preallocated cache (static capacity and step length, whatever the batch) is written in place. A
- // zero-capacity past (an absent ONNX past or an empty cache) has nothing to write into, so it grows by
- // concatenation instead. Same rule as the op's present shape inference.
- const auto is_static_input = node->has_fixed_kv_capacity();
// Quantize-on-write: when the cache is quantized, quantize the (post-RoPE) current K/V into the cache type
// before appending them, so the assembled present cache stays quantized and the past bytes are preserved
// verbatim (no re-rounding of past tokens). Matches ONNX Runtime MLAS/CUDA semantics.
- if (kv_quantized && !shared_kv) {
- K = quantize_kv(K, k_scale, kv_num_heads, kv_cache_bit_width, k_quant_type, kv_cache_type);
- V = quantize_kv(V, v_scale, kv_num_heads, kv_cache_bit_width, v_quant_type, kv_cache_type);
+ if (metadata->should_quantize_kv && !shared_kv) {
+ K = quantize_kv(K, metadata->k_scale, kv_num_heads, kv_cache_bit_width, k_quant_type, kv_cache_type);
+ V = quantize_kv(V, metadata->v_scale, kv_num_heads, kv_cache_bit_width, v_quant_type, kv_cache_type);
}
// past_seqlen expressed in the coordinate system the attention mask uses. Equals the absolute past
@@ -285,193 +288,52 @@ ov::OutputVector ov::pass::GroupQueryAttentionDecomposition::decompose(
V = past_value;
present_k = past_key;
present_v = past_value;
- } else if (node->get_sliding_window_cache()) {
- // Windowed KV cache (capacity C, rolled with front eviction). end_before/end_after are the resident
- // row counts before/after appending the S new tokens (see windowed_cache_end).
- const auto capacity = get_dimensions(past_key.get_node_shared_ptr(), {2});
- const auto capacity_scalar = register_new_node<v0::Squeeze>(capacity);
- const auto abs_past_scalar = register_new_node<v0::Squeeze>(past_seqlen); // P
- const auto abs_total_scalar = register_new_node<v0::Squeeze>(seqlens_1d); // P + S
- const auto end_before = windowed_cache_end(abs_past_scalar, capacity_scalar, local_window_size);
- const auto end_after = windowed_cache_end(abs_total_scalar, capacity_scalar, local_window_size);
-
- // Static single-token decode (S == 1) always fits the window and uses the in-place Gather +
- // ScatterUpdate assembly (static-shape friendly). Otherwise (dynamic S) a multi-token step may cross
- // an eviction, making the in-place kept = end_after - S negative, so it takes the staging path below.
- // A statically-known S > 1 is rejected up front (FE + op), so it never reaches here.
- const auto& q_ps = node->get_input_partial_shape(0);
- const bool static_single_token = q_ps.rank().is_static() && q_ps.rank().get_length() == 4 &&
- q_ps[2].is_static() && q_ps[2].get_length() == 1;
-
- const auto scatter_axis = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{1}, {2}));
- const auto zeros =
- register_new_node<v3::Broadcast>(register_new_node(v0::Constant::create(kv_cache_type, ov::Shape{}, {0})),
- register_new_node<v3::ShapeOf>(past_key));
-
- if (static_single_token) {
- // present = [survivors, new, zeros] left-aligned in the C buffer: the last kept = end_after - S
- // resident rows, then the S new tokens.
- const auto kept = register_new_node<v1::Subtract>(end_after, curr_seqlen_scalar); // end_after - S
- const auto survivor_start = register_new_node<v1::Subtract>(end_before, kept);
- const auto kept_row =
- register_new_node<v4::Range>(zero_without_shape, kept, one_without_shape, ov::element::i64);
- const auto survivor_idx = register_new_node<v1::Add>(kept_row, survivor_start);
- const auto survivor_k = register_new_node<v8::Gather>(past_key, survivor_idx, two);
- const auto survivor_v = register_new_node<v8::Gather>(past_value, survivor_idx, two);
- const auto kept_idx = kept_row;
- const auto new_row = register_new_node<v4::Range>(zero_without_shape,
- curr_seqlen_scalar,
- one_without_shape,
- ov::element::i64);
- const auto new_idx = register_new_node<v1::Add>(new_row, kept);
-
- present_k = register_new_node<v3::ScatterUpdate>(zeros, kept_idx, survivor_k, scatter_axis);
- present_k = register_new_node<v3::ScatterUpdate>(present_k, new_idx, K, scatter_axis);
- present_v = register_new_node<v3::ScatterUpdate>(zeros, kept_idx, survivor_v, scatter_axis);
- present_v = register_new_node<v3::ScatterUpdate>(present_v, new_idx, V, scatter_axis);
-
- // Attention runs on the trimmed [survivors, new] buffer (end_after rows, no trailing padding), so
- // the kernel's native LOWER_RIGHT + window sees the newest token as the last row. present_k/present_v
- // (left-aligned, padded to capacity C) stay the ORT-compatible op outputs. Mirrors the staging path.
- K = register_new_node<v0::Concat>(ov::OutputVector{survivor_k, K}, 2);
- V = register_new_node<v0::Concat>(ov::OutputVector{survivor_v, V}, 2);
- mask_past_seqlen = register_new_node<v0::Unsqueeze>(kept, zero);
- // First resident slot holds absolute key P - kept (the survivors start there).
- bias_col_offset =
- register_new_node<v0::Unsqueeze>(register_new_node<v1::Subtract>(abs_past_scalar, kept), zero);
- } else {
- // Staging (ORT parity): attend against a temp buffer of the end_before resident rows + S new
- // tokens, then write only the surviving tail (last end_after rows) back into the capacity-C cache.
- const auto end_before_1d = register_new_node<v0::Unsqueeze>(end_before, zero);
- const auto resident_k = register_new_node<v8::Slice>(past_key, zero, end_before_1d, one, two);
- const auto resident_v = register_new_node<v8::Slice>(past_value, zero, end_before_1d, one, two);
- const auto temp_k = register_new_node<v0::Concat>(ov::OutputVector{resident_k, K}, 2);
- const auto temp_v = register_new_node<v0::Concat>(ov::OutputVector{resident_v, V}, 2);
-
- // tail = last end_after rows of the temp buffer, scattered into [0, end_after) of the C buffer.
- const auto temp_len = register_new_node<v1::Add>(end_before, curr_seqlen_scalar);
- const auto tail_start = register_new_node<v1::Subtract>(temp_len, end_after);
- const auto tail_start_1d = register_new_node<v0::Unsqueeze>(tail_start, zero);
- const auto temp_len_1d = register_new_node<v0::Unsqueeze>(temp_len, zero);
- const auto tail_k = register_new_node<v8::Slice>(temp_k, tail_start_1d, temp_len_1d, one, two);
- const auto tail_v = register_new_node<v8::Slice>(temp_v, tail_start_1d, temp_len_1d, one, two);
- const auto present_row =
- register_new_node<v4::Range>(zero_without_shape, end_after, one_without_shape, ov::element::i64);
- present_k = register_new_node<v3::ScatterUpdate>(zeros, present_row, tail_k, scatter_axis);
- present_v = register_new_node<v3::ScatterUpdate>(zeros, present_row, tail_v, scatter_axis);
-
- // Attention runs on the temp buffer; only the returned present is the capacity-C tail.
- K = temp_k;
- V = temp_v;
- mask_past_seqlen = register_new_node<v0::Unsqueeze>(end_before, zero);
- // Temp buffer's first slot holds absolute key P - end_before.
- bias_col_offset =
- register_new_node<v0::Unsqueeze>(register_new_node<v1::Subtract>(abs_past_scalar, end_before), zero);
- }
- } else if (batched) {
- // Per-batch cache write (ORT ConcatStateChunkGQA, left-aligned): batch b keeps its first kv_past_b rows and
- // gets its S_kv new rows at [kv_past_b, kv_past_b + S_kv). The cache is viewed as [B * Nkv * L, D] rows and
- // written with one ScatterUpdate(axis 0) at row (b * Nkv + h) * L + kv_past_b + s: in place on a static buffer,
- // after a single Concat(past, new) for a growing cache (L = past rows + S_kv; rows past a batch's total are
- // unspecified, as in ORT). Index arithmetic stays rank 4 ([B, Nkv, S_kv, 1]) so plugins broadcast it in their
- // native layout.
- const auto kv_rows = independent_kv_len ? kv_seqlen : current_seqlen;
- const auto as_shape = [&](std::initializer_list<int64_t> shape) {
- return register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{shape.size()}, shape));
- };
- const auto batch = register_new_node<v0::Squeeze>(get_dimensions(register_new_node<v3::ShapeOf>(K), {0}));
- const auto batch_idx = register_new_node<v1::Reshape>(
- register_new_node<v4::Range>(zero_without_shape, batch, one_without_shape, ov::element::i64),
- as_shape({-1, 1, 1, 1}),
- false);
- std::vector<int64_t> heads(static_cast<size_t>(kv_num_heads));
- std::iota(heads.begin(), heads.end(), int64_t{0});
- const auto head_idx = register_new_node(
- v0::Constant::create(ov::element::i64, ov::Shape{1, static_cast<size_t>(kv_num_heads), 1, 1}, heads));
- const auto bh_idx = register_new_node<v1::Add>(
- register_new_node<v1::Multiply>(
- batch_idx,
- register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{}, {kv_num_heads}))),
- head_idx); // [B, Nkv, 1, 1]
- const auto new_row = register_new_node<v1::Add>(
- register_new_node<v1::Reshape>(kv_past_b, as_shape({-1, 1, 1, 1}), false),
- register_new_node<v1::Reshape>(register_new_node<v4::Range>(zero_without_shape,
- register_new_node<v0::Squeeze>(kv_rows),
- one_without_shape,
- ov::element::i64),
- as_shape({1, 1, -1, 1}),
- false)); // [B, 1, S_kv, 1]
- const auto write = [&](const ov::Output<ov::Node>& past, const ov::Output<ov::Node>& current) {
- const ov::Output<ov::Node> buffer =
- is_static_input ? past : register_new_node<v0::Concat>(ov::OutputVector{past, current}, 2)->output(0);
- const auto buffer_shape = register_new_node<v3::ShapeOf>(buffer);
- const auto rows_per_head = get_dimensions(buffer_shape, {2});
- const auto flat_idx = register_new_node<v1::Reshape>(
- register_new_node<v1::Add>(register_new_node<v1::Multiply>(bh_idx, rows_per_head), new_row),
- as_shape({-1}),
- false); // [B * Nkv * S_kv]
- const auto row_shape =
- register_new_node<v0::Concat>(ov::OutputVector{as_shape({-1}), get_dimensions(buffer_shape, {3})}, 0);
- const auto rows =
- register_new_node<v3::ScatterUpdate>(register_new_node<v1::Reshape>(buffer, row_shape, false),
- flat_idx,
- register_new_node<v1::Reshape>(current, row_shape, false),
- zero);
- return register_new_node<v1::Reshape>(rows, buffer_shape, false);
- };
- K = write(past_key, K);
- V = write(past_value, V);
- present_k = K;
- present_v = V;
- } else if (is_static_input) {
- // Static full-length cache (max length, valid KVs left-aligned). Insert current K/V at
- // [past_seqlen, past_seqlen + curr_seqlen] with ScatterUpdate, keeping the buffer shape.
- // An out-of-range past_seqlen is ScatterUpdate's own bounds-check responsibility, not something to
- // guard against here via a graph-level clamp; the decomposition assumes the caller-supplied
- // seqlens_k stays within the declared cache capacity.
- std::shared_ptr<ov::Node> scatter_idx =
- register_new_node<v4::Range>(zero_without_shape, curr_seqlen_scalar, one_without_shape, ov::element::i64);
- scatter_idx = register_new_node<v1::Add>(scatter_idx, past_seqlen);
- const auto scatter_axis = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{1}, {2}));
- K = register_new_node<v3::ScatterUpdate>(past_key, scatter_idx, K, scatter_axis);
- V = register_new_node<v3::ScatterUpdate>(past_value, scatter_idx, V, scatter_axis);
- present_k = K;
- present_v = V;
} else {
- auto construct_kv_cache = [&](const ov::Output<ov::Node>& past, const ov::Output<ov::Node>& current) {
- return register_new_node<v0::Concat>(ov::OutputVector{past, current}, 2);
- };
- const ov::Output<ov::Node> kept_past = independent_kv_len
- ? register_new_node<v1::Subtract>(seqlens_1d, kv_seqlen)->output(0)
- : past_seqlen->output(0);
- past_key = register_new_node<v8::Slice>(past_key, zero, kept_past, one, two);
- past_value = register_new_node<v8::Slice>(past_value, zero, kept_past, one, two);
- K = construct_kv_cache(past_key, K);
- V = construct_kv_cache(past_value, V);
- present_k = K;
- present_v = V;
+ const auto cache = batched ? construct_batched_kvcache(node,
+ past_key,
+ past_value,
+ K,
+ V,
+ kv_past_b,
+ independent_kv_len ? kv_seqlen : current_seqlen,
+ *metadata)
+ : construct_kvcache(node,
+ past_key,
+ past_value,
+ K,
+ V,
+ seqlens_1d,
+ kv_seqlen,
+ past_seqlen,
+ curr_seqlen_scalar,
+ *metadata);
+ K = cache.sdpa_key;
+ V = cache.sdpa_value;
+ present_k = cache.present_key;
+ present_v = cache.present_value;
+ mask_past_seqlen = cache.mask_past_seqlen;
+ bias_col_offset = cache.bias_col_offset;
}
- // The explicit attention chain consumes plain (dequantized) K/V, so skip the compressed-KV SDPA form.
- std::optional<CompressedKV> compressed_kv;
- if (!use_explicit_attention) {
- compressed_kv = prepare_compressed_kv(node, K, V, k_scale, v_scale);
+ // The explicit attention chain consumes plain (dequantized) K/V, so plugins must not keep a compressed KV for it.
+ if (use_explicit_attention && kv_quantized) {
+ OPENVINO_ASSERT(metadata->should_dequantize_kv,
+ "GroupQueryAttention with softcap requires dequantized KV cache");
}
-
// 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 && !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);
+ if (metadata->should_dequantize_kv) {
+ K = dequantize_kv(K, metadata->k_scale, kv_num_heads, kv_cache_bit_width, k_quant_type, T);
+ V = dequantize_kv(V, metadata->v_scale, kv_num_heads, kv_cache_bit_width, v_quant_type, T);
}
- const auto concat_kv_len = get_dimensions(K.get_node_shared_ptr(), {2});
+ const auto concat_kv_len = get_dimensions(K, {2});
const auto concat_kv_len_scalar = register_new_node<v0::Squeeze>(concat_kv_len);
// Broadcast KV if grouped query attention
const size_t kv_num_heads_factor = num_heads / kv_num_heads;
// The explicit chain groups query heads per KV head itself (no KV replication), see make_explicit_attention.
- if (kv_num_heads_factor > 1 && !compressed_kv && !use_explicit_attention) {
+ if (kv_num_heads_factor > 1 && metadata->should_broadcast_kv && !use_explicit_attention) {
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});
@@ -499,6 +361,7 @@ ov::OutputVector ov::pass::GroupQueryAttentionDecomposition::decompose(
// qk_output before softmax reports masked positions as 0 (ORT); they are found on the bias-free mask, so a large
// negative attention_bias reads logit + bias. The mask is then built once without the bias, and the aligned bias
// is added on top (same op count as the fused form).
+
const bool split_bias =
qk_output == ov::op::internal::GroupQueryAttentionQKOutput::BEFORE_SOFTMAX && external_bias.get_node();
const auto mask_bias = split_bias ? ov::Output<ov::Node>() : external_bias;
@@ -523,7 +386,8 @@ ov::OutputVector ov::pass::GroupQueryAttentionDecomposition::decompose(
bias_col_offset,
node->get_sliding_window_cache(),
scale,
- has_sink)
+ has_sink,
+ *metadata)
: make_attention_mask(curr_seqlen_scalar,
concat_kv_len_scalar,
concat_kv_len,
@@ -535,7 +399,8 @@ ov::OutputVector ov::pass::GroupQueryAttentionDecomposition::decompose(
bias_col_offset,
node->get_sliding_window_cache(),
scale,
- has_sink);
+ has_sink,
+ *metadata);
// qk_output before softmax reports masked positions as 0 (ORT). They are found on the mask without
// attention_bias, so a large negative bias value is reported as logit + bias, not as masked.
@@ -603,12 +468,12 @@ ov::OutputVector ov::pass::GroupQueryAttentionDecomposition::decompose(
}
} else if (sink.get_node_shared_ptr()) {
// SDPA's 6-input form requires an explicit scale.
- qga_output = make_sdpa(Q, K, V, mask, make_scale_node(), sink, false, local_window_size, compressed_kv);
+ qga_output = make_sdpa(Q, K, V, mask, make_scale_node(), sink, false, local_window_size, *metadata);
} 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, local_window_size, compressed_kv);
+ qga_output = make_sdpa(Q, K, V, mask, scale_node, {}, false, local_window_size, *metadata);
} else {
- qga_output = make_sdpa(Q, K, V, mask, {}, {}, !mask, local_window_size, compressed_kv);
+ qga_output = make_sdpa(Q, K, V, mask, {}, {}, !mask, local_window_size, *metadata);
}
// transpose the result from (batch_size, num_heads, sequence_length, head_size)
@@ -624,6 +489,228 @@ ov::OutputVector ov::pass::GroupQueryAttentionDecomposition::decompose(
return {output, present_k, present_v};
}
+ov::pass::GroupQueryAttentionDecomposition::KVCacheOutputs
+ov::pass::GroupQueryAttentionDecomposition::construct_kvcache(
+ const std::shared_ptr<ov::op::internal::GroupQueryAttention>& node,
+ const ov::Output<ov::Node>& past_key,
+ const ov::Output<ov::Node>& past_value,
+ const ov::Output<ov::Node>& key,
+ const ov::Output<ov::Node>& value,
+ const ov::Output<ov::Node>& seqlens_1d,
+ const std::shared_ptr<ov::Node>& kv_seqlen,
+ const std::shared_ptr<ov::Node>& past_seqlen,
+ const ov::Output<ov::Node>& current_seqlen_scalar,
+ [[maybe_unused]] KVCacheMetadata& metadata) {
+ const auto zero = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{1}, {0}));
+ const auto zero_without_shape = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{}, {0}));
+ const auto one = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{1}, {1}));
+ const auto one_without_shape = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{}, {1}));
+ const auto two = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{1}, {2}));
+ const auto kv_cache_type = past_key.get_element_type();
+ const bool independent_kv_len = node->has_independent_kv_length();
+
+ KVCacheOutputs outputs;
+ outputs.mask_past_seqlen = past_seqlen;
+ outputs.bias_col_offset = zero;
+
+ // A preallocated cache (static capacity and step length, whatever the batch) is written in place. A
+ // zero-capacity past (an absent ONNX past or an empty cache) has nothing to write into, so it grows by
+ // concatenation instead. Same rule as the op's present shape inference.
+ const auto is_static_input = node->has_fixed_kv_capacity();
+
+ if (node->get_sliding_window_cache()) {
+ // Windowed KV cache (capacity C, rolled with front eviction). end_before/end_after are the resident
+ // row counts before/after appending the S new tokens (see windowed_cache_end).
+ const auto local_window_size = node->get_local_window_size();
+ const auto capacity = get_dimensions(past_key, {2});
+ const auto capacity_scalar = register_new_node<v0::Squeeze>(capacity);
+ const auto abs_past_scalar = register_new_node<v0::Squeeze>(past_seqlen); // P
+ const auto abs_total_scalar = register_new_node<v0::Squeeze>(seqlens_1d); // P + S
+ const auto end_before = windowed_cache_end(abs_past_scalar, capacity_scalar, local_window_size);
+ const auto end_after = windowed_cache_end(abs_total_scalar, capacity_scalar, local_window_size);
+
+ // Static single-token decode (S == 1) always fits the window and uses the in-place Gather +
+ // ScatterUpdate assembly (static-shape friendly). Otherwise (dynamic S) a multi-token step may cross
+ // an eviction, making the in-place kept = end_after - S negative, so it takes the staging path below.
+ // A statically-known S > 1 is rejected up front (FE + op), so it never reaches here.
+ const auto& q_ps = node->get_input_partial_shape(0);
+ const bool static_single_token = q_ps.rank().is_static() && q_ps.rank().get_length() == 4 &&
+ q_ps[2].is_static() && q_ps[2].get_length() == 1;
+
+ const auto scatter_axis = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{1}, {2}));
+ const auto zeros =
+ register_new_node<v3::Broadcast>(register_new_node(v0::Constant::create(kv_cache_type, ov::Shape{}, {0})),
+ register_new_node<v3::ShapeOf>(past_key));
+
+ if (static_single_token) {
+ // present = [survivors, new, zeros] left-aligned in the C buffer: the last kept = end_after - S
+ // resident rows, then the S new tokens.
+ const auto kept = register_new_node<v1::Subtract>(end_after, current_seqlen_scalar); // end_after - S
+ const auto survivor_start = register_new_node<v1::Subtract>(end_before, kept);
+ const auto kept_row =
+ register_new_node<v4::Range>(zero_without_shape, kept, one_without_shape, ov::element::i64);
+ const auto survivor_idx = register_new_node<v1::Add>(kept_row, survivor_start);
+ const auto survivor_k = register_new_node<v8::Gather>(past_key, survivor_idx, two);
+ const auto survivor_v = register_new_node<v8::Gather>(past_value, survivor_idx, two);
+ const auto kept_idx = kept_row;
+ const auto new_row = register_new_node<v4::Range>(zero_without_shape,
+ current_seqlen_scalar,
+ one_without_shape,
+ ov::element::i64);
+ const auto new_idx = register_new_node<v1::Add>(new_row, kept);
+
+ outputs.present_key = register_new_node<v3::ScatterUpdate>(zeros, kept_idx, survivor_k, scatter_axis);
+ outputs.present_key = register_new_node<v3::ScatterUpdate>(outputs.present_key, new_idx, key, scatter_axis);
+ outputs.present_value = register_new_node<v3::ScatterUpdate>(zeros, kept_idx, survivor_v, scatter_axis);
+ outputs.present_value =
+ register_new_node<v3::ScatterUpdate>(outputs.present_value, new_idx, value, scatter_axis);
+
+ // Attention runs on the trimmed [survivors, new] buffer (end_after rows, no trailing padding), so
+ // the kernel's native LOWER_RIGHT + window sees the newest token as the last row. present_k/present_v
+ // (left-aligned, padded to capacity C) stay the ORT-compatible op outputs. Mirrors the staging path.
+ outputs.sdpa_key = register_new_node<v0::Concat>(ov::OutputVector{survivor_k, key}, 2);
+ outputs.sdpa_value = register_new_node<v0::Concat>(ov::OutputVector{survivor_v, value}, 2);
+ outputs.mask_past_seqlen = register_new_node<v0::Unsqueeze>(kept, zero);
+ // First resident slot holds absolute key P - kept (the survivors start there).
+ outputs.bias_col_offset =
+ register_new_node<v0::Unsqueeze>(register_new_node<v1::Subtract>(abs_past_scalar, kept), zero);
+ } else {
+ // Staging (ORT parity): attend against a temp buffer of the end_before resident rows + S new
+ // tokens, then write only the surviving tail (last end_after rows) back into the capacity-C cache.
+ const auto end_before_1d = register_new_node<v0::Unsqueeze>(end_before, zero);
+ const auto resident_k = register_new_node<v8::Slice>(past_key, zero, end_before_1d, one, two);
+ const auto resident_v = register_new_node<v8::Slice>(past_value, zero, end_before_1d, one, two);
+ const auto temp_k = register_new_node<v0::Concat>(ov::OutputVector{resident_k, key}, 2);
+ const auto temp_v = register_new_node<v0::Concat>(ov::OutputVector{resident_v, value}, 2);
+
+ // tail = last end_after rows of the temp buffer, scattered into [0, end_after) of the C buffer.
+ const auto temp_len = register_new_node<v1::Add>(end_before, current_seqlen_scalar);
+ const auto tail_start = register_new_node<v1::Subtract>(temp_len, end_after);
+ const auto tail_start_1d = register_new_node<v0::Unsqueeze>(tail_start, zero);
+ const auto temp_len_1d = register_new_node<v0::Unsqueeze>(temp_len, zero);
+ const auto tail_k = register_new_node<v8::Slice>(temp_k, tail_start_1d, temp_len_1d, one, two);
+ const auto tail_v = register_new_node<v8::Slice>(temp_v, tail_start_1d, temp_len_1d, one, two);
+ const auto present_row =
+ register_new_node<v4::Range>(zero_without_shape, end_after, one_without_shape, ov::element::i64);
+ outputs.present_key = register_new_node<v3::ScatterUpdate>(zeros, present_row, tail_k, scatter_axis);
+ outputs.present_value = register_new_node<v3::ScatterUpdate>(zeros, present_row, tail_v, scatter_axis);
+
+ // Attention runs on the temp buffer; only the returned present is the capacity-C tail.
+ outputs.sdpa_key = temp_k;
+ outputs.sdpa_value = temp_v;
+ outputs.mask_past_seqlen = register_new_node<v0::Unsqueeze>(end_before, zero);
+ // Temp buffer's first slot holds absolute key P - end_before.
+ outputs.bias_col_offset =
+ register_new_node<v0::Unsqueeze>(register_new_node<v1::Subtract>(abs_past_scalar, end_before), zero);
+ }
+ } else if (is_static_input) {
+ // Static full-length cache (max length, valid KVs left-aligned). Insert current K/V at
+ // [past_seqlen, past_seqlen + curr_seqlen] with ScatterUpdate, keeping the buffer shape.
+ // An out-of-range past_seqlen is ScatterUpdate's own bounds-check responsibility, not something to
+ // guard against here via a graph-level clamp; the decomposition assumes the caller-supplied
+ // seqlens_k stays within the declared cache capacity.
+ std::shared_ptr<ov::Node> scatter_idx = register_new_node<v4::Range>(zero_without_shape,
+ current_seqlen_scalar,
+ one_without_shape,
+ ov::element::i64);
+ scatter_idx = register_new_node<v1::Add>(scatter_idx, past_seqlen);
+ const auto scatter_axis = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{1}, {2}));
+ outputs.present_key = register_new_node<v3::ScatterUpdate>(past_key, scatter_idx, key, scatter_axis);
+ outputs.present_value = register_new_node<v3::ScatterUpdate>(past_value, scatter_idx, value, scatter_axis);
+ outputs.sdpa_key = outputs.present_key;
+ outputs.sdpa_value = outputs.present_value;
+ } else {
+ auto construct_kv_cache = [&](const ov::Output<ov::Node>& past, const ov::Output<ov::Node>& current) {
+ return register_new_node<v0::Concat>(ov::OutputVector{past, current}, 2);
+ };
+ const ov::Output<ov::Node> kept_past = independent_kv_len
+ ? register_new_node<v1::Subtract>(seqlens_1d, kv_seqlen)->output(0)
+ : past_seqlen->output(0);
+ const auto sliced_past_key = register_new_node<v8::Slice>(past_key, zero, kept_past, one, two);
+ const auto sliced_past_value = register_new_node<v8::Slice>(past_value, zero, kept_past, one, two);
+ outputs.present_key = construct_kv_cache(sliced_past_key, key);
+ outputs.present_value = construct_kv_cache(sliced_past_value, value);
+ outputs.sdpa_key = outputs.present_key;
+ outputs.sdpa_value = outputs.present_value;
+ }
+ return outputs;
+}
+
+ov::pass::GroupQueryAttentionDecomposition::KVCacheOutputs
+ov::pass::GroupQueryAttentionDecomposition::construct_batched_kvcache(
+ const std::shared_ptr<ov::op::internal::GroupQueryAttention>& node,
+ const ov::Output<ov::Node>& past_key,
+ const ov::Output<ov::Node>& past_value,
+ const ov::Output<ov::Node>& key,
+ const ov::Output<ov::Node>& value,
+ const std::shared_ptr<ov::Node>& kv_past_b,
+ const std::shared_ptr<ov::Node>& kv_rows,
+ [[maybe_unused]] KVCacheMetadata& metadata) {
+ const auto zero = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{1}, {0}));
+ const auto zero_without_shape = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{}, {0}));
+ const auto one_without_shape = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{}, {1}));
+ const auto kv_num_heads = node->get_kv_num_heads();
+ const auto is_static_input = node->has_fixed_kv_capacity();
+
+ KVCacheOutputs outputs;
+ outputs.bias_col_offset = zero;
+
+ // Per-batch cache write (ORT ConcatStateChunkGQA, left-aligned): batch b keeps its first kv_past_b rows and
+ // gets its S_kv new rows at [kv_past_b, kv_past_b + S_kv). The cache is viewed as [B * Nkv * L, D] rows and
+ // written with one ScatterUpdate(axis 0) at row (b * Nkv + h) * L + kv_past_b + s: in place on a static buffer,
+ // after a single Concat(past, new) for a growing cache (L = past rows + S_kv; rows past a batch's total are
+ // unspecified, as in ORT). Index arithmetic stays rank 4 ([B, Nkv, S_kv, 1]) so plugins broadcast it in their
+ // native layout.
+ const auto as_shape = [&](std::initializer_list<int64_t> shape) {
+ return register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{shape.size()}, shape));
+ };
+ const auto batch = register_new_node<v0::Squeeze>(get_dimensions(register_new_node<v3::ShapeOf>(key), {0}));
+ const auto batch_idx = register_new_node<v1::Reshape>(
+ register_new_node<v4::Range>(zero_without_shape, batch, one_without_shape, ov::element::i64),
+ as_shape({-1, 1, 1, 1}),
+ false);
+ std::vector<int64_t> heads(static_cast<size_t>(kv_num_heads));
+ std::iota(heads.begin(), heads.end(), int64_t{0});
+ const auto head_idx = register_new_node(
+ v0::Constant::create(ov::element::i64, ov::Shape{1, static_cast<size_t>(kv_num_heads), 1, 1}, heads));
+ const auto bh_idx = register_new_node<v1::Add>(
+ register_new_node<v1::Multiply>(
+ batch_idx,
+ register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{}, {kv_num_heads}))),
+ head_idx); // [B, Nkv, 1, 1]
+ const auto new_row = register_new_node<v1::Add>(
+ register_new_node<v1::Reshape>(kv_past_b, as_shape({-1, 1, 1, 1}), false),
+ register_new_node<v1::Reshape>(register_new_node<v4::Range>(zero_without_shape,
+ register_new_node<v0::Squeeze>(kv_rows),
+ one_without_shape,
+ ov::element::i64),
+ as_shape({1, 1, -1, 1}),
+ false)); // [B, 1, S_kv, 1]
+ const auto write = [&](const ov::Output<ov::Node>& past, const ov::Output<ov::Node>& current) {
+ const ov::Output<ov::Node> buffer =
+ is_static_input ? past : register_new_node<v0::Concat>(ov::OutputVector{past, current}, 2)->output(0);
+ const auto buffer_shape = register_new_node<v3::ShapeOf>(buffer);
+ const auto rows_per_head = get_dimensions(buffer_shape, {2});
+ const auto flat_idx = register_new_node<v1::Reshape>(
+ register_new_node<v1::Add>(register_new_node<v1::Multiply>(bh_idx, rows_per_head), new_row),
+ as_shape({-1}),
+ false); // [B * Nkv * S_kv]
+ const auto row_shape =
+ register_new_node<v0::Concat>(ov::OutputVector{as_shape({-1}), get_dimensions(buffer_shape, {3})}, 0);
+ const auto rows =
+ register_new_node<v3::ScatterUpdate>(register_new_node<v1::Reshape>(buffer, row_shape, false),
+ flat_idx,
+ register_new_node<v1::Reshape>(current, row_shape, false),
+ zero);
+ return register_new_node<v1::Reshape>(rows, buffer_shape, false);
+ };
+ outputs.sdpa_key = write(past_key, key);
+ outputs.sdpa_value = write(past_value, value);
+ outputs.present_key = outputs.sdpa_key;
+ outputs.present_value = outputs.sdpa_value;
+ return outputs;
+}
+
std::shared_ptr<ov::Node> ov::pass::GroupQueryAttentionDecomposition::make_sdpa(
const ov::Output<ov::Node>& query,
const ov::Output<ov::Node>& key,
@@ -633,9 +720,7 @@ std::shared_ptr<ov::Node> ov::pass::GroupQueryAttentionDecomposition::make_sdpa(
const ov::Output<ov::Node>& sink,
bool is_causal,
[[maybe_unused]] int64_t local_window_size,
- [[maybe_unused]] const std::optional<CompressedKV>& compressed_kv) {
- // local_window_size and compressed_kv are ignored by the reference v13::ScaledDotProductAttention op;
- // plugin overrides may apply them when the underlying kernel supports SWA / compressed KV natively.
+ [[maybe_unused]] const KVCacheMetadata& metadata) {
if (sink.get_node()) {
return register_new_node<v13::ScaledDotProductAttention>(query, key, value, mask, scale, sink, is_causal);
}
@@ -778,7 +863,8 @@ std::shared_ptr<ov::Node> ov::pass::GroupQueryAttentionDecomposition::make_atten
const ov::Output<ov::Node>& bias_col_offset,
[[maybe_unused]] bool sliding_window_cache,
[[maybe_unused]] float scale,
- [[maybe_unused]] bool has_sink) {
+ [[maybe_unused]] bool has_sink,
+ [[maybe_unused]] const KVCacheMetadata& metadata) {
const bool has_bias = external_bias.get_node_shared_ptr() != nullptr;
// A window is active for local_window_size >= 1; -1 disables it and 0 is rejected upstream (FE + op).
// A window is only ever paired with causal=1 (enforced upstream by the FE and the op), so it is only
@@ -952,10 +1038,9 @@ std::shared_ptr<ov::Node> ov::pass::GroupQueryAttentionDecomposition::get_dimens
return register_new_node<v8::Gather>(shape, dims_const, zero);
}
-std::shared_ptr<ov::Node> ov::pass::GroupQueryAttentionDecomposition::get_dimensions(
- const std::shared_ptr<ov::Node>& node,
- const std::vector<int>& dims) {
- return get_dimensions(register_new_node<v3::ShapeOf>(node), dims);
+std::shared_ptr<ov::Node> ov::pass::GroupQueryAttentionDecomposition::get_dimensions(const ov::Output<ov::Node>& output,
+ const std::vector<int>& dims) {
+ return get_dimensions(register_new_node<v3::ShapeOf>(output), dims);
}
ov::Output<ov::Node> ov::pass::GroupQueryAttentionDecomposition::make_qk_norm(const ov::Output<ov::Node>& input,
@@ -1020,7 +1105,7 @@ std::shared_ptr<ov::Node> ov::pass::GroupQueryAttentionDecomposition::rotaryEmbe
if (interleaved) {
input_shape = register_new_node<v3::ShapeOf>(rotary_input);
dim_bns = get_dimensions(input_shape, {0, 1, 2});
- half_head_size = get_dimensions(cos.get_node_shared_ptr(), {-1});
+ half_head_size = get_dimensions(cos, {-1});
perm_5d = v0::Constant::create(ov::element::i64, ov::Shape{5}, {0, 1, 2, 4, 3});
// Deinterleave: [bs,nh,seq,rotary_dim]
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl/stateless_kv.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl/stateless_kv.cpp
index 11383d3923b..9572585a51b 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl/stateless_kv.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl/stateless_kv.cpp
@@ -114,7 +114,8 @@ struct stateless_kv_impl : typed_primitive_impl_ocl<stateless_kv> {
kernel_arguments_data get_arguments(const typed_primitive_inst<stateless_kv>& instance) const override {
kernel_arguments_data args;
- args.inputs.push_back(instance.input_memory_ptr(0)); // past
+ const auto past = instance.input_memory_ptr(0);
+ args.inputs.push_back(past ? past : instance.input_memory_ptr(1)); // past
if (!_has_pos_idx_input) {
args.inputs.push_back(instance.input_memory_ptr(1)); // new_token_data
} else {
diff --git a/src/plugins/intel_gpu/src/graph/primitive_inst.cpp b/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
index 7253e652542..692fefe8ec0 100644
--- a/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
+++ b/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
@@ -849,12 +849,13 @@ void primitive_inst::realloc_outputs_for_stateless_kv() {
}
result.realloc_if_needed();
+ const bool past_empty = past_layout.count() == 0;
const auto past_tensor = input_memory_ptr(0);
- OPENVINO_ASSERT(past_tensor, "[GPU] Input memory is not prepared for stateless_kv node ", id());
+ OPENVINO_ASSERT(past_empty || past_tensor, "[GPU] Input memory is not prepared for stateless_kv node ", id());
const auto present_tensor = result.output_memory_ptr();
OPENVINO_ASSERT(present_tensor, "[GPU] Output memory of ", result.id(), " is not prepared for stateless_kv node ", id());
auto& engine = _network.get_engine();
- const auto is_same = engine.is_the_same_buffer(*present_tensor, *past_tensor);
+ const auto is_same = !past_empty && engine.is_the_same_buffer(*present_tensor, *past_tensor);
const auto& present_layout = result._impl_params->get_output_layout();
const auto same_placement = [&]() {
return past_layout.data_type == mid_layout.data_type && past_layout.format == mid_layout.format &&
@@ -901,9 +902,9 @@ void primitive_inst::realloc_outputs_for_stateless_kv() {
if (mid_layout == present_layout)
result.set_can_be_optimized(true);
}
- GPU_DEBUG_TRACE_DETAIL << id() << ": input[" << past_tensor->buffer_ptr() << "](" << past_tensor->get_layout().to_short_string() << ") and output["
- << present_tensor->buffer_ptr() << "](" << present_tensor->get_layout().to_short_string() << ")(" << result.id()
- << ") same:" << is_same << std::endl;
+ GPU_DEBUG_TRACE_DETAIL << id() << ": input[" << (past_tensor ? past_tensor->buffer_ptr() : nullptr) << "]("
+ << (past_tensor ? past_tensor->get_layout().to_short_string() : "") << ") and output[" << present_tensor->buffer_ptr() << "]("
+ << present_tensor->get_layout().to_short_string() << ")(" << result.id() << ") same:" << is_same << std::endl;
GPU_DEBUG_TRACE_DETAIL << id() << ": input[" << past_layout.to_short_string() << "] -> mid[" << mid_layout.to_short_string() << "]["
<< target_layout.to_short_string() << "] -> output[" << present_layout.to_short_string() << "](" << result.id()
<< ") opt:" << result.can_be_optimized() << std::endl;
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.cpp
index 77d66b23254..702d6b426cd 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
@@ -2,16 +2,20 @@
// SPDX-License-Identifier: Apache-2.0
//
-#include "group_query_attention_decomposition.hpp"
-
#include <limits>
+#include <optional>
#include <utility>
+#include "group_query_attention_decomposition.hpp"
+
#include "intel_gpu/op/sdpa.hpp"
+#include "intel_gpu/op/stateless_kv.hpp"
#include "openvino/op/broadcast.hpp"
#include "openvino/op/convert.hpp"
#include "openvino/op/group_query_attention.hpp"
#include "openvino/op/shape_of.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/transpose.hpp"
#include "ov_ops/rms.hpp"
namespace {
@@ -43,26 +47,38 @@ std::vector<uint64_t> compute_kv_group_sizes(const ov::PartialShape& data_shape,
namespace ov::intel_gpu {
-ov::Output<ov::Node> GroupQueryAttentionDecomposition::make_qk_norm(const ov::Output<ov::Node>& input, const ov::Output<ov::Node>& weight, float epsilon) {
- return register_new_node<ov::op::internal::RMS>(input, weight, epsilon, input.get_element_type());
-}
+namespace v0 = ov::op::v0;
+namespace v1 = ov::op::v1;
-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) {
+
+struct GroupQueryAttentionDecomposition::StatelessKVMetadata : public ov::pass::GroupQueryAttentionDecomposition::KVCacheMetadata {
+ struct CompressedKV {
+ ov::OutputVector quantization_inputs;
+ op::SDPA::QuantizationAttribute quantization_attrs;
+ };
+ std::optional<CompressedKV> compressed_kv;
+ std::vector<int64_t> transpose_v_order;
+ ~StatelessKVMetadata() override = default;
+};
+
+// Should only be called when is_kv_quantized=true, supports per-channel 4/8 bit quantize only.
+bool GroupQueryAttentionDecomposition::prepare_compressed_kv(const std::shared_ptr<ov::op::internal::GroupQueryAttention>& node,
+ const ov::element::Type& key_type,
+ const ov::element::Type& value_type,
+ const ov::PartialShape& key_partial_shape,
+ StatelessKVMetadata& metadata) {
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;
+ // Without immad, per-channel KV quntize is not working so skip for now
+ if ((kv_cache_bit_width != 8 && kv_cache_bit_width != 4) || key_type != value_type || !is_supported_compressed_kv_type(key_type) ||
+ key_quant_type == GQAQuantType::PER_TENSOR || value_quant_type == GQAQuantType::PER_TENSOR || !m_sdpa_support_immad)
+ return false;
+
+ auto& compressed_kv = metadata.compressed_kv.emplace();
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);
@@ -75,25 +91,136 @@ std::optional<GroupQueryAttentionDecomposition::CompressedKV> GroupQueryAttentio
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;
+ compressed_kv.quantization_attrs.quantization_type =
+ is_int4 ? ov::op::internal::DynamicQuantize::QuantizationType::Asymmetric : ov::op::internal::DynamicQuantize::QuantizationType::Symmetric;
+ compressed_kv.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};
+ compressed_kv.quantization_attrs.quantization_dt = is_int4 ? ov::element::u4 : key_type;
+ compressed_kv.quantization_attrs.scale_dt = ov::element::f16;
+ compressed_kv.quantization_inputs = {prepared_key_scale, prepared_value_scale};
if (is_int4) {
- m_quantization_attrs.zp_dt = ov::element::f16;
+ compressed_kv.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));
+ compressed_kv.quantization_inputs.push_back(register_new_node<ov::op::v3::Broadcast>(storage_zp, key_scale_shape));
+ compressed_kv.quantization_inputs.push_back(register_new_node<ov::op::v3::Broadcast>(storage_zp, value_scale_shape));
+ }
+ compressed_kv.quantization_attrs.group_sizes = compute_kv_group_sizes(key_partial_shape, prepared_key_scale.get_partial_shape());
+ compressed_kv.quantization_attrs.scales_zp_output_order = {0, 1, 2, 3};
+
+ metadata.should_dequantize_kv = false;
+ return true;
+}
+
+std::unique_ptr<ov::pass::GroupQueryAttentionDecomposition::KVCacheMetadata> GroupQueryAttentionDecomposition::create_metadata() {
+ return std::make_unique<StatelessKVMetadata>();
+}
+
+ov::Output<ov::Node> GroupQueryAttentionDecomposition::make_qk_norm(const ov::Output<ov::Node>& input, const ov::Output<ov::Node>& weight, float epsilon) {
+ return register_new_node<ov::op::internal::RMS>(input, weight, epsilon, input.get_element_type());
+}
+
+GroupQueryAttentionDecomposition::KVCacheOutputs GroupQueryAttentionDecomposition::construct_kvcache(
+ const std::shared_ptr<ov::op::internal::GroupQueryAttention>& node,
+ const ov::Output<ov::Node>& past_key,
+ const ov::Output<ov::Node>& past_value,
+ const ov::Output<ov::Node>& key,
+ const ov::Output<ov::Node>& value,
+ const ov::Output<ov::Node>& seqlens_1d,
+ const std::shared_ptr<ov::Node>& kv_seqlen,
+ const std::shared_ptr<ov::Node>& past_seqlen,
+ const ov::Output<ov::Node>& current_seqlen_scalar,
+ KVCacheMetadata& metadata_) {
+ using namespace ov::op;
+ static const std::vector<int64_t> transpose_v_order{0, 1, 3, 2};
+
+ auto& metadata = static_cast<StatelessKVMetadata&>(metadata_);
+
+ const bool need_qk_output = node->get_qk_output() != ov::op::internal::GroupQueryAttentionQKOutput::NONE;
+ const bool use_explicit_attention = node->get_softcap() > 0.0f || need_qk_output;
+ bool can_fuse_transpose_v = m_sdpa_support_immad && !use_explicit_attention;
+ // The explicit attention chain consumes plain (dequantized) K/V, so skip the compressed-KV SDPA form.
+ if (!use_explicit_attention) {
+ // covers ExpandBroadcastReshapeSDPAFusion, gpu sdpa supports broadcast natively
+ metadata.should_broadcast_kv = false;
+ if (node->is_kv_quantized()) {
+ if (!prepare_compressed_kv(node, past_key.get_element_type(), past_value.get_element_type(), past_key.get_partial_shape(), metadata)) {
+ // when failed to fuse compressed kv, should not fuse transpose_v, dequantized K/V expects original layout.
+ can_fuse_transpose_v = false;
+ }
+ }
+ }
+
+ KVCacheOutputs outputs;
+
+ if (!node->get_sliding_window_cache()) {
+
+ const auto key_cache = register_new_node<op::StatelessKV>(past_key, key, seqlens_1d, 2, true);
+
+ const auto value_transpose_order = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{4}, transpose_v_order));
+ const auto find_value_transpose = [](const ov::Output<ov::Node>& output) -> std::shared_ptr<v1::Transpose> {
+ const auto transpose = ov::as_type_ptr<v1::Transpose>(output.get_node_shared_ptr());
+ if (!transpose) {
+ return {};
+ }
+ const auto order = ov::as_type_ptr<v0::Constant>(transpose->input_value(1).get_node_shared_ptr());
+ if (!order || order->cast_vector<int64_t>() != transpose_v_order) {
+ return {};
+ }
+ return transpose;
+ };
+
+ std::shared_ptr<v1::Transpose> past_value_transpose;
+ std::shared_ptr<v1::Transpose> present_value_transpose;
+ // explicit attention hard-coded layout so don't fuse
+ if (can_fuse_transpose_v) {
+ past_value_transpose = find_value_transpose(node->input_value(4));
+ if (node->output(2).get_target_inputs().size() == 1) {
+ const auto target = *node->output(2).get_target_inputs().begin();
+ present_value_transpose = find_value_transpose(target.get_node()->output(target.get_index()));
+ }
+ }
+
+ std::shared_ptr<op::StatelessKV> value_cache;
+ if (past_value_transpose && present_value_transpose) {
+ metadata.transpose_v_order = transpose_v_order;
+ // Before: past_value -> Transpose -> GQA cache -> Transpose -> present_value.
+ // After: past_value -------------------------> StatelessKV(axis=3) -> present_value.
+ // current_value -> Transpose ----------^ (the output Transpose is bypassed)
+ const auto transposed_value = register_new_node<v1::Transpose>(value, value_transpose_order);
+ value_cache = register_new_node<op::StatelessKV>(past_value_transpose->input_value(0), transposed_value, seqlens_1d, 3, true);
+ present_value_transpose->output(0).replace(value_cache->output(0));
+ } else {
+ value_cache = register_new_node<op::StatelessKV>(past_value, value, seqlens_1d, 2, true);
+ }
+
+ outputs.present_key = key_cache->output(0);
+ outputs.present_value = value_cache->output(0);
+ if (need_qk_output) {
+ outputs.sdpa_key = key_cache->output(0);
+ outputs.sdpa_value = value_cache->output(0);
+ } else {
+ outputs.sdpa_key = key_cache->output(1);
+ outputs.sdpa_value = value_cache->output(1);
+ }
+ outputs.mask_past_seqlen = past_seqlen;
+ outputs.bias_col_offset = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{1}, {0}));
+
+ } else {
+ outputs = ov::pass::GroupQueryAttentionDecomposition::construct_kvcache(node,
+ past_key,
+ past_value,
+ key,
+ value,
+ seqlens_1d,
+ kv_seqlen,
+ past_seqlen,
+ current_seqlen_scalar,
+ metadata);
}
- 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)};
+ return outputs;
}
std::shared_ptr<ov::Node> GroupQueryAttentionDecomposition::make_sdpa(const ov::Output<ov::Node>& query,
@@ -104,10 +231,10 @@ std::shared_ptr<ov::Node> GroupQueryAttentionDecomposition::make_sdpa(const ov::
const ov::Output<ov::Node>& sink,
bool is_causal,
int64_t local_window_size,
- const std::optional<CompressedKV>& compressed_kv) {
- ov::OutputVector inputs{query,
- compressed_kv ? compressed_kv->key : key,
- compressed_kv ? compressed_kv->value : value};
+ const KVCacheMetadata& metadata_) {
+ const auto& metadata = static_cast<const StatelessKVMetadata&>(metadata_);
+ const auto& compressed_kv = metadata.compressed_kv;
+ ov::OutputVector inputs{query, key, value};
if (mask.get_node()) {
inputs.push_back(mask);
}
@@ -118,20 +245,28 @@ std::shared_ptr<ov::Node> GroupQueryAttentionDecomposition::make_sdpa(const ov::
inputs.push_back(sink);
}
if (compressed_kv) {
- inputs.insert(inputs.end(),
- compressed_kv->quantization_inputs.begin(),
- compressed_kv->quantization_inputs.end());
+ 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());
+ const auto& value_order = metadata.transpose_v_order.empty() ? order : metadata.transpose_v_order;
const auto alignment = is_causal ? op::SDPA::CausalMaskAlignment::LOWER_RIGHT : op::SDPA::CausalMaskAlignment::UPPER_LEFT;
// GQA's -1 sentinel for "no window" maps to SDPA's 0 = disabled.
const int64_t sdpa_window = (local_window_size >= 1) ? local_window_size : 0;
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, sdpa_window);
+ sdpa = register_new_node<op::SDPA>(inputs,
+ is_causal,
+ order,
+ order,
+ value_order,
+ order,
+ compressed_kv->quantization_attrs,
+ ov::element::dynamic,
+ alignment,
+ sdpa_window);
} else {
- sdpa = register_new_node<op::SDPA>(inputs, is_causal, order, order, order, order, ov::element::dynamic, alignment, sdpa_window);
+ sdpa = register_new_node<op::SDPA>(inputs, is_causal, order, order, value_order, order, ov::element::dynamic, alignment, sdpa_window);
}
return sdpa;
}
@@ -147,11 +282,11 @@ std::shared_ptr<ov::Node> GroupQueryAttentionDecomposition::make_attention_mask(
const ov::Output<ov::Node>& bias_col_offset,
bool sliding_window_cache,
float scale,
- bool has_sink) {
+ bool has_sink,
+ [[maybe_unused]] const KVCacheMetadata& metadata_) {
// The kernel applies the window natively via is_causal + sliding_window_size (see make_sdpa),
// so the explicit mask subgraph is unneeded whenever that path is reachable.
- if (causal && !external_bias.get_node() && scale == 0.0f && !has_sink &&
- (local_window_size == -1 || sliding_window_cache)) {
+ if (causal && (local_window_size == -1 || sliding_window_cache) && !external_bias.get_node() && scale == 0.0f && !has_sink) {
return nullptr;
}
@@ -166,7 +301,8 @@ std::shared_ptr<ov::Node> GroupQueryAttentionDecomposition::make_attention_mask(
bias_col_offset,
sliding_window_cache,
scale,
- has_sink);
+ has_sink,
+ metadata_);
}
} // namespace ov::intel_gpu
diff --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.hpp
index 04698137a8f..2e11a9f5978 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
@@ -12,9 +12,22 @@ namespace ov::intel_gpu {
class GroupQueryAttentionDecomposition : public ov::pass::GroupQueryAttentionDecomposition {
public:
OPENVINO_MATCHER_PASS_RTTI("ov::intel_gpu::GroupQueryAttentionDecomposition");
- GroupQueryAttentionDecomposition() = default;
+ GroupQueryAttentionDecomposition(bool sdpa_support_immad) : m_sdpa_support_immad(sdpa_support_immad) {}
protected:
+ struct StatelessKVMetadata;
+
+ std::unique_ptr<KVCacheMetadata> create_metadata() override;
+ KVCacheOutputs construct_kvcache(const std::shared_ptr<ov::op::internal::GroupQueryAttention>& node,
+ const ov::Output<ov::Node>& past_key,
+ const ov::Output<ov::Node>& past_value,
+ const ov::Output<ov::Node>& key,
+ const ov::Output<ov::Node>& value,
+ const ov::Output<ov::Node>& seqlens_1d,
+ const std::shared_ptr<ov::Node>& kv_seqlen,
+ const std::shared_ptr<ov::Node>& past_seqlen,
+ const ov::Output<ov::Node>& current_seqlen_scalar,
+ KVCacheMetadata& metadata) override;
std::shared_ptr<ov::Node> make_sdpa(const ov::Output<ov::Node>& query,
const ov::Output<ov::Node>& key,
const ov::Output<ov::Node>& value,
@@ -23,7 +36,7 @@ protected:
const ov::Output<ov::Node>& sink,
bool is_causal,
int64_t local_window_size,
- const std::optional<CompressedKV>& compressed_kv) override;
+ const KVCacheMetadata& metadata) 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,
@@ -35,17 +48,18 @@ protected:
const ov::Output<ov::Node>& bias_col_offset,
bool sliding_window_cache,
float scale,
- bool has_sink) override;
+ bool has_sink,
+ const KVCacheMetadata& metadata) override;
// RMSFusion runs before this pass on GPU, so QK-Norm is emitted as the fused RMS op directly.
ov::Output<ov::Node> make_qk_norm(const ov::Output<ov::Node>& input, const ov::Output<ov::Node>& weight, float epsilon) 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;
+
+ bool prepare_compressed_kv(const std::shared_ptr<ov::op::internal::GroupQueryAttention>& node,
+ const ov::element::Type& key_type,
+ const ov::element::Type& value_type,
+ const ov::PartialShape& key_partial_shape,
+ StatelessKVMetadata& metadata);
+
+ bool m_sdpa_support_immad;
};
} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/transpose_fusion.cpp b/src/plugins/intel_gpu/src/plugin/transformations/transpose_fusion.cpp
index eef6eef9394..fb236ba6f61 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations/transpose_fusion.cpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations/transpose_fusion.cpp
@@ -250,6 +250,20 @@ TransposeSDPAMatcher::TransposeSDPAMatcher() {
auto order_k = op::SDPA::default_order(sdpa->get_input_partial_shape(1).size());
auto order_v = op::SDPA::default_order(sdpa->get_input_partial_shape(2).size());
auto order_output = op::SDPA::default_order(sdpa->get_output_partial_shape(0).size());
+ if (gpu_sdpa) {
+ if (!gpu_sdpa->get_input0_transpose_order().empty()) {
+ order_q = gpu_sdpa->get_input0_transpose_order();
+ }
+ if (!gpu_sdpa->get_input1_transpose_order().empty()) {
+ order_k = gpu_sdpa->get_input1_transpose_order();
+ }
+ if (!gpu_sdpa->get_input2_transpose_order().empty()) {
+ order_v = gpu_sdpa->get_input2_transpose_order();
+ }
+ if (!gpu_sdpa->get_output_transpose_order().empty()) {
+ order_output = gpu_sdpa->get_output_transpose_order();
+ }
+ }
size_t input_q_output_idx = sdpa->get_input_source_output(0).get_index();
size_t input_k_output_idx = sdpa->get_input_source_output(1).get_index();
size_t input_v_output_idx = sdpa->get_input_source_output(2).get_index();
@@ -259,13 +273,27 @@ TransposeSDPAMatcher::TransposeSDPAMatcher() {
std::vector<int64_t>& order,
size_t& output_idx) {
auto transpose_order_const = ov::as_type_ptr<ov::op::v0::Constant>(transpose_order_const_node);
+ const auto transpose_order = transpose_order_const->cast_vector<int64_t>();
- order = transpose_order_const->cast_vector<int64_t>();
// Allow any transposes without head_size dim position change
- if (order.back() != static_cast<int64_t>(order.size() - 1)) {
+ if (transpose_order.back() != static_cast<int64_t>(transpose_order.size() - 1)) {
return false;
}
+ if (order.size() != transpose_order.size()) {
+ return false;
+ }
+
+ // composed[i] = transpose_order[order[i]]: keep the order already set on the SDPA
+ std::vector<int64_t> composed(order.size());
+ for (size_t i = 0; i < order.size(); ++i) {
+ if (order[i] < 0 || static_cast<size_t>(order[i]) >= transpose_order.size()) {
+ return false;
+ }
+ composed[i] = transpose_order[static_cast<size_t>(order[i])];
+ }
+ order = composed;
+
auto transpose = ov::as_type_ptr<ov::op::v1::Transpose>(transpose_node);
output_idx = transpose->get_input_source_output(0).get_index();
diff --git a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
index 81401993622..19733e83495 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
@@ -850,7 +850,7 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {
manager.register_pass<ov::intel_gpu::FuseGroupedDepthToSpace>();
manager.register_pass<ov::pass::CommonOptimizations>();
pass_config->disable<ov::pass::GroupQueryAttentionDecomposition>();
- manager.register_pass<ov::intel_gpu::GroupQueryAttentionDecomposition>();
+ manager.register_pass<ov::intel_gpu::GroupQueryAttentionDecomposition>(device_info.supports_immad);
// In the case of "zp/scale -> reshape -> transpose -> MOE",
// "zp/scale -> reshape -> transpose" is constant-folded in the above "CommonOptimizations".
diff --git a/src/plugins/intel_gpu/tests/unit/dynamic_execution/stateless_kv.cpp b/src/plugins/intel_gpu/tests/unit/dynamic_execution/stateless_kv.cpp
index 229e6e7a38f..f348305eeab 100644
--- a/src/plugins/intel_gpu/tests/unit/dynamic_execution/stateless_kv.cpp
+++ b/src/plugins/intel_gpu/tests/unit/dynamic_execution/stateless_kv.cpp
@@ -17,6 +17,7 @@
#include <intel_gpu/primitives/eltwise.hpp>
#include <intel_gpu/primitives/input_layout.hpp>
+#include <intel_gpu/primitives/reshape.hpp>
#include <intel_gpu/primitives/stateless_kv.hpp>
#include <intel_gpu/primitives/reorder.hpp>
@@ -37,15 +38,25 @@ class stateless_kv_runtime : public testing::TestWithParam<stateless_kv_runtime_
namespace {
-topology make_stateless_kv_topology(const layout& new_token_layout, data_types result_type = data_types::f32) {
- auto kv = stateless_kv("stateless_kv", {input_info("past"), input_info("new_token"), input_info("present_len")}, 2, true);
+topology make_stateless_kv_topology(const layout& new_token_layout, data_types result_type = data_types::f32, bool indirect_past = false) {
+ topology topology;
+ const auto past_id = indirect_past ? "past_unsqueeze" : "past";
+ if (indirect_past) {
+ topology.add(input_layout("past", layout{ov::PartialShape{2, -1, 4}, data_types::f32, format::bfyx}));
+ topology.add(
+ reshape("past_unsqueeze", input_info("past"), false, {0}, ov::PartialShape{1, 2, -1, 4}, reshape::reshape_mode::unsqueeze));
+ } else {
+ topology.add(input_layout("past", layout{ov::PartialShape{1, 2, -1, 4}, data_types::f32, format::bfyx}));
+ }
+
+ auto kv = stateless_kv("stateless_kv", {input_info(past_id), input_info("new_token"), input_info("present_len")}, 2, true);
kv.num_outputs = 2;
kv.output_data_types = {data_types::f32, data_types::f32};
- return topology(input_layout("past", layout{ov::PartialShape{1, 2, -1, 4}, data_types::f32, format::bfyx}),
- input_layout("new_token", new_token_layout),
- input_layout("present_len", layout{ov::PartialShape{1}, data_types::i64, format::bfyx}),
- kv,
- reorder("result", input_info("stateless_kv", 0), format::bfyx, result_type));
+ topology.add(input_layout("new_token", new_token_layout));
+ topology.add(input_layout("present_len", layout{ov::PartialShape{1}, data_types::i64, format::bfyx}));
+ topology.add(kv);
+ topology.add(reorder("result", input_info("stateless_kv", 0), format::bfyx, result_type));
+ return topology;
}
std::vector<float> expected_concatenated_cache(const std::vector<float>& past_values, const std::vector<float>& token_values,
@@ -268,6 +279,58 @@ TEST(stateless_kv_runtime, reallocation_across_executions) {
run_and_verify(20, 4000.0f, false);
}
+TEST(stateless_kv_runtime, zero_length_past) {
+ auto& engine = get_test_engine();
+
+ constexpr int64_t batch = 1;
+ constexpr int64_t heads = 2;
+ constexpr int64_t past_capacity = 0;
+ constexpr int64_t present_capacity = 16;
+ constexpr int64_t new_token_len = 2;
+ constexpr int64_t present_len = new_token_len;
+ constexpr int64_t head_size = 4;
+ const auto past_layout = layout{ov::Shape{heads, past_capacity, head_size}, data_types::f32, format::bfyx};
+ const auto present_layout = layout{ov::Shape{batch, heads, present_capacity, head_size}, data_types::f32, format::bfyx};
+ const auto new_token_layout = layout{ov::Shape{batch, heads, new_token_len, head_size}, data_types::f32, format::bfyx};
+ const auto seq_len_layout = layout{ov::Shape{1}, data_types::i64, format::bfyx};
+
+ auto topo = make_stateless_kv_topology(new_token_layout, data_types::f32, true);
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ network net(engine, topo, config);
+
+ auto past = engine.allocate_memory(past_layout);
+ auto present = engine.allocate_memory(present_layout);
+ auto new_token = engine.allocate_memory(new_token_layout);
+ auto seq_len = engine.allocate_memory(seq_len_layout);
+ std::vector<float> token_values(new_token_layout.count());
+ std::iota(token_values.begin(), token_values.end(), 1000.0f);
+ set_values(new_token, token_values);
+ set_values<int64_t>(seq_len, {present_len});
+
+ const auto expected = expected_concatenated_cache({}, token_values, ov::Shape{batch, heads, past_capacity, head_size}, new_token_len, 0);
+
+ net.set_input_data("past", past);
+ net.set_input_data("new_token", new_token);
+ net.set_input_data("present_len", seq_len);
+ net.set_output_memory("result", present);
+
+ const auto outputs = net.execute();
+ const auto result = outputs.at("result").get_memory();
+ const auto kv_output = net.get_primitive("stateless_kv")->output_memory_ptr(0);
+
+ ASSERT_NE(result, nullptr);
+ ASSERT_NE(kv_output, nullptr);
+ EXPECT_TRUE(engine.is_the_same_buffer(*result, *present));
+ EXPECT_TRUE(engine.is_the_same_buffer(*kv_output, *present));
+ EXPECT_EQ(kv_output->get_layout().get_partial_shape(), ov::PartialShape({batch, heads, new_token_len, head_size}));
+
+ mem_lock<float, mem_lock_type::read> output_lock(kv_output, get_test_stream());
+ const std::vector<float> actual(output_lock.begin(), output_lock.begin() + expected.size());
+ EXPECT_THAT(actual, testing::ElementsAreArray(expected));
+}
+
TEST(stateless_kv_runtime, caller_output_binding_respects_inplace_contract) {
auto& engine = get_test_engine();
const layout past_layout{ov::Shape{1, 2, 16, 4}, data_types::f32, format::bfyx};
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.cpp
index 0c5f99cb050..7d14060c9e2 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
@@ -4,22 +4,30 @@
#include "plugin/transformations/group_query_attention_decomposition.hpp"
+#include <gmock/gmock.h>
#include <gtest/gtest.h>
+#include <optional>
+#include <set>
+#include <vector>
+
#include "intel_gpu/op/sdpa.hpp"
+#include "intel_gpu/op/stateless_kv.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/matmul.hpp"
#include "openvino/op/parameter.hpp"
#include "openvino/op/result.hpp"
+#include "openvino/op/transpose.hpp"
#include "openvino/pass/manager.hpp"
namespace ov::test::intel_gpu {
namespace {
using QuantType = ov::op::internal::GroupQueryAttentionQuantType;
+using QKOutput = ov::op::internal::GroupQueryAttentionQKOutput;
constexpr int64_t num_heads = 2;
constexpr int64_t kv_num_heads = 1;
@@ -39,18 +47,23 @@ struct GQAConfig {
QuantType out_quant = QuantType::NONE;
ov::element::Type cache_type = ov::element::i8;
int64_t local_window_size = -1; // >= 1 enables sliding window attention
+ bool static_past_cache = false;
+ bool transpose_v = false;
+ bool should_fuse_transpose_v = true;
bool 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;
+ float softcap = 0.0f; // > 0 enables logit soft-capping
+ QKOutput qk_output = QKOutput::NONE;
ov::PartialShape key_scale_shape{1};
ov::PartialShape value_scale_shape{1};
};
std::shared_ptr<ov::Model> make_gqa_model(const GQAConfig& cfg) {
const auto f32 = ov::element::f32;
- const auto past_len = ov::Dimension::dynamic();
+ const auto past_len = cfg.static_past_cache ? ov::Dimension{128} : ov::Dimension::dynamic();
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});
@@ -58,7 +71,14 @@ std::shared_ptr<ov::Model> make_gqa_model(const GQAConfig& cfg) {
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});
+ const auto past_value_shape =
+ cfg.transpose_v ? ov::PartialShape{1, kv_num_heads, cache_head_size, past_len} : ov::PartialShape{1, kv_num_heads, past_len, cache_head_size};
+ auto past_value = std::make_shared<ov::op::v0::Parameter>(cache_type, past_value_shape);
+ ov::Output<ov::Node> gqa_past_value = past_value->output(0);
+ if (cfg.transpose_v) {
+ const auto value_transpose_order = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{4}, {0, 1, 3, 2});
+ gqa_past_value = std::make_shared<ov::op::v1::Transpose>(gqa_past_value, value_transpose_order);
+ }
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{});
@@ -67,7 +87,7 @@ std::shared_ptr<ov::Model> make_gqa_model(const GQAConfig& cfg) {
inputs[1] = key;
inputs[2] = value;
inputs[3] = past_key;
- inputs[4] = past_value;
+ inputs[4] = gqa_past_value;
inputs[5] = seqlens_k;
inputs[6] = total_sequence_length;
for (size_t i = 7; i <= 13; ++i) {
@@ -106,20 +126,42 @@ std::shared_ptr<ov::Model> make_gqa_model(const GQAConfig& cfg) {
cfg.local_window_size,
cfg.sliding_window_cache,
cfg.smooth_softmax,
- cfg.causal);
+ cfg.causal,
+ cfg.softcap,
+ 1e-6f,
+ cfg.qk_output);
ov::ResultVector results;
- for (const auto& output : gqa->outputs()) {
+ for (size_t output_idx = 0; output_idx < gqa->get_output_size(); ++output_idx) {
+ auto output = gqa->output(output_idx);
+ if (cfg.transpose_v && output_idx == 2) {
+ const auto value_transpose_order = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{4}, {0, 1, 3, 2});
+ output = std::make_shared<ov::op::v1::Transpose>(output, value_transpose_order);
+ }
results.push_back(std::make_shared<ov::op::v0::Result>(output));
}
return std::make_shared<ov::Model>(results, parameters);
}
-std::shared_ptr<ov::intel_gpu::op::SDPA> decompose_and_get_sdpa(const GQAConfig& cfg) {
+std::shared_ptr<ov::Model> decompose_gqa_model(const GQAConfig& cfg) {
auto model = make_gqa_model(cfg);
ov::pass::Manager manager;
- manager.register_pass<ov::intel_gpu::GroupQueryAttentionDecomposition>();
+ manager.register_pass<ov::intel_gpu::GroupQueryAttentionDecomposition>(cfg.should_fuse_transpose_v);
manager.run_passes(model);
+ return model;
+}
+
+void expect_sdpa_kv_not_broadcast(const std::shared_ptr<ov::intel_gpu::op::SDPA>& sdpa) {
+ for (size_t input_index = 1; input_index <= 2; ++input_index) {
+ const auto& kv_shape = sdpa->input_value(input_index).get_partial_shape();
+ ASSERT_TRUE(kv_shape.rank().is_static());
+ ASSERT_GE(kv_shape.rank().get_length(), 2);
+ EXPECT_EQ(kv_shape[1], ov::Dimension(kv_num_heads)) << "SDPA input " << input_index << " has broadcasted KV heads";
+ }
+}
+
+std::shared_ptr<ov::intel_gpu::op::SDPA> decompose_and_get_sdpa(const GQAConfig& cfg) {
+ auto model = decompose_gqa_model(cfg);
std::shared_ptr<ov::intel_gpu::op::SDPA> result;
for (const auto& node : model->get_ordered_ops()) {
@@ -128,9 +170,278 @@ std::shared_ptr<ov::intel_gpu::op::SDPA> decompose_and_get_sdpa(const GQAConfig&
result = sdpa;
}
}
+ EXPECT_NE(result, nullptr);
+ if (result) {
+ expect_sdpa_kv_not_broadcast(result);
+ }
return result;
}
+void expect_stateless_kv_cache_connections(const GQAConfig& cfg) {
+ const auto model = decompose_gqa_model(cfg);
+ const auto parameters = model->get_parameters();
+ const bool need_qk_output = cfg.qk_output != QKOutput::NONE;
+ EXPECT_EQ(parameters[3]->get_partial_shape().is_static(), cfg.static_past_cache);
+
+ std::shared_ptr<ov::intel_gpu::op::SDPA> sdpa;
+ std::vector<std::shared_ptr<ov::intel_gpu::op::StatelessKV>> statelesskvs;
+ for (const auto& node : model->get_ordered_ops()) {
+ if (auto current_sdpa = ov::as_type_ptr<ov::intel_gpu::op::SDPA>(node)) {
+ ASSERT_EQ(sdpa, nullptr);
+ sdpa = current_sdpa;
+ }
+ if (auto stateless_kv = ov::as_type_ptr<ov::intel_gpu::op::StatelessKV>(node)) {
+ statelesskvs.emplace_back(std::move(stateless_kv));
+ }
+ }
+
+ ASSERT_EQ(statelesskvs.size(), 2u);
+
+ if (need_qk_output) {
+ ASSERT_EQ(sdpa, nullptr);
+ ASSERT_EQ(model->get_output_size(), 4u);
+ } else {
+ ASSERT_NE(sdpa, nullptr);
+ expect_sdpa_kv_not_broadcast(sdpa);
+ }
+
+ std::shared_ptr<ov::intel_gpu::op::StatelessKV> key;
+ std::shared_ptr<ov::intel_gpu::op::StatelessKV> value;
+
+ const auto find_sdpa_index = [&](const std::set<ov::Input<ov::Node>>& targets, const auto& self) -> std::optional<size_t> {
+ for (const auto& target : targets) {
+ if (ov::is_type<ov::op::v0::ShapeOf>(target.get_node())) {
+ continue;
+ } else if (target.get_node() == sdpa.get()) {
+ return target.get_index();
+ }
+ if (need_qk_output && target.get_index() == 1) {
+ if (auto matmul = ov::as_type_ptr<ov::op::v0::MatMul>(target.get_node()->shared_from_this())) {
+ return matmul->get_transpose_b() ? 1 : 2;
+ }
+ }
+ }
+ for (const auto& target : targets) {
+ if (ov::is_type<ov::op::v0::ShapeOf>(target.get_node())) {
+ continue;
+ }
+ for (size_t i = 0; i < target.get_node()->get_output_size(); ++i) {
+ const auto targets_ = target.get_node()->get_output_target_inputs(i);
+ const auto result = self(targets_, self);
+ if (result) {
+ return result;
+ }
+ }
+ }
+ return std::nullopt;
+ };
+
+ const size_t kv_output_index = need_qk_output ? 0 : 1;
+ for (const auto& stateless_kv : statelesskvs) {
+ const auto sdpa_index = find_sdpa_index(stateless_kv->output(kv_output_index).get_target_inputs(), find_sdpa_index);
+ if (sdpa_index == 1) {
+ ASSERT_EQ(key, nullptr);
+ key = stateless_kv;
+ } else if (sdpa_index == 2) {
+ ASSERT_EQ(value, nullptr);
+ value = stateless_kv;
+ } else {
+ ASSERT_TRUE(sdpa_index == 1 || sdpa_index == 2);
+ }
+ }
+
+ const auto expected_cache_type = cfg.kv_cache_bit_width ? cfg.cache_type : ov::element::f32;
+ EXPECT_EQ(key->output(0).get_element_type(), expected_cache_type);
+ EXPECT_EQ(key->output(1).get_element_type(), expected_cache_type);
+ EXPECT_EQ(value->output(0).get_element_type(), expected_cache_type);
+ EXPECT_EQ(value->output(1).get_element_type(), expected_cache_type);
+
+ const bool fused_transpose_v = cfg.transpose_v && cfg.should_fuse_transpose_v && !need_qk_output;
+ const auto present_key_source = model->output(1).get_node()->input_value(0);
+ auto present_value_source = model->output(2).get_node()->input_value(0);
+ if (cfg.transpose_v && !fused_transpose_v) {
+ // Unfused: the output Transpose is kept, so the cache feeds it.
+ const auto output_transpose = ov::as_type_ptr<ov::op::v1::Transpose>(present_value_source.get_node_shared_ptr());
+ ASSERT_NE(output_transpose, nullptr);
+ const auto output_transpose_order = ov::as_type_ptr<ov::op::v0::Constant>(output_transpose->input_value(1).get_node_shared_ptr());
+ ASSERT_NE(output_transpose_order, nullptr);
+ EXPECT_THAT(output_transpose_order->cast_vector<int64_t>(), ::testing::ElementsAre(0, 1, 3, 2));
+ present_value_source = output_transpose->input_value(0);
+ }
+ ASSERT_EQ(present_key_source, key->output(0));
+ ASSERT_EQ(present_value_source, value->output(0));
+ EXPECT_EQ(key->get_concat_axis(), 2);
+ EXPECT_EQ(value->get_concat_axis(), fused_transpose_v ? 3 : 2);
+ EXPECT_EQ(key->input_value(0).get_node_shared_ptr(), parameters[3]);
+ const auto expect_current_kv = [&](const ov::Output<ov::Node>& current, const std::shared_ptr<ov::Node>& original) {
+ if (cfg.kv_cache_bit_width) {
+ EXPECT_EQ(current.get_element_type(), cfg.cache_type);
+ } else {
+ EXPECT_EQ(current.get_node_shared_ptr(), original);
+ }
+ };
+ expect_current_kv(key->input_value(1), parameters[1]);
+ if (fused_transpose_v) {
+ const auto value_transpose = ov::as_type_ptr<ov::op::v1::Transpose>(value->input_value(1).get_node_shared_ptr());
+ ASSERT_NE(value_transpose, nullptr);
+ const auto value_transpose_order = ov::as_type_ptr<ov::op::v0::Constant>(value_transpose->input_value(1).get_node_shared_ptr());
+ ASSERT_NE(value_transpose_order, nullptr);
+ EXPECT_THAT(value_transpose_order->cast_vector<int64_t>(), ::testing::ElementsAre(0, 1, 3, 2));
+ expect_current_kv(value_transpose->input_value(0), parameters[2]);
+ } else if (cfg.transpose_v) {
+ // Unfused: the past value Transpose is kept and feeds the cache directly.
+ const auto past_value_transpose = ov::as_type_ptr<ov::op::v1::Transpose>(value->input_value(0).get_node_shared_ptr());
+ ASSERT_NE(past_value_transpose, nullptr);
+ EXPECT_EQ(past_value_transpose->input_value(0).get_node_shared_ptr(), parameters[4]);
+ expect_current_kv(value->input_value(1), parameters[2]);
+ } else {
+ EXPECT_EQ(value->input_value(0).get_node_shared_ptr(), parameters[4]);
+ expect_current_kv(value->input_value(1), parameters[2]);
+ }
+ EXPECT_EQ(key->input_value(2).get_node_shared_ptr(), value->input_value(2).get_node_shared_ptr());
+
+ if (sdpa) {
+ if (fused_transpose_v) {
+ EXPECT_THAT(sdpa->get_input2_transpose_order(), ::testing::ElementsAre(0, 1, 3, 2));
+ } else {
+ EXPECT_EQ(sdpa->get_input2_transpose_order(), ov::intel_gpu::op::SDPA::default_order(4));
+ }
+ }
+}
+
+TEST(GQADecompositionTest, static_input_uses_stateless_kv) {
+ GQAConfig cfg;
+ cfg.static_past_cache = true;
+ expect_stateless_kv_cache_connections(cfg);
+}
+
+TEST(GQADecompositionTest, qk_output_uses_full_stateless_kv) {
+ GQAConfig cfg;
+ cfg.static_past_cache = true;
+ cfg.transpose_v = true;
+ for (const auto qk_output : {QKOutput::BEFORE_SOFTMAX, QKOutput::AFTER_SOFTMAX}) {
+ cfg.qk_output = qk_output;
+ expect_stateless_kv_cache_connections(cfg);
+ }
+}
+
+TEST(GQADecompositionTest, dynamic_input_uses_stateless_kv) {
+ GQAConfig cfg;
+
+ expect_stateless_kv_cache_connections(cfg);
+}
+
+TEST(GQADecompositionTest, transpose_v_fused) {
+ GQAConfig cfg;
+ cfg.transpose_v = true;
+ cfg.should_fuse_transpose_v = true;
+
+ expect_stateless_kv_cache_connections(cfg);
+}
+
+TEST(GQADecompositionTest, transpose_v_not_fused) {
+ GQAConfig cfg;
+ cfg.transpose_v = true;
+ cfg.should_fuse_transpose_v = false;
+
+ expect_stateless_kv_cache_connections(cfg);
+}
+
+TEST(GQADecompositionTest, softcap_transpose_v_not_fused) {
+ GQAConfig cfg;
+ cfg.transpose_v = true;
+ cfg.should_fuse_transpose_v = true;
+ cfg.softcap = 30.0f;
+
+ const auto model = decompose_gqa_model(cfg);
+
+ // Softcap replaces SDPA, so no SDPA op may remain.
+ for (const auto& node : model->get_ordered_ops()) {
+ EXPECT_FALSE(ov::is_type<ov::intel_gpu::op::SDPA>(node));
+ }
+
+ std::vector<std::shared_ptr<ov::intel_gpu::op::StatelessKV>> statelesskvs;
+ for (const auto& node : model->get_ordered_ops()) {
+ if (auto stateless_kv = ov::as_type_ptr<ov::intel_gpu::op::StatelessKV>(node)) {
+ statelesskvs.emplace_back(std::move(stateless_kv));
+ }
+ }
+ ASSERT_EQ(statelesskvs.size(), 2u);
+ // The transpose-v should not be fused for softcap, so concat axis is 2.
+ for (const auto& stateless_kv : statelesskvs) {
+ EXPECT_EQ(stateless_kv->get_concat_axis(), 2);
+ }
+
+ // The output Transpose is kept
+ const auto present_value_source = model->output(2).get_node()->input_value(0);
+ const auto output_transpose = ov::as_type_ptr<ov::op::v1::Transpose>(present_value_source.get_node_shared_ptr());
+ ASSERT_NE(output_transpose, nullptr);
+ const auto output_transpose_order = ov::as_type_ptr<ov::op::v0::Constant>(output_transpose->input_value(1).get_node_shared_ptr());
+ ASSERT_NE(output_transpose_order, nullptr);
+ EXPECT_THAT(output_transpose_order->cast_vector<int64_t>(), ::testing::ElementsAre(0, 1, 3, 2));
+}
+
+TEST(GQADecompositionTest, int4_per_tensor_kv_with_transpose_v_is_not_fused) {
+ GQAConfig cfg;
+ cfg.kv_cache_bit_width = 4;
+ cfg.kv_quant = QuantType::PER_TENSOR;
+ cfg.out_quant = QuantType::PER_TENSOR;
+ cfg.transpose_v = true;
+ cfg.should_fuse_transpose_v = true;
+
+ const auto model = decompose_gqa_model(cfg);
+ std::shared_ptr<ov::intel_gpu::op::SDPA> sdpa;
+ std::vector<std::shared_ptr<ov::intel_gpu::op::StatelessKV>> statelesskvs;
+ for (const auto& node : model->get_ordered_ops()) {
+ EXPECT_FALSE(ov::is_type<ov::op::internal::GroupQueryAttention>(node));
+ if (auto current_sdpa = ov::as_type_ptr<ov::intel_gpu::op::SDPA>(node)) {
+ ASSERT_EQ(sdpa, nullptr);
+ sdpa = current_sdpa;
+ }
+ if (auto stateless_kv = ov::as_type_ptr<ov::intel_gpu::op::StatelessKV>(node)) {
+ statelesskvs.emplace_back(std::move(stateless_kv));
+ }
+ }
+
+ ASSERT_NE(sdpa, nullptr);
+ expect_sdpa_kv_not_broadcast(sdpa);
+ EXPECT_FALSE(sdpa->get_kv_compressed());
+ ASSERT_EQ(sdpa->get_input_size(), 3u);
+ EXPECT_EQ(sdpa->input_value(1).get_element_type(), ov::element::f32);
+ EXPECT_EQ(sdpa->input_value(2).get_element_type(), ov::element::f32);
+
+ ASSERT_EQ(statelesskvs.size(), 2u);
+ for (const auto& stateless_kv : statelesskvs) {
+ EXPECT_EQ(stateless_kv->get_concat_axis(), 2);
+ }
+
+ const auto present_value_source = model->output(2).get_node()->input_value(0);
+ const auto output_transpose = ov::as_type_ptr<ov::op::v1::Transpose>(present_value_source.get_node_shared_ptr());
+ ASSERT_NE(output_transpose, nullptr);
+ const auto output_transpose_order = ov::as_type_ptr<ov::op::v0::Constant>(output_transpose->input_value(1).get_node_shared_ptr());
+ ASSERT_NE(output_transpose_order, nullptr);
+ EXPECT_THAT(output_transpose_order->cast_vector<int64_t>(), ::testing::ElementsAre(0, 1, 3, 2));
+}
+
+TEST(GQADecompositionTest, int4_per_channel_kv_with_transpose_v_is_fused) {
+ 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.transpose_v = true;
+ cfg.should_fuse_transpose_v = true;
+
+ expect_stateless_kv_cache_connections(cfg);
+
+ const auto sdpa = decompose_and_get_sdpa(cfg);
+ ASSERT_NE(sdpa, nullptr);
+ ASSERT_TRUE(sdpa->get_kv_compressed());
+ EXPECT_EQ(sdpa->get_quantization_attrs().quantization_dt, ov::element::u4);
+ EXPECT_THAT(sdpa->get_input2_transpose_order(), ::testing::ElementsAre(0, 1, 3, 2));
+}
+
// A mask produced by make_attention_mask() is a rank-4 broadcastable tensor.
// A rank-0 value in that slot means the optional inputs have shifted and the
// scale scalar landed there instead.
@@ -217,8 +528,8 @@ TEST(GQADecompositionTest, per_channel_kv_uses_compressed_sdpa) {
(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()));
+ EXPECT_TRUE(ov::is_type<ov::intel_gpu::op::StatelessKV>(sdpa->input_value(1).get_node_shared_ptr()));
+ EXPECT_TRUE(ov::is_type<ov::intel_gpu::op::StatelessKV>(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);
@@ -226,6 +537,24 @@ TEST(GQADecompositionTest, per_channel_kv_uses_compressed_sdpa) {
EXPECT_EQ(sdpa->input_value(num_data_inputs + 1).get_partial_shape(), ov::PartialShape({1, kv_num_heads, 1, head_size}));
}
+TEST(GQADecompositionTest, per_channel_kv_without_immad_uses_decompressed_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};
+ cfg.should_fuse_transpose_v = false;
+
+ 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, compressed_kv_preserves_optional_inputs) {
GQAConfig cfg;
cfg.kv_cache_bit_width = 8;
diff --git a/src/plugins/intel_gpu/tests/unit/transformations/transpose_sdpa_fusion_test.cpp b/src/plugins/intel_gpu/tests/unit/transformations/transpose_sdpa_fusion_test.cpp
index 2290dee1140..fad0cba06d6 100644
--- a/src/plugins/intel_gpu/tests/unit/transformations/transpose_sdpa_fusion_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/transformations/transpose_sdpa_fusion_test.cpp
@@ -24,7 +24,7 @@ namespace ov {
namespace test {
namespace intel_gpu {
-TEST_F(TransformationTestsF, TranposeSDPAFusion1) {
+TEST_F(TransformationTestsF, TransposeSDPAFusion1) {
const bool is_causal = true;
{
auto input_a = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
@@ -90,7 +90,7 @@ TEST_F(TransformationTestsF, TransformationTestsF) {
}
}
-TEST_F(TransformationTestsF, TranposeSDPAFusion3) {
+TEST_F(TransformationTestsF, TransposeSDPAFusion3) {
const bool is_causal = false;
{
auto input_a = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
@@ -127,7 +127,7 @@ TEST_F(TransformationTestsF, TranposeSDPAFusion3) {
}
}
-TEST_F(TransformationTestsF, TranposeSDPAFusion4) {
+TEST_F(TransformationTestsF, TransposeSDPAFusion4) {
const bool is_causal = false;
{
auto input_a = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
@@ -166,7 +166,7 @@ TEST_F(TransformationTestsF, TranposeSDPAFusion4) {
}
}
-TEST_F(TransformationTestsF, TranposeSDPAFusion5) {
+TEST_F(TransformationTestsF, TransposeSDPAFusion5) {
const bool is_causal = false;
{
auto input_a = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
@@ -202,6 +202,100 @@ TEST_F(TransformationTestsF, TranposeSDPAFusion5) {
}
}
+// Existing Q order {0,2,1,3} composes with input Transpose {0,2,1,3} to identity.
+TEST_F(TransformationTestsF, TransposeSDPAFusion_QComposed) {
+ const bool is_causal = false;
+ {
+ auto input_a = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
+ auto transpose_a_const = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{4}, {0, 2, 1, 3});
+ auto transpose_a = std::make_shared<ov::op::v1::Transpose>(input_a, transpose_a_const);
+ auto input_b = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
+ auto input_c = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
+
+ std::vector<int64_t> order_a = {0, 2, 1, 3};
+ std::vector<int64_t> order_b = {0, 1, 2, 3};
+ std::vector<int64_t> order_c = {0, 1, 2, 3};
+ std::vector<int64_t> order_output = {0, 1, 2, 3};
+ auto sdpa = std::make_shared<ov::intel_gpu::op::SDPA>(ov::OutputVector{transpose_a, input_b, input_c},
+ is_causal,
+ order_a,
+ order_b,
+ order_c,
+ order_output,
+ ov::element::dynamic);
+
+ model = std::make_shared<ov::Model>(ov::OutputVector{sdpa}, ov::ParameterVector{input_a, input_b, input_c});
+ manager.register_pass<TransposeFusion>();
+ }
+ {
+ auto input_a = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
+ auto input_b = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
+ auto input_c = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
+
+ std::vector<int64_t> order_a = {0, 1, 2, 3};
+ std::vector<int64_t> order_b = {0, 1, 2, 3};
+ std::vector<int64_t> order_c = {0, 1, 2, 3};
+ std::vector<int64_t> order_output = {0, 1, 2, 3};
+ auto sdpa = std::make_shared<ov::intel_gpu::op::SDPA>(ov::OutputVector{input_a, input_b, input_c},
+ is_causal,
+ order_a,
+ order_b,
+ order_c,
+ order_output,
+ ov::element::dynamic);
+
+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{sdpa}, ov::ParameterVector{input_a, input_b, input_c});
+ comparator.enable(FunctionsComparator::ATTRIBUTES);
+ }
+}
+
+// Existing K order {0,2,3,1} composes with input Transpose {0,2,1,3} to {0,1,3,2}; output order kept.
+TEST_F(TransformationTestsF, TransposeSDPAFusion_KComposed) {
+ const bool is_causal = false;
+ {
+ auto input_a = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
+ auto input_b = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
+ auto transpose_b_const = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{4}, {0, 2, 1, 3});
+ auto transpose_b = std::make_shared<ov::op::v1::Transpose>(input_b, transpose_b_const);
+ auto input_c = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
+
+ std::vector<int64_t> order_a = {0, 1, 2, 3};
+ std::vector<int64_t> order_b = {0, 2, 3, 1};
+ std::vector<int64_t> order_c = {0, 1, 2, 3};
+ std::vector<int64_t> order_output = {0, 2, 1, 3};
+ auto sdpa = std::make_shared<ov::intel_gpu::op::SDPA>(ov::OutputVector{input_a, transpose_b, input_c},
+ is_causal,
+ order_a,
+ order_b,
+ order_c,
+ order_output,
+ ov::element::dynamic);
+
+ model = std::make_shared<ov::Model>(ov::OutputVector{sdpa}, ov::ParameterVector{input_a, input_b, input_c});
+ manager.register_pass<TransposeFusion>();
+ }
+ {
+ auto input_a = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
+ auto input_b = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
+ auto input_c = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
+
+ std::vector<int64_t> order_a = {0, 1, 2, 3};
+ std::vector<int64_t> order_b = {0, 1, 3, 2};
+ std::vector<int64_t> order_c = {0, 1, 2, 3};
+ std::vector<int64_t> order_output = {0, 2, 1, 3};
+ auto sdpa = std::make_shared<ov::intel_gpu::op::SDPA>(ov::OutputVector{input_a, input_b, input_c},
+ is_causal,
+ order_a,
+ order_b,
+ order_c,
+ order_output,
+ ov::element::dynamic);
+
+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{sdpa}, ov::ParameterVector{input_a, input_b, input_c});
+ comparator.enable(FunctionsComparator::ATTRIBUTES);
+ }
+}
+
class TransposeSDPAFusionPrecisionTest : public TransformationTestsF,
public ::testing::WithParamInterface<ov::element::Type> {};