OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[GPU] Fuse SDPA output Transpose{0,2,1,3} into output_transpose_order (#37056)
Chon Ming Lee9d8ced513cec
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_micro.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_micro.cppindex 332ccf457f5..57d8d986385 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_micro.cpp+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_micro.cpp@@ -1045,7 +1045,8 @@ JitConstants SDPAMicroGenerator::get_jit_constants(const kernel_impl_params& parconst auto v_head_size = micro_get_head_size(params, 2);const auto d_max = get_d_max(k_head_size);- const auto batch = out_ps[0] * out_ps[1];+ const auto head_num = micro_get_num_heads(params, 0);+ const auto batch = out_ps[0] * static_cast<ov::Dimension>(head_num);auto ldq = k_head_size * ov::element::Type(Q.data_type).size();auto ldk = k_head_size * ov::element::Type(K.data_type).size();@@ -1448,7 +1449,7 @@ DispatchDataFunc SDPAMicroGenerator::get_dispatch_data_func() const {wgs.global[1] *= head_num;wgs.global[2] *= 1;} else {- wgs.global[1] *= out_ps[1].get_length();+ wgs.global[1] *= head_num;wgs.global[2] *= out_ps[0].get_length();}@@ -1510,7 +1511,8 @@ void SDPAMicroGenerator::init_microkernels(const kernel_impl_params& params,const ov::Dimension n_keys = micro_get_seq_length(params, 1);const ov::Dimension n_queries = micro_get_seq_length(params, 0);const ov::Dimension n_values = ov::Dimension(v_head_size);- const auto batch = out_ps[0] * out_ps[1];+ const auto head_num = micro_get_num_heads(params, 0);+ const auto batch = out_ps[0] * static_cast<ov::Dimension>(head_num);GPU_DEBUG_TRACE_DETAIL << "\nconfiguration.is_kv_compressed = " << configuration.is_kv_compressed << std::endl;GPU_DEBUG_TRACE_DETAIL << "k_head_size = " << k_head_size << ", v_head_size = " << v_head_size << ", d_max = " << d_max << ", batch = " << batch << "\n";diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_opt.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_opt.cppindex 95e727b330a..d464ffedd4a 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_opt.cpp+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_opt.cpp@@ -106,6 +106,28 @@ JitConstants SDPAOptGeneratorBase::get_jit_constants_base(const kernel_impl_paraif (info.supports_immad && broadcast_axis == -1 && k_head_size >= 128) {jit.make("LOAD_KEY_LEFTOVERS_IN_CALC_LOOP", 1);}++ // Signal when output_transpose_order is {0,2,1,3} (heads<->seq swap).+ // The kernel-side handling only supports this specific permutation;+ // enabling the flag for other non-identity orders would silently+ // corrupt outputs via wrong addressing.+ // Note: for a rank-3 SDPA the order is 3D (e.g. {0,1,2}); extend it to 4D+ // before comparing against the 4D identity/heads<->seq permutations.+ {+ auto extended_out_order = extend_order_in_num_heads_dim(desc->output_transpose_order);+ bool is_identity = (extended_out_order == std::vector<int64_t>{0, 1, 2, 3});+ bool is_heads_seq_swap = (extended_out_order == std::vector<int64_t>{0, 2, 1, 3});+ OPENVINO_ASSERT(is_identity || is_heads_seq_swap,+ "SDPA: unsupported output_transpose_order ",+ " (only identity and {0,2,1,3} heads<->seq swap are supported)");+ if (is_heads_seq_swap) {+ jit.make("OUTPUT_TRANSPOSE_ORDER_PRESENT", 1);+ jit.make("OUTPUT_TRANSPOSE_0", extended_out_order[0]);+ jit.make("OUTPUT_TRANSPOSE_1", extended_out_order[1]);+ jit.make("OUTPUT_TRANSPOSE_2", extended_out_order[2]);+ jit.make("OUTPUT_TRANSPOSE_3", extended_out_order[3]);+ }+ }}if (unaligned_head_size(k_head_size, v_head_size, subgroup_size)) {diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_opt.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_opt.clindex 5891268d39c..d2dbe58ec77 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_opt.cl+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_opt.cl@@ -18,6 +18,15 @@// max_logits [batch, heads_num, q_len, partition_idx]// tmp_out [batch, heads_num, q_len, partition_idx, head_size]+// When output_transpose_order is non-identity (e.g. {0,2,1,3} heads<->seq swap),+// the physical output buffer is transposed. SDPA_OUTPUT_GET_INDEX remaps logical+// (batch, heads, seq, head_size) indices through the transpose order to physical pitches.+#ifdef OUTPUT_TRANSPOSE_ORDER_PRESENT+ #define SDPA_OUTPUT_GET_INDEX(b, h, s, d) OUTPUT_GET_INDEX(b, s, h, d)+#else+ #define SDPA_OUTPUT_GET_INDEX(b, h, s, d) OUTPUT_GET_INDEX(b, h, s, d)+#endif+inline uint FUNC(get_input0_index_nt)(OPTIONAL_SHAPE_INFO_ARG uint b, uint f, uint w, uint z, uint y, uint x) {#if INPUT0_SIMPLEreturn GET_DATA_INDEX_6D(INPUT0, b, f, w, z, y, x);@@ -922,7 +931,7 @@ KERNEL(sdpa_opt)(} else {const uint seq_idx_end = 1;for (uint seq_idx = 0; seq_idx < seq_idx_end; seq_idx++) {- const uint output_offset = OUTPUT_GET_INDEX(b0_idx, b1_idx, target_seq_idx + seq_idx, head_size_idx);+ const uint output_offset = SDPA_OUTPUT_GET_INDEX(b0_idx, b1_idx, target_seq_idx + seq_idx, head_size_idx);output[output_offset] = acc[seq_idx];}}@@ -2607,8 +2616,12 @@ KERNEL(sdpa_opt)(uint output_offset = block_start_pos * V_HEAD_SIZE * NUM_HEADS + num_heads_dim * V_HEAD_SIZE + sgid * SUBGROUP_SIZE;const uint output_pitch = V_HEAD_SIZE * NUM_HEADS;#else- uint output_offset = OUTPUT_GET_INDEX(b0_idx, b1_idx, target_seq_idx, sgid * SUBGROUP_SIZE);- const uint output_pitch = V_HEAD_SIZE;+ uint output_offset = SDPA_OUTPUT_GET_INDEX(b0_idx, b1_idx, target_seq_idx, sgid * SUBGROUP_SIZE);+#ifdef OUTPUT_TRANSPOSE_ORDER_PRESENT+ const uint output_pitch = V_HEAD_SIZE * NUM_HEADS; // seq stride = FEATURE pitch in [B,S,H,D]+#else+ const uint output_pitch = V_HEAD_SIZE; // seq stride = Y pitch in [B,H,S,D]+#endif#endif#ifdef V_HEAD_SIZE_LEFTOVER@@ -2786,8 +2799,13 @@ KERNEL(sdpa_opt_finalization_stage)(acc += TO_SOFTMAX_ACCUMULATOR_TYPE(out_val) * TO_SOFTMAX_ACCUMULATOR_TYPE(max_logits_u_exp_sum[partition_idx]);}const uint out_offset = b0_idx * (NUM_HEADS * TARGET_SEQ_LEN * V_HEAD_SIZE) ++#ifdef OUTPUT_TRANSPOSE_ORDER_PRESENT+ target_seq_idx * (NUM_HEADS * V_HEAD_SIZE) ++ b1_idx * (V_HEAD_SIZE) ++#elseb1_idx * (TARGET_SEQ_LEN * V_HEAD_SIZE) +target_seq_idx * (V_HEAD_SIZE) ++#endiflocal_id;output[out_offset] = TO_OUTPUT_TYPE(acc) / TO_OUTPUT_TYPE(global_exp_sum);diff --git a/src/plugins/intel_gpu/src/graph/scaled_dot_product_attention.cpp b/src/plugins/intel_gpu/src/graph/scaled_dot_product_attention.cppindex 828ddff651b..461a49ecc12 100644--- a/src/plugins/intel_gpu/src/graph/scaled_dot_product_attention.cpp+++ b/src/plugins/intel_gpu/src/graph/scaled_dot_product_attention.cpp@@ -47,6 +47,8 @@ layout scaled_dot_product_attention_inst::calc_output_layout(scaled_dot_product_desc->input_v_transpose_order);output_shape[output_shape.size() - 1] = v_shape[v_shape.size() - 1];+ output_shape = transpose_shape(output_shape, desc->output_transpose_order);+return { layout{output_shape, output_type, output_format, desc->output_paddings[0]} };}diff --git a/src/plugins/intel_gpu/src/plugin/transformations/sdpa_transpose_fusion.cpp b/src/plugins/intel_gpu/src/plugin/transformations/sdpa_transpose_fusion.cppnew file mode 100644index 00000000000..44ab1e9a0ad--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/transformations/sdpa_transpose_fusion.cpp@@ -0,0 +1,186 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "sdpa_transpose_fusion.hpp"++#include "intel_gpu/op/sdpa.hpp"+#include "openvino/core/rt_info.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/scaled_dot_product_attention.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/pass/pattern/op/or.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "transformations/utils/utils.hpp"++#include <memory>+#include <vector>+#include "openvino/core/graph_util.hpp"+#include "openvino/core/node_vector.hpp"++using ov::pass::pattern::op::Or;++namespace ov::intel_gpu {++/// Compose two transpose orders: first apply `inner`, then `outer`.+/// compose_orders({a,b,c}, {x,y,z}) = {a[inner[x]], a[inner[y]], a[inner[z]]}+static std::vector<int64_t> compose_orders(const std::vector<int64_t>& inner,+ const std::vector<int64_t>& outer) {+ OPENVINO_ASSERT(inner.size() == outer.size());+ std::vector<int64_t> result(inner.size());+ for (size_t i = 0; i < inner.size(); ++i)+ result[i] = inner[outer[i]];+ return result;+}++/// Returns the {0,2,1,3} permutation of `transpose` if it is a rank-4+/// heads<->seq swap with a constant order, otherwise an empty vector.+static std::vector<int64_t> match_heads_seq_swap(const std::shared_ptr<ov::op::v1::Transpose>& transpose) {+ auto order_node =+ ov::as_type_ptr<ov::op::v0::Constant>(transpose->input_value(1).get_node_shared_ptr());+ if (!order_node)+ return {};++ auto order = order_node->cast_vector<int64_t>();+ if (order != std::vector<int64_t>{0, 2, 1, 3})+ return {};++ return order;+}++static bool is_rank_4(const ov::PartialShape& pshape) {+ return pshape.rank().is_static() && pshape.rank().get_length() == 4;+}++SDPATransposeFusion::SDPATransposeFusion() {+ using namespace ov::op;+ using namespace ov::pass::pattern;++ // A single matcher handles both SDPA flavors (MatcherPass supports only one+ // registered matcher):+ //+ // 1. Internal op::SDPA (produced by TransposeSDPAMatcher) followed by+ // Transpose({0,2,1,3}) — absorb the Transpose into output_transpose_order.+ //+ // 2. Framework v13::ScaledDotProductAttention followed by+ // Transpose({0,2,1,3}). TransposeSDPAMatcher converts v13 SDPA to the+ // internal op::SDPA, but it bails out entirely when any input transpose+ // moves the head_size dim (e.g. K preceded by Transpose({0,1,3,2}).+ // In that case the SDPA stays a framework op; convert it here with+ // identity input orders (leaving any input transposes as explicit ops)+ // and absorb the output Transpose into output_transpose_order.+ //+ // Note: the internal op::SDPA derives from v13::ScaledDotProductAttention,+ // so wrap_type<v13::...> would also match internal SDPA nodes and resetting+ // their input orders to identity would corrupt Q/K/V interpretation. The+ // Or alternatives are ordered so that internal SDPA nodes always take the+ // first (op::SDPA) branch.+ auto sdpa_m = wrap_type<ov::intel_gpu::op::SDPA>(consumers_count(1));+ auto sdpa_v13_m = wrap_type<v13::ScaledDotProductAttention>(consumers_count(1));+ auto any_sdpa_m = std::make_shared<Or>(OutputVector{sdpa_m, sdpa_v13_m});+ auto transpose_m = wrap_type<v1::Transpose>({any_sdpa_m, any_input()});++ ov::matcher_pass_callback callback = [=](ov::pass::pattern::Matcher& m) {+ const auto& pattern_map = m.get_pattern_value_map();+ auto transpose = ov::as_type_ptr<v1::Transpose>(+ pattern_map.at(transpose_m).get_node_shared_ptr());+ if (!transpose)+ return false;++ auto order = match_heads_seq_swap(transpose);+ if (order.empty())+ return false;++ std::shared_ptr<ov::Node> sdpa_node;+ std::shared_ptr<ov::intel_gpu::op::SDPA> new_sdpa;++ if (pattern_map.count(sdpa_m) > 0) {+ auto sdpa = ov::as_type_ptr<ov::intel_gpu::op::SDPA>(+ pattern_map.at(sdpa_m).get_node_shared_ptr());+ if (!sdpa || transformation_callback(sdpa))+ return false;++ // Only match rank-4 output.+ if (!is_rank_4(sdpa->get_output_partial_shape(0)))+ return false;++ // Absorb the trailing Transpose into the SDPA's output_transpose_order,+ // but only when that order is still identity. output_transpose_order is set+ // by prior transpose fusion around the SDPA (TransposeFusion fuses input+ // transposes; this pass is the only producer of a non-identity *output*+ // order). A non-identity output order therefore means the output layout was+ // already customized, and composing the Transpose again would double-apply+ // the permutation and mislayout the result. This is a layout invariant on+ // output_transpose_order+ auto cur_out_order = sdpa->get_output_transpose_order();+ for (size_t i = 0; i < cur_out_order.size(); ++i) {+ if (cur_out_order[i] != static_cast<int64_t>(i))+ return false;+ }+ auto new_out_order = compose_orders(cur_out_order, order);++ // Build replacement SDPA preserving the original's compression state.+ if (sdpa->get_kv_compressed()) {+ new_sdpa = std::make_shared<ov::intel_gpu::op::SDPA>(+ sdpa->input_values(),+ sdpa->get_causal(),+ sdpa->get_input0_transpose_order(),+ sdpa->get_input1_transpose_order(),+ sdpa->get_input2_transpose_order(),+ new_out_order,+ sdpa->get_quantization_attrs(),+ sdpa->get_output_type());+ } else {+ new_sdpa = std::make_shared<ov::intel_gpu::op::SDPA>(+ sdpa->input_values(),+ sdpa->get_causal(),+ sdpa->get_input0_transpose_order(),+ sdpa->get_input1_transpose_order(),+ sdpa->get_input2_transpose_order(),+ new_out_order,+ sdpa->get_output_type());+ }+ sdpa_node = sdpa;+ } else {+ auto sdpa = ov::as_type_ptr<v13::ScaledDotProductAttention>(+ pattern_map.at(sdpa_v13_m).get_node_shared_ptr());+ if (!sdpa || transformation_callback(sdpa))+ return false;++ // Only match rank-4 inputs/output.+ if (!is_rank_4(sdpa->get_output_partial_shape(0)))+ return false;+ for (size_t i = 0; i < 3; ++i) {+ if (!is_rank_4(sdpa->get_input_partial_shape(i)))+ return false;+ }++ // Keep identity input orders and only absorb the output Transpose.+ new_sdpa = std::make_shared<ov::intel_gpu::op::SDPA>(+ sdpa->input_values(),+ sdpa->get_causal(),+ ov::intel_gpu::op::SDPA::default_order(4),+ ov::intel_gpu::op::SDPA::default_order(4),+ ov::intel_gpu::op::SDPA::default_order(4),+ compose_orders(ov::intel_gpu::op::SDPA::default_order(4), order));+ sdpa_node = sdpa;+ }++ new_sdpa->set_friendly_name(sdpa_node->get_friendly_name());+ ov::copy_runtime_info(ov::NodeVector{sdpa_node, transpose}, new_sdpa);++ // Replace the SDPA node, then rewire Transpose consumers to the new+ // SDPA output (bypassing the now-dead Transpose).+ ov::replace_node(sdpa_node, new_sdpa);+ ov::replace_output_update_name(transpose->output(0),+ transpose->input_value(0));++ return true;+ };++ auto m = std::make_shared<ov::pass::pattern::Matcher>(transpose_m,+ "SDPATransposeFusion");+ this->register_matcher(m, callback);+}++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/plugin/transformations/sdpa_transpose_fusion.hpp b/src/plugins/intel_gpu/src/plugin/transformations/sdpa_transpose_fusion.hppnew file mode 100644index 00000000000..5c6c2d441b8--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/transformations/sdpa_transpose_fusion.hpp@@ -0,0 +1,45 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/graph_rewrite.hpp"++namespace ov::intel_gpu {++/// @brief Absorbs a Transpose({0,2,1,3}) following an SDPA into the SDPA's+/// output_transpose_order.+///+/// When an SDPA op is followed by a Transpose that swaps the heads and sequence+/// dimensions (axes 1 and 2 in a 4-D [b,h,seq,d] tensor), the Transpose can be+/// eliminated by composing it into the SDPA's output_transpose_order. Writing the+/// currently-absorbed order explicitly ({0,1,2,3} is the identity, i.e. nothing+/// absorbed yet, so out_order ∘ {0,1,2,3} == out_order):+///+/// SDPA(out_order ∘ {0,1,2,3}) → Transpose({0,2,1,3})+/// becomes+/// SDPA(out_order ∘ {0,2,1,3})+///+/// i.e. the {0,2,1,3} from the external Transpose replaces the identity in the+/// composition slot. (In this pass out_order is always the identity, so the+/// result is simply SDPA({0,2,1,3}).)+///+/// A second matcher handles framework v13::ScaledDotProductAttention ops that+/// were never converted to the internal op::SDPA (e.g. TransposeSDPAMatcher+/// bails when an input transpose moves the head_size dim, such as K preceded+/// by Transpose({0,1,3,2}). Those are converted to op::SDPA with+/// identity input orders, absorbing only the output Transpose. (The input+/// transposes are intentionally left standalone: absorbing a head_size-moving+/// transpose into the SDPA is correct but slower, as the kernel would then read+/// the input with a strided, non-contiguous head_size access pattern.)+///+/// This avoids a separate Permute kernel on GPU without changing the numerical+/// result.+class SDPATransposeFusion : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("SDPATransposeFusion");+ SDPATransposeFusion();+};++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cppindex 7c830adc809..ff98f467329 100644--- a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp+++ b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp@@ -115,6 +115,7 @@#include "plugin/transformations/reduce_fc_dimensions.hpp"#include "plugin/transformations/sink_reshape.hpp"#include "plugin/transformations/transpose_fusion.hpp"+#include "plugin/transformations/sdpa_transpose_fusion.hpp"#include "plugin/transformations/unsqueeze_broadcast_reshape_matmul_fusion.hpp"#include "plugin/transformations/unsqueeze_broadcast_reshape_sdpa_fusion.hpp"#include "plugin/transformations/disable_fp16_comp_rms.hpp"@@ -1640,6 +1641,9 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {manager.register_pass<ov::intel_gpu::KVCacheFusion>();manager.register_pass<ov::intel_gpu::FullyConnectedConvertFusion>();manager.register_pass<ov::intel_gpu::TransposeFusion>(device_info.supports_immad);+ // Absorb a trailing Transpose({0,2,1,3}) into the SDPA output order so+ // the attention output-projection FC reads a contiguous [S, H*D] input.+ manager.register_pass<ov::intel_gpu::SDPATransposeFusion>();if (!device_info.supports_immad) {manager.register_pass<ov::intel_gpu::UnsqueezeBroadcastReshapeMatmulFusion>();diff --git a/src/plugins/intel_gpu/tests/functional/single_layer_tests/dynamic/sdpa_transpose_fusion.cpp b/src/plugins/intel_gpu/tests/functional/single_layer_tests/dynamic/sdpa_transpose_fusion.cppnew file mode 100644index 00000000000..36aeac506fc--- /dev/null+++ b/src/plugins/intel_gpu/tests/functional/single_layer_tests/dynamic/sdpa_transpose_fusion.cpp@@ -0,0 +1,288 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "common_test_utils/ov_tensor_utils.hpp"+#include "common_test_utils/test_enums.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/result.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/opsets/opset13_decl.hpp"+#include "openvino/pass/manager.hpp"+#include "shared_test_classes/base/ov_subgraph.hpp"+#include "transformations/op_conversions/scaled_dot_product_attention_decomposition.hpp"++namespace {++using ov::test::InputShape;++struct SDPATransposeFusionGPUTestParams {+ ov::element::Type netPrecision;+ std::vector<InputShape> inputShapes; // Q, K, V (logical shapes)+ bool is_causal;+ std::vector<std::vector<int64_t>> input_transpose_orders; // per-input transpose (empty = identity)+ std::vector<int64_t> output_transpose_order; // {0,2,1,3} or empty for no-transpose+ bool expect_transpose_removed; // true if the pass should remove the Transpose+};++class SDPATransposeFusionGPUTest : public testing::WithParamInterface<SDPATransposeFusionGPUTestParams>,+ virtual public ov::test::SubgraphBaseTest {+public:+ static std::string getTestCaseName(const testing::TestParamInfo<SDPATransposeFusionGPUTestParams>& obj);++protected:+ void SetUp() override;+ void generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) override;+ bool expect_transpose_removed;+};++std::string SDPATransposeFusionGPUTest::getTestCaseName(+ const testing::TestParamInfo<SDPATransposeFusionGPUTestParams>& obj) {+ const auto& p = obj.param;+ std::ostringstream result;+ result << "netPRC=" << p.netPrecision << "_";+ result << "IS=";+ for (const auto& inputShape : p.inputShapes) {+ result << ov::test::utils::partialShape2str({inputShape.first}) << "_";+ }+ result << "causal=" << p.is_causal << "_";+ bool has_input_tp = !p.input_transpose_orders.empty() &&+ std::any_of(p.input_transpose_orders.begin(), p.input_transpose_orders.end(),+ [](const std::vector<int64_t>& o) { return !o.empty(); });+ if (has_input_tp) {+ result << "input_transpose_";+ for (const auto& o : p.input_transpose_orders) {+ for (auto v : o)+ result << v;+ result << ".";+ }+ result << "_";+ } else {+ result << "no_input_transpose_";+ }+ if (p.output_transpose_order.empty()) {+ result << "no_output_transpose_";+ } else {+ result << "output_transpose_";+ for (auto v : p.output_transpose_order)+ result << v;+ result << "_";+ }+ result << "expect_fused=" << p.expect_transpose_removed;+ return result.str();+}++void SDPATransposeFusionGPUTest::SetUp() {+ const auto& p = this->GetParam();+ targetDevice = ov::test::utils::DEVICE_GPU;+ expect_transpose_removed = p.expect_transpose_removed;++ // Permute the declared input shapes to match the input Transpose ops, so the+ // Parameters hold the physical (pre-transpose) layout while the SDPA consumes+ // the logical [B,H,S,D] layout (mirrors scaled_dot_product_attention.cpp).+ auto inputShapes = p.inputShapes;+ auto transpose_pshape = [](InputShape& pshapes, const std::vector<int64_t>& order) {+ auto transposed_pshape = ov::PartialShape::dynamic(pshapes.first.rank());+ std::vector<ov::Shape> transposed_cshapes(pshapes.second);+ auto& pshape = pshapes.first;+ auto& cshape = pshapes.second;+ for (size_t i = 0; i < order.size(); i++) {+ transposed_pshape[i] = pshape[order[i]];+ for (size_t j = 0; j < cshape.size(); j++) {+ transposed_cshapes[j][i] = cshape[j][order[i]];+ }+ }+ for (size_t i = 0; i < order.size(); i++) {+ pshape[i] = transposed_pshape[i];+ for (size_t j = 0; j < cshape.size(); j++) {+ cshape[j][i] = transposed_cshapes[j][i];+ }+ }+ };+ if (!p.input_transpose_orders.empty()) {+ for (size_t i = 0; i < p.input_transpose_orders.size() && i < inputShapes.size(); i++) {+ if (!p.input_transpose_orders[i].empty())+ transpose_pshape(inputShapes[i], p.input_transpose_orders[i]);+ }+ }+ init_input_shapes(inputShapes);++ ov::ParameterVector inputParams;+ for (size_t i = 0; i < 3; i++) {+ inputParams.push_back(std::make_shared<ov::op::v0::Parameter>(p.netPrecision, inputDynamicShapes[i]));+ }+ inputParams[0]->set_friendly_name("q");+ inputParams[1]->set_friendly_name("k");+ inputParams[2]->set_friendly_name("v");++ // Optionally transpose Q/K/V before the SDPA. These are fused into the internal+ // op::SDPA input_transpose_order by TransposeSDPAMatcher (pattern 1), so the+ // SDPA + output-Transpose fusion runs with non-identity input orders.+ ov::OutputVector sdpa_inputs;+ for (size_t i = 0; i < 3; i++) {+ if (!p.input_transpose_orders.empty() && !p.input_transpose_orders[i].empty()) {+ auto order_const = ov::op::v0::Constant::create(+ ov::element::i64,+ ov::Shape{p.input_transpose_orders[i].size()},+ p.input_transpose_orders[i]);+ auto in_tp = std::make_shared<ov::op::v1::Transpose>(inputParams[i], order_const);+ in_tp->set_friendly_name("input_transpose_" + std::to_string(i));+ sdpa_inputs.push_back(in_tp);+ } else {+ sdpa_inputs.push_back(inputParams[i]);+ }+ }++ auto sdpa = std::make_shared<ov::opset13::ScaledDotProductAttention>(+ sdpa_inputs[0], sdpa_inputs[1], sdpa_inputs[2], p.is_causal);+ sdpa->set_friendly_name("sdpa");++ // Apply output Transpose if order is specified+ ov::Output<ov::Node> final_output = sdpa;+ if (!p.output_transpose_order.empty()) {+ auto order_const = ov::op::v0::Constant::create(+ ov::element::i64,+ ov::Shape{p.output_transpose_order.size()},+ p.output_transpose_order);+ auto out_tp = std::make_shared<ov::op::v1::Transpose>(sdpa, order_const);+ out_tp->set_friendly_name("output_transpose");+ final_output = out_tp;+ }++ auto result = std::make_shared<ov::op::v0::Result>(final_output);+ function = std::make_shared<ov::Model>(ov::OutputVector{result}, inputParams, "sdpa_transpose_fusion_model");++ // Reference: decompose SDPA (with the same Transpose if present)+ functionRefs = function->clone();+ ov::pass::Manager manager;+ manager.register_pass<ov::pass::ScaledDotProductAttentionDecomposition>();+ manager.run_passes(functionRefs);++ // Relax tolerances for FP16 GPU inference+ if (p.netPrecision == ov::element::f16) {+ abs_threshold = 0.015;+ rel_threshold = 0.015;+ }+}++void SDPATransposeFusionGPUTest::generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) {+ const auto& model_inputs = function->inputs();+ inputs.clear();+ const auto netPrecision = model_inputs[0].get_element_type();+ ov::test::utils::InputGenerateData data(0, 8, 32);+ for (int i = 0; i < 3; ++i) {+ ov::Tensor data_tensor =+ ov::test::utils::create_and_fill_tensor(netPrecision, targetInputStaticShapes[i], data);+ inputs.insert({model_inputs[i].get_node_shared_ptr(), data_tensor});+ }+}++TEST_P(SDPATransposeFusionGPUTest, CompareWithRefs) {+ run();+}++TEST_P(SDPATransposeFusionGPUTest, CheckTransposeRemoved) {+ run();++ if (!expect_transpose_removed)+ GTEST_SKIP() << "This configuration is not expected to have the Transpose fused.";++ // Verify the output Transpose was absorbed into the SDPA output_transpose_order.+ // After fusion, the runtime model should have no Transpose or Permute between+ // the SDPA and the Result node.+ auto runtime_model = compiledModel.get_runtime_model();+ for (const auto& node : runtime_model->get_ordered_ops()) {+ const auto& rt_info = node->get_rt_info();+ const auto layer_type_it = rt_info.find("layerType");+ if (layer_type_it != rt_info.end()) {+ const auto layer_type = layer_type_it->second.as<std::string>();+ EXPECT_NE(layer_type, "Transpose")+ << "Transpose should have been fused into SDPA output_transpose_order";+ EXPECT_NE(layer_type, "Permute")+ << "Permute should have been fused into SDPA output_transpose_order";+ }+ }+}++// ── Test cases ──────────────────────────────────────────────────────────────++// Static 4-D shapes: [B, H, S, D] — most common path+const std::vector<InputShape> static_4d_small = {+ {ov::PartialShape{2, 8, 64, 64}, {ov::Shape{2, 8, 64, 64}}}, // Q+ {ov::PartialShape{2, 8, 64, 64}, {ov::Shape{2, 8, 64, 64}}}, // K+ {ov::PartialShape{2, 8, 64, 64}, {ov::Shape{2, 8, 64, 64}}}, // V+};++const std::vector<InputShape> static_4d_large = {+ {ov::PartialShape{1, 16, 384, 72}, {ov::Shape{1, 16, 384, 72}}}, // Q+ {ov::PartialShape{1, 16, 384, 72}, {ov::Shape{1, 16, 384, 72}}}, // K+ {ov::PartialShape{1, 16, 384, 72}, {ov::Shape{1, 16, 384, 72}}}, // V+};++// Non-causal + output Transpose — same head count+const std::vector<InputShape> static_4d_non_causal = {+ {ov::PartialShape{1, 8, 128, 64}, {ov::Shape{1, 8, 128, 64}}}, // Q+ {ov::PartialShape{1, 8, 128, 64}, {ov::Shape{1, 8, 128, 64}}}, // K+ {ov::PartialShape{1, 8, 128, 64}, {ov::Shape{1, 8, 128, 64}}}, // V+};++// Non-matching transpose — pass should NOT fuse, but output must still be numerically correct.+// Cover the guard: only {0,2,1,3} is absorbed; any other order must stay as a standalone Transpose.+const std::vector<InputShape> static_4d_wrong_tp = {+ {ov::PartialShape{2, 8, 64, 64}, {ov::Shape{2, 8, 64, 64}}}, // Q+ {ov::PartialShape{2, 8, 64, 64}, {ov::Shape{2, 8, 64, 64}}}, // K+ {ov::PartialShape{2, 8, 64, 64}, {ov::Shape{2, 8, 64, 64}}}, // V+};++INSTANTIATE_TEST_SUITE_P(+ SDPATransposeFusion_Fused,+ SDPATransposeFusionGPUTest,+ testing::Values(+ // Small static: causal + output Transpose{0,2,1,3}+ SDPATransposeFusionGPUTestParams{ov::element::f16, static_4d_small, false, {}, {0, 2, 1, 3}, true},+ SDPATransposeFusionGPUTestParams{ov::element::f16, static_4d_small, true, {}, {0, 2, 1, 3}, true},+ // Large static: causal + output Transpose+ SDPATransposeFusionGPUTestParams{ov::element::f16, static_4d_large, true, {}, {0, 2, 1, 3}, true},+ // Non-causal + output Transpose+ SDPATransposeFusionGPUTestParams{ov::element::f16, static_4d_non_causal, false, {}, {0, 2, 1, 3}, true},+ // Pattern-1 with non-identity QKV input orders+ SDPATransposeFusionGPUTestParams{ov::element::f16, static_4d_small, false,+ {{0, 2, 1, 3}, {0, 2, 1, 3}, {0, 2, 1, 3}}, {0, 2, 1, 3}, true},+ SDPATransposeFusionGPUTestParams{ov::element::f16, static_4d_small, true,+ {{0, 2, 1, 3}, {0, 2, 1, 3}, {0, 2, 1, 3}}, {0, 2, 1, 3}, true},+ // Mixed input orders (Q/K/V use different non-identity permutations)+ SDPATransposeFusionGPUTestParams{ov::element::f16, static_4d_small, false,+ {{0, 2, 1, 3}, {0, 1, 2, 3}, {0, 2, 1, 3}}, {0, 2, 1, 3}, true}+ ),+ SDPATransposeFusionGPUTest::getTestCaseName);++// Baseline: same configurations WITHOUT the output Transpose+// These ensure the SDPA itself works correctly in all variants.+INSTANTIATE_TEST_SUITE_P(+ SDPATransposeFusion_Baseline,+ SDPATransposeFusionGPUTest,+ testing::Values(+ SDPATransposeFusionGPUTestParams{ov::element::f16, static_4d_small, false, {}, {}, false},+ SDPATransposeFusionGPUTestParams{ov::element::f16, static_4d_small, true, {}, {}, false},+ SDPATransposeFusionGPUTestParams{ov::element::f16, static_4d_large, true, {}, {}, false},+ SDPATransposeFusionGPUTestParams{ov::element::f16, static_4d_non_causal, false, {}, {}, false}+ ),+ SDPATransposeFusionGPUTest::getTestCaseName);++// Non-matching transpose orders — pass must NOT fuse, but output+// must still match the decomposed CPU reference exactly.+INSTANTIATE_TEST_SUITE_P(+ SDPATransposeFusion_NotFused,+ SDPATransposeFusionGPUTest,+ testing::Values(+ // {0,3,1,2} — not the heads<->seq swap, must stay as standalone Transpose+ SDPATransposeFusionGPUTestParams{ov::element::f16, static_4d_wrong_tp, false, {}, {0, 3, 1, 2}, false},+ // {0,1,3,2} — head_size-moving, must stay+ SDPATransposeFusionGPUTestParams{ov::element::f16, static_4d_wrong_tp, false, {}, {0, 1, 3, 2}, false},+ // {1,0,2,3} — batch-head swap, must stay+ SDPATransposeFusionGPUTestParams{ov::element::f16, static_4d_wrong_tp, false, {}, {1, 0, 2, 3}, false}+ ),+ SDPATransposeFusionGPUTest::getTestCaseName);++} // namespacediff --git a/src/plugins/intel_gpu/tests/unit/transformations/sdpa_transpose_fusion_test.cpp b/src/plugins/intel_gpu/tests/unit/transformations/sdpa_transpose_fusion_test.cppnew file mode 100644index 00000000000..174c98f7aeb--- /dev/null+++ b/src/plugins/intel_gpu/tests/unit/transformations/sdpa_transpose_fusion_test.cpp@@ -0,0 +1,407 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "common_test_utils/ov_test_utils.hpp"++#include "intel_gpu/op/sdpa.hpp"+#include "openvino/core/model.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/result.hpp"+#include "openvino/op/scaled_dot_product_attention.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/pass/manager.hpp"+#include "plugin/transformations/sdpa_transpose_fusion.hpp"++#include <memory>+#include <vector>++using namespace testing;+using namespace ov::intel_gpu;++namespace ov {+namespace test {+namespace intel_gpu {++// ---------------------------------------------------------------------------+// helpers+// ---------------------------------------------------------------------------++static std::shared_ptr<ov::op::v1::Transpose> make_transpose(const ov::Output<ov::Node>& input,+ const std::vector<int64_t>& order) {+ auto order_c = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{order.size()}, order);+ return std::make_shared<ov::op::v1::Transpose>(input, order_c);+}++static std::shared_ptr<ov::intel_gpu::op::SDPA> make_internal_sdpa(+ const ov::Output<ov::Node>& q,+ const ov::Output<ov::Node>& k,+ const ov::Output<ov::Node>& v,+ bool causal,+ const std::vector<int64_t>& in0_order,+ const std::vector<int64_t>& in1_order,+ const std::vector<int64_t>& in2_order,+ const std::vector<int64_t>& out_order) {+ return std::make_shared<ov::intel_gpu::op::SDPA>(ov::OutputVector{q, k, v},+ causal,+ in0_order,+ in1_order,+ in2_order,+ out_order,+ ov::element::dynamic);+}++// Symmetric KV-cache-compressed internal op::SDPA: QKV + 2 scale inputs.+static std::shared_ptr<ov::intel_gpu::op::SDPA> make_internal_sdpa_compressed(+ const ov::Output<ov::Node>& q,+ const ov::Output<ov::Node>& k,+ const ov::Output<ov::Node>& v,+ const ov::Output<ov::Node>& k_scale,+ const ov::Output<ov::Node>& v_scale,+ bool causal,+ const std::vector<int64_t>& in0_order,+ const std::vector<int64_t>& in1_order,+ const std::vector<int64_t>& in2_order,+ const std::vector<int64_t>& out_order) {+ ov::intel_gpu::op::SDPA::QuantizationAttribute qattr;+ qattr.quantization_type = ov::op::internal::DynamicQuantize::QuantizationType::Symmetric;+ qattr.quantization_dt = ov::element::i8;+ qattr.scale_dt = ov::element::f16;+ qattr.output_storage_type = ov::op::internal::DynamicQuantize::OutputStorageType::Planar;+ qattr.group_sizes = {1, 1, 1, UINT64_MAX};+ qattr.scales_zp_output_order = {0, 1, 2, 3};+ return std::make_shared<ov::intel_gpu::op::SDPA>(ov::OutputVector{q, k, v, k_scale, v_scale},+ causal,+ in0_order,+ in1_order,+ in2_order,+ out_order,+ qattr,+ ov::element::dynamic);+}++// ---------------------------------------------------------------------------+// 1. Internal op::SDPA (identity output order) + Transpose({0,2,1,3})+// → SDPA with output_order = {0,2,1,3}, Transpose eliminated.+// ---------------------------------------------------------------------------+TEST_F(TransformationTestsF, SDPATransposeFusion_InternalSDPA_OutputTransposeFused) {+ const bool causal = false;+ const std::vector<int64_t> identity{0, 1, 2, 3};+ const std::vector<int64_t> swap_hs{0, 2, 1, 3};++ {+ auto q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto sdpa = make_internal_sdpa(q, k, v, causal, identity, identity, identity, identity);+ auto out_tp = make_transpose(sdpa, swap_hs);++ model = std::make_shared<ov::Model>(ov::OutputVector{out_tp}, ov::ParameterVector{q, k, v});+ manager.register_pass<SDPATransposeFusion>();+ }+ {+ auto q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ // Transpose absorbed: output order becomes {0,2,1,3}+ auto sdpa = make_internal_sdpa(q, k, v, causal, identity, identity, identity, swap_hs);++ model_ref = std::make_shared<ov::Model>(ov::OutputVector{sdpa}, ov::ParameterVector{q, k, v});+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ }+}++// ---------------------------------------------------------------------------+// 2. Internal op::SDPA (identity output order) + Transpose({0,2,1,3})+// causal=true variant — same fusion should apply regardless of causal flag.+// ---------------------------------------------------------------------------+TEST_F(TransformationTestsF, SDPATransposeFusion_InternalSDPA_Causal_OutputTransposeFused) {+ const bool causal = true;+ const std::vector<int64_t> identity{0, 1, 2, 3};+ const std::vector<int64_t> swap_hs{0, 2, 1, 3};++ {+ auto q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto sdpa = make_internal_sdpa(q, k, v, causal, identity, identity, identity, identity);+ auto out_tp = make_transpose(sdpa, swap_hs);++ model = std::make_shared<ov::Model>(ov::OutputVector{out_tp}, ov::ParameterVector{q, k, v});+ manager.register_pass<SDPATransposeFusion>();+ }+ {+ auto q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto sdpa = make_internal_sdpa(q, k, v, causal, identity, identity, identity, swap_hs);++ model_ref = std::make_shared<ov::Model>(ov::OutputVector{sdpa}, ov::ParameterVector{q, k, v});+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ }+}++// ---------------------------------------------------------------------------+// 3. Internal op::SDPA with non-identity output order already set+// → must NOT fuse (pass guards against double-applying).+// ---------------------------------------------------------------------------+TEST_F(TransformationTestsF, SDPATransposeFusion_InternalSDPA_NonIdentityOutputOrder_NoFusion) {+ const bool causal = false;+ const std::vector<int64_t> identity{0, 1, 2, 3};+ const std::vector<int64_t> custom_out{0, 2, 1, 3}; // already non-identity+ const std::vector<int64_t> swap_hs{0, 2, 1, 3};++ {+ auto q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ // SDPA already has a non-identity output order+ auto sdpa = make_internal_sdpa(q, k, v, causal, identity, identity, identity, custom_out);+ auto out_tp = make_transpose(sdpa, swap_hs);++ model = std::make_shared<ov::Model>(ov::OutputVector{out_tp}, ov::ParameterVector{q, k, v});+ manager.register_pass<SDPATransposeFusion>();+ }+ {+ // Graph must be unchanged — reference equals input+ auto q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto sdpa = make_internal_sdpa(q, k, v, causal, identity, identity, identity, custom_out);+ auto out_tp = make_transpose(sdpa, swap_hs);++ model_ref = std::make_shared<ov::Model>(ov::OutputVector{out_tp}, ov::ParameterVector{q, k, v});+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ }+}++// ---------------------------------------------------------------------------+// 4. Internal op::SDPA followed by a non-{0,2,1,3} Transpose+// → must NOT fuse (only the heads<->seq swap is absorbed).+// ---------------------------------------------------------------------------+TEST_F(TransformationTestsF, SDPATransposeFusion_InternalSDPA_WrongTransposeOrder_NoFusion) {+ const bool causal = false;+ const std::vector<int64_t> identity{0, 1, 2, 3};+ const std::vector<int64_t> wrong_order{0, 3, 1, 2}; // not the heads<->seq swap++ {+ auto q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto sdpa = make_internal_sdpa(q, k, v, causal, identity, identity, identity, identity);+ auto out_tp = make_transpose(sdpa, wrong_order);++ model = std::make_shared<ov::Model>(ov::OutputVector{out_tp}, ov::ParameterVector{q, k, v});+ manager.register_pass<SDPATransposeFusion>();+ }+ {+ auto q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto sdpa = make_internal_sdpa(q, k, v, causal, identity, identity, identity, identity);+ auto out_tp = make_transpose(sdpa, wrong_order);++ model_ref = std::make_shared<ov::Model>(ov::OutputVector{out_tp}, ov::ParameterVector{q, k, v});+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ }+}++// ---------------------------------------------------------------------------+// 5. Framework v13::ScaledDotProductAttention + Transpose({0,2,1,3})+// → converted to internal op::SDPA with identity input orders and+// output_order = {0,2,1,3}.+// ---------------------------------------------------------------------------+TEST_F(TransformationTestsF, SDPATransposeFusion_V13SDPA_OutputTransposeFused) {+ const bool causal = false;+ const std::vector<int64_t> identity{0, 1, 2, 3};+ const std::vector<int64_t> swap_hs{0, 2, 1, 3};++ {+ auto q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(q, k, v, causal);+ auto out_tp = make_transpose(sdpa, swap_hs);++ model = std::make_shared<ov::Model>(ov::OutputVector{out_tp}, ov::ParameterVector{q, k, v});+ manager.register_pass<SDPATransposeFusion>();+ }+ {+ auto q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ // v13 SDPA promoted to internal SDPA with identity input orders;+ // output Transpose absorbed into output_order.+ auto sdpa = make_internal_sdpa(q, k, v, causal, identity, identity, identity, swap_hs);++ model_ref = std::make_shared<ov::Model>(ov::OutputVector{sdpa}, ov::ParameterVector{q, k, v});+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ }+}++// ---------------------------------------------------------------------------+// 6. Framework v13::SDPA + causal + Transpose({0,2,1,3})+// ---------------------------------------------------------------------------+TEST_F(TransformationTestsF, SDPATransposeFusion_V13SDPA_Causal_OutputTransposeFused) {+ const bool causal = true;+ const std::vector<int64_t> identity{0, 1, 2, 3};+ const std::vector<int64_t> swap_hs{0, 2, 1, 3};++ {+ auto q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(q, k, v, causal);+ auto out_tp = make_transpose(sdpa, swap_hs);++ model = std::make_shared<ov::Model>(ov::OutputVector{out_tp}, ov::ParameterVector{q, k, v});+ manager.register_pass<SDPATransposeFusion>();+ }+ {+ auto q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto sdpa = make_internal_sdpa(q, k, v, causal, identity, identity, identity, swap_hs);++ model_ref = std::make_shared<ov::Model>(ov::OutputVector{sdpa}, ov::ParameterVector{q, k, v});+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ }+}++// ---------------------------------------------------------------------------+// 7. Framework v13::SDPA with input Transposes + Transpose({0,2,1,3}) on output.+// Input transposes must be left standalone; only the output is absorbed.+// ---------------------------------------------------------------------------+TEST_F(TransformationTestsF, SDPATransposeFusion_V13SDPA_WithInputTransposes_OnlyOutputFused) {+ const bool causal = false;+ const std::vector<int64_t> identity{0, 1, 2, 3};+ const std::vector<int64_t> swap_hs{0, 2, 1, 3};+ const std::vector<int64_t> k_perm{0, 1, 3, 2}; // head_size-moving — must stay explicit++ {+ auto q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto q_tp = make_transpose(q, swap_hs);+ auto k_tp = make_transpose(k, k_perm);+ auto sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(q_tp, k_tp, v, causal);+ auto out_tp = make_transpose(sdpa, swap_hs);++ model = std::make_shared<ov::Model>(ov::OutputVector{out_tp}, ov::ParameterVector{q, k, v});+ manager.register_pass<SDPATransposeFusion>();+ }+ {+ auto q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ // Input transposes stay explicit; output Transpose absorbed into SDPA.+ auto q_tp = make_transpose(q, swap_hs);+ auto k_tp = make_transpose(k, k_perm);+ auto sdpa = make_internal_sdpa(q_tp, k_tp, v, causal, identity, identity, identity, swap_hs);++ model_ref = std::make_shared<ov::Model>(ov::OutputVector{sdpa}, ov::ParameterVector{q, k, v});+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ }+}++// ---------------------------------------------------------------------------+// 8. Framework v13::SDPA with no output Transpose+// → no fusion, graph unchanged.+// ---------------------------------------------------------------------------+TEST_F(TransformationTestsF, SDPATransposeFusion_V13SDPA_NoOutputTranspose_NoFusion) {+ const bool causal = false;++ {+ auto q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(q, k, v, causal);++ model = std::make_shared<ov::Model>(ov::OutputVector{sdpa}, ov::ParameterVector{q, k, v});+ manager.register_pass<SDPATransposeFusion>();+ }+ {+ auto q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(q, k, v, causal);++ model_ref = std::make_shared<ov::Model>(ov::OutputVector{sdpa}, ov::ParameterVector{q, k, v});+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ }+}++// ---------------------------------------------------------------------------+// 9. Internal op::SDPA with non-identity input orders + Transpose({0,2,1,3})+// Input orders must be preserved after fusion.+// ---------------------------------------------------------------------------+TEST_F(TransformationTestsF, SDPATransposeFusion_InternalSDPA_NonIdentityInputOrders_Preserved) {+ const bool causal = false;+ const std::vector<int64_t> swap_hs{0, 2, 1, 3};+ const std::vector<int64_t> q_order{0, 2, 1, 3};+ const std::vector<int64_t> k_order{0, 2, 3, 1};+ const std::vector<int64_t> v_order{0, 1, 2, 3};++ {+ auto q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto sdpa = make_internal_sdpa(q, k, v, causal, q_order, k_order, v_order, {0, 1, 2, 3});+ auto out_tp = make_transpose(sdpa, swap_hs);++ model = std::make_shared<ov::Model>(ov::OutputVector{out_tp}, ov::ParameterVector{q, k, v});+ manager.register_pass<SDPATransposeFusion>();+ }+ {+ auto q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ // Input orders preserved; output order absorbs the Transpose.+ auto sdpa = make_internal_sdpa(q, k, v, causal, q_order, k_order, v_order, swap_hs);++ model_ref = std::make_shared<ov::Model>(ov::OutputVector{sdpa}, ov::ParameterVector{q, k, v});+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ }+}++// ---------------------------------------------------------------------------+// 10. Internal op::SDPA (first pattern) that is KV-cache compressed ++// Transpose({0,2,1,3}). Exercises the sdpa->get_kv_compressed() branch:+// the replacement must preserve the compression state / quantization attrs+// and the extra scale inputs, input orders preserved, output order absorbed.+// ---------------------------------------------------------------------------+TEST_F(TransformationTestsF, SDPATransposeFusion_InternalSDPA_KvCompressed_Preserved) {+ const bool causal = false;+ const std::vector<int64_t> identity{0, 1, 2, 3};+ const std::vector<int64_t> swap_hs{0, 2, 1, 3};++ {+ auto q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto ks = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape::dynamic(4));+ auto vs = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape::dynamic(4));+ auto sdpa = make_internal_sdpa_compressed(q, k, v, ks, vs, causal, identity, identity, identity, identity);+ auto out_tp = make_transpose(sdpa, swap_hs);++ model = std::make_shared<ov::Model>(ov::OutputVector{out_tp}, ov::ParameterVector{q, k, v, ks, vs});+ manager.register_pass<SDPATransposeFusion>();+ }+ {+ auto q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));+ auto ks = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape::dynamic(4));+ auto vs = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape::dynamic(4));+ // Compression state + scale inputs preserved; output order absorbs the Transpose.+ auto sdpa = make_internal_sdpa_compressed(q, k, v, ks, vs, causal, identity, identity, identity, swap_hs);++ model_ref = std::make_shared<ov::Model>(ov::OutputVector{sdpa}, ov::ParameterVector{q, k, v, ks, vs});+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ }+}++} // namespace intel_gpu+} // namespace test+} // namespace ov