Skip to content

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

[GPU] Enable statelesskv with optional query_seqlens (#39582)

ZackyLake2ad63894cb2d
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 fb5d5e7490b..5f36ee4058b 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
@@ -427,15 +427,7 @@ ov::OutputVector ov::pass::GroupQueryAttentionDecomposition::decompose(
const bool has_sink = has_head_sink || smooth_softmax;
// The explicit chain has no is_causal fallback, and shared KV must hide the past rows beyond `total`, so both
// always take the explicit (base) mask; overrides may otherwise drop it in favor of SDPA's causal flag.
- // A declared fixed (static) capacity can likewise sit in a capacity-padded KV buffer once query_seqlens grows
- // it past its static size, where kv_len - S no longer equals the true past offset -- an override's implicit
- // causal alignment (SDPA's native is_causal, which assumes the query is the buffer's tail) would then be
- // wrong, so force the explicit mask (built from the real past offset) there too. A growing (non-fixed-
- // capacity) or windowed cache keeps its existing exactly-sized buffer invariant (no capacity slack), so both
- // are left out to keep their native fast paths.
- const bool explicit_mask =
- use_explicit_attention || shared_kv ||
- (has_query_seqlens && node->has_fixed_kv_capacity() && !node->get_sliding_window_cache());
+ const bool explicit_mask = use_explicit_attention || shared_kv;
// 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).
diff --git a/src/plugins/intel_gpu/include/intel_gpu/op/stateless_kv.hpp b/src/plugins/intel_gpu/include/intel_gpu/op/stateless_kv.hpp
index a0831f0e779..0ea1fd6ba3c 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/op/stateless_kv.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/op/stateless_kv.hpp
@@ -29,6 +29,13 @@ public:
const Output<Node>& pos_idx,
int64_t concat_axis,
bool is_seq_len_present_len);
+ StatelessKV(const Output<Node>& past,
+ const Output<Node>& new_token_data,
+ const Output<Node>& seq_len,
+ const Output<Node>& cur_len,
+ int64_t concat_axis,
+ bool is_seq_len_present_len,
+ int64_t window_size);
bool visit_attributes(ov::AttributeVisitor& visitor) override;
@@ -57,11 +64,11 @@ public:
m_window_size = window_size;
}
- bool get_is_rolling() const {
- return m_is_rolling;
+ bool get_is_capacity_overflow() const {
+ return m_is_capacity_overflow;
}
- void set_is_rolling(bool is_rolling) {
- m_is_rolling = is_rolling;
+ void set_is_capacity_overflow(bool is_capacity_overflow) {
+ m_is_capacity_overflow = is_capacity_overflow;
}
std::optional<int64_t> get_update_offset() const {
@@ -78,15 +85,20 @@ public:
m_past_seq_len = past_seq_len;
}
+ bool get_has_pos_idx() const {
+ return m_has_pos_idx;
+ }
+
protected:
- StatelessKV(const OutputVector& inputs, int64_t concat_axis, bool is_seq_len_present_len, int64_t window_size);
+ StatelessKV(const OutputVector& inputs, int64_t concat_axis, bool is_seq_len_present_len, int64_t window_size, bool has_pos_idx);
int64_t m_concat_axis = 0;
std::optional<int64_t> m_update_offset;
std::optional<int64_t> m_past_seq_len;
bool m_is_seq_len_present_len = true;
int64_t m_window_size = 0;
- bool m_is_rolling = false;
+ bool m_is_capacity_overflow = false;
+ bool m_has_pos_idx = false;
};
std::vector<ov::PartialShape> shape_infer(const StatelessKV* op, const std::vector<ov::PartialShape>& input_shapes);
diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/stateless_kv.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/stateless_kv.hpp
index 1eec2f95e7a..4d3b26746f9 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/primitives/stateless_kv.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/stateless_kv.hpp
@@ -17,23 +17,31 @@ struct stateless_kv : public primitive_base<stateless_kv> {
const std::vector<input_info>& inputs,
const int64_t concat_axis,
const bool is_seq_len_present_len,
- const int64_t window_size = 0)
+ const int64_t window_size = 0,
+ const bool has_pos_idx = false)
: primitive_base(id, inputs),
concat_axis(concat_axis),
is_seq_len_present_len(is_seq_len_present_len),
- window_size(window_size) {
+ window_size(window_size),
+ has_pos_idx(has_pos_idx) {
OPENVINO_ASSERT(concat_axis >= 0, "[GPU] stateless_kv concat_axis must be normalized");
}
int64_t concat_axis = 0;
bool is_seq_len_present_len = true;
int64_t window_size = 0;
+ bool has_pos_idx = false;
+
+ bool has_cur_len() const {
+ return !has_pos_idx && input.size() == 4;
+ }
size_t hash() const override {
size_t seed = primitive::hash();
seed = hash_combine(seed, concat_axis);
seed = hash_combine(seed, is_seq_len_present_len);
seed = hash_combine(seed, window_size);
+ seed = hash_combine(seed, has_pos_idx);
return seed;
}
@@ -43,7 +51,8 @@ struct stateless_kv : public primitive_base<stateless_kv> {
auto rhs_casted = downcast<const stateless_kv>(rhs);
- return concat_axis == rhs_casted.concat_axis && is_seq_len_present_len == rhs_casted.is_seq_len_present_len && window_size == rhs_casted.window_size;
+ return concat_axis == rhs_casted.concat_axis && is_seq_len_present_len == rhs_casted.is_seq_len_present_len &&
+ window_size == rhs_casted.window_size && has_pos_idx == rhs_casted.has_pos_idx;
}
void save(BinaryOutputBuffer& ob) const override {
@@ -51,6 +60,7 @@ struct stateless_kv : public primitive_base<stateless_kv> {
ob << concat_axis;
ob << is_seq_len_present_len;
ob << window_size;
+ ob << has_pos_idx;
}
void load(BinaryInputBuffer& ib) override {
@@ -58,6 +68,7 @@ struct stateless_kv : public primitive_base<stateless_kv> {
ib >> concat_axis;
ib >> is_seq_len_present_len;
ib >> window_size;
+ ib >> has_pos_idx;
}
};
} // namespace cldnn
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 550c6efe46c..2a550f2cc3a 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
@@ -92,6 +92,14 @@ kernel_selector::scatter_update_axis convert_scatter_axis(int64_t axis, size_t r
return kernel_selector::scatter_update_axis::X;
}
+layout get_seq_dynamic_layout(layout l, int64_t axis) {
+ auto shape = l.get_partial_shape();
+ shape[axis] = ov::Dimension::dynamic();
+ l.set_partial_shape(shape);
+ l.data_padding._dynamic_dims_mask[axis] = true;
+ return l;
+}
+
} // namespace
struct stateless_kv_impl : multi_stage_primitive<stateless_kv> {
@@ -244,13 +252,13 @@ struct stateless_kv_impl : multi_stage_primitive<stateless_kv> {
static concat_kernel_params_t get_concat2_to1_kernel_params(const kernel_impl_params& impl_param,
const layout& input0_layout,
+ const layout& input1_layout,
size_t input0_shape_info_idx,
size_t input1_idx,
size_t output_idx,
bool is_shape_agnostic = false) {
const auto& primitive = impl_param.typed_desc<stateless_kv>();
auto params = get_default_params<concat_kernel_params_t>(impl_param, is_shape_agnostic);
- const auto& input1_layout = impl_param.get_input_layout(input1_idx);
const auto& output_layout = impl_param.get_output_layout(output_idx);
params.axis = convert_concat_axis(primitive->concat_axis, output_layout.get_rank());
params.inputs.resize(2);
@@ -347,16 +355,13 @@ struct stateless_kv_impl : multi_stage_primitive<stateless_kv> {
std::vector<stateless_kv_stage> stages;
kernels_data.reserve(swa ? swa_stage_count : 1);
stages.reserve(swa ? swa_stage_count : 1);
+ const auto new_layout = get_seq_dynamic_layout(params.get_input_layout(1), primitive->concat_axis);
if (primitive->window_size > 0) {
- OPENVINO_ASSERT(primitive->input.size() == 3, "[GPU] stateless_kv doesn't support window_size together with pos_idx");
+ OPENVINO_ASSERT(!primitive->has_pos_idx, "[GPU] stateless_kv doesn't support window_size together with pos_idx");
auto& kernel_selector = concat_kernel_selector_t::Instance();
- auto past_view_layout = params.get_input_layout(0);
- auto past_view_shape = past_view_layout.get_partial_shape();
- past_view_shape[primitive->concat_axis] = ov::Dimension::dynamic();
- past_view_layout.set_partial_shape(past_view_shape);
- past_view_layout.data_padding._dynamic_dims_mask[primitive->concat_axis] = true;
- auto concat_to_sdpa_params = get_concat2_to1_kernel_params(params, past_view_layout, 3, 1, 1, true);
+ const auto past_view_layout = get_seq_dynamic_layout(params.get_input_layout(0), primitive->concat_axis);
+ auto concat_to_sdpa_params = get_concat2_to1_kernel_params(params, past_view_layout, new_layout, primitive->input.size(), 1, 1, true);
concat_to_sdpa_params.stage_id = stages.size();
auto concat_to_sdpa_data = kernel_selector.get_best_kernel(concat_to_sdpa_params);
OPENVINO_ASSERT(concat_to_sdpa_data.kernels.size() == 2, "[GPU] stateless_kv concat-to-SDPA stage expects two sub-kernels");
@@ -364,20 +369,16 @@ struct stateless_kv_impl : multi_stage_primitive<stateless_kv> {
stages.push_back(stateless_kv_stage::concat_to_sdpa);
auto sdpa_to_present_params =
- get_swa_concat_kernel_params(params, stages.size(), params.get_output_layout(1), params.get_output_layout(0), 4, 0, true);
+ get_swa_concat_kernel_params(params, stages.size(), params.get_output_layout(1), params.get_output_layout(0), primitive->input.size() + 1, 0, true);
auto sdpa_to_present_data = kernel_selector.get_best_kernel(sdpa_to_present_params);
OPENVINO_ASSERT(sdpa_to_present_data.kernels.size() == 1, "[GPU] stateless_kv SDPA-to-present stage expects one sub-kernel");
kernels_data.push_back(std::move(sdpa_to_present_data));
stages.push_back(stateless_kv_stage::sdpa_to_present);
}
- if (primitive->input.size() == 3) {
- auto input0_layout = params.get_input_layout(0);
- auto input0_shape = input0_layout.get_partial_shape();
- input0_shape[primitive->concat_axis] = ov::Dimension::dynamic();
- input0_layout.set_partial_shape(input0_shape);
- input0_layout.data_padding._dynamic_dims_mask[primitive->concat_axis] = true;
- auto kernel_params = get_concat2_to1_kernel_params(params, input0_layout, 0, 1, 0, true);
+ if (!primitive->has_pos_idx) {
+ const auto input0_layout = get_seq_dynamic_layout(params.get_input_layout(0), primitive->concat_axis);
+ auto kernel_params = get_concat2_to1_kernel_params(params, input0_layout, new_layout, 0, 1, 0, true);
kernel_params.stage_id = stages.size();
kernel_params.is_shape_agnostic = kernel_params.has_dynamic_tensors();
auto& kernel_selector = concat_kernel_selector_t::Instance();
@@ -404,7 +405,7 @@ struct stateless_kv_impl : multi_stage_primitive<stateless_kv> {
if (state != nullptr) {
OPENVINO_ASSERT(!state->is_rolling() || (state->past_front_idx <= state->sdpa_front_idx && state->sdpa_front_idx <= state->present_front_idx));
OPENVINO_ASSERT(state->get_new_in_sdpa_offset() >= 0);
- OPENVINO_ASSERT(state->get_present_output_len() == std::max<int64_t>(0, state->get_new_in_present_offset()) + state->new_token_len -
+ OPENVINO_ASSERT(state->get_present_output_len() == std::max<int64_t>(0, state->get_new_in_present_offset()) + state->new_seq_len -
std::max<int64_t>(0, -state->get_new_in_present_offset()));
}
@@ -420,12 +421,13 @@ struct stateless_kv_impl : multi_stage_primitive<stateless_kv> {
switch (stage) {
case stateless_kv_stage::concat_to_sdpa: {
OPENVINO_ASSERT(swa && state != nullptr, "[GPU] stateless_kv concat-to-SDPA stage requires SWA");
- if (!rolling || (state->get_new_in_sdpa_offset() == 0 && state->new_token_len == 0)) {
+ if (!state->is_capacity_overflow()) {
skip_stage();
break;
}
const auto past_view = state->get_past_to_sdpa_input_layout(impl_param.get_input_layout(0), primitive->concat_axis);
- auto updated_params = get_concat2_to1_kernel_params(impl_param, past_view, 3, 1, 1, true);
+ const auto new_view = state->get_new_input_layout(impl_param.get_input_layout(1), primitive->concat_axis);
+ auto updated_params = get_concat2_to1_kernel_params(impl_param, past_view, new_view, primitive->input.size(), 1, 1, true);
updated_params.stage_id = stage_idx;
if (!kernel_data.params) {
kernel_data.params = std::make_shared<concat_kernel_params_t>(std::move(updated_params));
@@ -434,8 +436,6 @@ struct stateless_kv_impl : multi_stage_primitive<stateless_kv> {
}
kernel_data.update_dispatch_data_func(*kernel_data.params, kernel_data);
OPENVINO_ASSERT(kernel_data.kernels.size() == 2);
- for (auto& kernel : kernel_data.kernels)
- kernel.skip_execution = false;
break;
}
case stateless_kv_stage::sdpa_to_present: {
@@ -445,7 +445,8 @@ struct stateless_kv_impl : multi_stage_primitive<stateless_kv> {
break;
}
const auto sdpa_view = state->get_sdpa_to_present_input_layout(impl_param.get_output_layout(1), primitive->concat_axis);
- auto updated_params = get_swa_concat_kernel_params(impl_param, stage_idx, sdpa_view, impl_param.get_output_layout(0), 4, 0, false);
+ auto updated_params =
+ get_swa_concat_kernel_params(impl_param, stage_idx, sdpa_view, impl_param.get_output_layout(0), primitive->input.size() + 1, 0, false);
if (!kernel_data.params) {
kernel_data.params = std::make_shared<concat_kernel_params_t>(std::move(updated_params));
} else {
@@ -464,9 +465,12 @@ struct stateless_kv_impl : multi_stage_primitive<stateless_kv> {
skip_stage();
break;
}
- const auto concat_offset = swa ? std::optional<int64_t>(state->get_new_in_present_offset()) : get_concat_offset(impl_param);
+ OPENVINO_ASSERT(!primitive->has_cur_len() || _runtime_state.has_value(), "[GPU] stateless_kv with cur_len requires runtime state");
+ const auto concat_offset = _runtime_state ? std::optional<int64_t>(_runtime_state->get_new_in_present_offset()) : get_concat_offset(impl_param);
const auto input0_layout = get_concat_input0_layout(impl_param, concat_offset);
- auto updated_params = get_concat2_to1_kernel_params(impl_param, input0_layout, 0, 1, 0, true);
+ const auto input1_layout = _runtime_state ? _runtime_state->get_new_input_layout(impl_param.get_input_layout(1), primitive->concat_axis)
+ : impl_param.get_input_layout(1);
+ auto updated_params = get_concat2_to1_kernel_params(impl_param, input0_layout, input1_layout, 0, 1, 0, true);
updated_params.stage_id = stage_idx;
if (!kernel_data.params) {
kernel_data.params = std::make_shared<concat_kernel_params_t>(std::move(updated_params));
@@ -475,8 +479,7 @@ struct stateless_kv_impl : multi_stage_primitive<stateless_kv> {
}
kernel_data.update_dispatch_data_func(*kernel_data.params, kernel_data);
OPENVINO_ASSERT(kernel_data.kernels.size() == 2, "[GPU] stateless_kv concat expects two sub-kernels");
- kernel_data.kernels[0].skip_execution = _is_inplace;
- kernel_data.kernels[1].skip_execution = false;
+ kernel_data.kernels[0].skip_execution = kernel_data.kernels[0].skip_execution || _is_inplace;
if (concat_offset) {
OPENVINO_ASSERT(*concat_offset >= 0 && *concat_offset <= std::numeric_limits<uint32_t>::max());
auto& scalars = kernel_data.kernels[1].params.scalars;
diff --git a/src/plugins/intel_gpu/src/graph/include/stateless_kv_inst.h b/src/plugins/intel_gpu/src/graph/include/stateless_kv_inst.h
index 5897c783741..58cb1b7ff87 100644
--- a/src/plugins/intel_gpu/src/graph/include/stateless_kv_inst.h
+++ b/src/plugins/intel_gpu/src/graph/include/stateless_kv_inst.h
@@ -16,15 +16,22 @@ namespace cldnn {
struct stateless_kv_runtime_state {
int64_t past_seq_len = 0;
int64_t present_seq_len = 0;
- int64_t new_token_len = 0;
+ int64_t new_token_size = 0;
+ int64_t new_seq_len = 0;
+ int64_t padded_seq_len = 0;
int64_t past_front_idx = 0;
int64_t present_front_idx = 0;
+ int64_t padded_front_idx = 0;
int64_t sdpa_front_idx = 0;
bool is_rolling() const {
return present_front_idx > past_front_idx;
}
+ bool is_capacity_overflow() const {
+ return padded_front_idx > past_front_idx;
+ }
+
int64_t get_new_in_present_offset() const {
return past_seq_len - present_front_idx;
}
@@ -53,6 +60,8 @@ struct stateless_kv_runtime_state {
return window_size > 0 ? present_seq_len - sdpa_front_idx : present_seq_len;
}
+ layout get_new_input_layout(const layout& input_layout, int64_t concat_axis) const;
+
layout get_past_to_sdpa_input_layout(const layout& input_layout, int64_t concat_axis) const;
layout get_sdpa_to_present_input_layout(const layout& input_layout, int64_t concat_axis) const;
@@ -71,15 +80,17 @@ public:
}
std::vector<size_t> get_shape_infer_dependencies() const override {
+ if (get_primitive()->has_cur_len())
+ return {2, 3};
return {2};
}
std::vector<layout> get_shape_info_input_layouts() const override {
auto layouts = parent::get_shape_info_input_layouts();
- if (get_primitive()->input.size() != 3)
+ if (get_primitive()->has_pos_idx)
return layouts;
- OPENVINO_ASSERT(layouts.size() == 3);
+ OPENVINO_ASSERT(layouts.size() == get_primitive()->input.size());
const auto rank = layouts.front().get_rank();
const auto axis = get_primitive()->concat_axis;
OPENVINO_ASSERT(axis >= 0 && axis < static_cast<int64_t>(rank));
@@ -93,6 +104,8 @@ public:
};
// concat-based always treats input0 as dynamic in case input0 need to be copied
layouts[0] = get_dynamic_layout(layouts[0]);
+ // only the first new_seq_len tokens of input1 are copied
+ layouts[1] = get_dynamic_layout(layouts[1]);
if (get_primitive()->window_size != 0) {
layouts.push_back(layouts[0]);
layouts.push_back(is_valid_output_layout(1) ? get_dynamic_layout(get_output_layout(1)) : layouts[0]);
@@ -136,15 +149,9 @@ public:
typed_primitive_inst(network& network, const stateless_kv_node& desc);
typed_primitive_inst(network& network) : parent(network) {}
- // Kept across executions while present can't be written into the Result buffer in place.
- memory::ptr& private_present() {
- return m_private_present;
- }
-
private:
void on_execute() override;
bool m_is_inplace = false;
- memory::ptr m_private_present;
std::optional<stateless_kv_runtime_state> m_runtime_state;
};
diff --git a/src/plugins/intel_gpu/src/graph/primitive_inst.cpp b/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
index ed005cf4c20..e9833c7301d 100644
--- a/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
+++ b/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
@@ -843,15 +843,16 @@ bool primitive_inst::try_bind_remote_permute_output(const layout& actual_layout)
void primitive_inst::realloc_outputs_for_stateless_kv() {
const auto& users = get_user_insts();
const auto output_it = std::find_if(users.begin(), users.end(), [](primitive_inst* user) {
- return user->is_output();
+ return user->is_output() && user->get_node().is_type<reorder>() &&
+ user->get_node().get_dependency_with_port(0).second == 0;
});
OPENVINO_ASSERT(output_it != users.end(), "[GPU] stateless_kv should directly connect to an output");
+ primitive_inst& result = **output_it;
const auto& past_layout = _impl_params->get_input_layout();
const auto& mid_layout = _impl_params->get_output_layout(0); // output to present_kv
const auto& target_layout = _impl_params->get_output_layout(1); // output to sdpa
- auto& result = **output_it;
if (result.is_dynamic()) {
if (!result._update_shape_done_by_other) {
result.update_shape();
@@ -869,7 +870,10 @@ void primitive_inst::realloc_outputs_for_stateless_kv() {
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 = !past_empty && engine.is_the_same_buffer(*present_tensor, *past_tensor);
+ auto& memory_pool = get_network().get_memory_pool();
+ // output[0] may be cleared outside, conservatively treat output[1] as a separate buffer only when output[0] exists and not aliased.
+ const bool own_output1 = _outputs[0] && _outputs[1] && !engine.is_the_same_buffer(*_outputs[0], *_outputs[1]);
+ const auto is_same = present_tensor && !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 &&
@@ -894,71 +898,98 @@ void primitive_inst::realloc_outputs_for_stateless_kv() {
// a different element type or format, a restricted input, or past whose elements would move.
const auto use_private_present = present_layout.data_type != mid_layout.data_type || present_layout.format != mid_layout.format ||
aliases_restricted_input() || (is_same && !same_placement());
- auto kv_present = present_tensor;
- auto& private_present = downcast<stateless_kv_inst>(*this).private_present();
+
+ if (_outputs[0] && _mem_allocated) {
+ const auto reuse_private_present = use_private_present && mid_layout.get_linear_size() <= _max_output_layout_count[0];
+ GPU_DEBUG_TRACE_DETAIL << id() << ": current private_present, max=" << _max_output_layout_count[0] << " needs=" << mid_layout.get_linear_size()
+ << " => " << (reuse_private_present ? "reuse" : "release") << std::endl;
+ if (!reuse_private_present) {
+ memory_pool.release_memory(_outputs[0].get(), get_node().get_unique_id(), get_node().id(), get_network_id());
+ _mem_allocated = false;
+ _outputs[0] = {};
+ }
+ } else {
+ _outputs[0] = {};
+ }
+ // _outputs[0] exists means it's reused
if (use_private_present) {
- const bool can_reuse = private_present && private_present->size() >= mid_layout.bytes_count();
- auto& sp = *get_network().get_shape_predictor();
- const auto prealloc = sp.predict_preallocation_shape(id(), mid_layout, can_reuse);
- if (!can_reuse) {
- auto alloc_layout = mid_layout;
+ // The Result stays a real reorder and copies the private present into its own buffer.
+ result.set_can_be_optimized(false);
+ if (!_outputs[0]) {
+ auto& sp = *get_network().get_shape_predictor();
+ const auto prealloc = sp.predict_preallocation_shape(id(), mid_layout, false);
+ auto alloc_params = *_impl_params;
+ auto& alloc_layout = alloc_params.output_layouts[0];
if (prealloc.first && sp.can_preallocate(ov::shape_size(prealloc.second) * data_type_traits::size_of(mid_layout.data_type)))
alloc_layout = mid_layout.clone_with_other_shape(prealloc.second);
- if (alloc_layout.bytes_count() < mid_layout.bytes_count())
+ if (alloc_layout.get_linear_size() < mid_layout.get_linear_size())
alloc_layout = mid_layout;
- private_present = engine.allocate_memory(alloc_layout, engine.get_preferred_memory_allocation_type(), false);
+ _outputs[0] = allocate_output(engine,
+ memory_pool,
+ get_node(),
+ alloc_params,
+ _runtime_memory_dependencies,
+ get_network_id(),
+ get_network().is_internal(),
+ 0,
+ false,
+ is_output_buffer(this, true),
+ nullptr,
+ true);
+ _max_output_layout_count[0] = alloc_layout.get_linear_size();
+ _mem_allocated = true;
+ set_flag(ExecutionFlags::MEMORY_CHANGED);
}
- kv_present = engine.reinterpret_buffer(*private_present, mid_layout);
- // The Result stays a real reorder and copies the private present into its own buffer.
- result.set_can_be_optimized(false);
+ _outputs[0] = engine.reinterpret_buffer(*_outputs[0], mid_layout);
} else {
- private_present.reset();
if (mid_layout == present_layout)
result.set_can_be_optimized(true);
+ _max_output_layout_count[0] = result._max_output_layout_count[0];
+ _outputs[0] = present_tensor;
}
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;
+ << (past_tensor ? past_tensor->get_layout().to_short_string() : "") << ") and output["
+ << (present_tensor ? present_tensor->buffer_ptr() : nullptr) << "]("
+ << (present_tensor ? 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;
-
- _outputs[0] = kv_present;
+ << target_layout.to_short_string() << "] -> output[" << present_layout.to_short_string() << "](" << result.id()
+ << ") opt:" << result.can_be_optimized() << std::endl;
const auto& state = downcast<stateless_kv_inst>(*this).get_runtime_state();
OPENVINO_ASSERT(state.has_value(), "[GPU] stateless_kv runtime state wasn't initialized before output allocation");
const auto is_rolling = state->is_rolling();
- GPU_DEBUG_TRACE_DETAIL << id() << ": runtime state" << (is_rolling ? "(rolling)" : "") << ": past=" << state->past_seq_len
- << " present=" << state->present_seq_len << " new=" << state->new_token_len << ", front_idx: past=" << state->past_front_idx
- << " present=" << state->present_front_idx << " sdpa=" << state->sdpa_front_idx << std::endl;
- auto& memory_pool = get_network().get_memory_pool();
+ const auto is_overflow = state->is_capacity_overflow();
+ GPU_DEBUG_TRACE_DETAIL << id() << ": runtime state" << (is_overflow ? "(overflow)" : "") << (is_rolling ? "(rolling)" : "")
+ << ": past=" << state->past_seq_len << " present=" << state->present_seq_len << " new=" << state->new_token_size
+ << ", front_idx: past=" << state->past_front_idx << " present=" << state->present_front_idx << " sdpa=" << state->sdpa_front_idx
+ << std::endl;
- if (_mem_allocated) {
- OPENVINO_ASSERT(_outputs[1], "stateless_kv should only allocate output[1] for itself");
+ if (own_output1) {
const auto concat_axis = ov::util::normalize(get_typed_desc<stateless_kv>()->concat_axis, target_layout.get_rank());
const auto current_len = target_layout.get_partial_shape()[concat_axis].get_length();
const auto last_len = _outputs[1]->get_layout().get_partial_shape()[concat_axis].get_length();
const auto layout_match = target_layout == _outputs[1]->get_layout();
- const auto can_reuse = is_rolling && layout_match;
+ const auto reuse_output1 = is_overflow && layout_match;
GPU_DEBUG_TRACE_DETAIL << id() << ": current_len=" << current_len << " last_len=" << last_len << ", layout " << (layout_match ? "match" : "changed")
- << ", sdpa buffer:" << (can_reuse ? " reuse" : " release") << std::endl;
- if (!can_reuse){
+ << ", sdpa buffer:" << (reuse_output1 ? " reuse" : " release") << std::endl;
+ if (!reuse_output1) {
memory_pool.release_memory(_outputs[1].get(), get_node().get_unique_id(), get_node().id(), _network.get_id());
_outputs[1] = nullptr;
_max_output_layout_count[1] = 0;
- _mem_allocated = false;
}
+ } else {
+ _outputs[1] = nullptr;
}
-
- if (!is_rolling) {
- GPU_DEBUG_TRACE_DETAIL << id() << ": reuse present output as SDPA output for non-rolling update" << std::endl;
- _outputs[1] = engine.reinterpret_buffer(*kv_present, target_layout);
+ // _outputs[1] exists means it's reused
+ if (!is_overflow) {
+ GPU_DEBUG_TRACE_DETAIL << id() << ": use present output as SDPA output for non-overflow update" << std::endl;
+ _outputs[1] = engine.reinterpret_buffer(*_outputs[0], target_layout);
_max_output_layout_count[1] = target_layout.get_linear_size();
- _mem_allocated = false;
} else {
- if (!_mem_allocated) {
- _outputs[1] = nullptr;
- GPU_DEBUG_TRACE_DETAIL << id() << ": allocate independent SDPA output for rolling update, required=" << target_layout.bytes_count() << std::endl;
+ if (!_outputs[1]) {
+ GPU_DEBUG_TRACE_DETAIL << id() << ": allocate independent SDPA output for capacity overflow update, required=" << target_layout.bytes_count()
+ << std::endl;
_outputs[1] = allocate_output(engine,
memory_pool,
get_node(),
@@ -972,7 +1003,6 @@ void primitive_inst::realloc_outputs_for_stateless_kv() {
nullptr,
true);
_max_output_layout_count[1] = target_layout.get_linear_size();
- _mem_allocated = true;
set_flag(ExecutionFlags::MEMORY_CHANGED);
}
}
diff --git a/src/plugins/intel_gpu/src/graph/stateless_kv.cpp b/src/plugins/intel_gpu/src/graph/stateless_kv.cpp
index 6050805a59e..6441997d531 100644
--- a/src/plugins/intel_gpu/src/graph/stateless_kv.cpp
+++ b/src/plugins/intel_gpu/src/graph/stateless_kv.cpp
@@ -32,6 +32,10 @@ static layout get_input_view(const layout& input_layout, int64_t concat_axis, in
return view_layout;
}
+layout stateless_kv_runtime_state::get_new_input_layout(const layout& input_layout, int64_t concat_axis) const {
+ return get_input_view(input_layout, concat_axis, 0, new_seq_len);
+}
+
layout stateless_kv_runtime_state::get_past_to_sdpa_input_layout(const layout& input_layout, int64_t concat_axis) const {
return get_input_view(input_layout, concat_axis, get_sdpa_in_past_offset(), get_new_in_sdpa_offset());
}
@@ -53,21 +57,27 @@ int64_t stateless_kv_inst::get_swa_sequence_length(int64_t abs_seq_len, int64_t
return abs_seq_len - rolling_gap * rolling_count;
}
+static std::optional<int64_t> read_len_value(const memory::ptr& mem, const kernel_impl_params& impl_param) {
+ const auto layout = mem->get_layout();
+ if (layout.count() == 0)
+ return std::nullopt;
+
+ OPENVINO_ASSERT(layout.count() == 1);
+ cldnn::mem_lock<uint8_t, mem_lock_type::read> mem_lock_guard(mem, impl_param.get_stream());
+ auto tensor = make_tensor(layout, mem_lock_guard.data());
+ return ov::get_tensor_data_as<int64_t>(tensor)[0];
+}
+
std::optional<stateless_kv_runtime_state> stateless_kv_inst::compute_runtime_state(const kernel_impl_params& impl_param,
const stateless_kv& desc) {
const auto mem_dep_it = impl_param.memory_deps.find(2);
if (mem_dep_it == impl_param.memory_deps.end())
return std::nullopt;
- const auto& seq_len_mem = mem_dep_it->second;
- const auto seq_len_layout = seq_len_mem->get_layout();
- if (seq_len_layout.count() == 0)
+ const auto seq_len_opt = read_len_value(mem_dep_it->second, impl_param);
+ if (!seq_len_opt)
return std::nullopt;
-
- OPENVINO_ASSERT(seq_len_layout.count() == 1);
- cldnn::mem_lock<uint8_t, mem_lock_type::read> seq_len_mem_lock(seq_len_mem, impl_param.get_stream());
- auto seq_len_tensor = make_tensor(seq_len_layout, seq_len_mem_lock.data());
- const auto seq_len = ov::get_tensor_data_as<int64_t>(seq_len_tensor)[0];
+ const auto seq_len = *seq_len_opt;
const auto& past_layout = impl_param.get_input_layout(0);
const auto past_shape = past_layout.get_partial_shape();
@@ -83,39 +93,52 @@ std::optional<stateless_kv_runtime_state> stateless_kv_inst::compute_runtime_sta
const auto& current_dim = current_shape[static_cast<size_t>(current_sequence_axis)];
OPENVINO_ASSERT(current_dim.is_static());
+ const int64_t new_token_size = current_dim.get_length();
+ int64_t new_seq_len = new_token_size;
+ if (desc.has_cur_len()) {
+ const auto cur_len_mem_it = impl_param.memory_deps.find(3);
+ OPENVINO_ASSERT(cur_len_mem_it != impl_param.memory_deps.end());
+
+ const auto cur_len_opt = read_len_value(cur_len_mem_it->second, impl_param);
+ OPENVINO_ASSERT(cur_len_opt.has_value());
+ new_seq_len = *cur_len_opt;
+ }
+
int64_t past_seq_len = 0;
int64_t present_seq_len = 0;
if (desc.is_seq_len_present_len) {
present_seq_len = seq_len;
- past_seq_len = present_seq_len - current_dim.get_length();
+ past_seq_len = present_seq_len - new_seq_len;
} else {
past_seq_len = seq_len;
- present_seq_len = past_seq_len + current_dim.get_length();
+ present_seq_len = past_seq_len + new_seq_len;
}
- GPU_DEBUG_TRACE_DETAIL << desc.id << " : " << (desc.is_seq_len_present_len ? "present" : "past") << "_len[" << seq_len << "] cur_len["
- << current_dim.get_length() << "] past_tensor[" << past_dim.get_length() << "] "
+ GPU_DEBUG_TRACE_DETAIL << desc.id << " : " << (desc.is_seq_len_present_len ? "present" : "past") << "_len[" << seq_len << "] new_size[" << new_token_size
+ << "] new_len[" << new_seq_len << "] past_tensor[" << past_dim.get_length() << "] "
<< (present_seq_len <= past_dim.get_length() ? "update" : "concat") << std::endl;
- OPENVINO_ASSERT(past_seq_len >= 0, "[GPU] new_token_data shouldn't exceed present_seq_length");
+ OPENVINO_ASSERT(new_token_size >= new_seq_len && new_seq_len >= 0, "[GPU] new_seq_len shouldn't exceed new_token_data range");
+ OPENVINO_ASSERT(past_seq_len >= 0, "[GPU] cur_seq_length shouldn't exceed present_seq_length");
stateless_kv_runtime_state state;
state.past_seq_len = past_seq_len;
state.present_seq_len = present_seq_len;
- state.new_token_len = current_dim.get_length();
+ state.new_token_size = new_token_size;
+ state.new_seq_len = new_seq_len;
+ state.padded_seq_len = past_seq_len + new_token_size;
if (desc.window_size > 0) {
- OPENVINO_ASSERT(desc.input.size() == 3, "[GPU] stateless_kv doesn't support window_size together with pos_idx");
+ OPENVINO_ASSERT(!desc.has_pos_idx, "[GPU] stateless_kv doesn't support window_size together with pos_idx");
const auto cache_capacity = past_dim.get_length();
state.past_front_idx = past_seq_len - get_swa_sequence_length(past_seq_len, cache_capacity, desc.window_size);
state.present_front_idx = present_seq_len - get_swa_sequence_length(present_seq_len, cache_capacity, desc.window_size);
+ state.padded_front_idx = state.padded_seq_len - get_swa_sequence_length(state.padded_seq_len, cache_capacity, desc.window_size);
state.sdpa_front_idx = std::max<int64_t>(0, past_seq_len - desc.window_size + 1);
}
OPENVINO_ASSERT(state.get_past_output_len() >= 0 && state.get_present_output_len() >= 0);
OPENVINO_ASSERT(state.get_new_in_sdpa_offset() >= 0);
OPENVINO_ASSERT(state.get_sdpa_len(desc.window_size) ==
- (desc.window_size > 0
- ? std::min(state.present_seq_len, state.new_token_len + desc.window_size - 1)
- : state.present_seq_len));
+ (desc.window_size > 0 ? std::min(state.present_seq_len, state.new_seq_len + desc.window_size - 1) : state.present_seq_len));
return state;
}
@@ -132,12 +155,16 @@ void stateless_kv_inst::update_shape_info_tensor(const kernel_impl_params& param
const auto node_input_layouts = get_node().get_shape_info_input_layouts();
for (size_t i = 0; i < get_node().get_dependencies().size(); ++i) {
GPU_DEBUG_TRACE_DETAIL << id() << " : update shape_info for input[" << i << "]" << std::endl;
- if (i == 0 && desc->input.size() == 3) {
+ if (i == 0 && !desc->has_pos_idx) {
OPENVINO_ASSERT(m_runtime_state.has_value(), "[GPU] stateless_kv runtime state wasn't initialized during shape update");
const auto& state = *m_runtime_state;
const auto copy_len = state.is_rolling() ? 0 : state.get_new_in_present_offset();
const auto past_view = get_input_view(params.get_input_layout(0), desc->concat_axis, 0, copy_len);
fill_shape_info_data(past_view, node_input_layouts[i], shape_info_ptr, offset);
+ } else if (i == 1 && !desc->has_pos_idx) {
+ OPENVINO_ASSERT(m_runtime_state.has_value(), "[GPU] stateless_kv runtime state wasn't initialized during shape update");
+ const auto new_view = m_runtime_state->get_new_input_layout(params.get_input_layout(1), desc->concat_axis);
+ fill_shape_info_data(new_view, node_input_layouts[i], shape_info_ptr, offset);
} else {
fill_shape_info_data(params.input_layouts[i], node_input_layouts[i], shape_info_ptr, offset);
}
@@ -145,16 +172,19 @@ void stateless_kv_inst::update_shape_info_tensor(const kernel_impl_params& param
if (desc->window_size > 0) {
OPENVINO_ASSERT(m_runtime_state.has_value(), "[GPU] stateless_kv SWA runtime state wasn't initialized during shape update");
- OPENVINO_ASSERT(desc->input.size() == 3);
- OPENVINO_ASSERT(node_input_layouts.size() == 5);
+ OPENVINO_ASSERT(!desc->has_pos_idx);
+ const auto sdpa_past_idx = desc->input.size();
+ OPENVINO_ASSERT(node_input_layouts.size() == sdpa_past_idx + 2);
const auto& state = *m_runtime_state;
- if (state.is_rolling()) {
+ if (state.is_capacity_overflow()) {
auto past_view = state.get_past_to_sdpa_input_layout(params.get_input_layout(0), desc->concat_axis);
GPU_DEBUG_TRACE_DETAIL << id() << " : update shape_info for SWA sdpa's past input" << std::endl;
- fill_shape_info_data(past_view, node_input_layouts[3], shape_info_ptr, offset);
+ fill_shape_info_data(past_view, node_input_layouts[sdpa_past_idx], shape_info_ptr, offset);
+ }
+ if (state.is_rolling()) {
auto sdpa_view = state.get_sdpa_to_present_input_layout(params.get_output_layout(1), desc->concat_axis);
GPU_DEBUG_TRACE_DETAIL << id() << " : update shape_info for SWA present's sdpa input" << std::endl;
- fill_shape_info_data(sdpa_view, node_input_layouts[4], shape_info_ptr, offset);
+ fill_shape_info_data(sdpa_view, node_input_layouts[sdpa_past_idx + 1], shape_info_ptr, offset);
}
}
@@ -186,14 +216,14 @@ std::vector<layout> stateless_kv_inst::calc_output_layouts(const stateless_kv_no
const auto runtime_state = stateless_kv_inst::compute_runtime_state(impl_param, *desc);
if (runtime_state) {
op.set_update_offset(runtime_state->get_new_in_present_offset());
- op.set_is_rolling(runtime_state->is_rolling());
+ op.set_is_capacity_overflow(runtime_state->is_capacity_overflow());
op.set_past_seq_len(runtime_state->past_seq_len);
}
auto output_shapes = shape_infer(&op, input_shapes);
int64_t lower_padding = 0;
int64_t upper_padding = 0;
- if (runtime_state && !runtime_state->is_rolling() && output_shapes[0][concat_axis].is_static()) {
+ if (runtime_state && !runtime_state->is_capacity_overflow() && output_shapes[0][concat_axis].is_static()) {
lower_padding = runtime_state->get_sdpa_in_present_offset();
upper_padding = output_shapes[0][concat_axis].get_length() - output_shapes[1][concat_axis].get_length() - lower_padding;
OPENVINO_ASSERT(lower_padding >= 0 && upper_padding >= 0);
diff --git a/src/plugins/intel_gpu/src/plugin/ops/stateless_kv.cpp b/src/plugins/intel_gpu/src/plugin/ops/stateless_kv.cpp
index 6db76b9d384..f5f3d52b607 100644
--- a/src/plugins/intel_gpu/src/plugin/ops/stateless_kv.cpp
+++ b/src/plugins/intel_gpu/src/plugin/ops/stateless_kv.cpp
@@ -28,7 +28,8 @@ void CreateStatelessKVOp(ProgramBuilder& p, const std::shared_ptr<ov::op::intern
inputs,
ov::util::normalize(op->get_concat_axis(), rank),
op->get_is_seq_len_present_len(),
- op->get_window_size());
+ op->get_window_size(),
+ op->get_has_pos_idx());
prim.num_outputs = op->get_output_size();
prim.output_data_types = get_output_data_types(op);
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 e64844e9b95..3c446d1e7d3 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
@@ -10,6 +10,7 @@
#include "intel_gpu/op/sdpa.hpp"
#include "intel_gpu/op/stateless_kv.hpp"
+#include "intel_gpu/runtime/debug_configuration.hpp"
#include "openvino/op/add.hpp"
#include "openvino/op/broadcast.hpp"
#include "openvino/op/convert.hpp"
@@ -17,6 +18,7 @@
#include "openvino/op/shape_of.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/maximum.hpp"
+#include "openvino/op/slice.hpp"
#include "openvino/op/squeeze.hpp"
#include "openvino/op/subtract.hpp"
#include "openvino/op/transpose.hpp"
@@ -54,6 +56,7 @@ namespace ov::intel_gpu {
namespace v0 = ov::op::v0;
namespace v1 = ov::op::v1;
+namespace v8 = ov::op::v8;
struct GroupQueryAttentionDecomposition::StatelessKVMetadata : public ov::pass::GroupQueryAttentionDecomposition::KVCacheMetadata {
@@ -127,15 +130,6 @@ ov::Output<ov::Node> GroupQueryAttentionDecomposition::make_qk_norm(const ov::Ou
return register_new_node<ov::op::internal::RMS>(input, weight, epsilon, input.get_element_type());
}
-namespace {
-// StatelessKV has nothing to append to for a 0-row past; a free predicate (vs. an inline shape probe) keeps the
-// fallback condition self-documenting and easy to narrow once StatelessKV can roll a 0-row past with query_seqlens.
-bool has_empty_past(const ov::Output<ov::Node>& past_key) {
- const auto& past_ps = past_key.get_partial_shape();
- return past_ps.rank().is_static() && past_ps[2].is_static() && past_ps[2].get_length() == 0;
-}
-} // namespace
-
GroupQueryAttentionDecomposition::KVCacheOutputs GroupQueryAttentionDecomposition::construct_kvcache(
const std::shared_ptr<ov::op::internal::GroupQueryAttention>& node,
const ov::Output<ov::Node>& past_key,
@@ -143,41 +137,23 @@ GroupQueryAttentionDecomposition::KVCacheOutputs GroupQueryAttentionDecompositio
const ov::Output<ov::Node>& key,
const ov::Output<ov::Node>& value,
const ov::Output<ov::Node>& seqlens_1d,
- [[maybe_unused]] const std::shared_ptr<ov::Node>& kv_seqlen,
+ const std::shared_ptr<ov::Node>& kv_seqlen,
const std::shared_ptr<ov::Node>& past_seqlen,
- [[maybe_unused]] const ov::Output<ov::Node>& current_seqlen_scalar,
+ 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_);
- // StatelessKV rolls a windowed cache by its present length, which a right-padded chunk (query_seqlens) would
- // overstate; the generic staging path writes back only the valid rows.
const bool query_seqlens = node->has_query_seqlens();
- if (query_seqlens && node->get_sliding_window_cache()) {
- // GPU SDPA broadcasts the KV heads natively; the explicit chain groups them itself.
- metadata.should_broadcast_kv = false;
- return ov::pass::GroupQueryAttentionDecomposition::construct_kvcache(node, past_key, past_value, key, value, seqlens_1d, kv_seqlen,
- past_seqlen, current_seqlen_scalar, metadata_);
- }
- // A padded chunk with an empty past has nothing for StatelessKV to append to; keep the generic present sizing.
- // A declared fixed capacity has the same problem when total_sequence_length exceeds it: StatelessKV's own
- // shape inference only grows past a static past_rows when its update offset folds to a constant (it almost
- // never does for a runtime seqlens_k), so it would silently keep producing a past_rows-sized buffer while the
- // op's own shape inference (fixed up for this case) declares max(past_rows, total_sequence_length).
- if (query_seqlens && (has_empty_past(past_key) || node->has_fixed_kv_capacity())) {
- return ov::pass::GroupQueryAttentionDecomposition::construct_kvcache(node, past_key, past_value, key, value, seqlens_1d, kv_seqlen,
- past_seqlen, current_seqlen_scalar, 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;
+ 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.
@@ -186,19 +162,37 @@ GroupQueryAttentionDecomposition::KVCacheOutputs GroupQueryAttentionDecompositio
}
}
+ const auto get_exclusive_to_result = [](const Output<ov::Node>& output) -> const v0::Result* {
+ const auto inputs = output.get_target_inputs();
+ if (inputs.size() != 1) {
+ GPU_DEBUG_TRACE_DETAIL << "GQA's output " << output.get_index() << " connects to " << inputs.size() << " nodes" << std::endl;
+ return nullptr;
+ }
+ ov::Node* const node = inputs.begin()->get_node();
+ if (!ov::is_type<v0::Result>(node)) {
+ GPU_DEBUG_TRACE_DETAIL << "GQA's output " << output.get_index() << " not connects to Result, get: " << node->get_type_name() << ":"
+ << node->get_friendly_name() << std::endl;
+ return nullptr;
+ }
+ return ov::as_type<v0::Result>(node);
+ };
+ const v0::Result* present_key = get_exclusive_to_result(node->output(1));
+ const v0::Result* present_value = get_exclusive_to_result(node->output(2));
+
KVCacheOutputs outputs;
const bool sliding_window = node->get_sliding_window_cache();
const int64_t window_size = sliding_window ? node->get_local_window_size() : 0;
- // StatelessKV takes the present length and writes the S new rows at present - S. A right-padded chunk writes them
- // at its past P = total - Q, so it passes P + S; SDPA's lower-right causal mask then lets row s see keys <= P + s.
- const ov::Output<ov::Node> present_len =
- query_seqlens ? register_new_node<v1::Add>(past_seqlen, current_seqlen_scalar)->output(0) : seqlens_1d;
+ std::optional<ov::Output<ov::Node>> cur_seq_len;
+ if (query_seqlens) {
+ cur_seq_len = node->input_value(static_cast<size_t>(ov::op::internal::GroupQueryAttentionInputs::QUERY_SEQLENS));
+ }
const auto make_stateless_kv = [&](const ov::Output<ov::Node>& past, const ov::Output<ov::Node>& current, int64_t concat_axis) {
- return register_new_node<op::StatelessKV>(past, current, present_len, concat_axis, true, window_size);
+ if (query_seqlens) {
+ return register_new_node<op::StatelessKV>(past, current, seqlens_1d, *cur_seq_len, concat_axis, true, window_size);
+ }
+ return register_new_node<op::StatelessKV>(past, current, seqlens_1d, concat_axis, true, window_size);
};
- const auto key_cache = make_stateless_kv(past_key, key, 2);
-
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());
@@ -222,6 +216,42 @@ GroupQueryAttentionDecomposition::KVCacheOutputs GroupQueryAttentionDecompositio
present_value_transpose = find_value_transpose(target.get_node()->output(target.get_index()));
}
}
+ if (past_value_transpose && present_value_transpose) {
+ OPENVINO_ASSERT(!present_value);
+ GPU_DEBUG_TRACE_DETAIL << "pending transpose_v fusion on " << present_value_transpose->get_friendly_name() << std::endl;
+ present_value = get_exclusive_to_result(present_value_transpose->output(0));
+ }
+
+ if (!present_key || !present_value) {
+ GPU_DEBUG_TRACE_DETAIL << "GQA not having key&value both exclusively connects to Result, key: "
+ << (present_key ? present_key->get_friendly_name() : "null")
+ << " value: " << (present_value ? present_value->get_friendly_name() : "null") << " so fallback to common decompose"
+ << std::endl;
+ auto outputs = ov::pass::GroupQueryAttentionDecomposition::construct_kvcache(node,
+ past_key,
+ past_value,
+ key,
+ value,
+ seqlens_1d,
+ kv_seqlen,
+ past_seqlen,
+ current_seqlen_scalar,
+ metadata_);
+ if (!use_explicit_attention && node->get_causal() && !node->get_sliding_window_cache() && node->has_fixed_kv_capacity()) {
+ // static path put full buffer to SDPA, trim it for causal.
+ const auto slice_start = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{1}, {0}));
+ const auto slice_step = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{1}, {1}));
+ const auto slice_axis = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{1}, {2}));
+ const auto sdpa_end = register_new_node<v1::Add>(past_seqlen, current_seqlen_scalar);
+ outputs.sdpa_key = register_new_node<v8::Slice>(outputs.sdpa_key, slice_start, sdpa_end, slice_step, slice_axis);
+ outputs.sdpa_value = register_new_node<v8::Slice>(outputs.sdpa_value, slice_start, sdpa_end, slice_step, slice_axis);
+ GPU_DEBUG_TRACE_DETAIL << "GQA static path fix: SDPA key/value trimmed" << std::endl;
+ }
+ return outputs;
+ }
+
+ const auto key_cache = make_stateless_kv(past_key, key, 2);
+ key_cache->set_friendly_name(present_key->get_friendly_name() + "_stateless");
std::shared_ptr<op::StatelessKV> value_cache;
if (past_value_transpose && present_value_transpose) {
@@ -235,6 +265,7 @@ GroupQueryAttentionDecomposition::KVCacheOutputs GroupQueryAttentionDecompositio
} else {
value_cache = make_stateless_kv(past_value, value, 2);
}
+ value_cache->set_friendly_name(present_value->get_friendly_name() + "_stateless");
outputs.present_key = key_cache->output(0);
outputs.present_value = value_cache->output(0);
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/op/stateless_kv.cpp b/src/plugins/intel_gpu/src/plugin/transformations/op/stateless_kv.cpp
index a4265c34677..dd8feb999c8 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations/op/stateless_kv.cpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations/op/stateless_kv.cpp
@@ -10,19 +10,35 @@
namespace ov::intel_gpu::op {
-StatelessKV::StatelessKV(const OutputVector& inputs, int64_t concat_axis, bool is_seq_len_present_len, int64_t window_size)
+StatelessKV::StatelessKV(const OutputVector& inputs,
+ int64_t concat_axis,
+ bool is_seq_len_present_len,
+ int64_t window_size,
+ bool has_pos_idx)
: Op(inputs),
m_concat_axis(concat_axis),
m_is_seq_len_present_len(is_seq_len_present_len),
- m_window_size(window_size) {}
+ m_window_size(window_size),
+ m_has_pos_idx(has_pos_idx) {}
+
+StatelessKV::StatelessKV(const Output<Node>& past,
+ const Output<Node>& new_token_data,
+ const Output<Node>& seq_len,
+ int64_t concat_axis,
+ bool is_seq_len_present_len,
+ int64_t window_size)
+ : StatelessKV({past, new_token_data, seq_len}, concat_axis, is_seq_len_present_len, window_size, false) {
+ validate_and_infer_types();
+}
StatelessKV::StatelessKV(const Output<Node>& past,
const Output<Node>& new_token_data,
const Output<Node>& seq_len,
+ const Output<Node>& cur_len,
int64_t concat_axis,
bool is_seq_len_present_len,
int64_t window_size)
- : StatelessKV({past, new_token_data, seq_len}, concat_axis, is_seq_len_present_len, window_size) {
+ : StatelessKV({past, new_token_data, seq_len, cur_len}, concat_axis, is_seq_len_present_len, window_size, false) {
validate_and_infer_types();
}
@@ -32,7 +48,7 @@ StatelessKV::StatelessKV(const Output<Node>& past,
const Output<Node>& pos_idx,
int64_t concat_axis,
bool is_seq_len_present_len)
- : StatelessKV({past, new_token_data, seq_len, pos_idx}, concat_axis, is_seq_len_present_len, 0) {
+ : StatelessKV({past, new_token_data, seq_len, pos_idx}, concat_axis, is_seq_len_present_len, 0, true) {
validate_and_infer_types();
}
@@ -40,6 +56,7 @@ bool StatelessKV::visit_attributes(ov::AttributeVisitor& visitor) {
visitor.on_attribute("concat_axis", m_concat_axis);
visitor.on_attribute("is_seq_len_present_len", m_is_seq_len_present_len);
visitor.on_attribute("window_size", m_window_size);
+ visitor.on_attribute("has_pos_idx", m_has_pos_idx);
return true;
}
@@ -51,7 +68,7 @@ void StatelessKV::validate_and_infer_types() {
const auto& seq_len_dtype = get_input_element_type(2);
OPENVINO_ASSERT(m_window_size >= 0, "[GPU] stateless_kv window_size must be non-negative");
- OPENVINO_ASSERT(m_window_size == 0 || get_input_size() == 3,
+ OPENVINO_ASSERT(m_window_size == 0 || !m_has_pos_idx,
"[GPU] stateless_kv doesn't support window_size together with pos_idx");
OPENVINO_ASSERT(input_shape.rank().is_static() && append_shape.rank().is_static(), "[GPU] stateless_kv requires static input rank");
OPENVINO_ASSERT(input_shape.rank() == append_shape.rank(), "[GPU] stateless_kv requires input and new_token being the same rank");
@@ -75,10 +92,19 @@ void StatelessKV::validate_and_infer_types() {
std::shared_ptr<Node> StatelessKV::clone_with_new_inputs(const ov::OutputVector& new_args) const {
check_new_args_count(this, new_args);
- if (new_args.size() == 3) {
- return std::make_shared<StatelessKV>(new_args.at(0), new_args.at(1), new_args.at(2), m_concat_axis, m_is_seq_len_present_len, m_window_size);
+ if (m_has_pos_idx) {
+ return std::make_shared<StatelessKV>(new_args.at(0), new_args.at(1), new_args.at(2), new_args.at(3), m_concat_axis, m_is_seq_len_present_len);
+ }
+ if (new_args.size() == 4) {
+ return std::make_shared<StatelessKV>(new_args.at(0),
+ new_args.at(1),
+ new_args.at(2),
+ new_args.at(3),
+ m_concat_axis,
+ m_is_seq_len_present_len,
+ m_window_size);
}
- return std::make_shared<StatelessKV>(new_args.at(0), new_args.at(1), new_args.at(2), new_args.at(3), m_concat_axis, m_is_seq_len_present_len);
+ return std::make_shared<StatelessKV>(new_args.at(0), new_args.at(1), new_args.at(2), m_concat_axis, m_is_seq_len_present_len, m_window_size);
}
std::vector<ov::PartialShape> shape_infer(const StatelessKV* op, const std::vector<ov::PartialShape>& input_shapes) {
@@ -95,8 +121,8 @@ std::vector<ov::PartialShape> shape_infer(const StatelessKV* op, const std::vect
OPENVINO_ASSERT(updated_len >= 0, "[GPU] stateless_kv update offset produces a negative output length");
if (op->get_window_size() > 0) {
const auto windowed_len = input_shapes[1][concat_axis].get_length() + op->get_window_size() - 1;
- if (op->get_is_rolling()) {
- OPENVINO_ASSERT(op->get_past_seq_len().has_value(), "[GPU] stateless_kv rolling SWA shape inference requires past_seq_len");
+ if (op->get_is_capacity_overflow()) {
+ OPENVINO_ASSERT(op->get_past_seq_len().has_value(), "[GPU] stateless_kv capacity overflow SWA shape inference requires past_seq_len");
const auto present_len = *op->get_past_seq_len() + input_shapes[1][concat_axis].get_length();
trim_shape[concat_axis] = std::min(windowed_len, present_len);
} else {
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 2f6ea9d8932..62c78279a30 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
@@ -5,23 +5,24 @@
#include "test_utils.h"
#include "intel_gpu/op/stateless_kv.hpp"
+#include "openvino/core/except.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/multiply.hpp"
#include "openvino/op/parameter.hpp"
#include "openvino/runtime/core.hpp"
#include "openvino/runtime/intel_gpu/ocl/ocl.hpp"
#include "openvino/runtime/intel_gpu/properties.hpp"
-
-#include <algorithm>
-#include <numeric>
+#include "stateless_kv_inst.h"
#include <intel_gpu/primitives/eltwise.hpp>
#include <intel_gpu/primitives/input_layout.hpp>
+#include <intel_gpu/primitives/reorder.hpp>
#include <intel_gpu/primitives/reshape.hpp>
#include <intel_gpu/primitives/stateless_kv.hpp>
-#include <intel_gpu/primitives/reorder.hpp>
-#include "stateless_kv_inst.h"
+#include <algorithm>
+#include <numeric>
+#include <optional>
using namespace cldnn;
using namespace ::tests;
@@ -29,6 +30,7 @@ using namespace ::tests;
struct stateless_kv_runtime_params {
int64_t new_token_len;
int64_t seq_len;
+ int64_t cur_seq_len;
bool is_seq_len_present_len;
bool has_pos_idx;
bool use_caching = false;
@@ -36,15 +38,12 @@ struct stateless_kv_runtime_params {
class stateless_kv_runtime : public testing::TestWithParam<stateless_kv_runtime_params> {};
-namespace {
-
-topology make_stateless_kv_topology(const layout& new_token_layout, data_types result_type = data_types::f32, bool indirect_past = false) {
+static 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));
+ 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}));
}
@@ -59,25 +58,66 @@ topology make_stateless_kv_topology(const layout& new_token_layout, data_types r
return topology;
}
-std::vector<float> expected_concatenated_cache(const std::vector<float>& past_values, const std::vector<float>& token_values,
- const ov::Shape& past_shape, size_t output_capacity, size_t logical_past_len) {
+// Rows [0, token_count) hold plane * 1000 + absolute position; the remaining rows are -1.
+static std::vector<float> make_token_values(int64_t batch, int64_t heads, int64_t head_size, int64_t capacity, int64_t first_token_id, int64_t token_count) {
+ std::vector<float> values(static_cast<size_t>(batch * heads * capacity * head_size), -1.0f);
+ for (int64_t plane = 0; plane < batch * heads; ++plane) {
+ for (int64_t row = 0; row < token_count; ++row) {
+ const auto offset = (plane * capacity + row) * head_size;
+ std::fill_n(values.begin() + offset, head_size, static_cast<float>(plane * 1000 + first_token_id + row));
+ }
+ }
+ return values;
+}
+
+// Returns the full [batch, heads, output_capacity, head_size] cache; only the first new_seq_len token rows are appended.
+static std::vector<float> expected_concatenated_cache(const std::vector<float>& past_values,
+ const std::vector<float>& token_values,
+ const ov::Shape& past_shape,
+ size_t output_capacity,
+ size_t logical_past_len,
+ std::optional<size_t> new_seq_len = std::nullopt) {
const size_t planes = past_shape[0] * past_shape[1];
const size_t past_capacity = past_shape[2];
const size_t head_size = past_shape[3];
const size_t token_len = token_values.size() / (planes * head_size);
+ OPENVINO_ASSERT(!new_seq_len.has_value() || *new_seq_len <= token_len, "new_seq_len exceeds token len");
+ const size_t copy_len = new_seq_len.value_or(token_len);
+ OPENVINO_ASSERT(copy_len + logical_past_len <= output_capacity, "appended tokens exceed output capacity");
std::vector<float> expected(planes * output_capacity * head_size);
for (size_t plane = 0; plane < planes; ++plane) {
- std::copy_n(past_values.begin() + plane * past_capacity * head_size,
- past_capacity * head_size,
- expected.begin() + plane * output_capacity * head_size);
+ std::copy_n(past_values.begin() + plane * past_capacity * head_size, past_capacity * head_size, expected.begin() + plane * output_capacity * head_size);
std::copy_n(token_values.begin() + plane * token_len * head_size,
- token_len * head_size,
+ copy_len * head_size,
expected.begin() + (plane * output_capacity + logical_past_len) * head_size);
}
return expected;
}
-} // namespace
+// Copies the first seq_len rows of each [batch, heads] plane of a dense [batch, heads, capacity, head_size] source
+static std::vector<float> copy_partial_seqlen(const float* src, int64_t batch, int64_t heads, int64_t head_size, int64_t capacity, int64_t seq_len) {
+ std::vector<float> values(static_cast<size_t>(batch * heads * seq_len * head_size));
+ auto dst = values.begin();
+ for (int64_t plane = 0; plane < batch * heads; ++plane) {
+ dst = std::copy_n(src + plane * capacity * head_size, seq_len * head_size, dst);
+ }
+ return values;
+}
+
+static std::vector<float> read_token_values(const memory::ptr& output, int64_t batch, int64_t heads, int64_t head_size, int64_t token_count) {
+ const auto& output_layout = output->get_layout();
+ const auto shape = output_layout.get_shape();
+ OPENVINO_ASSERT(shape.size() == 4 && static_cast<int64_t>(shape[0]) == batch && static_cast<int64_t>(shape[1]) == heads &&
+ static_cast<int64_t>(shape[3]) == head_size && static_cast<int64_t>(shape[2]) >= token_count,
+ "output shape does not match the requested batch/heads/head_size/token_count");
+ // A view keeps the buffer's physical seq length as shape + padding; other dims must be unpadded.
+ const auto padded = output_layout.get_padded_dims();
+ OPENVINO_ASSERT(padded[0] == batch && padded[1] == heads && padded[3] == head_size, "only the seq dim may be padded");
+ const auto capacity = padded[2];
+ const auto base_offset = output_layout.get_linear_offset();
+ mem_lock<float, mem_lock_type::read> output_lock(output, get_test_stream());
+ return copy_partial_seqlen(output_lock.data() + base_offset, batch, heads, head_size, capacity, token_count);
+}
TEST_P(stateless_kv_runtime, output_memory_reuse) {
const auto& params = GetParam();
@@ -87,15 +127,24 @@ TEST_P(stateless_kv_runtime, output_memory_reuse) {
constexpr int64_t batch = 1;
constexpr int64_t heads = 2;
constexpr int64_t head_size = 4;
- const auto logical_past_len = params.is_seq_len_present_len ? params.seq_len - params.new_token_len : params.seq_len;
- const auto logical_present_len = params.is_seq_len_present_len ? params.seq_len : params.seq_len + params.new_token_len;
- const auto output_capacity = std::max(past_capacity, logical_present_len);
- const bool reuse_past_buffer = logical_present_len <= past_capacity;
+ const bool has_cur_len = params.cur_seq_len != -1;
+ const auto new_seq_len = has_cur_len ? params.cur_seq_len : params.new_token_len;
+ const auto logical_past_len = params.is_seq_len_present_len ? params.seq_len - new_seq_len : params.seq_len;
+ const auto logical_present_len = params.is_seq_len_present_len ? params.seq_len : params.seq_len + new_seq_len;
+ const auto padded_present_len = logical_past_len + params.new_token_len;
+ const auto output_capacity = std::max(past_capacity, padded_present_len);
+ const bool reuse_past_buffer = padded_present_len <= past_capacity;
const auto past_layout = layout{ov::PartialShape{batch, heads, past_capacity, head_size}, data_types::f32, format::bfyx};
const auto new_token_layout = layout{ov::PartialShape{batch, heads, params.new_token_len, head_size}, data_types::f32, format::bfyx};
const auto seq_len_layout = layout{ov::PartialShape{1}, data_types::i64, format::bfyx};
const auto pos_idx_layout = layout{ov::PartialShape{params.new_token_len}, data_types::i32, format::bfyx};
+ if (has_cur_len) {
+ ASSERT_FALSE(params.has_pos_idx);
+ ASSERT_GT(params.cur_seq_len, 0);
+ ASSERT_LE(params.cur_seq_len, params.new_token_len);
+ }
+
std::vector<input_info> stateless_kv_inputs = {
input_info("past"),
input_info("new_token"),
@@ -104,7 +153,10 @@ TEST_P(stateless_kv_runtime, output_memory_reuse) {
if (params.has_pos_idx) {
stateless_kv_inputs.emplace_back("pos_idx");
}
- auto stateless_kv_prim = stateless_kv("stateless_kv", stateless_kv_inputs, 2, params.is_seq_len_present_len);
+ if (has_cur_len) {
+ stateless_kv_inputs.emplace_back("cur_seq_len");
+ }
+ auto stateless_kv_prim = stateless_kv("stateless_kv", stateless_kv_inputs, 2, params.is_seq_len_present_len, 0, params.has_pos_idx);
stateless_kv_prim.num_outputs = 2;
stateless_kv_prim.output_data_types = {data_types::f32, data_types::f32};
@@ -115,6 +167,9 @@ TEST_P(stateless_kv_runtime, output_memory_reuse) {
if (params.has_pos_idx) {
topology.add(input_layout("pos_idx", pos_idx_layout));
}
+ if (has_cur_len) {
+ topology.add(input_layout("cur_seq_len", seq_len_layout));
+ }
topology.add(stateless_kv_prim);
topology.add(reorder("result", input_info("stateless_kv", 0), format::bfyx, data_types::f32));
@@ -128,14 +183,9 @@ TEST_P(stateless_kv_runtime, output_memory_reuse) {
auto new_token = engine.allocate_memory(new_token_layout);
auto seq_len = engine.allocate_memory(seq_len_layout);
auto pos_idx = engine.allocate_memory(pos_idx_layout);
- std::vector<float> past_values(past_layout.count());
- std::vector<float> new_token_values(new_token_layout.count());
- for (size_t i = 0; i < past_values.size(); ++i) {
- past_values[i] = static_cast<float>(i);
- }
- for (size_t i = 0; i < new_token_values.size(); ++i) {
- new_token_values[i] = static_cast<float>(1000 + i);
- }
+ auto cur_seq_len = engine.allocate_memory(seq_len_layout);
+ const auto past_values = make_token_values(batch, heads, head_size, past_capacity, 0, logical_past_len);
+ const auto new_token_values = make_token_values(batch, heads, head_size, params.new_token_len, logical_past_len, params.new_token_len);
set_values(past, past_values);
set_values(new_token, new_token_values);
set_values<int64_t>(seq_len, {params.seq_len});
@@ -143,7 +193,7 @@ TEST_P(stateless_kv_runtime, output_memory_reuse) {
std::iota(pos_idx_values.begin(), pos_idx_values.end(), static_cast<int32_t>(logical_past_len));
set_values(pos_idx, pos_idx_values);
- const auto expected = expected_concatenated_cache(past_values, new_token_values, past_layout.get_shape(), output_capacity, logical_past_len);
+ const auto expected = expected_concatenated_cache(past_values, new_token_values, past_layout.get_shape(), output_capacity, logical_past_len, new_seq_len);
network.set_input_data("past", past);
network.set_input_data("new_token", new_token);
@@ -151,6 +201,10 @@ TEST_P(stateless_kv_runtime, output_memory_reuse) {
if (params.has_pos_idx) {
network.set_input_data("pos_idx", pos_idx);
}
+ if (has_cur_len) {
+ set_values<int64_t>(cur_seq_len, {params.cur_seq_len});
+ network.set_input_data("cur_seq_len", cur_seq_len);
+ }
network.set_output_memory("result", past);
const auto outputs = network.execute();
@@ -166,88 +220,60 @@ TEST_P(stateless_kv_runtime, output_memory_reuse) {
EXPECT_TRUE(engine.is_the_same_buffer(*output1, *output0));
EXPECT_EQ(engine.is_the_same_buffer(*output0, *past), reuse_past_buffer);
EXPECT_EQ(output0->get_layout().get_partial_shape(), ov::PartialShape({batch, heads, output_capacity, head_size}));
- EXPECT_EQ(output1->get_layout().get_partial_shape(), ov::PartialShape({batch, heads, logical_present_len, head_size}));
+ EXPECT_EQ(output1->get_layout().get_partial_shape(), ov::PartialShape({batch, heads, padded_present_len, head_size}));
ASSERT_NE(output0->get_mem_tracker(), nullptr);
ASSERT_GE(output0->get_mem_tracker()->size(), output0->get_layout().bytes_count());
- mem_lock<float, mem_lock_type::read> output_lock(output0, get_test_stream());
- const std::vector<float> actual(output_lock.begin(), output_lock.begin() + expected.size());
- EXPECT_THAT(actual, testing::ElementsAreArray(expected));
+ const auto expected_present = copy_partial_seqlen(expected.data(), batch, heads, head_size, output_capacity, logical_present_len);
+ EXPECT_THAT(read_token_values(output0, batch, heads, head_size, logical_present_len), testing::ElementsAreArray(expected_present));
}
INSTANTIATE_TEST_SUITE_P(smoke,
stateless_kv_runtime,
- testing::Values(stateless_kv_runtime_params{4, 0, false, false},
- stateless_kv_runtime_params{2, 15, true, false},
- stateless_kv_runtime_params{1, 16, true, false},
- stateless_kv_runtime_params{2, 18, true, false},
- stateless_kv_runtime_params{2, 13, false, false},
- stateless_kv_runtime_params{1, 15, false, false},
- stateless_kv_runtime_params{2, 15, false, false},
- stateless_kv_runtime_params{2, 16, false, false},
- stateless_kv_runtime_params{2, 15, true, true},
- stateless_kv_runtime_params{1, 16, true, true},
- stateless_kv_runtime_params{2, 18, true, true},
- stateless_kv_runtime_params{2, 13, false, true},
- stateless_kv_runtime_params{1, 15, false, true},
- stateless_kv_runtime_params{2, 16, false, true},
- stateless_kv_runtime_params{2, 15, true, false, true},
- stateless_kv_runtime_params{2, 15, false, false, true},
- stateless_kv_runtime_params{2, 15, true, true, true}),
+ testing::Values(stateless_kv_runtime_params{4, 0, -1, false, false},
+ stateless_kv_runtime_params{2, 15, -1, true, false},
+ stateless_kv_runtime_params{1, 16, -1, true, false},
+ stateless_kv_runtime_params{2, 18, -1, true, false},
+ stateless_kv_runtime_params{2, 13, -1, false, false},
+ stateless_kv_runtime_params{1, 15, -1, false, false},
+ stateless_kv_runtime_params{2, 15, -1, false, false},
+ stateless_kv_runtime_params{2, 16, -1, false, false},
+ stateless_kv_runtime_params{2, 15, -1, true, true},
+ stateless_kv_runtime_params{1, 16, -1, true, true},
+ stateless_kv_runtime_params{2, 18, -1, true, true},
+ stateless_kv_runtime_params{2, 13, -1, false, true},
+ stateless_kv_runtime_params{1, 15, -1, false, true},
+ stateless_kv_runtime_params{2, 16, -1, false, true},
+ stateless_kv_runtime_params{2, 15, -1, true, false, true},
+ stateless_kv_runtime_params{2, 15, -1, false, false, true},
+ stateless_kv_runtime_params{2, 15, -1, true, true, true},
+ stateless_kv_runtime_params{4, 13, 1, false, false},
+ stateless_kv_runtime_params{4, 14, 2, true, false},
+ stateless_kv_runtime_params{4, 16, 1, true, false},
+ stateless_kv_runtime_params{4, 15, 4, false, false},
+ stateless_kv_runtime_params{4, 0, 2, false, false},
+ stateless_kv_runtime_params{4, 15, 2, false, false},
+ stateless_kv_runtime_params{4, 17, 3, true, false},
+ stateless_kv_runtime_params{4, 13, 1, false, false, true},
+ stateless_kv_runtime_params{4, 17, 3, true, false, true}),
[](const testing::TestParamInfo<stateless_kv_runtime_params>& info) {
const auto& params = info.param;
return std::string{params.is_seq_len_present_len ? "PresentSeq" : "PastSeq"} + std::to_string(params.seq_len) + "_NewToken" +
- std::to_string(params.new_token_len) + (params.has_pos_idx ? "_Scatter" : "_Concat") +
- (params.use_caching ? "_cached" : "");
+ std::to_string(params.new_token_len) + (params.cur_seq_len != -1 ? "_Cur" + std::to_string(params.cur_seq_len) : "") +
+ (params.has_pos_idx ? "_Scatter" : "_Concat") + (params.use_caching ? "_cached" : "");
});
-namespace swa_helper {
-
-// Rows [0, token_count) hold plane * 1000 + absolute position; the remaining rows are -1.
-static std::vector<float> make_token_values(int64_t batch, int64_t heads, int64_t head_size, int64_t capacity, int64_t first_token_id, int64_t token_count) {
- std::vector<float> values(static_cast<size_t>(batch * heads * capacity * head_size), -1.0f);
- for (int64_t plane = 0; plane < batch * heads; ++plane) {
- for (int64_t row = 0; row < token_count; ++row) {
- const auto offset = (plane * capacity + row) * head_size;
- std::fill_n(values.begin() + offset, head_size, static_cast<float>(plane * 1000 + first_token_id + row));
- }
- }
- return values;
-}
-
-// Reads the first token_count rows of each [batch, heads] plane in make_token_values order.
-static std::vector<float> read_token_values(const memory::ptr& output, int64_t batch, int64_t heads, int64_t head_size, int64_t token_count) {
- const auto& output_layout = output->get_layout();
- const auto pitches = output_layout.get_pitches();
- const auto base_offset = output_layout.get_linear_offset();
- mem_lock<float, mem_lock_type::read> output_lock(output, get_test_stream());
- std::vector<float> values;
- values.reserve(static_cast<size_t>(batch * heads * token_count * head_size));
- for (int64_t b = 0; b < batch; ++b) {
- for (int64_t head = 0; head < heads; ++head) {
- for (int64_t token = 0; token < token_count; ++token) {
- for (int64_t element = 0; element < head_size; ++element) {
- values.push_back(output_lock[base_offset + b * pitches[0] + head * pitches[1] + token * pitches[2] + element * pitches[3]]);
- }
- }
- }
- }
- return values;
-}
-
// Absolute position of the first resident row in a window-sized rolling cache.
-static int64_t get_front_idx(int64_t seq_len, int64_t capacity, int64_t window_size) {
+static int64_t swa_get_front_idx(int64_t seq_len, int64_t capacity, int64_t window_size) {
if (seq_len <= capacity)
return int64_t{0};
const auto rolling_gap = capacity - window_size + 1;
return rolling_gap * (1 + (seq_len - capacity - 1) / rolling_gap);
}
-} // namespace swa_helper
-
struct stateless_kv_swa_runtime_params : stateless_kv_runtime_params {
- stateless_kv_swa_runtime_params(int64_t new_token_len, int64_t past_seq_len, bool reuse_present_buffer, bool use_caching = false)
- : stateless_kv_runtime_params{new_token_len, past_seq_len, false, false, use_caching},
+ stateless_kv_swa_runtime_params(int64_t new_token_len, int64_t past_seq_len, int64_t cur_seq_len, bool reuse_present_buffer, bool use_caching = false)
+ : stateless_kv_runtime_params{new_token_len, past_seq_len, cur_seq_len, false, false, use_caching},
reuse_present_buffer(reuse_present_buffer) {}
bool reuse_present_buffer;
@@ -266,31 +292,48 @@ TEST_P(stateless_kv_swa_runtime, swa_memory) {
constexpr int64_t window_size = 4;
ASSERT_FALSE(params.has_pos_idx);
ASSERT_FALSE(params.is_seq_len_present_len);
+ const bool has_cur_len = params.cur_seq_len != -1;
+ if (has_cur_len) {
+ ASSERT_GT(params.cur_seq_len, 0);
+ ASSERT_LE(params.cur_seq_len, params.new_token_len);
+ }
+ const auto new_token_size = params.new_token_len;
+ const auto new_seq_len = has_cur_len ? params.cur_seq_len : new_token_size;
const auto past_seq_len = params.seq_len;
- const auto present_seq_len = past_seq_len + params.new_token_len;
- const auto past_front_idx = swa_helper::get_front_idx(past_seq_len, past_capacity, window_size);
- const auto present_front_idx = swa_helper::get_front_idx(present_seq_len, past_capacity, window_size);
- const auto is_rolling = present_front_idx > past_front_idx;
+ const auto present_seq_len = past_seq_len + new_seq_len;
+ const auto padded_seq_len = past_seq_len + new_token_size;
+ const auto past_front_idx = swa_get_front_idx(past_seq_len, past_capacity, window_size);
+ const auto present_front_idx = swa_get_front_idx(present_seq_len, past_capacity, window_size);
+ const auto padded_front_idx = swa_get_front_idx(padded_seq_len, past_capacity, window_size);
+ const auto is_capacity_overflow = padded_front_idx > past_front_idx;
const auto past_resident_len = past_seq_len - past_front_idx;
const auto present_resident_len = present_seq_len - present_front_idx;
const auto sdpa_front_idx = std::max<int64_t>(0, past_seq_len - window_size + 1);
const auto sdpa_seq_len = present_seq_len - sdpa_front_idx;
+ const auto sdpa_buffer_seq_len = new_token_size + std::min<int64_t>(window_size - 1, past_seq_len);
const auto past_layout = layout{ov::PartialShape{batch, heads, past_capacity, head_size}, data_types::f32, format::bfyx};
const auto new_token_layout = layout{ov::PartialShape{batch, heads, params.new_token_len, head_size}, data_types::f32, format::bfyx};
const auto seq_len_layout = layout{ov::PartialShape{1}, data_types::i64, format::bfyx};
- auto stateless_kv_prim =
- stateless_kv("stateless_kv", {input_info("past"), input_info("new_token"), input_info("seq_len")}, 2, params.is_seq_len_present_len, window_size);
+ std::vector<input_info> stateless_kv_inputs = {input_info("past"), input_info("new_token"), input_info("seq_len")};
+ if (has_cur_len) {
+ stateless_kv_inputs.emplace_back("cur_seq_len");
+ }
+ auto stateless_kv_prim = stateless_kv("stateless_kv", stateless_kv_inputs, 2, params.is_seq_len_present_len, window_size);
stateless_kv_prim.num_outputs = 2;
stateless_kv_prim.output_data_types = {data_types::f32, data_types::f32};
- topology topology(input_layout("past", layout{ov::PartialShape{batch, heads, -1, head_size}, data_types::f32, format::bfyx}),
- input_layout("new_token", new_token_layout),
- input_layout("seq_len", seq_len_layout),
- stateless_kv_prim,
- reorder("result", input_info("stateless_kv", 0), format::bfyx, data_types::f32));
+ topology topology;
+ topology.add(input_layout("past", layout{ov::PartialShape{batch, heads, -1, head_size}, data_types::f32, format::bfyx}));
+ topology.add(input_layout("new_token", new_token_layout));
+ topology.add(input_layout("seq_len", seq_len_layout));
+ if (has_cur_len) {
+ topology.add(input_layout("cur_seq_len", seq_len_layout));
+ }
+ topology.add(stateless_kv_prim);
+ topology.add(reorder("result", input_info("stateless_kv", 0), format::bfyx, data_types::f32));
ExecutionConfig config = get_test_default_config(engine);
config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
@@ -302,12 +345,17 @@ TEST_P(stateless_kv_swa_runtime, swa_memory) {
auto past = engine.allocate_memory(past_layout);
auto new_token = engine.allocate_memory(new_token_layout);
auto seq_len = engine.allocate_memory(seq_len_layout);
- set_values(past, swa_helper::make_token_values(batch, heads, head_size, past_capacity, past_front_idx, past_resident_len));
- set_values(new_token, swa_helper::make_token_values(batch, heads, head_size, params.new_token_len, past_seq_len, params.new_token_len));
+ auto cur_seq_len = engine.allocate_memory(seq_len_layout);
+ set_values(past, make_token_values(batch, heads, head_size, past_capacity, past_front_idx, past_resident_len));
+ set_values(new_token, make_token_values(batch, heads, head_size, params.new_token_len, past_seq_len, params.new_token_len));
set_values<int64_t>(seq_len, {params.seq_len});
network.set_input_data("past", past);
network.set_input_data("new_token", new_token);
network.set_input_data("seq_len", seq_len);
+ if (has_cur_len) {
+ set_values<int64_t>(cur_seq_len, {params.cur_seq_len});
+ network.set_input_data("cur_seq_len", cur_seq_len);
+ }
network.set_output_memory("result", past);
const auto outputs = network.execute();
@@ -321,39 +369,45 @@ TEST_P(stateless_kv_swa_runtime, swa_memory) {
ASSERT_NE(result, nullptr);
EXPECT_TRUE(engine.is_the_same_buffer(*present, *result));
EXPECT_TRUE(engine.is_the_same_buffer(*present, *past));
- ASSERT_EQ(params.reuse_present_buffer, !is_rolling);
+ ASSERT_EQ(params.reuse_present_buffer, !is_capacity_overflow);
EXPECT_EQ(engine.is_the_same_buffer(*sdpa, *present), params.reuse_present_buffer);
ASSERT_EQ(present->get_layout().get_partial_shape(), ov::PartialShape({batch, heads, past_capacity, head_size}));
- ASSERT_EQ(sdpa->get_layout().get_partial_shape(), ov::PartialShape({batch, heads, sdpa_seq_len, head_size}));
+ ASSERT_EQ(sdpa->get_layout().get_partial_shape(), ov::PartialShape({batch, heads, sdpa_buffer_seq_len, head_size}));
- const auto present_ref = swa_helper::make_token_values(batch, heads, head_size, present_resident_len, present_front_idx, present_resident_len);
- const auto sdpa_ref = swa_helper::make_token_values(batch, heads, head_size, sdpa_seq_len, sdpa_front_idx, sdpa_seq_len);
- EXPECT_THAT(swa_helper::read_token_values(present, batch, heads, head_size, present_resident_len), testing::ElementsAreArray(present_ref));
- EXPECT_THAT(swa_helper::read_token_values(sdpa, batch, heads, head_size, sdpa_seq_len), testing::ElementsAreArray(sdpa_ref));
+ const auto present_ref = make_token_values(batch, heads, head_size, present_resident_len, present_front_idx, present_resident_len);
+ const auto sdpa_ref = make_token_values(batch, heads, head_size, sdpa_seq_len, sdpa_front_idx, sdpa_seq_len);
+ EXPECT_THAT(read_token_values(present, batch, heads, head_size, present_resident_len), testing::ElementsAreArray(present_ref));
+ EXPECT_THAT(read_token_values(sdpa, batch, heads, head_size, sdpa_seq_len), testing::ElementsAreArray(sdpa_ref));
}
INSTANTIATE_TEST_SUITE_P(smoke,
stateless_kv_swa_runtime,
- testing::Values(stateless_kv_swa_runtime_params{1, 0, true}, // empty past, no rolling
- stateless_kv_swa_runtime_params{16, 0, true}, // empty past, fills capacity without rolling
- stateless_kv_swa_runtime_params{17, 0, false}, // empty past, rolls
- stateless_kv_swa_runtime_params{1, 14, true}, // no previous overflow, no rolling
- stateless_kv_swa_runtime_params{1, 16, false}, // no previous overflow, token 0 rolls
- stateless_kv_swa_runtime_params{3, 16, false}, // no previous overflow, token 0 rolls
- stateless_kv_swa_runtime_params{3, 15, false}, // no previous overflow, token 1 rolls
- stateless_kv_swa_runtime_params{13, 15, false}, // rolling with sdpa being same length with capacity
- stateless_kv_swa_runtime_params{1, 17, true}, // previous overflow, no rolling
- stateless_kv_swa_runtime_params{1, 29, false}, // previous overflow, token 0 rolls
- stateless_kv_swa_runtime_params{3, 29, false}, // previous overflow, token 0 rolls
- stateless_kv_swa_runtime_params{3, 28, false}, // previous overflow, token 1 rolls
- stateless_kv_swa_runtime_params{16, 29, false}, // block crosses multiple eviction boundaries
- stateless_kv_swa_runtime_params{1, 0, true, true},
- stateless_kv_swa_runtime_params{1, 14, true, true},
- stateless_kv_swa_runtime_params{3, 16, false, true},
- stateless_kv_swa_runtime_params{16, 29, false, true}),
+ testing::Values(stateless_kv_swa_runtime_params{1, 0, -1, true}, // empty past, no rolling
+ stateless_kv_swa_runtime_params{16, 0, -1, true}, // empty past, fills capacity without rolling
+ stateless_kv_swa_runtime_params{17, 0, -1, false}, // empty past, rolls
+ stateless_kv_swa_runtime_params{1, 14, -1, true}, // no previous overflow, no rolling
+ stateless_kv_swa_runtime_params{1, 16, -1, false}, // no previous overflow, token 0 rolls
+ stateless_kv_swa_runtime_params{3, 16, -1, false}, // no previous overflow, token 0 rolls
+ stateless_kv_swa_runtime_params{3, 15, -1, false}, // no previous overflow, token 1 rolls
+ stateless_kv_swa_runtime_params{13, 15, -1, false}, // rolling with sdpa being same length with capacity
+ stateless_kv_swa_runtime_params{1, 17, -1, true}, // previous overflow, no rolling
+ stateless_kv_swa_runtime_params{1, 29, -1, false}, // previous overflow, token 0 rolls
+ stateless_kv_swa_runtime_params{3, 29, -1, false}, // previous overflow, token 0 rolls
+ stateless_kv_swa_runtime_params{3, 28, -1, false}, // previous overflow, token 1 rolls
+ stateless_kv_swa_runtime_params{16, 29, -1, false}, // block crosses multiple eviction boundaries
+ stateless_kv_swa_runtime_params{1, 0, -1, true, true},
+ stateless_kv_swa_runtime_params{1, 14, -1, true, true},
+ stateless_kv_swa_runtime_params{3, 16, -1, false, true},
+ stateless_kv_swa_runtime_params{16, 29, -1, false, true},
+ stateless_kv_swa_runtime_params{3, 15, 1, false}, // overflow, no rolling
+ stateless_kv_swa_runtime_params{3, 16, 2, false}, // ovrflow and token 1 rolls
+ stateless_kv_swa_runtime_params{16, 0, 1, true}, // empty past, fills capacity without rolling
+ stateless_kv_swa_runtime_params{16, 29, 5, false}, // overflow crosses multiple eviction boundaries, token 5 rolls
+ stateless_kv_swa_runtime_params{3, 15, 1, false, true}),
[](const testing::TestParamInfo<stateless_kv_swa_runtime_params>& info) {
const auto& params = info.param;
return std::string{"Past"} + std::to_string(params.seq_len) + "_NewToken" + std::to_string(params.new_token_len) +
+ (params.cur_seq_len != -1 ? "_Cur" + std::to_string(params.cur_seq_len) : "") +
(params.reuse_present_buffer ? "_ReusePresent" : "_SeparateSDPA") + (params.use_caching ? "_cached" : "");
});
@@ -401,7 +455,7 @@ TEST(stateless_kv_runtime, swa_runtime_state_refresh) {
const auto& state = *instance->get_runtime_state();
EXPECT_EQ(state.past_seq_len, absolute_past_len);
EXPECT_EQ(state.present_seq_len, absolute_past_len + 1);
- EXPECT_EQ(state.new_token_len, 1);
+ EXPECT_EQ(state.new_token_size, 1);
EXPECT_EQ(state.is_rolling(), expected_rolling);
EXPECT_EQ(engine.is_the_same_buffer(*instance->output_memory_ptr(0), *instance->output_memory_ptr(1)), !expected_rolling);
};
@@ -450,8 +504,8 @@ TEST(stateless_kv_runtime, reallocation_across_executions) {
set_values(new_token, new_token_values);
set_values<int64_t>(seq_len, {present_len});
- auto expected = expected_concatenated_cache(current_values, new_token_values, current_past->get_layout().get_shape(),
- output_capacity, logical_past_len);
+ auto expected =
+ expected_concatenated_cache(current_values, new_token_values, current_past->get_layout().get_shape(), output_capacity, logical_past_len);
network.set_input_data("past", current_past);
network.set_input_data("new_token", new_token);
@@ -474,9 +528,7 @@ TEST(stateless_kv_runtime, reallocation_across_executions) {
ASSERT_NE(output0->get_mem_tracker(), nullptr);
ASSERT_GE(output0->get_mem_tracker()->size(), output0->get_layout().bytes_count());
- mem_lock<float, mem_lock_type::read> output_lock(output0, get_test_stream());
- const std::vector<float> actual(output_lock.begin(), output_lock.begin() + expected.size());
- EXPECT_THAT(actual, testing::ElementsAreArray(expected));
+ EXPECT_THAT(read_token_values(output0, batch, heads, head_size, output_capacity), testing::ElementsAreArray(expected));
current_past = output0;
current_values = std::move(expected);
@@ -519,8 +571,8 @@ TEST(stateless_kv_runtime, swa_shape_changes) {
auto run_and_verify = [&](int64_t batch, int64_t capacity, int64_t past_seq_len, bool expect_rolling) {
const auto present_seq_len = past_seq_len + new_token_len;
- const auto past_front_idx = swa_helper::get_front_idx(past_seq_len, capacity, window_size);
- const auto present_front_idx = swa_helper::get_front_idx(present_seq_len, capacity, window_size);
+ const auto past_front_idx = swa_get_front_idx(past_seq_len, capacity, window_size);
+ const auto present_front_idx = swa_get_front_idx(present_seq_len, capacity, window_size);
const auto past_resident_len = past_seq_len - past_front_idx;
const auto present_resident_len = present_seq_len - present_front_idx;
const auto sdpa_front_idx = std::max<int64_t>(0, past_seq_len - window_size + 1);
@@ -531,8 +583,8 @@ TEST(stateless_kv_runtime, swa_shape_changes) {
auto past = engine.allocate_memory(past_layout, allocation_type::usm_host);
auto new_token = engine.allocate_memory(new_token_layout);
- set_values(past, swa_helper::make_token_values(batch, heads, head_size, capacity, past_front_idx, past_resident_len));
- set_values(new_token, swa_helper::make_token_values(batch, heads, head_size, new_token_len, past_seq_len, new_token_len));
+ set_values(past, make_token_values(batch, heads, head_size, capacity, past_front_idx, past_resident_len));
+ set_values(new_token, make_token_values(batch, heads, head_size, new_token_len, past_seq_len, new_token_len));
set_values<int64_t>(past_len, {past_seq_len});
network.set_input_data("past", past);
@@ -557,10 +609,10 @@ TEST(stateless_kv_runtime, swa_shape_changes) {
EXPECT_EQ(result->get_layout().get_partial_shape(), ov::PartialShape({batch, heads, capacity, head_size}));
EXPECT_EQ(sdpa->get_layout().get_partial_shape(), ov::PartialShape({batch, heads, sdpa_seq_len, head_size}));
- const auto present_ref = swa_helper::make_token_values(batch, heads, head_size, present_resident_len, present_front_idx, present_resident_len);
- const auto sdpa_ref = swa_helper::make_token_values(batch, heads, head_size, sdpa_seq_len, sdpa_front_idx, sdpa_seq_len);
- EXPECT_THAT(swa_helper::read_token_values(result, batch, heads, head_size, present_resident_len), testing::ElementsAreArray(present_ref));
- EXPECT_THAT(swa_helper::read_token_values(sdpa, batch, heads, head_size, sdpa_seq_len), testing::ElementsAreArray(sdpa_ref));
+ const auto present_ref = make_token_values(batch, heads, head_size, present_resident_len, present_front_idx, present_resident_len);
+ const auto sdpa_ref = make_token_values(batch, heads, head_size, sdpa_seq_len, sdpa_front_idx, sdpa_seq_len);
+ EXPECT_THAT(read_token_values(result, batch, heads, head_size, present_resident_len), testing::ElementsAreArray(present_ref));
+ EXPECT_THAT(read_token_values(sdpa, batch, heads, head_size, sdpa_seq_len), testing::ElementsAreArray(sdpa_ref));
};
run_and_verify(1, 16, 10, false);
@@ -615,9 +667,7 @@ TEST(stateless_kv_runtime, zero_length_past) {
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));
+ EXPECT_THAT(read_token_values(kv_output, batch, heads, head_size, new_token_len), testing::ElementsAreArray(expected));
}
TEST(stateless_kv_runtime, caller_output_binding_respects_inplace_contract) {
@@ -747,8 +797,7 @@ TEST(stateless_kv_runtime, concat_growth_with_aliased_caller_buffer) {
EXPECT_TRUE(engine.is_the_same_buffer(*result, *caller_buffer));
EXPECT_FALSE(engine.is_the_same_buffer(*kv_output, *caller_buffer));
- mem_lock<float, mem_lock_type::read> actual(caller_buffer, get_test_stream());
- EXPECT_THAT(std::vector<float>(actual.begin(), actual.begin() + expected.size()), testing::ElementsAreArray(expected));
+ EXPECT_THAT(read_token_values(caller_buffer, 1, heads, head_size, present_len), testing::ElementsAreArray(expected));
}
// stateless_kv must not write f32 present into the f16 buffer of a converting Result.
@@ -949,10 +998,9 @@ TEST_P(stateless_kv_caller_host_output, repeated_inference) {
}
}
-INSTANTIATE_TEST_SUITE_P(smoke,
- stateless_kv_caller_host_output,
- testing::Bool(),
- [](const testing::TestParamInfo<bool>& info) { return info.param ? "RemotePast" : "CallerHostPast"; });
+INSTANTIATE_TEST_SUITE_P(smoke, stateless_kv_caller_host_output, testing::Bool(), [](const testing::TestParamInfo<bool>& info) {
+ return info.param ? "RemotePast" : "CallerHostPast";
+});
// Another reader of past must still see the original past, whether or not present is bound over it.
TEST(stateless_kv_runtime, infer_request_aliased_past_with_another_reader) {
diff --git a/src/plugins/intel_gpu/tests/unit/shape_infer/stateless_kv_si_test.cpp b/src/plugins/intel_gpu/tests/unit/shape_infer/stateless_kv_si_test.cpp
index 86e1f41bdd2..8f517269552 100644
--- a/src/plugins/intel_gpu/tests/unit/shape_infer/stateless_kv_si_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/shape_infer/stateless_kv_si_test.cpp
@@ -27,6 +27,7 @@ struct stateless_kv_test_params {
std::vector<layout> expected_layouts;
int64_t window_size = 0;
int64_t seq_len = -1;
+ bool has_pos_idx = false;
};
class stateless_kv_test : public testing::TestWithParam<stateless_kv_test_params> {};
@@ -46,8 +47,7 @@ TEST_P(stateless_kv_test, shape_infer) {
}
const auto concat_axis = ov::util::normalize(p.concat_axis, p.input_layouts[0].get_rank());
- auto stateless_kv_prim =
- std::make_shared<stateless_kv>("output", input_prim_ids, concat_axis, p.is_seq_len_present_len, p.window_size);
+ auto stateless_kv_prim = std::make_shared<stateless_kv>("output", input_prim_ids, concat_axis, p.is_seq_len_present_len, p.window_size, p.has_pos_idx);
stateless_kv_prim->num_outputs = 2;
stateless_kv_prim->output_data_types = {p.input_layouts[0].data_type, p.input_layouts[0].data_type};
auto& stateless_kv_node = prog.get_or_create(stateless_kv_prim);
@@ -98,6 +98,9 @@ INSTANTIATE_TEST_SUITE_P(
layout{ov::PartialShape{-1, 2, -1, 4}, data_types::f32, format::bfyx},
layout{ov::PartialShape{-1, 2, -1, 4}, data_types::f32, format::bfyx, padding{{}, {}, padding::DynamicDimsMask{"0100"}}},
},
+ 0,
+ -1,
+ true,
},
{
{
@@ -125,6 +128,9 @@ INSTANTIATE_TEST_SUITE_P(
layout{ov::PartialShape{-1, 2, -1, 4}, data_types::f32, format::bfyx},
layout{ov::PartialShape{-1, 2, -1, 4}, data_types::f32, format::bfyx, padding{{}, {}, padding::DynamicDimsMask{"0100"}}},
},
+ 0,
+ -1,
+ true,
},
{
{
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 a6e27dbee29..c5eb1720604 100644
--- a/src/plugins/intel_gpu/tests/unit/transformations/group_query_attention_decomposition_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/transformations/group_query_attention_decomposition_test.cpp
@@ -7,6 +7,7 @@
#include <gmock/gmock.h>
#include <gtest/gtest.h>
+#include <algorithm>
#include <optional>
#include <set>
#include <vector>
@@ -20,7 +21,9 @@
#include "openvino/op/group_query_attention.hpp"
#include "openvino/op/matmul.hpp"
#include "openvino/op/parameter.hpp"
+#include "openvino/op/reshape.hpp"
#include "openvino/op/result.hpp"
+#include "openvino/op/slice.hpp"
#include "openvino/op/transpose.hpp"
#include "openvino/pass/manager.hpp"
@@ -61,9 +64,10 @@ struct GQAConfig {
ov::PartialShape key_scale_shape{1};
ov::PartialShape value_scale_shape{1};
// Right-padded query chunk (ONNX query_seqlens, input 16): when set, query/key/value get sequence_length
- // rows (S > 1) and a query_seqlens Parameter is wired in, exercising the StatelessKV P+S present-length path.
+ // rows (S > 1) and a query_seqlens Parameter is wired in, exercising the StatelessKV cur_len path.
bool query_seqlens = false;
int64_t sequence_length = 1;
+ bool present_key_slice = false; // routes present key through a Slice before its Result
};
std::shared_ptr<ov::Model> make_gqa_model(const GQAConfig& cfg) {
@@ -151,6 +155,13 @@ std::shared_ptr<ov::Model> make_gqa_model(const GQAConfig& cfg) {
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);
}
+ if (cfg.present_key_slice && output_idx == 1) {
+ const auto starts = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0});
+ const auto stops = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
+ const auto steps = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
+ const auto axes = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {2});
+ output = std::make_shared<ov::op::v8::Slice>(output, starts, stops, steps, axes);
+ }
results.push_back(std::make_shared<ov::op::v0::Result>(output));
}
return std::make_shared<ov::Model>(results, parameters);
@@ -269,6 +280,15 @@ void expect_stateless_kv_cache_connections(const GQAConfig& cfg) {
EXPECT_EQ(value->output(0).get_element_type(), expected_cache_type);
EXPECT_EQ(value->output(1).get_element_type(), expected_cache_type);
+ // qk reads the full present (output 0, shaped like the cache input); SDPA reads the trimmed view (output 1).
+ if (need_qk_output) {
+ EXPECT_EQ(key->output(0).get_partial_shape().is_static(), parameters[3]->get_partial_shape().is_static());
+ EXPECT_EQ(value->output(0).get_partial_shape().is_static(), parameters[4]->get_partial_shape().is_static());
+ } else {
+ EXPECT_TRUE(key->output(1).get_partial_shape().is_dynamic());
+ EXPECT_TRUE(value->output(1).get_partial_shape().is_dynamic());
+ }
+
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);
@@ -334,6 +354,69 @@ void expect_stateless_kv_cache_connections(const GQAConfig& cfg) {
}
}
+std::shared_ptr<ov::Model> expect_no_stateless_kv(const GQAConfig& cfg) {
+ const auto model = decompose_gqa_model(cfg);
+ const bool need_qk_output = cfg.qk_output != QKOutput::NONE;
+ const bool use_explicit_attention = cfg.softcap > 0.0f || need_qk_output;
+ const bool sdpa_kv_dynamic = !cfg.static_past_cache || (cfg.causal && !cfg.sliding_window_cache && !use_explicit_attention);
+
+ std::shared_ptr<ov::intel_gpu::op::SDPA> sdpa;
+ for (const auto& node : model->get_ordered_ops()) {
+ EXPECT_FALSE(ov::is_type<ov::intel_gpu::op::StatelessKV>(node)) << "StatelessKV must not appear for this config";
+ if (auto current_sdpa = ov::as_type_ptr<ov::intel_gpu::op::SDPA>(node)) {
+ EXPECT_EQ(sdpa, nullptr);
+ sdpa = current_sdpa;
+ }
+ }
+
+ if (use_explicit_attention) {
+ // Explicit attention replaces SDPA, so no SDPA op may remain.
+ EXPECT_EQ(sdpa, nullptr);
+ if (need_qk_output) {
+ EXPECT_EQ(model->get_output_size(), 4u);
+ }
+ } else {
+ EXPECT_NE(sdpa, nullptr);
+ if (sdpa) {
+ expect_sdpa_kv_not_broadcast(sdpa);
+ if (sdpa->get_causal()) {
+ EXPECT_EQ(sdpa->get_input_size(), 3u) << "causal SDPA must not carry an explicit mask";
+ } else {
+ EXPECT_GT(sdpa->get_input_size(), 3u) << "non-causal SDPA must carry an explicit mask";
+ if (sdpa_kv_dynamic) {
+ EXPECT_TRUE(sdpa->input_value(3).get_partial_shape().is_dynamic()) << "explicit mask must follow the dynamic K/V length";
+ }
+ }
+ for (size_t input_index = 1; input_index <= 2; ++input_index) {
+ const auto& kv_shape = sdpa->input_value(input_index).get_partial_shape();
+ EXPECT_EQ(kv_shape[2].is_dynamic(), sdpa_kv_dynamic) << "SDPA input " << input_index << " seqlen dim dynamic mismatch";
+ }
+ }
+ }
+
+ if (cfg.transpose_v) {
+ 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());
+ EXPECT_NE(output_transpose, nullptr);
+ if (output_transpose) {
+ const auto output_transpose_order = ov::as_type_ptr<ov::op::v0::Constant>(output_transpose->input_value(1).get_node_shared_ptr());
+ EXPECT_NE(output_transpose_order, nullptr);
+ if (output_transpose_order) {
+ EXPECT_THAT(output_transpose_order->cast_vector<int64_t>(), ::testing::ElementsAre(0, 1, 3, 2));
+ }
+ }
+ }
+
+ if (cfg.sliding_window_cache && sdpa) {
+ EXPECT_EQ(sdpa->get_input_size(), 3u);
+ EXPECT_TRUE(sdpa->get_causal());
+ EXPECT_EQ(sdpa->get_causal_mask_alignment(), ov::intel_gpu::op::SDPA::CausalMaskAlignment::LOWER_RIGHT);
+ EXPECT_EQ(sdpa->get_sliding_window_size(), cfg.local_window_size);
+ }
+
+ return model;
+}
+
TEST(GQADecompositionTest, static_input_uses_stateless_kv) {
GQAConfig cfg;
cfg.static_past_cache = true;
@@ -343,7 +426,6 @@ TEST(GQADecompositionTest, static_input_uses_stateless_kv) {
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);
@@ -356,18 +438,13 @@ TEST(GQADecompositionTest, dynamic_input_uses_stateless_kv) {
expect_stateless_kv_cache_connections(cfg);
}
-// Right-padded query chunk (query_seqlens, S=4 > Q): a static single batch stays on StatelessKV's P + S
-// present-length path (construct_kvcache), not the generic windowed/dynamic-batch fallback. Guards against the
-// present length silently reverting to plain seqlens_1d and losing the padded-tail offset.
TEST(GQADecompositionTest, padded_query_uses_stateless_kv_present_length) {
GQAConfig cfg;
- // A declared fixed (static) capacity instead falls back to the generic writer (see
- // padded_query_fixed_capacity_falls_back_to_generic_cache below) -- keep the past dynamic here so this
- // config stays on the path it is meant to exercise.
cfg.query_seqlens = true;
cfg.sequence_length = 4;
const auto model = decompose_gqa_model(cfg);
+ const auto parameters = model->get_parameters();
std::shared_ptr<ov::intel_gpu::op::SDPA> sdpa;
std::vector<std::shared_ptr<ov::intel_gpu::op::StatelessKV>> statelesskvs;
@@ -385,20 +462,16 @@ TEST(GQADecompositionTest, padded_query_uses_stateless_kv_present_length) {
ASSERT_EQ(statelesskvs.size(), 2u);
for (const auto& stateless_kv : statelesskvs) {
- // present_len (input 2) must be P + S (an Add), not the plain total seqlens_1d a non-padded chunk uses;
- // StatelessKV would otherwise roll the cache by the full chunk length and drop the padded-tail offset.
- EXPECT_TRUE(ov::is_type<ov::op::v1::Add>(stateless_kv->input_value(2).get_node()))
- << "StatelessKV present length is not P + S for a right-padded query chunk";
+ ASSERT_EQ(stateless_kv->get_input_size(), 4u);
+ // Input 2 is the total seqlens (present length); input 3 is query_seqlens as cur_len.
+ EXPECT_TRUE(ov::is_type<ov::op::v1::Reshape>(stateless_kv->input_value(2).get_node()))
+ << "StatelessKV present length is not the total seqlens_1d";
+ EXPECT_EQ(stateless_kv->input_value(3).get_node_shared_ptr(), parameters.back())
+ << "StatelessKV cur_len is not query_seqlens";
}
}
-// A declared fixed (static) capacity falls back to the generic (non-StatelessKV) cache writer instead: the
-// capacity can need growing past its static size (ORT's max(past_rows, total_sequence_length)), which
-// StatelessKV's own shape inference does not do for a runtime present length. The generic writer's present
-// buffer can then hold capacity slack beyond the true past + current total, so this must also take an
-// explicit (mask-based) SDPA rather than the native is_causal + LOWER_RIGHT alignment, which assumes the
-// query sits at the buffer's tail -- untrue once there is capacity slack.
-TEST(GQADecompositionTest, padded_query_fixed_capacity_falls_back_to_generic_cache) {
+TEST(GQADecompositionTest, padded_query_fixed_capacity_uses_stateless_kv_present_length) {
GQAConfig cfg;
cfg.static_past_cache = true;
cfg.query_seqlens = true;
@@ -416,10 +489,53 @@ TEST(GQADecompositionTest, padded_query_fixed_capacity_falls_back_to_generic_cac
++statelesskv_count;
}
}
- EXPECT_EQ(statelesskv_count, 0u) << "a fixed-capacity padded chunk must not use StatelessKV's present-length path";
+ EXPECT_EQ(statelesskv_count, 2u);
ASSERT_NE(sdpa, nullptr);
- EXPECT_FALSE(sdpa->get_causal()) << "a fixed-capacity padded chunk must take an explicit mask, not the native LOWER_RIGHT alignment";
+ EXPECT_TRUE(sdpa->get_causal());
+ EXPECT_EQ(sdpa->get_causal_mask_alignment(), ov::intel_gpu::op::SDPA::CausalMaskAlignment::LOWER_RIGHT);
+}
+
+TEST(GQADecompositionTest, indirect_present_skips_stateless_kv) {
+ GQAConfig cfg;
+ cfg.present_key_slice = true;
+
+ const auto model = expect_no_stateless_kv(cfg);
+
+ const auto present_key_source = model->output(1).get_node()->input_value(0);
+ ASSERT_TRUE(ov::is_type<ov::op::v8::Slice>(present_key_source.get_node()));
+}
+
+TEST(GQADecompositionTest, static_indirect_present_skips_stateless_kv) {
+ GQAConfig cfg;
+ cfg.static_past_cache = true;
+ cfg.present_key_slice = true;
+
+ expect_no_stateless_kv(cfg);
+}
+
+// An explicit scale disables mask elision, so SDPA keeps the causal mask; present_key_slice avoids StatelessKV.
+TEST(GQADecompositionTest, explicit_scale_mask_has_dynamic_shapes) {
+ GQAConfig cfg;
+ cfg.present_key_slice = true;
+ cfg.scale = 0.125f;
+
+ expect_no_stateless_kv(cfg);
+}
+
+TEST(GQADecompositionTest, static_causal_sdpa_kv_is_trimmed) {
+ GQAConfig cfg;
+ cfg.static_past_cache = true;
+ cfg.present_key_slice = true; // forces the common-decompose fallback
+ expect_no_stateless_kv(cfg);
+}
+
+TEST(GQADecompositionTest, static_non_causal_sdpa_kv_keeps_static_shape) {
+ GQAConfig cfg;
+ cfg.static_past_cache = true;
+ cfg.causal = false;
+ cfg.present_key_slice = true; // forces the common-decompose fallback
+ expect_no_stateless_kv(cfg);
}
TEST(GQADecompositionTest, transpose_v_fused) {
@@ -430,49 +546,24 @@ TEST(GQADecompositionTest, transpose_v_fused) {
expect_stateless_kv_cache_connections(cfg);
}
-TEST(GQADecompositionTest, transpose_v_not_fused) {
+TEST(GQADecompositionTest, transpose_v_skips_stateless_kv) {
GQAConfig cfg;
cfg.transpose_v = true;
cfg.should_fuse_transpose_v = false;
- expect_stateless_kv_cache_connections(cfg);
+ expect_no_stateless_kv(cfg);
}
-TEST(GQADecompositionTest, softcap_transpose_v_not_fused) {
+TEST(GQADecompositionTest, softcap_transpose_v_skips_stateless_kv) {
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));
+ expect_no_stateless_kv(cfg);
}
-TEST(GQADecompositionTest, int4_per_tensor_kv_with_transpose_v_is_not_fused) {
+TEST(GQADecompositionTest, int4_per_tensor_kv_with_transpose_v_skips_stateless_kv) {
GQAConfig cfg;
cfg.kv_cache_bit_width = 4;
cfg.kv_quant = QuantType::PER_TENSOR;
@@ -480,38 +571,22 @@ TEST(GQADecompositionTest, int4_per_tensor_kv_with_transpose_v_is_not_fused) {
cfg.transpose_v = true;
cfg.should_fuse_transpose_v = true;
- const auto model = decompose_gqa_model(cfg);
+ const auto model = expect_no_stateless_kv(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) {