Skip to content

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

[GPU] Fix SDPA K/V batch broadcast out-of-bounds on optimized kernels (#38467)

Jade Chof766febd1c0c
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_base.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_base.cpp
index 53bc68127ce..7f0b55d7b84 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_base.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_base.cpp
@@ -319,6 +319,9 @@ JitConstants SDPABase::get_jit_constants(const kernel_impl_params& params) const
jit.make("TARGET_SEQ_LEN", q_jitter.dim(get_transposed_channel(ChannelName::Y, extended_input_q_transpose_order)));
jit.make("SOURCE_SEQ_LEN", k_jitter.dim(get_transposed_channel(ChannelName::Y, extended_input_k_transpose_order)));
+ jit.make("Q_BATCH_NUM", q_jitter.dim(get_transposed_channel(ChannelName::BATCH, extended_input_q_transpose_order)));
+ jit.make("K_BATCH_NUM", k_jitter.dim(get_transposed_channel(ChannelName::BATCH, extended_input_k_transpose_order)));
+ jit.make("V_BATCH_NUM", v_jitter.dim(get_transposed_channel(ChannelName::BATCH, extended_input_v_transpose_order)));
auto get_static_or_runtime_dim = [](int64_t dim, std::string runtime_dim, const char* dim_name) {
if (dim < 0)
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_micro.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_micro.cpp
index 59ab8b914bf..68e37576e56 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_micro.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_micro.cpp
@@ -1527,6 +1527,17 @@ JitConstants SDPAMicroGenerator::get_jit_constants(const kernel_impl_params& par
jit.add(convert_strides("KEY", "INPUT1", extended_input_k_transpose_order));
jit.add(convert_strides("VAL", "INPUT2", extended_input_v_transpose_order));
jit.add(convert_strides("DST", "OUTPUT", extended_output_transpose_order));
+
+ // Q/K/V batch may be broadcast (each is 1 or equal). An input whose batch differs from the
+ // output batch, or is dynamic, needs a modulo on its batch index in the kernel.
+ const auto q_batch = get_batch_size(params.get_input_layout(0), extended_input_q_transpose_order);
+ const auto k_batch = get_batch_size(params.get_input_layout(1), extended_input_k_transpose_order);
+ const auto v_batch = get_batch_size(params.get_input_layout(2), extended_input_v_transpose_order);
+ // -1 means dynamic
+ const auto out_batch = get_broadcast_batch(q_batch, k_batch, v_batch);
+ jit.make("BROADCAST_Q_BATCH", (out_batch == -1) || (q_batch != out_batch) ? 1 : 0);
+ jit.make("BROADCAST_K_BATCH", (out_batch == -1) || (k_batch != out_batch) ? 1 : 0);
+ jit.make("BROADCAST_V_BATCH", (out_batch == -1) || (v_batch != out_batch) ? 1 : 0);
}
jit.add(unit_parameters("QRY"));
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_opt.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_opt.cpp
index 946fce8193f..ebf3fe34b5b 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_opt.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_opt.cpp
@@ -129,6 +129,21 @@ JitConstants SDPAOptGeneratorBase::get_jit_constants_base(const kernel_impl_para
jit.make("OUTPUT_TRANSPOSE_3", extended_out_order[3]);
}
}
+
+ // Q/K/V batch may be broadcast (each is 1 or equal). An input whose batch differs from the
+ // output batch, or is dynamic, needs a modulo on its batch index in the kernel.
+ {
+ auto extended_input_q_transpose_order = extend_order_in_num_heads_dim(desc->input_q_transpose_order);
+ const auto q_batch = get_batch_size(params.get_input_layout(0), extended_input_q_transpose_order);
+ const auto k_batch = get_batch_size(params.get_input_layout(1), extended_input_k_transpose_order);
+ const auto v_batch = get_batch_size(params.get_input_layout(2), extended_input_v_transpose_order);
+ // -1 means dynamic
+ const auto out_batch = get_broadcast_batch(q_batch, k_batch, v_batch);
+
+ jit.make("BROADCAST_Q_BATCH", (out_batch == -1) || (q_batch != out_batch) ? 1 : 0);
+ jit.make("BROADCAST_K_BATCH", (out_batch == -1) || (k_batch != out_batch) ? 1 : 0);
+ jit.make("BROADCAST_V_BATCH", (out_batch == -1) || (v_batch != out_batch) ? 1 : 0);
+ }
}
OPENVINO_ASSERT(k_head_size > 0 && v_head_size > 0, "SDPA: invalid head sizes for JIT constants generation");
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_ref.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_ref.cpp
index 2b75c857d05..2823a87cc49 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_ref.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_ref.cpp
@@ -3,6 +3,9 @@
//
#include "sdpa_ref.hpp"
+#include <algorithm>
+#include <iterator>
+
#include "../primitive_ocl_base.hpp"
#include "../utils/jitter.hpp"
#include "../utils/kernel_generator.hpp"
@@ -152,14 +155,22 @@ public:
std::vector<BufferDescriptor> internal_buffers;
auto desc = params.typed_desc<scaled_dot_product_attention>();
- const auto& q_l = params.input_layouts[0];
const auto acc_type = get_accumulator_type(params);
if (!params.is_dynamic()) {
const auto& k_l = params.input_layouts[1];
-
- const auto& q_shape = q_l.get_shape();
- const auto& k_shape = k_l.get_shape();
- const size_t buf_size = q_l.count() / q_shape[desc->input_q_transpose_order[3]] * k_shape[desc->input_k_transpose_order[2]];
+ const auto& out_l = params.output_layouts[0];
+ auto out_shape = out_l.get_shape();
+ size_t head_size_axis = out_shape.size() - 1;
+ if (!desc->output_transpose_order.empty()) {
+ const auto& order = desc->output_transpose_order;
+ OPENVINO_ASSERT(order.size() <= out_shape.size(), "SDPA: output transpose rank exceeds output rank");
+ const auto head_size_pos = std::find(order.begin(), order.end(), order.size() - 1);
+ OPENVINO_ASSERT(head_size_pos != order.end(), "SDPA: output transpose order is missing the head size axis");
+ head_size_axis = out_shape.size() - order.size() + std::distance(order.begin(), head_size_pos);
+ }
+ // Scratch is [output batch, heads, query length, key length], independent of the V head size.
+ out_shape.erase(out_shape.begin() + head_size_axis);
+ const size_t buf_size = ov::shape_size(out_shape) * get_seq_length(k_l, desc->input_k_transpose_order);
internal_buffers.emplace_back(buf_size, acc_type);
} else {
internal_buffers.emplace_back(1, acc_type);
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_utils.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_utils.hpp
index 4e11c0608ec..5ab474fab94 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_utils.hpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_utils.hpp
@@ -122,6 +122,27 @@ inline int64_t get_batch_size(const cldnn::layout& qkv, const std::vector<int64_
return dim.get_length();
}
+// Output batch of Q/K/V (numpy broadcast). Static batches are always checked. Returns -1 if any batch is dynamic.
+inline int64_t get_broadcast_batch(int64_t q_batch, int64_t k_batch, int64_t v_batch) {
+ bool has_dynamic = false;
+ int64_t out_batch = 1;
+ for (const auto batch : {q_batch, k_batch, v_batch}) {
+ if (batch == -1) {
+ has_dynamic = true;
+ continue;
+ }
+ OPENVINO_ASSERT(batch == 1 || out_batch == 1 || batch == out_batch,
+ "SDPA: Q/K/V batch sizes cannot be broadcast: ",
+ q_batch,
+ ", ",
+ k_batch,
+ ", ",
+ v_batch);
+ out_batch = std::max(out_batch, batch);
+ }
+ return has_dynamic ? -1 : out_batch;
+}
+
inline int64_t get_num_heads(const cldnn::layout& qkv, const std::vector<int64_t>& order) {
// 4D - BHLS
// 3D - BLS and H=1
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_micro.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_micro.cl
index 1ba457b83b6..6c7cd733934 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_micro.cl
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_micro.cl
@@ -263,6 +263,29 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG
#else
uint b0_kv = b0 / KV_GROUP_SIZE;
#endif
+#if !IS_PAGED_ATTENTION
+ // Q/K/V batch may be broadcast (the output batch is their numpy broadcast): wrap the batch index by their own batch size.
+ // The flags are compile-time, so the modulo is dropped when no broadcast is needed.
+#if BROADCAST_Q_BATCH
+ const uint b1_q = b1 % QRY_D0;
+#else
+ const uint b1_q = b1;
+#endif
+#if BROADCAST_K_BATCH
+ const uint b1_k = b1 % KEY_D0;
+#else
+ const uint b1_k = b1;
+#endif
+#if BROADCAST_V_BATCH
+ const uint b1_v = b1 % VAL_D0;
+#else
+ const uint b1_v = b1;
+#endif
+#else
+ const uint b1_q = b1;
+ const uint b1_k = b1;
+ const uint b1_v = b1;
+#endif
#if IS_PAGED_ATTENTION
uint wg_j0 = subsequence_query_block_idx;
@@ -465,9 +488,9 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG
#endif
#else
/* KEY_OFF/VAL_OFF and offsets address the physical byte-backed layouts. */
- K += KEY_OFF(b1, b0_kv, 0, 0) + INPUT1_OFFSET;
- Q += (QRY_OFF(b1, b0, 0, 0) + INPUT0_OFFSET);
- V += VAL_OFF(b1, b0_kv, 0, 0) + INPUT2_OFFSET;
+ K += KEY_OFF(b1_k, b0_kv, 0, 0) + INPUT1_OFFSET;
+ Q += (QRY_OFF(b1_q, b0, 0, 0) + INPUT0_OFFSET);
+ V += VAL_OFF(b1_v, b0_kv, 0, 0) + INPUT2_OFFSET;
A += DST_OFF(b1, b0, 0, 0, 0);
#if WITH_ATTN_MASK
uint ldmsk = MSK_S2;
@@ -476,22 +499,22 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG
#endif
#if KEY_SCALES
- K_scales += KEY_COMP_OFF(b1, b0_kv, 0, 0);
+ K_scales += KEY_COMP_OFF(b1_k, b0_kv, 0, 0);
#endif
#if KEY_SCALES == QUANTIZE_COMMON
float k_scale = convert_float(*K_scales);
#endif
#if KEY_ZERO_POINTS
- K_zp += KEY_COMP_OFF(b1, b0_kv, 0, 0) / KEY_ZP_ELEMENTS_PER_BYTE;
+ K_zp += KEY_COMP_OFF(b1_k, b0_kv, 0, 0) / KEY_ZP_ELEMENTS_PER_BYTE;
#endif
#if VAL_SCALES
- V_scales += VAL_COMP_OFF(b1, b0_kv, 0, 0);
+ V_scales += VAL_COMP_OFF(b1_v, b0_kv, 0, 0);
#endif
#if VAL_SCALES == QUANTIZE_COMMON
float v_scale = convert_float(*V_scales);
#endif
#if VAL_ZERO_POINTS
- V_zp += VAL_COMP_OFF(b1, b0_kv, 0, 0) / VAL_ZP_ELEMENTS_PER_BYTE;
+ V_zp += VAL_COMP_OFF(b1_v, b0_kv, 0, 0) / VAL_ZP_ELEMENTS_PER_BYTE;
#endif
__builtin_assume_aligned(K, K_ALIGN);
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_opt.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_opt.cl
index 1e92e5b788f..36117f0c02e 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_opt.cl
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_opt.cl
@@ -208,6 +208,23 @@ KERNEL(sdpa_opt)(
const uint batch_idx = get_global_id(0);
const uint b0_idx = batch_idx / NUM_HEADS; /* BATCH dim */
const uint b1_idx = batch_idx % NUM_HEADS; /* HEADS_NUM dim */
+ // Q/K/V batch may be broadcast (the output batch is their numpy broadcast): wrap the batch index by their own batch size.
+ // The flags are compile-time, so the modulo is dropped when no broadcast is needed.
+#if BROADCAST_Q_BATCH
+ const uint b_q_idx = b0_idx % Q_BATCH_NUM;
+#else
+ const uint b_q_idx = b0_idx;
+#endif
+#if BROADCAST_K_BATCH
+ const uint b_k_idx = b0_idx % K_BATCH_NUM;
+#else
+ const uint b_k_idx = b0_idx;
+#endif
+#if BROADCAST_V_BATCH
+ const uint b_v_idx = b0_idx % V_BATCH_NUM;
+#else
+ const uint b_v_idx = b0_idx;
+#endif
const uint target_seq_idx = get_global_id(1);
const uint lid = get_local_id(2);
@@ -266,11 +283,11 @@ KERNEL(sdpa_opt)(
uint query_local_offset = block_idx * SUBGROUP_SIZE + sglid;
const uint seq_idx_end = 1;
#ifdef INPUT0_DIMS_ORDER
- uint query_offset = FUNC_CALL(get_input0_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, target_seq_idx, (block_idx * SUBGROUP_SIZE));
- uint query_offset_next_seq = FUNC_CALL(get_input0_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, target_seq_idx + 1, (block_idx * SUBGROUP_SIZE));
+ uint query_offset = FUNC_CALL(get_input0_index)(OPTIONAL_SHAPE_INFO_TENSOR b_q_idx, b1_idx, 0, 0, target_seq_idx, (block_idx * SUBGROUP_SIZE));
+ uint query_offset_next_seq = FUNC_CALL(get_input0_index)(OPTIONAL_SHAPE_INFO_TENSOR b_q_idx, b1_idx, 0, 0, target_seq_idx + 1, (block_idx * SUBGROUP_SIZE));
const uint query_pitch = query_offset_next_seq - query_offset;
#else
- uint query_offset = INPUT0_GET_INDEX(b0_idx, b1_idx, target_seq_idx, (block_idx * SUBGROUP_SIZE));
+ uint query_offset = INPUT0_GET_INDEX(b_q_idx, b1_idx, target_seq_idx, (block_idx * SUBGROUP_SIZE));
const uint query_pitch = QUERY_STEP_LOCAL;
#endif
#if SG_SCALE_FACTOR == 2
@@ -299,10 +316,10 @@ KERNEL(sdpa_opt)(
// HEAD_SIZE / SUBGROUPS_PER_WG times in the loop and saves the result to the qk_local SLM buffer
#if IS_INT4_COMPRESSED && !defined(BEAM_TABLE_TYPE)
#ifdef INPUT1_DIMS_ORDER
- const uint key_base_p0 = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 0, 0);
- const uint key_packed_pitch_p0 = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 1, 0) - key_base_p0;
+ const uint key_base_p0 = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b_k_idx, b1_idx, 0, 0, 0, 0);
+ const uint key_packed_pitch_p0 = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b_k_idx, b1_idx, 0, 0, 1, 0) - key_base_p0;
#else
- const uint key_base_p0 = INPUT1_GET_INDEX(b0_idx, b1_idx, 0, 0);
+ const uint key_base_p0 = INPUT1_GET_INDEX(b_k_idx, b1_idx, 0, 0);
const uint key_packed_pitch_p0 = INPUT1_SIZE_X;
#endif
#endif
@@ -310,7 +327,7 @@ KERNEL(sdpa_opt)(
#ifdef BEAM_TABLE_TYPE
const uint b_idx = beam_table[FUNC_CALL(get_bt_index_key)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, start_partition_idx + seq_len, 0)];
#else
- const uint b_idx = b0_idx;
+ const uint b_idx = b_k_idx;
#endif
#if IS_INT4_COMPRESSED && !defined(BEAM_TABLE_TYPE)
@@ -743,8 +760,8 @@ KERNEL(sdpa_opt)(
OUTPUT_COMPUTE_TYPE acc[TARGET_SEQ_LEN_BLOCK_SIZE] = {OUTPUT_VAL_ZERO};
#ifndef BEAM_TABLE_TYPE
#ifdef INPUT2_DIMS_ORDER
- uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 0, 0);
- uint value_offset_next_seq = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 1, 0);
+ uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_v_idx, b1_idx, 0, 0, 0, 0);
+ uint value_offset_next_seq = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_v_idx, b1_idx, 0, 0, 1, 0);
#if IS_INT4_COMPRESSED
const uint value_pitch = value_offset_next_seq - value_offset;
#else
@@ -768,9 +785,9 @@ KERNEL(sdpa_opt)(
const uint nibble_sel_p0 = sglid & 1;
#ifndef BEAM_TABLE_TYPE
#ifdef INPUT2_DIMS_ORDER
- const uint value_base_p0 = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 0, val_packed_x);
+ const uint value_base_p0 = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_v_idx, b1_idx, 0, 0, 0, val_packed_x);
#else
- const uint value_base_p0 = INPUT2_GET_INDEX(b0_idx, b1_idx, 0, val_packed_x);
+ const uint value_base_p0 = INPUT2_GET_INDEX(b_v_idx, b1_idx, 0, val_packed_x);
#endif
#endif // !BEAM_TABLE_TYPE
#endif
@@ -793,7 +810,7 @@ KERNEL(sdpa_opt)(
uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + (seq_len * SUBGROUP_SIZE) + sglid, sgid * SUBGROUP_SIZE);
#endif
#else
- const uint b_idx = b0_idx;
+ const uint b_idx = b_v_idx;
#if IS_INT4_COMPRESSED
uint value_offset = value_base_p0 + (start_partition_idx + (seq_len * SUBGROUP_SIZE)) * value_pitch;
#elif defined(INPUT2_DIMS_ORDER)
@@ -862,7 +879,7 @@ KERNEL(sdpa_opt)(
#ifdef BEAM_TABLE_TYPE
const uint b_idx = beam_table[FUNC_CALL(get_bt_index_value)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, start_partition_idx + seq_len, head_size_idx)];
#else
- const uint b_idx = b0_idx;
+ const uint b_idx = b_v_idx;
#endif
#if IS_INT4_COMPRESSED
@@ -1325,6 +1342,23 @@ KERNEL(sdpa_opt)(
#define num_heads_dim ((uint)get_global_id(0))
#define b0_idx (batch_idx / NUM_HEADS)
#define b1_idx (batch_idx % NUM_HEADS)
+ // Q/K/V batch may be broadcast (the output batch is their numpy broadcast): wrap the batch index by their own batch size.
+ // The flags are compile-time, so the modulo is dropped when no broadcast is needed.
+#if BROADCAST_Q_BATCH
+ #define b_q_idx (b0_idx % Q_BATCH_NUM)
+#else
+ #define b_q_idx (b0_idx)
+#endif
+#if BROADCAST_K_BATCH
+ #define b_k_idx (b0_idx % K_BATCH_NUM)
+#else
+ #define b_k_idx (b0_idx)
+#endif
+#if BROADCAST_V_BATCH
+ #define b_v_idx (b0_idx % V_BATCH_NUM)
+#else
+ #define b_v_idx (b0_idx)
+#endif
#define target_seq_dim ((uint)get_global_id(1))
#if IS_PAGED_ATTENTION
#define target_seq_idx ((uint)block_start_pos - subsequence_begins[gws_seq_indexes_correspondence[target_seq_dim]])
@@ -1440,11 +1474,11 @@ KERNEL(sdpa_opt)(
const uint query_pitch = (K_HEAD_SIZE * NUM_HEADS + INPUT0_PAD_BEFORE_FEATURE_NUM + INPUT0_PAD_AFTER_FEATURE_NUM);
#else
#ifdef INPUT0_DIMS_ORDER
- uint query_offset = FUNC_CALL(get_input0_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, target_seq_idx, (k_head_size_idx));
- uint query_offset_next_seq = FUNC_CALL(get_input0_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, target_seq_idx + 1, (k_head_size_idx));
+ uint query_offset = FUNC_CALL(get_input0_index)(OPTIONAL_SHAPE_INFO_TENSOR b_q_idx, b1_idx, 0, 0, target_seq_idx, (k_head_size_idx));
+ uint query_offset_next_seq = FUNC_CALL(get_input0_index)(OPTIONAL_SHAPE_INFO_TENSOR b_q_idx, b1_idx, 0, 0, target_seq_idx + 1, (k_head_size_idx));
const uint query_pitch = query_offset_next_seq - query_offset;
#else
- uint query_offset = INPUT0_GET_INDEX(b0_idx, b1_idx, target_seq_idx, (k_head_size_idx));
+ uint query_offset = INPUT0_GET_INDEX(b_q_idx, b1_idx, target_seq_idx, (k_head_size_idx));
const uint query_pitch = K_HEAD_SIZE;
#endif
@@ -1579,10 +1613,10 @@ KERNEL(sdpa_opt)(
#if IS_INT4_COMPRESSED && !defined(BEAM_TABLE_TYPE)
#ifdef INPUT1_DIMS_ORDER
- const uint key_base_s1 = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 0, 0);
- const uint key_packed_pitch_s1 = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 1, 0) - key_base_s1;
+ const uint key_base_s1 = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b_k_idx, b1_idx, 0, 0, 0, 0);
+ const uint key_packed_pitch_s1 = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b_k_idx, b1_idx, 0, 0, 1, 0) - key_base_s1;
#else
- const uint key_base_s1 = INPUT1_GET_INDEX(b0_idx, b1_idx, 0, 0);
+ const uint key_base_s1 = INPUT1_GET_INDEX(b_k_idx, b1_idx, 0, 0);
const uint key_packed_pitch_s1 = INPUT1_SIZE_X;
#endif
#endif
@@ -1623,16 +1657,16 @@ KERNEL(sdpa_opt)(
const uint b_idx = beam_table[FUNC_CALL(get_bt_index_key)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, seq_len + sglid, 0)];
const uint key_offset = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, seq_len + sglid, 0);
#else
- const uint b_idx = b0_idx;
+ const uint b_idx = b_k_idx;
#if IS_INT4_COMPRESSED
uint key_offset = key_base_s1 + seq_len * key_packed_pitch_s1;
const uint key_pitch = key_packed_pitch_s1;
#elif defined(INPUT1_DIMS_ORDER)
- uint key_offset = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, seq_len, 0);
- uint key_offset_next_seq = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, seq_len + 1, 0);
+ uint key_offset = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, seq_len, 0);
+ uint key_offset_next_seq = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, seq_len + 1, 0);
const uint key_pitch = key_offset_next_seq - key_offset;
#else
- uint key_offset = INPUT1_GET_INDEX(b0_idx, b1_idx, seq_len, 0);
+ uint key_offset = INPUT1_GET_INDEX(b_idx, b1_idx, seq_len, 0);
const uint key_pitch = K_HEAD_SIZE;
#endif
#endif // BEAM_TABLE_TYPE
@@ -2215,8 +2249,8 @@ KERNEL(sdpa_opt)(
const uint value_pitch = (V_HEAD_SIZE * NUM_KV_HEADS + INPUT2_PAD_BEFORE_FEATURE_NUM + INPUT2_PAD_AFTER_FEATURE_NUM);
#else
#ifdef INPUT2_DIMS_ORDER
- uint value_offset_base = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 0, 0);
- uint value_offset_next_seq = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 1, 0);
+ uint value_offset_base = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_v_idx, b1_idx, 0, 0, 0, 0);
+ uint value_offset_next_seq = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_v_idx, b1_idx, 0, 0, 1, 0);
#if IS_INT4_COMPRESSED
const uint value_pitch = value_offset_next_seq - value_offset_base;
#else
@@ -2238,9 +2272,9 @@ KERNEL(sdpa_opt)(
const uint nibble_sel_s1 = sglid & 1;
#ifndef BEAM_TABLE_TYPE
#ifdef INPUT2_DIMS_ORDER
- const uint value_base_s1 = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 0, val_packed_x_s1);
+ const uint value_base_s1 = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_v_idx, b1_idx, 0, 0, 0, val_packed_x_s1);
#else
- const uint value_base_s1 = INPUT2_GET_INDEX(b0_idx, b1_idx, 0, val_packed_x_s1);
+ const uint value_base_s1 = INPUT2_GET_INDEX(b_v_idx, b1_idx, 0, val_packed_x_s1);
#endif
#endif // !BEAM_TABLE_TYPE
#endif
@@ -2269,13 +2303,13 @@ KERNEL(sdpa_opt)(
const uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + (seq_len) + sglid, sgid * SUBGROUP_SIZE);
#endif
#else
- const uint b_idx = b0_idx;
+ const uint b_idx = b_v_idx;
#if IS_INT4_COMPRESSED
uint value_offset = value_base_s1 + (start_partition_idx + (seq_len)) * value_pitch;
#elif defined(INPUT2_DIMS_ORDER)
- uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, start_partition_idx + (seq_len), head_size_idx);
+ uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + (seq_len), head_size_idx);
#else
- uint value_offset = INPUT2_GET_INDEX(b0_idx, b1_idx, start_partition_idx + (seq_len), head_size_idx);
+ uint value_offset = INPUT2_GET_INDEX(b_idx, b1_idx, start_partition_idx + (seq_len), head_size_idx);
#endif
#endif
#endif
@@ -2383,13 +2417,13 @@ KERNEL(sdpa_opt)(
uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + (seq_len * SUBGROUP_SIZE) + sglid, sgid * SUBGROUP_SIZE);
#endif
#else
- const uint b_idx = b0_idx;
+ const uint b_idx = b_v_idx;
#if IS_INT4_COMPRESSED
uint value_offset = value_base_s1 + (start_partition_idx + (seq_len * SUBGROUP_SIZE)) * value_pitch;
#elif defined(INPUT2_DIMS_ORDER)
- uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, start_partition_idx + (seq_len * SUBGROUP_SIZE), head_size_idx);
+ uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + (seq_len * SUBGROUP_SIZE), head_size_idx);
#else
- uint value_offset = INPUT2_GET_INDEX(b0_idx, b1_idx, start_partition_idx + (seq_len * SUBGROUP_SIZE), head_size_idx);
+ uint value_offset = INPUT2_GET_INDEX(b_idx, b1_idx, start_partition_idx + (seq_len * SUBGROUP_SIZE), head_size_idx);
#endif
#endif
#endif
@@ -2502,13 +2536,13 @@ KERNEL(sdpa_opt)(
const uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + seq_len_leftovers_start + sglid, sgid * SUBGROUP_SIZE);
#endif
#else
- const uint b_idx = b0_idx;
+ const uint b_idx = b_v_idx;
#if IS_INT4_COMPRESSED
uint value_offset = value_base_s1 + (start_partition_idx + seq_len_leftovers_start) * value_pitch;
#elif defined(INPUT2_DIMS_ORDER)
- uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, start_partition_idx + seq_len_leftovers_start, head_size_idx);
+ uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + seq_len_leftovers_start, head_size_idx);
#else
- uint value_offset = INPUT2_GET_INDEX(b0_idx, b1_idx, start_partition_idx + seq_len_leftovers_start, head_size_idx);
+ uint value_offset = INPUT2_GET_INDEX(b_idx, b1_idx, start_partition_idx + seq_len_leftovers_start, head_size_idx);
#endif
#endif
#endif
diff --git a/src/plugins/intel_gpu/src/graph/scaled_dot_product_attention.cpp b/src/plugins/intel_gpu/src/graph/scaled_dot_product_attention.cpp
index 1c60cceef3f..765931a4150 100644
--- a/src/plugins/intel_gpu/src/graph/scaled_dot_product_attention.cpp
+++ b/src/plugins/intel_gpu/src/graph/scaled_dot_product_attention.cpp
@@ -36,6 +36,7 @@ layout scaled_dot_product_attention_inst::calc_output_layout(scaled_dot_product_
};
auto input0_layout = impl_param.get_input_layout(0);
+ auto input1_layout = impl_param.get_input_layout(1);
auto input2_layout = impl_param.get_input_layout(2);
auto default_out_dt = data_type_traits::is_floating_point(input0_layout.data_type) ? input0_layout.data_type : data_types::f32;
@@ -48,6 +49,14 @@ layout scaled_dot_product_attention_inst::calc_output_layout(scaled_dot_product_
desc->input_v_transpose_order);
output_shape[output_shape.size() - 1] = v_shape[v_shape.size() - 1];
+ // The batch dim is numpy-broadcast across Q, K and V.
+ auto k_shape = transpose_shape(input1_layout.get_partial_shape(), desc->input_k_transpose_order);
+ if (k_shape.rank() == q_shape.rank() && v_shape.rank() == q_shape.rank()) {
+ const bool batch_compatible = ov::Dimension::broadcast_merge(output_shape[0], output_shape[0], k_shape[0]) &&
+ ov::Dimension::broadcast_merge(output_shape[0], output_shape[0], v_shape[0]);
+ OPENVINO_ASSERT(batch_compatible, "[GPU] SDPA: Q/K/V batch sizes cannot be broadcast");
+ }
+
output_shape = transpose_shape(output_shape, desc->output_transpose_order);
return { layout{output_shape, output_type, output_format, desc->output_paddings[0]} };
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/op/sdpa.cpp b/src/plugins/intel_gpu/src/plugin/transformations/op/sdpa.cpp
index c312b2c5a21..7ff2413f39d 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations/op/sdpa.cpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations/op/sdpa.cpp
@@ -163,7 +163,8 @@ std::vector<ov::PartialShape> shape_infer(const SDPA* op,
((shape_q_t.size() == shape_k_t.size()) && (shape_q_t.size() == shape_v_t.size()));
if (is_broadcastable) {
size_t max_rank = shape_q_t.size() -1;
- for (size_t i = 0; i < max_rank; ++i) {
+ // Skip the batch dim (i = 0): it is numpy-broadcast by the core shape inference.
+ for (size_t i = 1; i < max_rank; ++i) {
if (shape_q_t[i].is_static() && shape_k_t[i].is_static()) {
auto broadcasted_dim = shape_q_t[i].get_length();
shape_k_t[i] = broadcasted_dim;
diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/sdpa_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/sdpa_gpu_test.cpp
index b51a2a0e0ec..47c15c84456 100644
--- a/src/plugins/intel_gpu/tests/unit/test_cases/sdpa_gpu_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/test_cases/sdpa_gpu_test.cpp
@@ -18,9 +18,11 @@
#include <array>
#include <iostream>
#include <vector>
+#include <algorithm>
#include <cmath>
#include <limits>
#include <numeric>
+#include <tuple>
#include <iostream>
#include <intel_gpu/primitives/input_layout.hpp>
@@ -1964,4 +1966,376 @@ TEST(sdpa_gpu_custom, scalar_placeholder_mask_matches_scale_only) {
<< std::endl;
}
}
+
+struct sdpa_ref_scratch_test : public ::testing::TestWithParam<std::tuple<data_types, int, bool>> {};
+
+TEST_P(sdpa_ref_scratch_test, native_q_broadcast) {
+ const auto dt = std::get<0>(GetParam());
+ const auto order_kind = std::get<1>(GetParam());
+ const auto dynamic_batch = std::get<2>(GetParam());
+ auto& engine = get_test_engine();
+
+ auto dims = [&](int64_t batch, int64_t sequence, int64_t head_size) {
+ switch (order_kind) {
+ case 1:
+ return ov::PartialShape{batch, sequence, 4, head_size};
+ case 2:
+ return ov::PartialShape{sequence, batch, 4, head_size};
+ default:
+ return ov::PartialShape{batch, 4, sequence, head_size};
+ }
+ };
+ const std::vector<std::vector<int64_t>> orders = {{0, 1, 2, 3}, {0, 2, 1, 3}, {1, 2, 0, 3}};
+ const auto& order = orders.at(order_kind);
+ const int64_t kv_batch = dynamic_batch ? -1 : 2;
+ topology topo;
+ topo.add(input_layout("q", layout(dims(1, 2, 64), dt, format::bfyx)));
+ topo.add(input_layout("k", layout(dims(kv_batch, 16, 64), dt, format::bfyx)));
+ // A dynamic V head size naturally selects SDPARef, without implementation forcing.
+ topo.add(input_layout("v", layout(dims(kv_batch, 16, -1), dt, format::bfyx)));
+ topo.add(
+ scaled_dot_product_attention("sdpa", {input_info("q"), input_info("k"), input_info("v")}, false, -1, order, order, order, {0, 1, 2, 3}, {}, false));
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ auto net = get_network(engine, topo, config, get_test_stream_ptr(), false);
+ auto& stream = net->get_stream();
+ const auto sdpa = net->get_primitive("sdpa");
+ ASSERT_EQ(sdpa->get_impl()->m_manager->get_type_info(), ov::intel_gpu::ocl::SDPARef::get_type_info_static());
+ const auto initial_descriptors = sdpa->get_impl()->get_internal_buffer_descs(*sdpa->get_impl_params());
+ ASSERT_EQ(initial_descriptors.size(), 1u);
+ ASSERT_EQ(initial_descriptors[0].m_layout.count(), 1u);
+
+ const std::vector<int64_t> batches = dynamic_batch ? std::vector<int64_t>{1, 2, 1} : std::vector<int64_t>{2};
+ for (const auto batch : batches) {
+ SCOPED_TRACE(::testing::Message() << "KV batch=" << batch);
+ auto set_input = [&](const std::string& id, int64_t input_batch, int64_t sequence, int64_t head_size) {
+ const layout input_layout(dims(input_batch, sequence, head_size), dt, format::bfyx);
+ auto memory = engine.allocate_memory(input_layout);
+ std::vector<float> values(input_layout.count(), 0.f);
+ if (id == "v") {
+ for (size_t i = 0; i < values.size(); ++i) {
+ const auto b = order_kind == 2 ? (i / (4 * head_size)) % input_batch : i / (4 * sequence * head_size);
+ values[i] = 0.25f + 0.5f * static_cast<float>(b);
+ }
+ }
+ if (dt == data_types::f32) {
+ set_values(memory, values);
+ } else if (dt == data_types::f16) {
+ set_values(memory, std::vector<ov::float16>(values.begin(), values.end()));
+ } else {
+ set_values(memory, std::vector<ov::bfloat16>(values.begin(), values.end()));
+ }
+ net->set_input_data(id, memory);
+ };
+ // Keep Q at batch 1: no tiling or oversized backing allocations.
+ set_input("q", 1, 2, 64);
+ set_input("k", batch, 16, 64);
+ set_input("v", batch, 16, 32);
+
+ // Check the normal allocation before enqueue, so the regression fails without an out-of-bounds write.
+ net->set_arguments();
+ for (const auto& id : net->get_executed_primitive_ids()) {
+ const auto instance = net->get_primitive(id);
+ instance->reset_events();
+ instance->prepare_primitive();
+ if (id == "sdpa") {
+ ASSERT_EQ(instance->get_impl()->m_manager->get_type_info(), ov::intel_gpu::ocl::SDPARef::get_type_info_static());
+ ASSERT_EQ(instance->get_output_layout().get_shape(), (ov::Shape{static_cast<size_t>(batch), 4, 2, 32}));
+ const auto descriptors = instance->get_impl()->get_internal_buffer_descs(*instance->get_impl_params());
+ ASSERT_EQ(descriptors.size(), 1u);
+ const data_types scratch_type = dt == data_types::bf16 ? data_types::f32 : dt;
+ const size_t required_elements = static_cast<size_t>(batch) * 4 * 2 * 16;
+ ASSERT_EQ(descriptors[0].m_layout.data_type, scratch_type);
+ ASSERT_EQ(descriptors[0].m_layout.count(), required_elements) << "SDPARef scratch must cover the broadcast output batch";
+ // Descriptor-only checks: output transposes and padding do not change the scratch geometry.
+ // Do not enqueue the reference kernel with these synthetic output layouts.
+ for (const auto& output_order : std::vector<std::vector<int64_t>>{{}, {0, 2, 1, 3}, {3, 0, 1, 2}}) {
+ auto params = *instance->get_impl_params();
+ auto desc = std::make_shared<scaled_dot_product_attention>(*params.typed_desc<scaled_dot_product_attention>());
+ desc->output_transpose_order = output_order;
+ params.desc = desc;
+ const auto shape = params.output_layouts[0].get_shape();
+ auto transposed_shape = shape;
+ for (size_t i = 0; i < output_order.size(); ++i) {
+ transposed_shape[i] = shape[output_order[i]];
+ }
+ params.output_layouts[0] = layout(transposed_shape, dt, format::bfyx, padding{{0, 0, 1, 1}, {0, 0, 1, 1}});
+ ASSERT_EQ(instance->get_impl()->get_internal_buffer_descs(params)[0].m_layout.count(), required_elements);
+ }
+ const auto& memories = instance->get_intermediates_memories();
+ ASSERT_EQ(memories.size(), 1u);
+ ASSERT_GE(memories[0]->size(), descriptors[0].m_layout.bytes_count());
+ }
+ instance->execute();
+ }
+ stream.finish();
+ const auto kernels = sdpa->get_impl()->get_kernels_dump_info(*sdpa->get_impl_params()).get_entries();
+ ASSERT_NE(kernels.find("sdpa_ref"), std::string::npos) << kernels;
+
+ auto check_output = [&](const auto& output) {
+ ASSERT_EQ(output.size(), static_cast<size_t>(batch) * 4 * 2 * 32);
+ for (size_t i = 0; i < output.size(); ++i) {
+ const float expected = 0.25f + 0.5f * static_cast<float>(i / (4 * 2 * 32));
+ ASSERT_FLOAT_EQ(static_cast<float>(output[i]), expected) << "Output index " << i;
+ }
+ };
+ const auto output = sdpa->output_memory_ptr();
+ if (dt == data_types::f32) {
+ check_output(mem_lock<float, mem_lock_type::read>(output, stream));
+ } else if (dt == data_types::f16) {
+ check_output(mem_lock<ov::float16, mem_lock_type::read>(output, stream));
+ } else {
+ check_output(mem_lock<ov::bfloat16, mem_lock_type::read>(output, stream));
+ }
+ for (const auto& id : net->get_executed_primitive_ids()) {
+ net->get_primitive(id)->reset_flags();
+ }
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(sdpa_ref_scratch,
+ sdpa_ref_scratch_test,
+ ::testing::Combine(::testing::Values(data_types::f32, data_types::f16, data_types::bf16),
+ ::testing::Values(0, 1, 2),
+ ::testing::Bool()));
+
+// Compare FP16 optimized SDPA batch broadcasting with the FP32 reference implementation.
+
+struct sdpa_broadcast_test_params {
+ int q_batch;
+ int k_batch;
+ int v_batch;
+ int num_heads;
+ int seq_q;
+ int seq_kv;
+ int head_size;
+ bool dynamic_batch; // batch dim is dynamic in the network (tensors are static)
+ int order_kind; // 0: [B,H,L,E] default order; 1: [B,L,H,E] order {0,2,1,3}; 2: [L,B,H,E] order {1,2,0,3}
+
+ sdpa_broadcast_test_params(int qb, int kb, int vb, int nh, int sq, int sk, int hs, bool dyn_batch, int kind)
+ : q_batch(qb), k_batch(kb), v_batch(vb), num_heads(nh), seq_q(sq), seq_kv(sk), head_size(hs),
+ dynamic_batch(dyn_batch), order_kind(kind) {}
+};
+
+struct sdpa_broadcast_test : public ::testing::TestWithParam<sdpa_broadcast_test_params> {
+ tests::random_generator rg;
+
+ void SetUp() override {
+ rg.set_seed(GET_SUITE_NAME);
+ }
+
+ // Select SDPARef through a dynamic V head size; verify the actual implementation on both paths.
+ cldnn::memory::ptr run_broadcast_network(const cldnn::layout& q_layout,
+ const cldnn::layout& k_layout,
+ const cldnn::layout& v_layout,
+ cldnn::memory::ptr q_mem,
+ cldnn::memory::ptr k_mem,
+ cldnn::memory::ptr v_mem,
+ const std::string& impl,
+ int order_kind) {
+ auto& engine = get_test_engine();
+ topology topo;
+ topo.add(input_layout("q", q_layout));
+ topo.add(input_layout("k", k_layout));
+ auto v_shape = v_layout.get_partial_shape();
+ if (impl == "sdpa_ref")
+ v_shape[3] = ov::Dimension::dynamic();
+ topo.add(input_layout("v", cldnn::layout(v_shape, v_layout.data_type, v_layout.format)));
+
+ const std::vector<std::vector<int64_t>> orders = {{0, 1, 2, 3}, {0, 2, 1, 3}, {1, 2, 0, 3}};
+ const std::vector<int64_t>& in_order = orders.at(order_kind);
+ auto sdpa_prim = scaled_dot_product_attention("sdpa",
+ {input_info("q"), input_info("k"), input_info("v")},
+ false,
+ -1,
+ in_order,
+ in_order,
+ in_order,
+ {0, 1, 2, 3},
+ {},
+ false);
+ topo.add(sdpa_prim);
+ topo.add(reorder("result", input_info("sdpa"), format::bfyx, q_layout.data_type));
+
+ ExecutionConfig config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ if (!impl.empty() && impl != "sdpa_ref") {
+ config.set_property(ov::intel_gpu::force_implementations(ov::intel_gpu::ImplForcingMap{
+ {"sdpa", {format::type::bfyx, impl}}}));
+ }
+
+ auto net = get_network(engine, topo, config, get_test_stream_ptr(), false);
+ // A removable output reorder may rename the SDPA node to "result".
+ std::string sdpa_id;
+ for (const auto& info : net->get_primitives_info()) {
+ if (info.type_id == "scaled_dot_product_attention")
+ sdpa_id = info.original_id;
+ }
+ EXPECT_FALSE(sdpa_id.empty()) << "Expected an SDPA primitive";
+ if (sdpa_id.empty())
+ return nullptr;
+ auto verify_manager = [&]() {
+ const auto& manager = net->get_primitive(sdpa_id)->get_impl()->m_manager;
+ const auto& expected_type =
+ impl == "sdpa_ref" ? ov::intel_gpu::ocl::SDPARef::get_type_info_static() : ov::intel_gpu::ocl::SDPAOpt::get_type_info_static();
+ EXPECT_EQ(manager->get_type_info(), expected_type) << "Unexpected SDPA implementation";
+ };
+ verify_manager();
+ net->set_input_data("q", q_mem);
+ net->set_input_data("k", k_mem);
+ net->set_input_data("v", v_mem);
+ auto result = net->execute().at("result").get_memory();
+ verify_manager();
+ const auto instance = net->get_primitive(sdpa_id);
+ const auto executed_kernels = instance->get_impl()->get_kernels_dump_info(*instance->get_impl_params()).get_entries();
+ const bool is_reference = impl == "sdpa_ref";
+ EXPECT_EQ(executed_kernels.find("sdpa_ref") != std::string::npos, is_reference) << "Executed kernels: " << executed_kernels;
+ EXPECT_EQ(executed_kernels.find("sdpa_micro") != std::string::npos || executed_kernels.find("sdpa_opt") != std::string::npos, !is_reference)
+ << "Executed kernels: " << executed_kernels;
+ RecordProperty(is_reference ? "reference_kernels" : "optimized_kernels", executed_kernels);
+ EXPECT_EQ(result->get_layout().data_type, q_layout.data_type);
+ return result;
+ }
+
+ void check_broadcast() {
+ const auto& p = GetParam();
+ auto& engine = get_test_engine();
+
+ auto dims = [&](int64_t b, int64_t seq) {
+ switch (p.order_kind) {
+ case 1: return ov::PartialShape{b, seq, p.num_heads, p.head_size};
+ case 2: return ov::PartialShape{seq, b, p.num_heads, p.head_size};
+ default: return ov::PartialShape{b, p.num_heads, seq, p.head_size};
+ }
+ };
+ const auto q_layout = cldnn::layout(dims(p.q_batch, p.seq_q), data_types::f16, format::bfyx);
+ const auto k_layout = cldnn::layout(dims(p.k_batch, p.seq_kv), data_types::f16, format::bfyx);
+ const auto v_layout = cldnn::layout(dims(p.v_batch, p.seq_kv), data_types::f16, format::bfyx);
+ const auto net_q_layout = p.dynamic_batch ? cldnn::layout(dims(-1, p.seq_q), data_types::f16, format::bfyx) : q_layout;
+ const auto net_k_layout = p.dynamic_batch ? cldnn::layout(dims(-1, p.seq_kv), data_types::f16, format::bfyx) : k_layout;
+ const auto net_v_layout = p.dynamic_batch ? cldnn::layout(dims(-1, p.seq_kv), data_types::f16, format::bfyx) : v_layout;
+
+ // Bound logits to reduce FP16 rounding sensitivity; V values distinguish logical batches.
+ auto q_data = rg.generate_random_1d<ov::float16>(q_layout.count(), -1.0f, 1.0f);
+ auto k_data = rg.generate_random_1d<ov::float16>(k_layout.count(), -1.0f, 1.0f);
+ auto v_data = rg.generate_random_1d<ov::float16>(v_layout.count(), 0.25f, 0.75f);
+
+ const auto v_shape = v_layout.get_shape();
+ for (size_t i = 0; i < v_data.size(); ++i) {
+ const size_t batch = p.order_kind == 2 ? (i / (v_shape[2] * v_shape[3])) % v_shape[1] : i / (v_shape[1] * v_shape[2] * v_shape[3]);
+ v_data[i] = ov::float16(static_cast<float>(v_data[i]) + 0.5f * static_cast<float>(batch));
+ }
+
+ // Fill the space after the real Q/K/V data with NaN, so any read past the batch shows up as NaN.
+ const int max_batch = std::max({p.q_batch, p.k_batch, p.v_batch});
+ std::vector<cldnn::memory::ptr> keep_alive;
+ auto make_guarded = [&](const cldnn::layout& real_layout, const std::vector<ov::float16>& data) {
+ auto shape = real_layout.get_shape();
+ shape[p.order_kind == 2 ? 1 : 0] = static_cast<size_t>(max_batch);
+ cldnn::layout big_layout(shape, real_layout.data_type, real_layout.format);
+ auto big = engine.allocate_memory(big_layout);
+ std::vector<ov::float16> padded(big_layout.count(), ov::float16(std::numeric_limits<float>::quiet_NaN()));
+ std::copy(data.begin(), data.end(), padded.begin());
+ set_values(big, padded);
+ keep_alive.push_back(big);
+ return engine.reinterpret_buffer(*big, real_layout);
+ };
+ auto q_mem = make_guarded(q_layout, q_data);
+ auto k_mem = make_guarded(k_layout, k_data);
+ auto v_mem = make_guarded(v_layout, v_data);
+
+ // sdpa_micro on systolic devices, sdpa_opt otherwise (micro is disabled on xe3p for head_size <= 64).
+ auto& device_info = engine.get_device_info();
+ const bool micro_eligible = device_info.supports_immad && !(device_info.arch == cldnn::gpu_arch::xe3p && p.head_size <= 64);
+ const std::string opt_impl = micro_eligible ? "sdpa_micro" : "sdpa_opt";
+
+ // Static batches that are neither equal nor 1 cannot be broadcast: kernel generation must reject them.
+ auto batches_conflict = [](int a, int b) { return a != 1 && b != 1 && a != b; };
+ if (!p.dynamic_batch && (batches_conflict(p.q_batch, p.k_batch) || batches_conflict(p.q_batch, p.v_batch) ||
+ batches_conflict(p.k_batch, p.v_batch))) {
+ EXPECT_ANY_THROW(run_broadcast_network(net_q_layout, net_k_layout, net_v_layout, q_mem, k_mem, v_mem, opt_impl, p.order_kind));
+ return;
+ }
+
+ // Compute the reference in FP32 from the exact FP16 input values, not unrounded random values.
+ auto as_f32_layout = [](cldnn::layout input) {
+ input.data_type = data_types::f32;
+ return input;
+ };
+ auto make_f32_memory = [&](const cldnn::layout& input_layout, const std::vector<ov::float16>& input_data) {
+ auto memory = engine.allocate_memory(as_f32_layout(input_layout));
+ set_values(memory, std::vector<float>(input_data.begin(), input_data.end()));
+ return memory;
+ };
+ auto ref_q_mem = make_f32_memory(q_layout, q_data);
+ auto ref_k_mem = make_f32_memory(k_layout, k_data);
+ auto ref_v_mem = make_f32_memory(v_layout, v_data);
+ auto mem_ref = run_broadcast_network(as_f32_layout(net_q_layout),
+ as_f32_layout(net_k_layout),
+ as_f32_layout(net_v_layout),
+ ref_q_mem,
+ ref_k_mem,
+ ref_v_mem,
+ "sdpa_ref",
+ p.order_kind);
+ auto mem_opt = run_broadcast_network(net_q_layout, net_k_layout, net_v_layout, q_mem, k_mem, v_mem, opt_impl, p.order_kind);
+
+ ASSERT_NE(mem_ref, nullptr);
+ ASSERT_NE(mem_opt, nullptr);
+ cldnn::mem_lock<float, mem_lock_type::read> ref_ptr(mem_ref, get_test_stream());
+ cldnn::mem_lock<ov::float16, mem_lock_type::read> opt_ptr(mem_opt, get_test_stream());
+
+ ASSERT_EQ(mem_ref->get_layout().get_shape(), mem_opt->get_layout().get_shape());
+ ASSERT_EQ(ref_ptr.size(), opt_ptr.size());
+ // Keep the reference away from zero so invalid reads cannot hide within the tolerance.
+ float max_abs_ref = 0.f;
+ for (size_t i = 0; i < ref_ptr.size(); ++i) {
+ ASSERT_TRUE(std::isfinite(static_cast<float>(ref_ptr[i]))) << "Reference output is not finite at index " << i;
+ max_abs_ref = std::max(max_abs_ref, std::abs(static_cast<float>(ref_ptr[i])));
+ }
+ ASSERT_GT(max_abs_ref, 0.3f) << "Reference output too small: the test would not detect wrong K/V reads";
+ for (size_t i = 0; i < ref_ptr.size(); ++i) {
+ ASSERT_TRUE(std::isfinite(static_cast<float>(opt_ptr[i]))) << "Optimized output is not finite at index " << i;
+ ASSERT_NEAR(static_cast<float>(opt_ptr[i]), static_cast<float>(ref_ptr[i]), 1e-2f)
+ << "Broadcast SDPA mismatch at index " << i
+ << ", opt=" << static_cast<float>(opt_ptr[i])
+ << " ref=" << static_cast<float>(ref_ptr[i])
+ << " (Q batch=" << p.q_batch << " K batch=" << p.k_batch << " V batch=" << p.v_batch << ")"
+ << std::endl;
+ }
+ }
+};
+
+TEST_P(sdpa_broadcast_test, matches_reference) {
+ check_broadcast();
+}
+
+INSTANTIATE_TEST_SUITE_P(
+ sdpa_broadcast,
+ sdpa_broadcast_test,
+ ::testing::Values(
+ // K/V batch = 1 (K and V broadcast, then each alone), default layout [B,H,L,E]
+ sdpa_broadcast_test_params(2, 1, 1, 16, 1, 1024, 64, true, 0),
+ sdpa_broadcast_test_params(2, 1, 1, 16, 64, 1024, 64, true, 0),
+ sdpa_broadcast_test_params(2, 1, 1, 16, 1, 1024, 64, false, 0),
+ sdpa_broadcast_test_params(2, 2, 1, 16, 1, 1024, 64, true, 0),
+ sdpa_broadcast_test_params(2, 1, 2, 16, 1, 1024, 64, true, 0),
+ // transposed layout [B,L,H,E] with order {0,2,1,3}
+ sdpa_broadcast_test_params(2, 1, 1, 16, 64, 1024, 64, true, 1),
+ sdpa_broadcast_test_params(2, 1, 1, 16, 1, 1024, 64, false, 1),
+ // layout [L,B,H,E] with order {1,2,0,3}: the logical batch is not layout dim 0
+ sdpa_broadcast_test_params(2, 1, 1, 16, 1, 1024, 64, true, 2),
+ sdpa_broadcast_test_params(2, 1, 1, 16, 1, 1024, 64, false, 2),
+ sdpa_broadcast_test_params(2, 2, 2, 16, 1, 1, 64, false, 2),
+ // incompatible static batches are rejected
+ sdpa_broadcast_test_params(4, 2, 2, 16, 64, 1024, 64, false, 0),
+ // Q batch 1 is broadcast to K/V batch
+ sdpa_broadcast_test_params(1, 2, 2, 16, 1, 1024, 64, true, 0),
+ sdpa_broadcast_test_params(1, 2, 2, 16, 64, 1024, 64, true, 0),
+ sdpa_broadcast_test_params(1, 2, 2, 16, 1, 1024, 64, false, 0),
+ sdpa_broadcast_test_params(1, 4, 1, 16, 1, 1024, 64, true, 0),
+ sdpa_broadcast_test_params(1, 1, 4, 16, 1, 1024, 64, true, 0),
+ sdpa_broadcast_test_params(1, 2, 2, 16, 1, 1024, 64, true, 2),
+ sdpa_broadcast_test_params(1, 2, 2, 16, 1, 1024, 64, false, 1)));
+
} // namespace