OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[PT FE] Convert enable_gqa SDPA to rank-4 SDPA with repeated key/value heads (#39415)
Clémence Lesné9e84a9995937
diff --git a/src/frontends/pytorch/src/op/scaled_dot_product_attention.cpp b/src/frontends/pytorch/src/op/scaled_dot_product_attention.cppindex 55f766f6aa1..ef8d1f22345 100644--- a/src/frontends/pytorch/src/op/scaled_dot_product_attention.cpp+++ b/src/frontends/pytorch/src/op/scaled_dot_product_attention.cpp@@ -4,21 +4,18 @@#include "openvino/op/scaled_dot_product_attention.hpp"+#include <limits>+#include "openvino/frontend/pytorch/node_context.hpp"-#include "openvino/op/add.hpp"+#include "openvino/op/broadcast.hpp"#include "openvino/op/concat.hpp"#include "openvino/op/constant.hpp"-#include "openvino/op/convert.hpp"#include "openvino/op/convert_like.hpp"#include "openvino/op/divide.hpp"-#include "openvino/op/multiply.hpp"#include "openvino/op/reshape.hpp"-#include "openvino/op/scaled_dot_product_attention.hpp"#include "openvino/op/shape_of.hpp"-#include "openvino/op/strided_slice.hpp"-#include "openvino/op/subtract.hpp"+#include "openvino/op/slice.hpp"#include "openvino/op/unsqueeze.hpp"-#include "openvino/op/util/framework_node.hpp"#include "utils.hpp"namespace ov::frontend::pytorch::op {@@ -49,111 +46,96 @@ ov::OutputVector prepare_inputs_to_sdpa(const NodeContext& context,return inputs;}-// Extracts a dimension using a negative index, -1 means last dimension, etc.-ov::Output<ov::Node> get_dim_for_negative_idx(const NodeContext& context,- const ov::Output<ov::Node>& input_shape,- int64_t idx) {- OPENVINO_ASSERT(idx < 0, "This get_dim only supports negative indexing from the end.");-- // Get shape of shape (i.e., rank of input)- auto input_rank = context.mark_node(std::make_shared<ov::op::v3::ShapeOf>(input_shape, element::i64));- auto scalar_shape = ov::op::v0::Constant::create(element::i64, Shape{0}, {});- auto scalar_rank = context.mark_node(std::make_shared<ov::op::v1::Reshape>(input_rank, scalar_shape, false));-- // Compute positive index: rank + idx (since idx is negative)- auto idx_const = ov::op::v0::Constant::create(element::i64, Shape{}, {idx});- auto positive_index = context.mark_node(std::make_shared<ov::op::v1::Add>(scalar_rank, idx_const));-- // Slice shape[positive_index : positive_index + 1]- auto begin = context.mark_node(- std::make_shared<ov::op::v1::Reshape>(positive_index,- ov::op::v0::Constant::create(element::i64, Shape{1}, {1}),- false));- auto one_const = ov::op::v0::Constant::create(element::i64, Shape{1}, {1});- auto end = context.mark_node(std::make_shared<ov::op::v1::Add>(begin, one_const));-- auto stride = ov::op::v0::Constant::create(element::i64, Shape{1}, {1});- auto res_dim = context.mark_node(std::make_shared<ov::op::v1::StridedSlice>(input_shape,- begin,- end,- stride,- std::vector<int64_t>{0},- std::vector<int64_t>{0},- std::vector<int64_t>{0},- std::vector<int64_t>{0}));- return res_dim;+// Number of heads (axis -3) of an SDPA input [B..., H, L, E], dynamic when unknown at conversion time.+Dimension get_num_heads(const Output<Node>& input) {+ const auto& shape = input.get_partial_shape();+ return shape.rank().is_static() ? shape[-3] : Dimension::dynamic();}-// Returns sub-shape[0 : rank - delta]-ov::Output<ov::Node> get_prefix_shape_until_rank_minus_delta(const NodeContext& context,- const Output<Node>& input_shape,- int64_t delta) {- auto input_rank = context.mark_node(std::make_shared<v3::ShapeOf>(input_shape, element::i64));-- // end = rank - delta- auto const_delta = v0::Constant::create(element::i64, Shape{}, {delta});- auto end_index = context.mark_node(std::make_shared<v1::Subtract>(input_rank, const_delta));-- // Slice shape[0:end_index]- auto begin = v0::Constant::create(element::i64, Shape{1}, {0});- auto stride = v0::Constant::create(element::i64, Shape{1}, {1});-- return context.mark_node(std::make_shared<v1::StridedSlice>(input_shape,- begin,- end_index,- stride,- std::vector<int64_t>{0}, // begin_mask- std::vector<int64_t>{0}, // end_mask- std::vector<int64_t>{0}, // new_axis_mask- std::vector<int64_t>{0} // shrink_axis_mask- ));+// Elements [begin, end) of a 1-D shape tensor; negative bounds count from the end.+Output<Node> slice_dims(const NodeContext& context, const Output<Node>& shape, int64_t begin, int64_t end) {+ auto begin_const = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {begin}));+ auto end_const = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {end}));+ auto step = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {1}));+ return context.mark_node(std::make_shared<v8::Slice>(shape, begin_const, end_const, step));}+// Repeats the heads of key or value to match the query, like torch repeat_interleave(Hq / Hkv, dim=-3):+// [B..., Hkv, S, E] -> Unsqueeze -> [B..., Hkv, 1, S, E] -> Broadcast -> [B..., Hkv, G, S, E]+// -> Reshape -> [B..., Hq, S, E]+// This is the graph that aten::expand produces for transformers' repeat_kv, which the KV-cache fusions match+// (ov::op::util::match_multi_query_bcst, GPU ExpandBroadcastReshapeSDPAFusion, SDPAToPagedAttention). The broadcast+// target is a Concat of kv's own dims whose second-to-last input is S, as NPUW's find_kv_cache_concat expects. A+// single ShapeOf of kv feeds every shape computation: CPU StatefulSDPAFusion accepts one ShapeOf consumer on the+// KV-cache Concat.+Output<Node> repeat_kv_heads(const NodeContext& context, const Output<Node>& kv, const Output<Node>& query) {+ const auto num_q_heads = get_num_heads(query);+ const auto num_kv_heads = get_num_heads(kv);+ const bool static_heads = num_q_heads.is_static() && num_kv_heads.is_static();+ if (static_heads) {+ PYTORCH_OP_CONVERSION_CHECK(+ num_kv_heads.get_length() > 0 && num_q_heads.get_length() % num_kv_heads.get_length() == 0,+ "Number of heads in key and value must divide the number of heads in query, got ",+ num_kv_heads,+ " and ",+ num_q_heads);+ if (num_q_heads == num_kv_heads) {+ // An all-ones Broadcast would be removed by EliminateNopBroadcast, leaving Unsqueeze -> Reshape,+ // which the KV-cache fusions don't match. SDPA takes the input as is.+ return kv;+ }+ }++ auto kv_shape = context.mark_node(std::make_shared<v3::ShapeOf>(kv, element::i64));+ Output<Node> q_heads, group;+ if (static_heads) {+ q_heads = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {num_q_heads.get_length()}));+ group = context.mark_node(+ v0::Constant::create(element::i64, Shape{1}, {num_q_heads.get_length() / num_kv_heads.get_length()}));+ } else {+ auto q_shape = context.mark_node(std::make_shared<v3::ShapeOf>(query, element::i64));+ q_heads = slice_dims(context, q_shape, -3, -2);+ group = context.mark_node(std::make_shared<v1::Divide>(q_heads, slice_dims(context, kv_shape, -3, -2)));+ }+ auto seq_len = slice_dims(context, kv_shape, -2, -1);+ auto head_size = slice_dims(context, kv_shape, -1, std::numeric_limits<int64_t>::max());+ auto target_shape = context.mark_node(+ std::make_shared<v0::Concat>(OutputVector{slice_dims(context, kv_shape, 0, -2), group, seq_len, head_size}, 0));+ auto output_shape = context.mark_node(+ std::make_shared<v0::Concat>(OutputVector{slice_dims(context, kv_shape, 0, -3), q_heads, seq_len, head_size},+ 0));+ auto axis = context.mark_node(v0::Constant::create(element::i64, Shape{1}, {-3}));+ auto unsqueezed = context.mark_node(std::make_shared<v0::Unsqueeze>(kv, axis));+ auto broadcasted =+ context.mark_node(std::make_shared<v3::Broadcast>(unsqueezed, target_shape, BroadcastType::BIDIRECTIONAL));+ return context.mark_node(std::make_shared<v1::Reshape>(broadcasted, output_shape, false));+}++// enable_gqa: query [B..., Hq, L, E], key [B..., Hk, S, E], value [B..., Hv, S, Ev], with Hk and Hv dividing Hq+// (they may differ). Key and value heads are repeated to Hq separately, then a regular SDPA of the input rank is+// created, so the KV-cache fusions see the same graph as for transformers' repeat_kv.std::shared_ptr<Node> decompose_gqa(const NodeContext& context,- const Output<Node>& query, // [B,..., Hq, L, D]- const Output<Node>& key, // [B,..., Hk, S, D]- const Output<Node>& value, // [B,..., Hk, S, Dv]+ const Output<Node>& query,+ const Output<Node>& key,+ const Output<Node>& value,const Output<Node>& scale, // optionalconst Output<Node>& attn_mask, // optionalbool is_causal) {- auto q_shape = context.mark_node(std::make_shared<v3::ShapeOf>(query, element::i64));- auto v_shape = context.mark_node(std::make_shared<v3::ShapeOf>(value, element::i64));-- auto Hq = get_dim_for_negative_idx(context, q_shape, -3);- auto L = get_dim_for_negative_idx(context, q_shape, -2);- auto D = get_dim_for_negative_idx(context, q_shape, -1);- auto Dv = get_dim_for_negative_idx(context, v_shape, -1);- auto Hk = get_dim_for_negative_idx(context, v_shape, -3);-- // Extract prefix shape for query [B, ...]. it excludes [Hq, L, D]- auto prefix_shape = get_prefix_shape_until_rank_minus_delta(context, q_shape, 3);-- // Compute group_size = Hq / Hk- auto group_size = context.mark_node(std::make_shared<v1::Divide>(Hq, Hk));-- // Reshape query: [B,..., Hq, T, D] -> [B,..., Hk, group_size, T, D]- auto reshape_q_shape =- context.mark_node(std::make_shared<v0::Concat>(OutputVector{prefix_shape, Hk, group_size, L, D}, 0));- auto q_reshaped = context.mark_node(std::make_shared<v1::Reshape>(query, reshape_q_shape, true));-- // Unsqueeze key, value: [B,..., Hk, T, D] -> [B,..., Hk, 1, T, D]- auto axis = v0::Constant::create(element::i64, Shape{1}, {-3});- auto k_unsqueezed = context.mark_node(std::make_shared<v0::Unsqueeze>(key, axis));- auto v_unsqueezed = context.mark_node(std::make_shared<v0::Unsqueeze>(value, axis));-- ov::Output<ov::Node> unsqueezed_attn_mask = attn_mask;- if (attn_mask.get_node() && attn_mask.get_partial_shape().rank().is_static() &&- attn_mask.get_partial_shape().rank().get_length() > 2) {- // need to adjust shape as well since auxiliary dimension for group is introduced- unsqueezed_attn_mask = context.mark_node(std::make_shared<v0::Unsqueeze>(attn_mask, axis));+ for (const auto& input : {query, key, value}) {+ const auto& rank = input.get_partial_shape().rank();+ PYTORCH_OP_CONVERSION_CHECK(rank.is_dynamic() || rank.get_length() >= 3,+ "scaled_dot_product_attention with enable_gqa=True expects inputs of rank 3 or "+ "higher, got rank ",+ rank);}-- auto inputs = prepare_inputs_to_sdpa(context, q_reshaped, k_unsqueezed, v_unsqueezed, scale, unsqueezed_attn_mask);- auto attn = context.mark_node(std::make_shared<v13::ScaledDotProductAttention>(inputs, is_causal));-- // Reshape back: [B,..., Hk, group_size, T, Dv] -> [B,..., Hq, T, Dv]- auto reshape_out_shape = context.mark_node(std::make_shared<v0::Concat>(OutputVector{prefix_shape, Hq, L, Dv}, 0));- return context.mark_node(std::make_shared<v1::Reshape>(attn, reshape_out_shape, true));+ // The mask is broadcastable to [B..., Hq, L, S] and is applied as is.+ auto inputs = prepare_inputs_to_sdpa(context,+ query,+ repeat_kv_heads(context, key, query),+ repeat_kv_heads(context, value, query),+ scale,+ attn_mask);+ return context.mark_node(std::make_shared<v13::ScaledDotProductAttention>(inputs, is_causal));}} // namespacediff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/stateful_sdpa_fusion.cpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/stateful_sdpa_fusion.cppindex 792b1ef63e8..d9c238d7dbf 100644--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/stateful_sdpa_fusion.cpp+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/stateful_sdpa_fusion.cpp@@ -24,10 +24,12 @@#include "openvino/core/rt_info.hpp"#include "openvino/core/type.hpp"#include "openvino/core/type/element_type.hpp"+#include "openvino/core/validation_util.hpp"#include "openvino/op/assign.hpp"#include "openvino/op/concat.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/convert.hpp"+#include "openvino/op/convert_like.hpp"#include "openvino/op/gather.hpp"#include "openvino/op/read_value.hpp"#include "openvino/op/scaled_dot_product_attention.hpp"@@ -55,6 +57,86 @@ using namespace ov::pass;namespace ov::intel_cpu {+namespace {+// ScaledDotProductAttentionWithKVCache and the CPU ScaledAttn node implement a narrower contract than v13 SDPA.+// The fusion drops the key/value head repeat and feeds the raw caches, so it declines the graphs that the node+// cannot execute; the unfused SDPA is then decomposed as the spec defines. Each declined case either fails to+// compile or gives wrong results when fused, so declining slows down no graph that works today.+bool is_supported_by_fused_node(const ov::op::v13::ScaledDotProductAttention& sdpa,+ const ov::Output<ov::Node>& q,+ const ov::Output<ov::Node>& cur_k,+ const ov::Output<ov::Node>& cur_v,+ const ov::Output<ov::Node>& past_k,+ const ov::Output<ov::Node>& past_v,+ const std::vector<size_t>& permute_axes) {+ // The node takes a rank-4 query ([B, H, L, D] or a permutation of it) and rank-4 caches.+ const auto& q_rank = q.get_partial_shape().rank();+ if (q_rank.is_dynamic() || q_rank.get_length() != 4) {+ return false;+ }+ for (const auto& kv : {cur_k, cur_v, past_k, past_v}) {+ const auto& rank = kv.get_partial_shape().rank();+ if (rank.is_static() && rank.get_length() != 4) {+ return false;+ }+ }+ // The node broadcasts a mask of rank 2 to 4 against the attention weights. A lower rank, such as the scalar+ // zero mask a frontend adds when only the scale is given, is rejected at run time unless the SDPA is causal.+ if (sdpa.get_input_size() > 3) {+ const auto& mask_rank = sdpa.get_input_partial_shape(3).rank();+ if (mask_rank.is_static() &&+ (mask_rank.get_length() > 4 || (mask_rank.get_length() < 2 && !sdpa.get_causal()))) {+ return false;+ }+ }+ // Key and value caches must have the same number of heads, and it must divide the query's. The inputs are in+ // their original layout: with Transposes, the head axis is the one moved to position 1.+ const size_t head_axis = permute_axes.empty() ? 1 : permute_axes[1];+ auto num_heads = [head_axis](const ov::Output<ov::Node>& cur, const ov::Output<ov::Node>& past) {+ auto heads =+ cur.get_partial_shape().rank().is_static() ? cur.get_partial_shape()[head_axis] : ov::Dimension::dynamic();+ if (past.get_partial_shape().rank().is_static()) {+ // A mismatch between the cache and the current key or value is already rejected by the Concat.+ std::ignore = ov::Dimension::merge(heads, heads, past.get_partial_shape()[head_axis]);+ }+ return heads;+ };+ const auto k_heads = num_heads(cur_k, past_k);+ const auto v_heads = num_heads(cur_v, past_v);+ if (k_heads.is_static() && v_heads.is_static() && k_heads != v_heads) {+ return false;+ }+ const auto& q_heads = q.get_partial_shape()[head_axis];+ for (const auto& heads : {k_heads, v_heads}) {+ if (q_heads.is_static() && heads.is_static() &&+ (heads.get_length() == 0 || q_heads.get_length() % heads.get_length() != 0)) {+ return false;+ }+ }+ // The kernels read a zero scale as "use 1 / sqrt(head size)", while v13 multiplies by it. A scale that is not+ // a constant is read at run time and kept. ConvertLike is not folded by get_constant_from_source, so look+ // through it.+ if (sdpa.get_input_size() > 4) {+ auto scale_source = sdpa.input_value(4);+ if (const auto convert_like = ov::as_type_ptr<ov::op::v1::ConvertLike>(scale_source.get_node_shared_ptr())) {+ scale_source = convert_like->input_value(0);+ }+ if (const auto scale = ov::util::get_constant_from_source(scale_source)) {+ const auto values = scale->cast_vector<float>();+ if (std::any_of(values.begin(), values.end(), [](float value) {+ return value == 0.0F;+ })) {+ return false;+ }+ }+ }+ // is_causal is not checked: the fused kernels align the causal mask bottom-right while v13 aligns it top-left.+ // Both agree when the cache is empty, which is unknown at compile time, and models traced with is_causal and+ // made stateful expect bottom-right, so declining would slow them down and change their output.+ return true;+}+} // namespace+StatefulSDPAFusion::StatefulSDPAFusion() {MATCHER_SCOPE(StatefulSDPAFusion);using namespace ov::pass::pattern;@@ -279,6 +361,16 @@ StatefulSDPAFusion::StatefulSDPAFusion() {}}+ if (!is_supported_by_fused_node(*sdp_node,+ pattern_map.at(cur_q),+ pattern_map.at(cur_k),+ pattern_map.at(cur_v),+ gather_k_node->input_value(0),+ gather_v_node->input_value(0),+ config.permute_axes)) {+ return false;+ }+const auto& old_node = sdp_node;auto new_node = std::make_shared<ov::intel_cpu::ScaledDotProductAttentionWithKVCache>(args, config);new_node->set_friendly_name(old_node->get_friendly_name());diff --git a/src/plugins/intel_cpu/tests/unit/sources.cmake b/src/plugins/intel_cpu/tests/unit/sources.cmakeindex b46e18470c2..d632009cb20 100644--- a/src/plugins/intel_cpu/tests/unit/sources.cmake+++ b/src/plugins/intel_cpu/tests/unit/sources.cmake@@ -41,6 +41,7 @@ set(CPU_UNIT_TESTS_SRCS${CMAKE_CURRENT_LIST_DIR}/transformations/permute_slice_n_interpolation.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/readvalue_subgraph.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/state_concat_sdpa.cpp+ ${CMAKE_CURRENT_LIST_DIR}/transformations/state_concat_sdpa_gqa.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/swap_convert_transpose.cpp${CMAKE_CURRENT_LIST_DIR}/shape_inference_test/adaptive_avg_pool_shape_inference_test.cpp${CMAKE_CURRENT_LIST_DIR}/shape_inference_test/adaptive_max_pool_shape_inference_test.cpp@@ -280,6 +281,7 @@ if(ENABLE_UNITY_BUILD)${CMAKE_CURRENT_LIST_DIR}/transformations/permute_slice_n_interpolation.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/readvalue_subgraph.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/state_concat_sdpa.cpp+ ${CMAKE_CURRENT_LIST_DIR}/transformations/state_concat_sdpa_gqa.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/swap_convert_transpose.cpp)group_source_files(unit_src_custom_shape_infer${CMAKE_CURRENT_LIST_DIR}/shape_inference_test/custom_shape_infer/adaptive_avg_pool.cppdiff --git a/src/plugins/intel_cpu/tests/unit/transformations/state_concat_sdpa_gqa.cpp b/src/plugins/intel_cpu/tests/unit/transformations/state_concat_sdpa_gqa.cppnew file mode 100644index 00000000000..c745296e163--- /dev/null+++ b/src/plugins/intel_cpu/tests/unit/transformations/state_concat_sdpa_gqa.cpp@@ -0,0 +1,307 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <gtest/gtest.h>++#include <limits>+#include <memory>+#include <transformations/cpu_opset/common/op/sdpa.hpp>+#include <transformations/cpu_opset/common/pass/stateful_sdpa_fusion.hpp>+#include <vector>++#include "common_test_utils/ov_test_utils.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/assign.hpp"+#include "openvino/op/broadcast.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/convert_like.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/read_value.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/result.hpp"+#include "openvino/op/scaled_dot_product_attention.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/op/unsqueeze.hpp"++using namespace testing;+using namespace ov;+using namespace ov::intel_cpu;++namespace {+// Grouped-query attention over a KV cache, with the key/value heads repeated the way the PyTorch frontend converts+// scaled_dot_product_attention(enable_gqa=True) with static head counts: [B, Hk, S, D] -> Unsqueeze(-3)+// -> Broadcast(BIDIRECTIONAL, Concat(ShapeOf[:-2], G, ShapeOf[-2], ShapeOf[-1]))+// -> Reshape(Concat(ShapeOf[:-3], Hq, ShapeOf[-2], ShapeOf[-1])). Key/value with as many heads as the query are not+// repeated. The ShapeOf adds a consumer to the KV-cache Concat, which the fusion must accept.+struct KvCacheCase {+ int64_t rank = 4; // 5 adds a static prefix dimension: [B, X, H, L, D]+ int64_t q_heads = 8;+ int64_t k_heads = 2;+ int64_t v_heads = 2;+ bool causal = false;+ bool transposed = false; // [B, L, H, D] inputs, transposed to [B, H, L, D] for the SDPA (rank 4 only)+ enum class Mask { None, Input, ScalarZero } mask = Mask::None;+ enum class Scale { None, Constant, F16Constant, ConvertLikeConstant, Input } scale = Scale::None;+ float scale_value = 0.125F;+};++std::shared_ptr<ov::Model> make_gqa_kv_cache_model(const KvCacheCase& c, bool is_ref) {+ constexpr int64_t head_size = 64;+ auto input_shape = [&](int64_t heads) {+ std::vector<Dimension> dims{-1};+ if (c.rank == 5) {+ dims.emplace_back(3);+ }+ if (c.transposed) {+ dims.insert(dims.end(), {-1, heads, head_size});+ } else {+ dims.insert(dims.end(), {heads, -1, head_size});+ }+ return PartialShape(dims);+ };+ ParameterVector params;+ auto make_param = [&](const element::Type& type, const PartialShape& shape) {+ params.push_back(std::make_shared<ov::op::v0::Parameter>(type, shape));+ return params.back();+ };+ auto q = make_param(element::f32, input_shape(c.q_heads));+ auto k = make_param(element::f32, input_shape(c.k_heads));+ auto v = make_param(element::f32, input_shape(c.v_heads));+ auto beam_idx = make_param(element::i32, PartialShape{-1});+ auto var_k = std::make_shared<ov::op::util::Variable>(+ ov::op::util::VariableInfo{input_shape(c.k_heads), element::f32, "pastk"});+ auto var_v = std::make_shared<ov::op::util::Variable>(+ ov::op::util::VariableInfo{input_shape(c.v_heads), element::f32, "pastv"});+ auto past_k = std::make_shared<ov::op::v6::ReadValue>(k, var_k);+ auto past_v = std::make_shared<ov::op::v6::ReadValue>(v, var_v);++ // Mask and scale inputs, laid out as the PyTorch frontend does: a scale without a mask gets a scalar zero mask.+ OutputVector mask_and_scale;+ const auto mask = c.scale != KvCacheCase::Scale::None && c.mask == KvCacheCase::Mask::None+ ? KvCacheCase::Mask::ScalarZero+ : c.mask;+ if (mask == KvCacheCase::Mask::Input) {+ mask_and_scale.push_back(make_param(element::f32, PartialShape{-1, 1, -1, -1}));+ } else if (mask == KvCacheCase::Mask::ScalarZero) {+ mask_and_scale.push_back(+ std::make_shared<ov::op::v1::ConvertLike>(ov::op::v0::Constant::create(element::f32, {}, {0.0F}), q));+ }+ if (c.scale == KvCacheCase::Scale::Constant) {+ mask_and_scale.push_back(ov::op::v0::Constant::create(element::f32, {}, {c.scale_value}));+ } else if (c.scale == KvCacheCase::Scale::F16Constant) {+ mask_and_scale.push_back(+ std::make_shared<ov::op::v0::Convert>(ov::op::v0::Constant::create(element::f16, {}, {c.scale_value}),+ element::f32));+ } else if (c.scale == KvCacheCase::Scale::ConvertLikeConstant) {+ mask_and_scale.push_back(+ std::make_shared<ov::op::v1::ConvertLike>(ov::op::v0::Constant::create(element::f32, {}, {c.scale_value}),+ q));+ } else if (c.scale == KvCacheCase::Scale::Input) {+ mask_and_scale.push_back(make_param(element::f32, PartialShape{}));+ }++ Output<Node> sdpa, present_k, present_v;+ if (is_ref) {+ ScaledDotProductAttentionWithKVCache::Config config;+ config.fuse_concat = true;+ config.is_causal = c.causal;+ if (c.transposed) {+ config.permute_axes = {0, 2, 1, 3};+ }+ OutputVector args{q, k, v};+ args.insert(args.end(), mask_and_scale.begin(), mask_and_scale.end());+ args.insert(args.end(), {beam_idx, past_k, past_v});+ auto fused = std::make_shared<ScaledDotProductAttentionWithKVCache>(args, config);+ sdpa = fused->output(0);+ present_k = fused->output(1);+ present_v = fused->output(2);+ } else {+ auto axis = ov::op::v0::Constant::create(element::i32, {1}, {0});+ present_k = std::make_shared<ov::op::v0::Concat>(+ OutputVector{std::make_shared<ov::op::v8::Gather>(past_k, beam_idx, axis), k},+ c.transposed ? 1 : c.rank - 2);+ present_v = std::make_shared<ov::op::v0::Concat>(+ OutputVector{std::make_shared<ov::op::v8::Gather>(past_v, beam_idx, axis), v},+ c.transposed ? 1 : c.rank - 2);+ auto repeat_heads = [&](const Output<Node>& kv, int64_t kv_heads) -> Output<Node> {+ if (kv_heads == c.q_heads) {+ return kv;+ }+ auto shape = std::make_shared<ov::op::v3::ShapeOf>(kv, element::i64);+ auto slice_dims = [&](int64_t begin, int64_t end) {+ return std::make_shared<ov::op::v8::Slice>(shape,+ ov::op::v0::Constant::create(element::i64, {1}, {begin}),+ ov::op::v0::Constant::create(element::i64, {1}, {end}),+ ov::op::v0::Constant::create(element::i64, {1}, {1}));+ };+ const auto group = ov::op::v0::Constant::create(element::i64, {1}, {c.q_heads / kv_heads});+ const auto q_heads = ov::op::v0::Constant::create(element::i64, {1}, {c.q_heads});+ auto head_dim = slice_dims(-1, std::numeric_limits<int64_t>::max());+ if (c.transposed) {+ // [B, L, Hk, D] -> [B, L, Hk, 1, D] -> [B, L, Hk, G, D] -> [B, L, Hq, D]+ auto target = std::make_shared<ov::op::v0::Concat>(OutputVector{slice_dims(0, -1), group, head_dim}, 0);+ auto output_shape =+ std::make_shared<ov::op::v0::Concat>(OutputVector{slice_dims(0, -2), q_heads, head_dim}, 0);+ auto unsqueezed =+ std::make_shared<ov::op::v0::Unsqueeze>(kv, ov::op::v0::Constant::create(element::i64, {1}, {-2}));+ auto broadcasted =+ std::make_shared<ov::op::v3::Broadcast>(unsqueezed, target, ov::op::BroadcastType::BIDIRECTIONAL);+ return std::make_shared<ov::op::v1::Reshape>(broadcasted, output_shape, false);+ }+ auto seq_len = slice_dims(-2, -1);+ auto target =+ std::make_shared<ov::op::v0::Concat>(OutputVector{slice_dims(0, -2), group, seq_len, head_dim}, 0);+ auto output_shape =+ std::make_shared<ov::op::v0::Concat>(OutputVector{slice_dims(0, -3), q_heads, seq_len, head_dim}, 0);+ auto unsqueezed =+ std::make_shared<ov::op::v0::Unsqueeze>(kv, ov::op::v0::Constant::create(element::i64, {1}, {-3}));+ auto broadcasted =+ std::make_shared<ov::op::v3::Broadcast>(unsqueezed, target, ov::op::BroadcastType::BIDIRECTIONAL);+ return std::make_shared<ov::op::v1::Reshape>(broadcasted, output_shape, false);+ };+ OutputVector inputs{q, repeat_heads(present_k, c.k_heads), repeat_heads(present_v, c.v_heads)};+ if (c.transposed) {+ const auto order = ov::op::v0::Constant::create(element::i64, {4}, {0, 2, 1, 3});+ for (size_t i = 0; i < 3; ++i) {+ inputs[i] = std::make_shared<ov::op::v1::Transpose>(inputs[i], order);+ }+ }+ inputs.insert(inputs.end(), mask_and_scale.begin(), mask_and_scale.end());+ sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(inputs, c.causal);+ }+ auto add = std::make_shared<ov::op::v1::Add>(sdpa, ov::op::v0::Constant::create(element::f32, {1}, {1.0F}));+ SinkVector sinks{std::make_shared<ov::op::v6::Assign>(present_k, var_k),+ std::make_shared<ov::op::v6::Assign>(present_v, var_v)};+ return std::make_shared<ov::Model>(ResultVector{std::make_shared<ov::op::v0::Result>(add)},+ sinks,+ params,+ "GqaKvCache");+}+} // namespace++#if defined(OPENVINO_ARCH_X86_64) && (defined(__ANDROID__) || defined(ANDROID))+# define SKIP_ON_ANDROID_X64() \+ test_skipped = true; \+ GTEST_SKIP() << "Skipping StatefulSDPAFusion tests on Android X64"+#else+# define SKIP_ON_ANDROID_X64()+#endif++TEST_F(TransformationTestsF, StateConcatSDPAGroupedQueryShapeOfBroadcast) {+ SKIP_ON_ANDROID_X64();+ model = make_gqa_kv_cache_model({}, false);+ model_ref = make_gqa_kv_cache_model({}, true);+ manager.register_pass<StatefulSDPAFusion>();+}++TEST_F(TransformationTestsF, StateConcatSDPAMultiQueryShapeOfBroadcast) {+ SKIP_ON_ANDROID_X64();+ KvCacheCase c;+ c.k_heads = c.v_heads = 1;+ model = make_gqa_kv_cache_model(c, false);+ model_ref = make_gqa_kv_cache_model(c, true);+ manager.register_pass<StatefulSDPAFusion>();+}++// Cases the fused node supports: the fusion still applies.+class StateConcatSDPAFusedTest : public TransformationTestsF, public WithParamInterface<KvCacheCase> {};++TEST_P(StateConcatSDPAFusedTest, Fused) {+ SKIP_ON_ANDROID_X64();+ // is_causal and permute_axes are attributes of the fused node+ comparator.enable(FunctionsComparator::CmpValues::ATTRIBUTES);+ model = make_gqa_kv_cache_model(GetParam(), false);+ model_ref = make_gqa_kv_cache_model(GetParam(), true);+ manager.register_pass<StatefulSDPAFusion>();+}++namespace {+KvCacheCase transposed_case(int64_t k_heads, int64_t v_heads) {+ KvCacheCase c;+ c.transposed = true;+ c.k_heads = k_heads;+ c.v_heads = v_heads;+ return c;+}++KvCacheCase fused_case(bool causal, KvCacheCase::Mask mask, KvCacheCase::Scale scale, int64_t heads = 2) {+ KvCacheCase c;+ c.causal = causal;+ c.mask = mask;+ c.scale = scale;+ c.k_heads = c.v_heads = heads;+ if (heads == -1) {+ c.q_heads = -1;+ }+ return c;+}+} // namespace++INSTANTIATE_TEST_SUITE_P(+ TransformationTests,+ StateConcatSDPAFusedTest,+ ::testing::Values(fused_case(true, KvCacheCase::Mask::None, KvCacheCase::Scale::None),+ fused_case(false, KvCacheCase::Mask::Input, KvCacheCase::Scale::Constant),+ fused_case(false, KvCacheCase::Mask::Input, KvCacheCase::Scale::F16Constant),+ fused_case(false, KvCacheCase::Mask::Input, KvCacheCase::Scale::ConvertLikeConstant),+ // a scale computed at run time can't be checked for zero: kept+ fused_case(false, KvCacheCase::Mask::Input, KvCacheCase::Scale::Input),+ // the scalar zero mask is not checked by the node when the SDPA is causal+ fused_case(true, KvCacheCase::Mask::None, KvCacheCase::Scale::Constant),+ // dynamic head counts (no repeat) are not checked at compile time+ fused_case(false, KvCacheCase::Mask::None, KvCacheCase::Scale::None, -1),+ // [B, L, H, D] caches with Transposes: the head axis is permute_axes[1]+ transposed_case(2, 2)));++// Cases the fused node can't execute: the fusion leaves the SDPA to the generic decomposition.+class StateConcatSDPANotFusedTest : public TransformationTestsF, public WithParamInterface<KvCacheCase> {};++TEST_P(StateConcatSDPANotFusedTest, NotFused) {+ SKIP_ON_ANDROID_X64();+ model = make_gqa_kv_cache_model(GetParam(), false);+ manager.register_pass<StatefulSDPAFusion>();+}++namespace {+KvCacheCase not_fused_case(int64_t rank,+ int64_t k_heads,+ int64_t v_heads,+ KvCacheCase::Mask mask = KvCacheCase::Mask::None,+ KvCacheCase::Scale scale = KvCacheCase::Scale::None,+ float scale_value = 0.125F) {+ KvCacheCase c;+ c.rank = rank;+ c.k_heads = k_heads;+ c.v_heads = v_heads;+ c.mask = mask;+ c.scale = scale;+ c.scale_value = scale_value;+ return c;+}+} // namespace++INSTANTIATE_TEST_SUITE_P(+ TransformationTests,+ StateConcatSDPANotFusedTest,+ ::testing::Values(+ // rank-5 query: grouped and plain+ not_fused_case(5, 2, 2),+ not_fused_case(5, 8, 8),+ // key and value caches with different head counts+ not_fused_case(4, 2, 4),+ // explicit zero scale, also behind a decompression Convert or a ConvertLike+ not_fused_case(4, 2, 2, KvCacheCase::Mask::Input, KvCacheCase::Scale::Constant, 0.0F),+ not_fused_case(4, 2, 2, KvCacheCase::Mask::Input, KvCacheCase::Scale::F16Constant, 0.0F),+ not_fused_case(4, 2, 2, KvCacheCase::Mask::Input, KvCacheCase::Scale::ConvertLikeConstant, 0.0F),+ // scalar zero mask added for a scale without a mask, not causal+ not_fused_case(4, 2, 2, KvCacheCase::Mask::None, KvCacheCase::Scale::Constant),+ // [B, L, H, D] caches with Transposes and different key/value head counts+ transposed_case(2, 4)));++#undef SKIP_ON_ANDROID_X64diff --git a/tests/layer_tests/pytorch_tests/test_scaled_dot_product_attention.py b/tests/layer_tests/pytorch_tests/test_scaled_dot_product_attention.pyindex aec9e2f2223..b8ef9c213b3 100644--- a/tests/layer_tests/pytorch_tests/test_scaled_dot_product_attention.py+++ b/tests/layer_tests/pytorch_tests/test_scaled_dot_product_attention.py@@ -2,7 +2,9 @@# SPDX-License-Identifier: Apache-2.0import numpy as np+import openvino as ovimport pytest+import torchfrom pytorch_layer_test_class import PytorchLayerTest@@ -140,3 +142,349 @@ class TestScaledDotProductAttentionWithGroupQuery(PytorchLayerTest):self._test(*self.create_model(mask, is_causal, dtype, mask_shape),ie_device, precision, ir_version, dynamic_shapes=dyn_shapes,kwargs_to_prepare_input={"dtype": dtype})+++# Rank-4 [B, H, L, D] inputs with enable_gqa=True, the layout real LLMs use (Hq=8, L=5, S=16, D=4).+# name -> (Bq, Hq, Bkv, Hk, Hv, Dv)+GQA_L, GQA_S, GQA_D = 5, 16, 4+GQA_RANK4_LAYOUTS = {+ "gqa": (1, 8, 1, 2, 2, 4), # group size 4+ "mqa": (1, 8, 1, 1, 1, 4), # single K/V head+ "g1": (1, 8, 1, 8, 8, 4), # Hq == Hkv: plain SDPA when the head counts are static+ "dk_ne_dv": (1, 8, 1, 2, 2, 6), # value head size differs from query/key head size+ "kv_batch_bcast": (2, 8, 1, 2, 2, 4), # K/V batch broadcast against Q batch+ "hk_ne_hv": (1, 8, 1, 2, 4, 4), # key and value are repeated by different factors+}+# Layouts also run with torch.export, which ignores the conversion options below.+GQA_RANK4_EXPORT_LAYOUTS = ("gqa", "mqa", "g1")+# mask kind -> (attn_mask shape, dtype, passed as model input); "causal" means is_causal=True without a mask+# (torch rejects an explicit attn_mask together with is_causal=True).+GQA_RANK4_MASKS = {+ "none": None,+ "causal": None,+ "LS": ((GQA_L, GQA_S), np.float32, False),+ "11LS": ((1, 1, GQA_L, GQA_S), np.float32, False),+ "1HLS": ((1, 8, GQA_L, GQA_S), np.float32, False),+ "HLS": ((8, GQA_L, GQA_S), np.float32, False),+ "bool_1HLS": ((1, 8, GQA_L, GQA_S), bool, False),+ "input_1HLS": ((1, 8, GQA_L, GQA_S), np.float32, True),+}+# How the model reaches the translator, which decides what it can read from the input shapes:+# script: TorchScript scripting, inputs of dynamic rank;+# trace: TorchScript tracing, static rank with dynamic dimensions;+# static: convert_model with static input shapes, every dimension known (static group size).+GQA_CONVERSIONS = {+ "script": {"dynamic_shapes": True},+ "trace": {"dynamic_shapes": True, "trace_model": True},+ "static": {"dynamic_shapes": False, "use_convert_model": True},+}+++class TestScaledDotProductAttentionGQARank4(PytorchLayerTest):+ def _prepare_input(self, layout, mask_kind):+ bq, hq, bkv, hk, hv, dv = GQA_RANK4_LAYOUTS[layout]+ q_len, kv_len, head_size = GQA_L, GQA_S, GQA_D+ inputs = (self.random.randn(bq, hq, q_len, head_size, dtype=np.float32),+ self.random.randn(bkv, hk, kv_len, head_size, dtype=np.float32),+ self.random.randn(bkv, hv, kv_len, dv, dtype=np.float32))+ mask = GQA_RANK4_MASKS[mask_kind]+ if mask is not None and mask[2]:+ inputs += (self.random.randn(*mask[0], dtype=np.float32),)+ return inputs++ def create_model(self, mask_kind):+ import torch.nn.functional as F++ mask = GQA_RANK4_MASKS[mask_kind]+ is_causal = mask_kind == "causal"+ attn_mask = None+ if mask is not None and not mask[2]:+ # Random values, so a mask applied to the wrong head or position changes the result.+ if mask[1] is bool:+ values = self.random.random_bool(*mask[0])+ values[..., 0] = True # no fully masked row+ else:+ values = self.random.randn(*mask[0], dtype=np.float32)+ attn_mask = torch.from_numpy(values)++ class aten_sdpa_gqa(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.mask = attn_mask+ self.is_causal = is_causal++ def forward(self, query, key, value):+ a = F.scaled_dot_product_attention(query, key, value, attn_mask=self.mask,+ is_causal=self.is_causal, enable_gqa=True)+ b = F.scaled_dot_product_attention(query, key, value, attn_mask=self.mask,+ is_causal=self.is_causal, scale=0.25, enable_gqa=True)+ return a, b++ class aten_sdpa_gqa_mask_input(torch.nn.Module):+ def forward(self, query, key, value, mask):+ a = F.scaled_dot_product_attention(query, key, value, attn_mask=mask, enable_gqa=True)+ b = F.scaled_dot_product_attention(query, key, value, attn_mask=mask, scale=0.25, enable_gqa=True)+ return a, b++ model = aten_sdpa_gqa_mask_input() if (mask is not None and mask[2]) else aten_sdpa_gqa()+ return model, "aten::scaled_dot_product_attention"++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.precommit_torch_export+ @pytest.mark.parametrize("layout", list(GQA_RANK4_LAYOUTS))+ @pytest.mark.parametrize("mask_kind", list(GQA_RANK4_MASKS))+ @pytest.mark.parametrize("conversion", list(GQA_CONVERSIONS))+ def test_scaled_dot_product_atten_gqa_rank4(self, ie_device, precision, ir_version, layout, mask_kind, conversion):+ if PytorchLayerTest.use_torch_export() and (conversion != "script" or layout not in GQA_RANK4_EXPORT_LAYOUTS):+ pytest.skip("torch.export ignores the TorchScript conversion options and runs a subset of layouts")+ self._test(*self.create_model(mask_kind), ie_device, precision, ir_version,+ kwargs_to_prepare_input={"layout": layout, "mask_kind": mask_kind},+ **GQA_CONVERSIONS[conversion])+++class TestScaledDotProductAttentionGQARank3(PytorchLayerTest):+ # Unbatched [H, L, D] inputs: Hq=8 over Hkv=2.+ def _prepare_input(self):+ return (self.random.randn(8, GQA_L, GQA_D, dtype=np.float32),+ self.random.randn(2, GQA_S, GQA_D, dtype=np.float32),+ self.random.randn(2, GQA_S, GQA_D, dtype=np.float32))++ def create_model(self, is_causal):+ import torch.nn.functional as F++ class aten_sdpa_gqa_rank3(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.is_causal = is_causal++ def forward(self, query, key, value):+ return F.scaled_dot_product_attention(query, key, value, is_causal=self.is_causal, enable_gqa=True)++ return aten_sdpa_gqa_rank3(), "aten::scaled_dot_product_attention"++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize("is_causal", [False, True])+ @pytest.mark.parametrize("conversion", list(GQA_CONVERSIONS))+ def test_scaled_dot_product_atten_gqa_rank3(self, ie_device, precision, ir_version, is_causal, conversion):+ self._test(*self.create_model(is_causal), ie_device, precision, ir_version,+ **GQA_CONVERSIONS[conversion])+++class TestScaledDotProductAttentionGQAGraph:+ """Check that enable_gqa converts to an SDPA of the input rank with repeated key/value heads.++ Key and value heads are repeated by Unsqueeze -> Broadcast(BIDIRECTIONAL) -> Reshape, the form the SDPA+ fusions match.+ """++ class aten_sdpa_gqa(torch.nn.Module):+ def forward(self, query, key, value):+ return torch.nn.functional.scaled_dot_product_attention(query, key, value, enable_gqa=True)++ @staticmethod+ def _static_heads(ov_model):+ # Whether the translator saw static head counts for query, key and value.+ shapes = [param.get_partial_shape() for param in ov_model.get_parameters()]+ return all(shape.rank.is_static and shape[-3].is_static for shape in shapes)++ @staticmethod+ def _convert(conversion, example):+ # Returns the converted model and whether the translator saw static head counts.+ model = TestScaledDotProductAttentionGQAGraph.aten_sdpa_gqa()+ shapes = [ov.PartialShape(list(x.shape)) for x in example]+ if conversion == "trace_static":+ ov_model = ov.convert_model(model, example_input=example, input=shapes)+ elif conversion == "trace_dynamic":+ ov_model = ov.convert_model(model, example_input=example, input=[ov.PartialShape([-1] * 4)] * 3)+ elif conversion == "script_dynamic_rank":+ ov_model = ov.convert_model(torch.jit.script(model))+ static_heads = TestScaledDotProductAttentionGQAGraph._static_heads(ov_model)+ # Inputs are of dynamic rank here; set static shapes to make the graph checkable.+ ov_model.reshape(dict(zip(ov_model.inputs, shapes)))+ return ov_model, static_heads+ elif conversion == "export":+ ov_model = ov.convert_model(torch.export.export(model, example))+ else:+ raise ValueError(conversion)+ return ov_model, TestScaledDotProductAttentionGQAGraph._static_heads(ov_model)++ @staticmethod+ def _assert_repeated(ov_model, sdpa, port):+ reshape = sdpa.input_value(port).get_node()+ assert reshape.get_type_name() == "Reshape", f"SDPA input {port}: {reshape}"+ assert reshape.get_output_partial_shape(0).rank.get_length() == 4+ broadcast = reshape.input_value(0).get_node()+ assert broadcast.get_type_name() == "Broadcast", f"SDPA input {port}: {broadcast}"+ assert broadcast.get_attributes()["mode"] == "bidirectional", broadcast.get_attributes()+ unsqueeze = broadcast.input_value(0).get_node()+ assert unsqueeze.get_type_name() == "Unsqueeze", f"SDPA input {port}: {unsqueeze}"+ assert unsqueeze.input_value(1).get_node().get_type_name() == "Constant", "Unsqueeze axis must be a Constant"+ # [B, Hkv, 1, S, E]: the group axis follows the kv heads, so each kv head is repeated in place+ # (kv_head = q_head // G, as torch repeat_interleave), not tiled.+ unsq_shape = unsqueeze.get_output_partial_shape(0)+ assert unsq_shape.rank.get_length() == 5, unsq_shape+ assert unsq_shape[2] == ov.Dimension(1), unsq_shape+ # The repeat applies to its own input (key for port 1, value for port 2), directly.+ source = unsqueeze.input_value(0).get_node()+ assert source.get_friendly_name() == ov_model.get_parameters()[port].get_friendly_name(), source+ # GPU ExpandBroadcastReshapeSDPAFusion requires each node of the chain to have a single consumer.+ for node in (unsqueeze, broadcast, reshape):+ assert len(node.output(0).get_target_inputs()) == 1, node++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize("layout", ["gqa", "mqa", "dk_ne_dv", "hk_ne_hv", "g1"])+ @pytest.mark.parametrize("conversion", ["trace_static", "trace_dynamic", "script_dynamic_rank", "export"])+ def test_scaled_dot_product_atten_gqa_graph(self, ie_device, precision, layout, conversion):+ if ie_device != "CPU" or precision != "FP32":+ pytest.skip("graph structure does not depend on device or precision")+ bq, hq, bkv, hk, hv, dv = GQA_RANK4_LAYOUTS[layout]+ example = (torch.randn(bq, hq, GQA_L, GQA_D),+ torch.randn(bkv, hk, GQA_S, GQA_D),+ torch.randn(bkv, hv, GQA_S, dv))+ ov_model, static_heads = self._convert(conversion, example)+ sdpas = [n for n in ov_model.get_ordered_ops() if n.get_type_name() == "ScaledDotProductAttention"]+ assert len(sdpas) == 1, [n.get_type_name() for n in ov_model.get_ordered_ops()]+ sdpa = sdpas[0]+ for port in range(sdpa.get_input_size()):+ rank = sdpa.get_input_partial_shape(port).rank+ assert rank.is_static, f"SDPA input {port} has dynamic rank"+ assert rank.get_length() <= 4, f"SDPA input {port} has rank {rank}"+ assert sdpa.get_input_partial_shape(0).rank.get_length() == 4+ if static_heads and hq == hk == hv:+ # Static group size 1: no repeat (an all-ones Broadcast would be removed by EliminateNopBroadcast+ # and the leftover Unsqueeze -> Reshape is not matched by the SDPA fusions).+ op_types = {n.get_type_name() for n in ov_model.get_ordered_ops()}+ assert "Broadcast" not in op_types, op_types+ for port in (1, 2):+ assert sdpa.input_value(port).get_node().get_type_name() == "Parameter"+ else:+ for port in (1, 2):+ self._assert_repeated(ov_model, sdpa, port)+++class TestScaledDotProductAttentionGQAKVCacheFusion:+ """Check the converted enable_gqa attention over a stateful KV cache on CPU.++ The attention over the present key/value is converted from PyTorch; a KV cache (ReadValue -> Gather(beam_idx)+ -> Concat -> Assign) is then put in place of the present key/value inputs. StatefulSDPAFusion must turn the+ result into one ScaledDotProductAttention node that reads the un-repeated cache; the layouts that node can't+ execute must still compile. Either way the outputs match torch.+ """++ class aten_sdpa_gqa(torch.nn.Module):+ def __init__(self, scale=None):+ super().__init__()+ self.scale = scale++ def forward(self, query, present_key, present_value, attn_mask=None):+ return torch.nn.functional.scaled_dot_product_attention(query, present_key, present_value,+ attn_mask=attn_mask, scale=self.scale,+ enable_gqa=True)++ @staticmethod+ def _make_stateful_model(heads, head_size, prefix=(), scale=None, with_mask=False):+ import openvino.opset13 as ops+ from openvino import op++ num_q_heads, num_k_heads, num_v_heads = heads+ lead = [1, *prefix]+ example = [torch.randn(*lead, num_q_heads, 2, head_size),+ torch.randn(*lead, num_k_heads, 5, head_size),+ torch.randn(*lead, num_v_heads, 5, head_size)]+ shapes = [ov.PartialShape([-1, *prefix, h, -1, head_size]) for h in heads]+ if with_mask:+ example.append(torch.randn(1, 1, 2, 5))+ shapes.append(ov.PartialShape([1, 1, -1, -1]))+ attention = ov.convert_model(TestScaledDotProductAttentionGQAKVCacheFusion.aten_sdpa_gqa(scale),+ example_input=tuple(example), input=shapes)+ query, present_key, present_value, *mask = attention.get_parameters()+ query.output(0).get_tensor().set_names({"query"})+ if mask:+ mask[0].output(0).get_tensor().set_names({"attn_mask"})+ key = ops.parameter([-1, *prefix, num_k_heads, -1, head_size], np.float32, name="key")+ value = ops.parameter([-1, *prefix, num_v_heads, -1, head_size], np.float32, name="value")+ beam_idx = ops.parameter([-1], np.int32, name="beam_idx")+ batch = ops.gather(ops.shape_of(query), ops.constant([0]), ops.constant(0))+ assigns = []+ for present, current, num_heads, name in ((present_key, key, num_k_heads, "past_key"),+ (present_value, value, num_v_heads, "past_value")):+ info = op.util.VariableInfo()+ info.data_shape = ov.PartialShape([-1, *prefix, num_heads, -1, head_size])+ info.data_type = ov.Type.f32+ info.variable_id = name+ cache_variable = op.util.Variable(info)+ empty_shape = ops.concat([batch, ops.constant([*prefix, num_heads, 0, head_size], dtype=np.int64)], 0)+ empty = ops.broadcast(ops.constant(np.float32(0)), empty_shape)+ past = ops.gather(ops.read_value(empty, cache_variable), beam_idx, ops.constant(0))+ cache = ops.concat([past, current], len(prefix) + 2)+ present.output(0).replace(cache.output(0))+ assigns.append(ops.assign(cache, cache_variable))+ return ov.Model(attention.get_results(), assigns, [query, key, value, beam_idx, *mask], "gqa_kv_cache")++ @staticmethod+ def _check_outputs(compiled, heads, head_size, prefix=(), scale=None, with_mask=False):+ # Prefill, then one decode step over the cache; every output must match torch.+ num_q_heads, num_k_heads, num_v_heads = heads+ request = compiled.create_infer_request()+ rng = np.random.RandomState(0)+ keys, values = [], []+ for length in (5, 1):+ inputs = {"query": rng.randn(1, *prefix, num_q_heads, length, head_size).astype(np.float32),+ "key": rng.randn(1, *prefix, num_k_heads, length, head_size).astype(np.float32),+ "value": rng.randn(1, *prefix, num_v_heads, length, head_size).astype(np.float32),+ "beam_idx": np.zeros(1, dtype=np.int32)}+ keys.append(inputs["key"])+ values.append(inputs["value"])+ mask = None+ if with_mask:+ inputs["attn_mask"] = rng.randn(1, 1, length, sum(k.shape[-2] for k in keys)).astype(np.float32)+ mask = torch.from_numpy(inputs["attn_mask"])+ out = request.infer(inputs)[0]+ ref = torch.nn.functional.scaled_dot_product_attention(+ torch.from_numpy(inputs["query"]), torch.from_numpy(np.concatenate(keys, -2)),+ torch.from_numpy(np.concatenate(values, -2)), attn_mask=mask, scale=scale, enable_gqa=True).numpy()+ np.testing.assert_allclose(out, ref, atol=1e-5, rtol=1e-5)++ @staticmethod+ def _compile(model, ie_device):+ compiled = ov.Core().compile_model(model, ie_device, {"INFERENCE_PRECISION_HINT": "f32",+ "KV_CACHE_PRECISION": "f32"})+ op_types = [node.get_rt_info()["layerType"].astype(str) for node in compiled.get_runtime_model().get_ops()]+ return compiled, op_types++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize("num_kv_heads,scale,with_mask", [(2, None, False), (1, None, False), (2, 0.125, True)])+ def test_scaled_dot_product_atten_gqa_kv_cache_fusion(self, ie_device, precision, num_kv_heads, scale, with_mask):+ if ie_device != "CPU" or precision != "FP32":+ pytest.skip("checks the CPU KV-cache fusion")+ heads, head_size = (8, num_kv_heads, num_kv_heads), 64+ model = self._make_stateful_model(heads, head_size, scale=scale, with_mask=with_mask)+ compiled, op_types = self._compile(model, ie_device)+ assert op_types.count("ScaledDotProductAttention") == 1, op_types+ assert not {"MatMul", "Softmax", "Subgraph"} & set(op_types), op_types+ self._check_outputs(compiled, heads, head_size, scale=scale, with_mask=with_mask)++ # Layouts the fused CPU node can't execute: they must compile and match torch.+ # name -> (heads (Hq, Hk, Hv), prefix dimensions, scale, with_mask)+ FALLBACK_CASES = {+ "rank5": ((8, 2, 2), (3,), None, False),+ "hk_ne_hv": ((8, 2, 4), (), None, False),+ "zero_scale": ((8, 2, 2), (), 0.0, True),+ "scale_without_mask": ((8, 2, 2), (), 0.125, False),+ }++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize("case", list(FALLBACK_CASES))+ def test_scaled_dot_product_atten_gqa_kv_cache_fallback(self, ie_device, precision, case):+ if ie_device != "CPU" or precision != "FP32":+ pytest.skip("checks the CPU KV-cache fusion")+ heads, prefix, scale, with_mask = self.FALLBACK_CASES[case]+ head_size = 64+ model = self._make_stateful_model(heads, head_size, prefix, scale, with_mask)+ compiled, _ = self._compile(model, ie_device)+ self._check_outputs(compiled, heads, head_size, prefix, scale, with_mask)