Skip to content

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

[GPU] Eliminate unnecessary Permute and Crop primitive execution from QWen-VL Vision Merger and QWen-Omni Vision Encoder with TransposeSplitMatcher (#36246)

cecilia peng3f24992895e4
diff --git a/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_buffer_fusing.cpp b/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_buffer_fusing.cpp
index 2b729580d0a..3f6e0059907 100644
--- a/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_buffer_fusing.cpp
+++ b/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_buffer_fusing.cpp
@@ -620,9 +620,11 @@ bool crop_in_place_optimization::optimize(crop_node& node) {
// crop output buffer
// |_low_pad_|__data_size__|___|<-upper pad
if (!node.is_dynamic() && can_crop_be_optimized_along_feature(crop_layout, input_layout)) {
+ std::pair<const program_node*, layout> user_info;
update_in_place_crop_padding_along_feature(node,
crop_layout,
input_layout,
+ user_info,
crop_params->input_offsets[0],
node.get_primitive()->axis,
false);
@@ -657,6 +659,7 @@ bool crop_in_place_optimization::optimize(crop_node& node) {
void crop_in_place_optimization::update_in_place_crop_padding_along_feature(const program_node& node,
layout& crop_layout,
layout& input_layout,
+ std::pair<const program_node*, layout>& user_info,
const tensor offsets,
size_t crop_axis,
bool is_runtime) {
@@ -697,6 +700,88 @@ void crop_in_place_optimization::update_in_place_crop_padding_along_feature(cons
padding::DynamicDimsMask dyn_pad_sizes;
dyn_pad_sizes[crop_axis] = true;
crop_layout.data_padding = padding(lower_sizes, upper_sizes, dyn_pad_sizes);
+
+ // Explicitly propagate the crop's feature-axis padding into the
+ // reshape output layout. reshape_inst::calc_output_layouts resets
+ // padding to empty for reshape_mode::base, so relying on a follow-up
+ // reshape_inst->update_shape() call would drop the padding silently.
+ if (user_info.first && user_info.first->is_type<reshape>()) {
+ const auto reshape_desc = user_info.first->as<reshape>().get_primitive();
+ const auto reshape_mode = reshape_desc->mode;
+ const auto reshape_ps = user_info.second.get_partial_shape();
+ const auto output_rank = std::max(reshape_ps.size(), static_cast<size_t>(4));
+ const auto crop_ps = crop_layout.get_partial_shape();
+ const auto crop_dim_val = crop_ps[crop_axis].get_length();
+
+ std::vector<ov::Dimension::value_type> reshape_lower_sizes(output_rank, 0);
+ std::vector<ov::Dimension::value_type> reshape_upper_sizes(output_rank, 0);
+ padding::DynamicDimsMask reshape_dyn_pad_mask;
+
+ // TransposeSplitMatcher pattern: crop [L, 1, H, S(, ...)] cut on the
+ // feature axis (crop_axis == 1, crop_dim_val == 1) feeding a base-mode
+ // reshape that drops the size-1 feature dim ([L, H, S(, ...)]).
+ //
+ // With crop_dim_val == 1 the standard axis-mapping algorithm below
+ // (mirrored from update_in_place_crop_padding_simple_data_format)
+ // would place raw `k` on the reshape's last axis. That yields
+ // get_linear_offset() == k and get_pitches()[0] == pshape[-1] +
+ // pad, both of which are physically wrong for downstream CM/OCL
+ // kernels that read the layout via those standard APIs.
+ //
+ // The parent buffer per-token stride is F * H * S(...) and slice-k
+ // starts at k * H * S(...) inside it. To make the reshape output
+ // layout carry those exact numbers we place scaled padding on the
+ // reshape's dim 1 (bfyx feature position, which corresponds to
+ // pshape[1] == H after the squeeze):
+ // _lower_size[1] = k * H_size
+ // _upper_size[1] = (F-1-k) * H_size
+ // yielding padded_dim[1] = F * H_size, therefore:
+ // get_pitches()[0] = padded_dim[1] * padded_dim[2] * ... = F * H * S(...)
+ // get_linear_offset() = _lower_size[1] * pitch[1] = k * H * S(...)
+ // Only inner-axis padding contributes to pitches[0], so this
+ // scaling cannot be represented on the L (batch) axis.
+ const bool is_axis1_size1_squeeze = reshape_mode == reshape::reshape_mode::base && crop_axis == 1 && crop_dim_val == 1 &&
+ reshape_ps.size() + 1 == crop_ps.size() && reshape_ps.size() >= 2 && reshape_ps[1].is_static();
+
+ if (is_axis1_size1_squeeze) {
+ const auto h_size = reshape_ps[1].get_length();
+ reshape_lower_sizes[1] = lower_sizes[crop_axis] * h_size;
+ reshape_upper_sizes[1] = upper_sizes[crop_axis] * h_size;
+ reshape_dyn_pad_mask[1] = true;
+ } else {
+ // Fallback: mirror update_in_place_crop_padding_simple_data_format
+ // axis-mapping so build-time (dyn mask) and runtime (mask +
+ // explicit sizes) paths pick the same reshape axis for patterns
+ // that do not need scaling.
+ size_t reshape_axis = crop_axis;
+ if (reshape_mode == reshape::reshape_mode::base) {
+ reshape_axis = reshape_ps.size() - 1;
+ ov::Dimension::value_type mul = 1;
+ for (size_t i = reshape_ps.size(); i > 1; i--) {
+ if (reshape_ps[i - 1].is_dynamic() || mul == crop_dim_val)
+ break;
+ mul *= reshape_ps[i - 1].get_length();
+ reshape_axis = i - 1;
+ }
+ } else if (reshape_mode == reshape::reshape_mode::unsqueeze || reshape_mode == reshape::reshape_mode::squeeze) {
+ const auto& output_pattern = reshape_desc->output_pattern;
+ for (size_t i = 0; i < output_pattern.size(); i++) {
+ if (output_pattern[i] <= static_cast<int64_t>(reshape_axis)) {
+ reshape_axis += reshape_mode == reshape::reshape_mode::unsqueeze ? 1 : -1;
+ }
+ }
+ }
+
+ OPENVINO_ASSERT(reshape_axis < output_rank,
+ "[GPU] Calculated reshape_axis is out of range for along-feature crop propagation.");
+
+ reshape_lower_sizes[reshape_axis] = lower_sizes[crop_axis];
+ reshape_upper_sizes[reshape_axis] = upper_sizes[crop_axis];
+ reshape_dyn_pad_mask[reshape_axis] = true;
+ }
+
+ user_info.second.data_padding = padding(reshape_lower_sizes, reshape_upper_sizes, reshape_dyn_pad_mask);
+ }
} else {
crop_layout.data_padding = padding(lower_sizes, upper_sizes);
}
@@ -719,18 +804,43 @@ bool crop_in_place_optimization::update_in_place_crop_padding_simple_data_format
auto reshape_mode = reshape_desc->mode;
auto reshape_axis = crop_axis;
if (reshape_mode == reshape::reshape_mode::base) {
- if (crop_axis == 0 && !crop_layout.get_partial_shape()[0].is_dynamic() &&
- crop_layout.get_partial_shape()[0].get_length() == 1 &&
- !reshape_desc->output_pattern.empty() &&
- reshape_desc->output_pattern[0] != 0 && reshape_desc->output_pattern[0] != 1) {
+ const auto crop_ps = crop_layout.get_partial_shape();
+ const auto reshape_ps = user_info.second.get_partial_shape();
+
+ // TransposeSplitMatcher pattern: crop_axis == 1 with a unit
+ // slice feeding a base-mode reshape that drops the size-1
+ // feature dim ([L, 1, H, S(, ...)] -> [L, H, S(, ...)]).
+ //
+ // The runtime along-feature helper (see
+ // update_in_place_crop_padding_along_feature) places scaled
+ // padding on the reshape's dim 1 (H axis) so that
+ // get_linear_offset() == k * H * S(...) and get_pitches()[0]
+ // == F * H * S(...). Downstream OCL consumers (RoPE,
+ // eltwise, MVN, ...) JIT-compile against this build-time
+ // layout snapshot and bake in "read pad from shape_info slot
+ // for axis N" from the dyn-pad mask set here. If the
+ // build-time mask sits on a different axis than the runtime
+ // one, fill_shape_info_data writes 0 into the JIT-baked slot
+ // and consumers walk the wrong memory. Mirror the runtime
+ // helper's axis choice to keep build-time and runtime in
+ // sync.
+ const bool is_axis1_size1_squeeze = crop_axis == 1 && crop_ps[crop_axis].is_static() &&
+ crop_ps[crop_axis].get_length() == 1 &&
+ reshape_ps.size() + 1 == crop_ps.size() && reshape_ps.size() >= 2 &&
+ reshape_ps[1].is_static();
+
+ if (is_axis1_size1_squeeze) {
+ reshape_axis = 1;
+ } else if (crop_axis == 0 && !crop_ps[0].is_dynamic() && crop_ps[0].get_length() == 1 &&
+ !reshape_desc->output_pattern.empty() && reshape_desc->output_pattern[0] != 0 &&
+ reshape_desc->output_pattern[0] != 1) {
// The crop produces exactly batch=1 per slice and the reshape squeezes that dim.
// output_pattern[0] == -1 means the batch dim is absorbed (squeezed).
reshape_axis = 0;
} else {
ov::Dimension::value_type mul = 1;
- auto reshape_ps = user_info.second.get_partial_shape();
reshape_axis = reshape_ps.size() - 1;
- auto crop_dim_val = crop_layout.get_partial_shape()[crop_axis].get_length();
+ auto crop_dim_val = crop_ps[crop_axis].get_length();
for (size_t i = reshape_ps.size(); i > 1; i--) {
if (reshape_ps[i - 1].is_dynamic() || mul == crop_dim_val)
break;
@@ -911,9 +1021,11 @@ void prepare_buffer_fusing::run(program& p) {
auto crop_layout = node.get_output_layout();
auto crop_params = node.get_kernel_impl_params();
if (!node.is_dynamic() && crop_in_place_optimization::can_crop_be_optimized_along_feature(crop_layout, pred_layout)) {
+ std::pair<const program_node*, layout> user_info;
crop_in_place_optimization::update_in_place_crop_padding_along_feature(node,
crop_layout,
pred_layout,
+ user_info,
crop_params->input_offsets[0],
node.get_primitive()->axis,
false);
diff --git a/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_buffer_fusing.h b/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_buffer_fusing.h
index d11b315cb28..0aa6c1866a8 100644
--- a/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_buffer_fusing.h
+++ b/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_buffer_fusing.h
@@ -74,9 +74,19 @@ struct crop_in_place_optimization : pattern_match_optimization_typed<crop_in_pla
layout& input_layout,
bool is_runtime = false);
bool optimize(crop_node& node);
+ // user_info.first: the reshape user program_node (or nullptr if the crop
+ // has no propagatable reshape user). When non-null, the
+ // helper writes the propagated padding into
+ // user_info.second so the caller can install it on the
+ // reshape's runtime output layout. Passing user_info
+ // aligns the along-feature helper with
+ // update_in_place_crop_padding_simple_data_format and
+ // avoids relying on reshape's calc_output_layouts (which
+ // resets padding to empty for reshape_mode::base).
static void update_in_place_crop_padding_along_feature(const program_node& node,
layout& crop_layout,
layout& pred_layout,
+ std::pair<const program_node*, layout>& user_info,
const tensor offsets,
size_t crop_axis,
bool is_runtime);
diff --git a/src/plugins/intel_gpu/src/graph/include/primitive_inst.h b/src/plugins/intel_gpu/src/graph/include/primitive_inst.h
index 1992bab3b36..ad5acde1fb3 100644
--- a/src/plugins/intel_gpu/src/graph/include/primitive_inst.h
+++ b/src/plugins/intel_gpu/src/graph/include/primitive_inst.h
@@ -384,6 +384,8 @@ public:
bool all_dependencies_cpu_impl() const;
protected:
+ friend class PrimitiveInstTestHelper;
+
primitive_inst(network& network, program_node const& node, bool allocate_memory);
network& _network;
diff --git a/src/plugins/intel_gpu/src/graph/include/reshape_inst.h b/src/plugins/intel_gpu/src/graph/include/reshape_inst.h
index 69b96a7ed64..463d662a2a2 100644
--- a/src/plugins/intel_gpu/src/graph/include/reshape_inst.h
+++ b/src/plugins/intel_gpu/src/graph/include/reshape_inst.h
@@ -58,11 +58,32 @@ public:
if (!has_outer_padding_offset() && get_users().size() == 1 && get_users().front()->get_preferred_impl_type() == impl_types::onednn)
return false;
- // TODO: If user is mvn or vl_sdpa and dynamic padding exists, output padding propagation is not supported in the base mode
- // vl_sdpa uses raw SVM pointers (CM kernel) without shape_info support, so it cannot apply dynamic padding offsets
- if (get_users().size() == 1 && (get_users().front()->is_type<mvn>() || get_users().front()->is_type<vl_sdpa>()))
+ // MVN canonicalizes input strides and cannot tolerate dynamic padding offsets.
+ if (get_users().size() == 1 && get_users().front()->is_type<mvn>())
return false;
+ // vl_sdpa uses a CM kernel that receives raw SVM pointers. Generic dynamic
+ // padding (e.g. from an inner-axis crop) cannot be applied through shape_info
+ // as with OCL kernels. The one exception is the TransposeSplitMatcher axis=1
+ // pattern: crop axis=1 with a size-1 input[1] followed by a rank-reducing reshape.
+ // In that case the CM kernel receives dedicated token_offset_q / token_offset_k / token_offset_v
+ // scalars computed from _lower_size[1], so propagation IS safe.
+ // All other vl_sdpa paths remain blocked.
+ if (get_users().size() == 1 && get_users().front()->is_type<vl_sdpa>()) {
+ // Allow only if the crop is the axis=1 / size-1 squeeze pattern handled by
+ // the token_offset scalars in the CM kernel. That pattern is already checked
+ // below (axis == 1 block), so we fall through here without blocking.
+ auto axis = input().as<crop>().get_primitive()->axis;
+ const auto& input_pshape = input().get_output_layout(false).get_partial_shape();
+ const bool is_axis1_size1_squeeze =
+ axis == 1 &&
+ !input_pshape[1].is_dynamic() &&
+ input_pshape[1].get_length() == 1 &&
+ prim->output_partial_shape.size() + 1 == input_pshape.size();
+ if (!is_axis1_size1_squeeze)
+ return false;
+ }
+
auto axis = input().as<crop>().get_primitive()->axis;
const auto& input_pshape = input().get_output_layout(false).get_partial_shape();
@@ -85,6 +106,42 @@ public:
return true;
}
+ // TransposeSplitMatcher optimization: when Transpose+Split(axis=0) over a
+ // [-1, 3, H, S] QKV tensor is replaced by Split(axis=1), each crop output
+ // has shape [-1, 1, H, S] with axis=1. The reshape that follows squeezes
+ // the size-1 dim-1, producing [-1, H, S].
+ //
+ // Why this pattern is safe to propagate padding through:
+ // - The crop offset lives on axis=1 (the "3" dimension, i.e. Q/K/V slot).
+ // - The reshape only removes that size-1 dimension; it does NOT reorder or
+ // merge any bytes. The memory layout of the remaining dimensions
+ // (batch=-1, H, S) is therefore identical before and after the reshape,
+ // and the buffer pointer + pitch of the outer dynamic batch dimension is
+ // still valid after the squeeze.
+ // - The crop size along axis=1 is always exactly 1 (static), so the
+ // offset is a known, constant stride-multiple — no runtime-shape-info
+ // lookup is required to compute it.
+ // - Downstream consumers (RoPE, oneDNN SDPA) only receive the squeezed
+ // [-1, H, S] view and never observe the axis=1 padding, so no consumer
+ // needs to be updated.
+ //
+ // Conditions checked:
+ // 1. axis == 1 (crop is on the QKV-slot dimension)
+ // 2. input_pshape[1] is static 1 (exactly one Q/K/V slice per crop)
+ // 3. output rank == input rank - 1 (reshape only drops that size-1 dim)
+ //
+ // Note: output_pattern is NOT required here. The safety argument depends
+ // only on the input crop axis and the output rank, not on the specific
+ // output_pattern values. In practice the Qwen3-VL model uses a dynamic
+ // shape tensor (not a compile-time constant) for the Reshape second input,
+ // leaving output_pattern empty — requiring it would incorrectly block this
+ // case even though conditions 1–3 are fully sufficient.
+ if (axis == 1 && !input_pshape[1].is_dynamic() && input_pshape[1].get_length() == 1) {
+ if (prim->output_partial_shape.size() + 1 == input_pshape.size()) {
+ return true;
+ }
+ }
+
auto input_rank = input_pshape.size();
auto input_last_dim = static_cast<int64_t>(input_rank - 1);
if (axis != input_last_dim || input_pshape[input_last_dim].is_dynamic())
diff --git a/src/plugins/intel_gpu/src/graph/primitive_inst.cpp b/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
index 696eafc49f3..539e69e7435 100644
--- a/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
+++ b/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
@@ -1925,16 +1925,17 @@ void primitive_inst::do_runtime_in_place_crop() {
const auto& crop_users = u->get_user_insts();
std::pair<const program_node*, layout> user_info;
- if (crop_users.front()->get_node().is_type<reshape>()) {
+ primitive_inst* reshape_inst = nullptr;
+ if (crop_users.size() == 1 && crop_users.front()->get_node().is_type<reshape>()) {
OPENVINO_ASSERT(crop_users.size() == 1, "[GPU] Expected number of reshape users is 1, but it is ", crop_users.size());
- auto reshape_inst = crop_users.front();
+ reshape_inst = crop_users.front();
if (!reshape_inst->_update_shape_done_by_other) {
GPU_DEBUG_TRACE_DETAIL << "[In place crop] update shape for " << reshape_inst->id() << std::endl;
reshape_inst->update_shape();
reshape_inst->_update_shape_done_by_other = true;
- user_info.first = &reshape_inst->get_node();
- user_info.second = reshape_inst->_impl_params->get_output_layout();
}
+ user_info.first = &reshape_inst->get_node();
+ user_info.second = reshape_inst->_impl_params->get_output_layout();
}
layout crop_layout = u->_impl_params->get_output_layout();
@@ -1948,14 +1949,49 @@ void primitive_inst::do_runtime_in_place_crop() {
auto crop_axis = u->_impl_params->typed_desc<crop>()->axis;
auto offsets = u->_impl_params->input_offsets[0];
if (crop_in_place_optimization::can_crop_be_optimized_along_feature(crop_layout, pred_layout)) {
- // TODO: If crop is optimized out w/ data padding along feature and crop's user is reshape
- // manual dynamic padding update to reshape output layout is not currently supported
+ // If there is a reshape user, we can still optimize when the reshape is able to
+ // propagate runtime padding (is_runtime_propagatable_padding() == true).
+ //
+ // This covers the TransposeSplitMatcher case: Transpose+Split(axis=0) over a
+ // packed QKV tensor [-1,3,H,S] is replaced by Split(axis=1), so each crop has
+ // shape [-1,1,H,S] with crop axis=1 (feature axis). The following reshape
+ // squeezes that size-1 dim to [-1,H,S].
+ //
+ // For out0/out1 (→ Reshape → RoPE): is_runtime_propagatable_padding() is true
+ // because the downstream RoPE can handle the propagated padding via the standard
+ // dynamic-layout mechanism.
+ //
+ // For out2 (→ Reshape → vl_sdpa): is_runtime_propagatable_padding() is also true
+ // for the axis=1/size-1 pattern (see reshape_inst.h). The CM kernel reads the
+ // dynamic padding offset via dedicated token_offset_q/token_offset_k/token_offset_v scalars
+ // (see vl_sdpa_opt.cpp), so it does NOT need shape_info — the offset is applied
+ // directly to the SVM pointer before dispatch.
+ //
+ // In both cases we update the reshape output layout so downstream nodes see the
+ // correct padded view — same as the simple_data_format path does below.
if (user_info.first) {
- u->set_can_be_optimized(false);
- GPU_DEBUG_TRACE_DETAIL << "[In place crop] " << u->id() << " cannot be optimized " << std::endl;
- continue;
+ auto reshape_inst_node = static_cast<const reshape_node*>(user_info.first);
+ if (!reshape_inst_node->is_runtime_propagatable_padding()) {
+ u->set_can_be_optimized(false);
+ GPU_DEBUG_TRACE_DETAIL << "[In place crop] " << u->id() << " cannot be optimized " << std::endl;
+ continue;
+ }
+ }
+ crop_in_place_optimization::update_in_place_crop_padding_along_feature(u->get_node(), crop_layout, pred_layout, user_info, offsets, crop_axis, true);
+ // Install the padded crop layout and propagate the reshape
+ // output padding computed by the helper. Assigning the
+ // reshape output layout directly (mirroring the
+ // simple_data_format branch below) avoids a second
+ // reshape_inst->update_shape() call, which would run
+ // reshape_inst::calc_output_layouts and reset the padding
+ // to empty for reshape_mode::base.
+ u->_impl_params->output_layouts[0] = crop_layout;
+ if (user_info.first) {
+ auto reshape_inst = crop_users.front();
+ reshape_inst->_impl_params->output_layouts[0] = user_info.second;
+ reshape_inst->set_flag(ExecutionFlags::SHAPE_CHANGED);
}
- crop_in_place_optimization::update_in_place_crop_padding_along_feature(u->get_node(), crop_layout, pred_layout, offsets, crop_axis, true);
+ GPU_DEBUG_TRACE_DETAIL << "[In place crop] " << u->id() << " update_in_place_crop_padding_along_feature " << offsets << ", " << crop_axis << std::endl;
} else if (crop_in_place_optimization::can_crop_be_optimized_simple_data_format(crop_layout, pred_layout)) {
if (!crop_in_place_optimization::update_in_place_crop_padding_simple_data_format(crop_layout, pred_layout, user_info, offsets, crop_axis, true)) {
u->set_can_be_optimized(false);
@@ -1967,6 +2003,7 @@ void primitive_inst::do_runtime_in_place_crop() {
reshape_inst->_impl_params->output_layouts[0] = user_info.second;
reshape_inst->set_flag(ExecutionFlags::SHAPE_CHANGED);
}
+ GPU_DEBUG_TRACE_DETAIL << "[In place crop] " << u->id() << " update_in_place_crop_padding_simple_data_format " << offsets << ", " << crop_axis << std::endl;
} else {
u->set_can_be_optimized(false);
GPU_DEBUG_TRACE_DETAIL << "[In place crop] " << u->id() << " cannot be optimized " << std::endl;
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/transpose_fusion.cpp b/src/plugins/intel_gpu/src/plugin/transformations/transpose_fusion.cpp
index 11ec247ffac..e2f7a050760 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations/transpose_fusion.cpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations/transpose_fusion.cpp
@@ -16,6 +16,8 @@
#include "openvino/op/scaled_dot_product_attention.hpp"
#include "openvino/op/convert.hpp"
#include "openvino/op/transpose.hpp"
+#include "openvino/op/split.hpp"
+#include "openvino/op/reshape.hpp"
#include "openvino/core/rt_info.hpp"
#include "openvino/pass/pattern/op/wrap_type.hpp"
#include "openvino/pass/pattern/op/or.hpp"
@@ -79,6 +81,7 @@ TransposeFusion::TransposeFusion(bool supports_immad) {
add_matcher<TransposeMatMulMatcher>(supports_immad);
add_matcher<TransposeSDPAMatcher>();
add_matcher<TransposeVLSDPAMatcher>();
+ add_matcher<TransposeSplitMatcher>();
}
TransposeVLSDPAMatcher::TransposeVLSDPAMatcher() {
@@ -472,4 +475,125 @@ TransposeMatMulTransposeMatcher::TransposeMatMulTransposeMatcher(bool supports_i
this->register_matcher(m, callback);
}
+// TransposeSplitMatcher: Optimize Transpose+Split pattern from Qwen-VL Vision Merger
+//
+// Background:
+// This pattern appears in Qwen-VL Vision Merger models (Qwen2-VL, Qwen2.5-VL, Qwen3-VL, etc.)
+// where a combined QKV tensor
+// with shape [-1, 3, num_head, head_size] needs to be split into separate Q, K, V tensors.
+// The original framework uses Transpose to move the channel dimension to the front,
+// then splits along that dimension.
+//
+// Original Pattern (from Qwen-VL Vision Merger):
+// Parameter[-1, 3, H, S] → Transpose[1,0,2,3] → [3, -1, H, S]
+// → Split(axis=0, num_splits=3) → 3x [1, -1, H, S]
+// → Reshape[0] → [-1, H, S] → RoPE → VLSDPA
+// → Reshape[1] → [-1, H, S] → RoPE ↗
+// → Reshape[2] → [-1, H, S] -------↗
+//
+// Optimized Pattern:
+// Parameter[-1, 3, H, S] → Split(axis=1, num_splits=3) → 3x [-1, 1, H, S]
+// → Reshape[0] → [-1, H, S] → RoPE → VLSDPA
+// → Reshape[1] → [-1, H, S] → RoPE ↗
+// → Reshape[2] → [-1, H, S] -------↗
+//
+// Benefits:
+// - Eliminates unnecessary Transpose operation (saves memory bandwidth and kernel launch)
+// - Produces functionally equivalent results: both patterns extract the same 3 slices
+// from the channel dimension, just with different intermediate shapes
+// - Reshape operations following the Split automatically adapt to the new input shape
+//
+// Applicability:
+// - Input shape: [-1, C, H, S] where C is strictly 3 (not dynamic)
+// - Transpose order: [1, 0, 2, 3] (swaps first two dimensions only)
+// - Split axis: 0 (after transpose, which corresponds to dim 1 before transpose)
+// - num_splits: 3 (matching the channel count)
+//
+TransposeSplitMatcher::TransposeSplitMatcher() {
+ // Pattern: Parameter[-1, 3, H, S] -> Transpose[3, -1, H, S] -> Split(axis=0) -> 3x[1, -1, H, S]
+ // Optimize to: Parameter[-1, 3, H, S] -> Split(axis=1) -> 3x[-1, 1, H, S]
+
+ auto input_m = any_input();
+ auto transpose_order_m = wrap_type<ov::op::v0::Constant>(consumers_count(1));
+ auto transpose_m = wrap_type<ov::op::v1::Transpose>({input_m, transpose_order_m});
+ auto split_axis_m = wrap_type<ov::op::v0::Constant>();
+ auto split_m = wrap_type<ov::op::v1::Split>({transpose_m, split_axis_m});
+
+ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](Matcher& m) {
+ const auto& pattern_map = m.get_pattern_value_map();
+
+ auto split = ov::as_type_ptr<ov::op::v1::Split>(pattern_map.at(split_m).get_node_shared_ptr());
+ auto transpose = ov::as_type_ptr<ov::op::v1::Transpose>(pattern_map.at(transpose_m).get_node_shared_ptr());
+ auto input_node = pattern_map.at(input_m).get_node_shared_ptr();
+
+ if (!split || !transpose || transformation_callback(split)) {
+ return false;
+ }
+
+ // Get transpose order
+ auto transpose_order_const = ov::as_type_ptr<ov::op::v0::Constant>(
+ pattern_map.at(transpose_order_m).get_node_shared_ptr());
+ if (!transpose_order_const) {
+ return false;
+ }
+ auto transpose_order = transpose_order_const->cast_vector<int64_t>();
+
+ // Get split axis
+ auto split_axis_const = ov::as_type_ptr<ov::op::v0::Constant>(
+ pattern_map.at(split_axis_m).get_node_shared_ptr());
+ if (!split_axis_const) {
+ return false;
+ }
+ auto split_axis_vec = split_axis_const->cast_vector<int64_t>();
+ if (split_axis_vec.size() != 1) {
+ return false;
+ }
+ int64_t split_axis = split_axis_vec[0];
+
+ // Get input shape
+ auto input_pshape = input_node->get_output_partial_shape(0);
+ if (input_pshape.rank().is_dynamic() || input_pshape.rank().get_length() != 4) {
+ return false;
+ }
+
+ // Check conditions for the optimization:
+ // 1. Input shape: [-1, 3, H, S] where dim[1] is strictly 3
+ // 2. Transpose order: [1, 0, 2, 3] (swaps first two dimensions)
+ // 3. Split axis: 0 (after transpose, splitting the "3" dimension)
+ // 4. num_splits: 3
+
+ // Condition 1: Check dim[1] is strictly 3
+ if (input_pshape[1].is_dynamic() || input_pshape[1].get_length() != 3) {
+ return false;
+ }
+
+ // Condition 2: Check transpose order is [1, 0, 2, 3]
+ std::vector<int64_t> expected_transpose_order = {1, 0, 2, 3};
+ if (transpose_order != expected_transpose_order) {
+ return false;
+ }
+
+ // Condition 3: Check split axis is 0 (after transpose)
+ if (split_axis != 0) {
+ return false;
+ }
+
+ // Condition 4: Check num_splits is 3
+ if (split->get_num_splits() != 3) {
+ return false;
+ }
+
+ // Create new Split that operates directly on axis=1 of the input (before transpose)
+ // This produces 3 outputs of shape [-1, 1, H, S] instead of [1, -1, H, S]
+ auto new_split_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {1});
+ auto new_split = std::make_shared<ov::op::v1::Split>(input_node, new_split_axis, split->get_num_splits());
+ ov::copy_runtime_info(m.get_matched_nodes(), new_split);
+ ov::replace_node(split, new_split);
+ return true;
+ };
+
+ auto matcher = std::make_shared<ov::pass::pattern::Matcher>(split_m, "TransposeSplitMatcher");
+ this->register_matcher(matcher, callback);
+}
+
} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/transpose_fusion.hpp b/src/plugins/intel_gpu/src/plugin/transformations/transpose_fusion.hpp
index 2f0b45db43d..6611206140d 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations/transpose_fusion.hpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations/transpose_fusion.hpp
@@ -38,4 +38,10 @@ public:
TransposeVLSDPAMatcher();
};
+class TransposeSplitMatcher : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("TransposeSplitMatcher");
+ TransposeSplitMatcher();
+};
+
} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/runtime/layout.cpp b/src/plugins/intel_gpu/src/runtime/layout.cpp
index 3db8b50dc84..c2bf999ae13 100644
--- a/src/plugins/intel_gpu/src/runtime/layout.cpp
+++ b/src/plugins/intel_gpu/src/runtime/layout.cpp
@@ -237,17 +237,32 @@ std::string layout::to_short_string() const {
}
}
};
+ auto dump_padding_sizes = [](std::stringstream& stream,
+ const std::array<ov::Dimension::value_type, SHAPE_RANK_MAX>& values,
+ size_t rank) {
+ stream << "[";
+ for (size_t i = 0; i < rank; ++i) {
+ if (i)
+ stream << ",";
+ stream << values[i];
+ }
+ stream << "]";
+ };
s << ov::element::Type(data_type) << ":" << format.to_string() << ":";
dump_shape(s, size);
if (data_padding.is_dynamic()) {
- s << ":dyn_pad_dims";
- } else {
- if (data_padding)
- s << ":pad";
- else
- s << ":nopad";
+ s << ":dyn_pad_dims[" << data_padding._dynamic_dims_mask.to_string() << "]";
+ }
+
+ if (data_padding) {
+ s << ":pad_l";
+ dump_padding_sizes(s, data_padding._lower_size, format.dimension());
+ s << ":pad_u";
+ dump_padding_sizes(s, data_padding._upper_size, format.dimension());
+ } else if (!data_padding.is_dynamic()) {
+ s << ":nopad";
}
return s.str();
diff --git a/src/plugins/intel_gpu/tests/functional/subgraph_tests/transpose_split_vlsdpa.cpp b/src/plugins/intel_gpu/tests/functional/subgraph_tests/transpose_split_vlsdpa.cpp
new file mode 100644
index 00000000000..b84e6e931d0
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/functional/subgraph_tests/transpose_split_vlsdpa.cpp
@@ -0,0 +1,500 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "common_test_utils/ov_tensor_utils.hpp"
+#include "common_test_utils/ov_test_utils.hpp"
+#include "openvino/core/coordinate_diff.hpp"
+#include "openvino/core/strides.hpp"
+#include "openvino/pass/manager.hpp"
+#include "openvino/runtime/core.hpp"
+#include "openvino/runtime/exec_model_info.hpp"
+#include "shared_test_classes/base/ov_subgraph.hpp"
+#include "intel_gpu/runtime/engine.hpp"
+#include "intel_gpu/runtime/engine_configuration.hpp"
+
+#include "openvino/opsets/opset1.hpp"
+#include "openvino/opsets/opset8.hpp"
+#include "openvino/opsets/opset13.hpp"
+#include "ov_ops/vl_sdpa.hpp"
+
+#include "openvino/util/log.hpp"
+#include "intel_gpu/runtime/execution_config.hpp"
+
+#include <algorithm>
+#include <cmath>
+#include <limits>
+
+//=================================================================================
+// Subgraph Topology:
+// Parameter + Transpose + Split → RoPE + VLSDPA pattern
+// (Testing Split axis optimization: Transpose+Split(axis=0) → Split(axis=1))
+//
+// This pattern is from Qwen-VL Vision Merger models (Qwen2-VL, Qwen2.5-VL, Qwen3-VL, etc.)
+// where a combined QKV tensor needs to be split into separate Q, K, V tensors.
+//
+// Before optimization:
+// Parameter[-1,3,H,S] → Transpose[3,-1,H,S] → Split(axis=0) → 3x[1,-1,H,S]
+// → Reshape[0][-1,H,S] → RoPE → VLSDPA
+// → Reshape[1][-1,H,S] → RoPE ↗
+// → Reshape[2][-1,H,S] -------↗
+//
+// After optimization:
+// Parameter[-1,3,H,S] → Split(axis=1) → 3x[-1,1,H,S]
+// → Reshape[0][-1,H,S] → RoPE → VLSDPA
+// → Reshape[1][-1,H,S] → RoPE ↗
+// → Reshape[2][-1,H,S] -------↗
+//
+// The transformation preserves results because:
+// - Old: Transpose [N,C,H,S→C,N,H,S] then Split axis=0 extracts each channel
+// - New: Split axis=1 directly extracts each channel without transpose
+// - Both produce the same 3 tensors of shape [-1,H,S] with identical data
+//=================================================================================
+
+namespace ov {
+namespace test {
+using namespace ov;
+using namespace ov::opset13;
+using namespace ov::intel_gpu;
+
+enum class AttentionType {
+ SDPA, // ScaledDotProductAttention
+ VLSDPA // Vision Language SDPA (for Qwen-VL models)
+};
+
+using TransposeSplitVLSDPATestParams = std::tuple<ElementType,
+ ov::Dimension::value_type, // num_head
+ ov::Dimension::value_type, // head_size
+ std::vector<int32_t>>; // cu_seqlens
+
+class TransposeSplitVLSDPATestOnGPU: public testing::WithParamInterface<TransposeSplitVLSDPATestParams>,
+ virtual public test::SubgraphBaseTest {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<TransposeSplitVLSDPATestParams>& obj) {
+ ElementType inType;
+ ov::Dimension::value_type num_head, head_size;
+ std::vector<int32_t> cu_seqlens;
+
+ std::tie(inType, num_head, head_size, cu_seqlens) = obj.param;
+
+ std::ostringstream result;
+ result << "device=(" << std::string(utils::DEVICE_GPU) << ")_";
+ result << "num_head=(" << to_str(num_head) << ")_";
+ result << "head_size=(" << to_str(head_size) << ")_";
+ result << test::utils::vec2str<int32_t>(cu_seqlens) << "_";
+ result << "Prc=" << inType;
+ return result.str();
+ }
+
+ static std::shared_ptr<Parameter> make_param(const PartialShape& pshape,
+ element::Type element_type,
+ const std::string& name) {
+ auto param = std::make_shared<Parameter>(element_type, pshape);
+ param->set_friendly_name(name);
+ param->get_output_tensor(0).set_names({name});
+ return param;
+ }
+
+ static std::shared_ptr<ov::Node> create_sdpa_with_transpose(
+ const std::shared_ptr<ov::Node>& q,
+ const std::shared_ptr<ov::Node>& k,
+ const std::shared_ptr<ov::Node>& v,
+ const std::shared_ptr<ov::Node>& attn_mask) {
+ const std::vector<int64_t> order{1, 0, 2};
+ auto transpose_q = std::make_shared<Transpose>(q, Constant::create(element::i64, Shape{3}, order));
+ auto transpose_k = std::make_shared<Transpose>(k, Constant::create(element::i64, Shape{3}, order));
+ auto transpose_v = std::make_shared<Transpose>(v, Constant::create(element::i64, Shape{3}, order));
+
+ auto sdpa = std::make_shared<ScaledDotProductAttention>(transpose_q, transpose_k, transpose_v, attn_mask, false);
+ auto transpose_o = std::make_shared<Transpose>(sdpa, Constant::create(element::i64, Shape{3}, order));
+ return transpose_o;
+ }
+
+ static bool check_vlsdpa_available() {
+ try {
+ // Create a minimal SDPA model to test VLSDPA transformation availability
+ const int64_t num_head = 8;
+ const int64_t head_size = 32;
+
+ // Create Q, K, V parameters
+ auto q = make_param(PartialShape{1, num_head, head_size}, element::f16, "q");
+ auto k = make_param(PartialShape{1, num_head, head_size}, element::f16, "k");
+ auto v = make_param(PartialShape{1, num_head, head_size}, element::f16, "v");
+ auto attention_mask = make_param(PartialShape{1, 1, 1}, element::f16, "attention_mask");
+
+ auto sdpa_output = create_sdpa_with_transpose(q, k, v, attention_mask);
+ auto model = std::make_shared<Model>(sdpa_output, ParameterVector{q, k, v, attention_mask});
+
+ // Request VLSDPA transformation by setting model hint
+ model->set_rt_info("QWenVL", "model_type_hint");
+
+ // Try to compile with GPU plugin; if it succeeds and the compiled model
+ // has "cu_seq_lens" input, VLSDPA transformation was applied
+ ov::Core core;
+ try {
+ auto compiled = core.compile_model(model, "GPU");
+ // Check if transformation was applied: compiled model should have cu_seq_lens input
+ for (const auto& input : compiled.inputs()) {
+ const auto& names = input.get_names();
+ if (names.find("cu_seq_lens") != names.end() ||
+ names.find("cu_window_seqlens") != names.end()) {
+ return true;
+ }
+ }
+ return false;
+ } catch (const std::exception&) {
+ return false;
+ }
+ } catch (const std::exception&) {
+ return false;
+ }
+ }
+
+protected:
+ void SetUp() override {
+ ElementType inType;
+ ov::Dimension::value_type num_head, head_size;
+ std::vector<int32_t> cu_seqlens;
+ std::tie(inType, num_head, head_size, cu_seqlens) = GetParam();
+
+ targetDevice = test::utils::DEVICE_GPU;
+ // f16 SDPA accumulation error grows with head_size
+ rel_threshold = head_size <= 16 ? 0.02f : 0.05f;
+ abs_threshold = head_size <= 16 ? 0.02f : 0.05f;
+ if (inType == ov::element::f32)
+ configuration[ov::hint::inference_precision.name()] = ov::element::f32.get_type_name();
+
+ ASSERT_FALSE(cu_seqlens.empty());
+ ASSERT_EQ(cu_seqlens.front(), 0);
+ const auto cumsum = cu_seqlens.back();
+ const auto L = static_cast<size_t>(cumsum);
+ const auto H = static_cast<size_t>(num_head);
+ const auto S = static_cast<size_t>(head_size);
+ std::vector<InputShape> inputShapes = {
+ // qkv: [-1, 3, H, S]
+ {PartialShape{-1, 3, num_head, head_size}, {Shape{L, 3, H, S}}},
+ // cos: [-1, 1, S]
+ {PartialShape{-1, 1, head_size}, {Shape{L, 1, S}}},
+ // sin: [-1, 1, S]
+ {PartialShape{-1, 1, head_size}, {Shape{L, 1, S}}},
+ };
+ inputShapes.emplace_back(PartialShape{-1}, std::vector<Shape>{Shape{cu_seqlens.size()}});
+
+ init_input_shapes(inputShapes);
+
+ // Create function using an explicit VLSDPA op for the VLSDPA path;
+ // use the regular SDPA op for the reference path.
+ function = get_function(inType, num_head, head_size, AttentionType::VLSDPA);
+ functionRefs = get_function(inType, num_head, head_size, AttentionType::SDPA);
+
+ m_cu_seqlens = cu_seqlens;
+ }
+
+ std::shared_ptr<ov::Model> get_function(ov::element::Type inType,
+ ov::Dimension::value_type num_head,
+ ov::Dimension::value_type head_size,
+ AttentionType attn_type) {
+ return create_model(inType, num_head, head_size, attn_type);
+ }
+
+ std::shared_ptr<ov::Model> create_model(ov::element::Type inType,
+ ov::Dimension::value_type num_head,
+ ov::Dimension::value_type head_size,
+ AttentionType attn_type) {
+ // Parameter with shape [-1, 3, num_head, head_size]
+ auto qkv = make_param(PartialShape{ov::Dimension::dynamic(), 3, num_head, head_size},
+ inType, "qkv");
+
+ // Transpose: [-1, 3, H, S] -> [3, -1, H, S]
+ auto transpose_order = Constant::create(element::i64, Shape{4}, std::vector<int64_t>{1, 0, 2, 3});
+ auto transpose = std::make_shared<Transpose>(qkv, transpose_order);
+ transpose->set_friendly_name("transpose_qkv");
+
+ // Split along axis 0: [3, -1, H, S] -> 3x [1, -1, H, S]
+ auto split_axis = Constant::create(element::i64, Shape{}, std::vector<int64_t>{0});
+ auto split = std::make_shared<Split>(transpose, split_axis, 3);
+ split->set_friendly_name("split_qkv");
+
+ // Reshape each split output: [1, -1, H, S] -> [-1, H, S]
+ auto reshape_pattern = Constant::create(element::i64, Shape{3}, std::vector<int64_t>{-1, num_head, head_size});
+
+ auto reshape_q = std::make_shared<Reshape>(split->output(0), reshape_pattern, false);
+ reshape_q->set_friendly_name("reshape_q");
+
+ auto reshape_k = std::make_shared<Reshape>(split->output(1), reshape_pattern, false);
+ reshape_k->set_friendly_name("reshape_k");
+
+ auto reshape_v = std::make_shared<Reshape>(split->output(2), reshape_pattern, false);
+ reshape_v->set_friendly_name("reshape_v");
+
+ // Real Qwen-VL RoPE pattern (GPTNEOX_3D style):
+ // input [-1, H, S]
+ // cos_param [-1, 1, S], sin_param [-1, 1, S]
+ //
+ // rope(input) = input * cos + rotate_half(input) * sin
+ // rotate_half: [-x_right, x_left] (split along head_size dim)
+ auto cos_param = make_param(PartialShape{ov::Dimension::dynamic(), 1, head_size}, inType, "cos");
+ auto sin_param = make_param(PartialShape{ov::Dimension::dynamic(), 1, head_size}, inType, "sin");
+
+ auto apply_rope = [&](const std::shared_ptr<ov::Node>& x, const std::string& prefix) {
+ // rotate_half: split at head_size/2, negate right half, concat [-right, left]
+ auto neg_one = Constant::create(inType, Shape{1, 1, 1}, {-1.0f});
+ auto vs = std::make_shared<ov::opset1::VariadicSplit>(
+ x,
+ Constant::create(element::i64, Shape{}, {2}),
+ Constant::create(element::i64, Shape{2}, std::vector<int64_t>{head_size / 2, head_size / 2}));
+ vs->set_friendly_name(prefix + "_vs");
+ auto neg = std::make_shared<Multiply>(vs->output(1), neg_one);
+ neg->set_friendly_name(prefix + "_neg");
+ auto rotated = std::make_shared<ov::opset1::Concat>(ov::OutputVector{neg, vs->output(0)}, -1);
+ rotated->set_friendly_name(prefix + "_rotated");
+
+ auto cos_mul = std::make_shared<Multiply>(x, cos_param);
+ cos_mul->set_friendly_name(prefix + "_cos_mul");
+ auto sin_mul = std::make_shared<Multiply>(rotated, sin_param);
+ sin_mul->set_friendly_name(prefix + "_sin_mul");
+ auto rope_out = std::make_shared<ov::opset1::Add>(cos_mul, sin_mul);
+ rope_out->set_friendly_name(prefix + "_rope");
+ return rope_out;
+ };
+
+ auto rope_q = apply_rope(reshape_q, "q");
+ auto rope_k = apply_rope(reshape_k, "k");
+
+ const std::vector<int64_t> order{1, 0, 2};
+
+ if (attn_type == AttentionType::VLSDPA) {
+ auto cu_seq_lens = std::make_shared<Parameter>(element::i32, PartialShape{-1});
+ cu_seq_lens->set_friendly_name("cu_seq_lens");
+ cu_seq_lens->get_output_tensor(0).set_names({"cu_seq_lens"});
+
+ auto vlsdpa = std::make_shared<ov::op::internal::VLSDPA>(OutputVector{rope_q, rope_k, reshape_v, cu_seq_lens},
+ order,
+ order,
+ order,
+ order);
+ vlsdpa->set_friendly_name("vlsdpa");
+
+ return std::make_shared<Model>(OutputVector{vlsdpa}, ParameterVector{qkv, cos_param, sin_param, cu_seq_lens});
+ } else {
+ auto attention_mask = make_param(PartialShape{1, ov::Dimension::dynamic(), ov::Dimension::dynamic()}, ov::element::f16, "attention_mask");
+
+ auto sdpa_output = create_sdpa_with_transpose(rope_q, rope_k, reshape_v, attention_mask);
+
+ return std::make_shared<Model>(sdpa_output, ParameterVector{qkv, cos_param, sin_param, attention_mask});
+ }
+ }
+
+ template <typename T>
+ void fill_tensor_with_non_zero_pattern(ov::Tensor& tensor) const {
+ auto* data = tensor.data<T>();
+ const auto size = tensor.get_size();
+ for (size_t i = 0; i < size; ++i) {
+ const float value = 0.25f + 0.25f * static_cast<float>((i % 7) + 1);
+ data[i] = static_cast<T>(value);
+ }
+ }
+
+ void fill_tensor_with_non_zero_pattern(ov::Tensor& tensor) const {
+ switch (tensor.get_element_type()) {
+ case ov::element::f16:
+ fill_tensor_with_non_zero_pattern<ov::float16>(tensor);
+ break;
+ case ov::element::f32:
+ fill_tensor_with_non_zero_pattern<float>(tensor);
+ break;
+ case ov::element::i32:
+ fill_tensor_with_non_zero_pattern<int32_t>(tensor);
+ break;
+ default:
+ throw std::runtime_error("Unsupported tensor element type for deterministic input generation");
+ }
+ }
+
+ template <typename T>
+ void compare_tensor_elements(const ov::Tensor& expected,
+ const ov::Tensor& actual,
+ size_t output_index) const {
+ const auto* expected_data = expected.data<T>();
+ const auto* actual_data = actual.data<T>();
+ // Use the SubgraphBaseTest-level abs_threshold / rel_threshold set in
+ // SetUp() (0.02–0.05 depending on head_size). f16 SDPA accumulates
+ // enough rounding error over head_size to invalidate a hardcoded
+ // 1e-4 tolerance — the previous 1e-4 constants matched only f32.
+ const float abs_tol = static_cast<float>(abs_threshold);
+ const float rel_tol = static_cast<float>(rel_threshold);
+ for (size_t i = 0; i < expected.get_size(); ++i) {
+ const float expected_value = static_cast<float>(expected_data[i]);
+ const float actual_value = static_cast<float>(actual_data[i]);
+ const float abs_diff = std::abs(expected_value - actual_value);
+ const float allowed_tol = abs_tol + rel_tol * std::abs(expected_value);
+ ASSERT_LE(abs_diff, allowed_tol)
+ << "Element-wise mismatch at output[" << output_index << "] index[" << i
+ << "]: expected=" << expected_value << ", actual=" << actual_value;
+ }
+ }
+
+ ov::Tensor create_attention_mask_from_cu_seqlens(const std::vector<int32_t>& cu_seqlens,
+ const ov::element::Type& element_type) const {
+ const auto seq_len = static_cast<size_t>(cu_seqlens.back());
+ const Shape mask_shape{1, seq_len, seq_len};
+ ov::Tensor mask(element_type, mask_shape);
+
+ if (element_type == ov::element::f16) {
+ auto* data = mask.data<ov::float16>();
+ std::fill(data, data + mask.get_size(), ov::float16(-std::numeric_limits<float>::infinity()));
+ for (size_t i = 1; i < cu_seqlens.size(); ++i) {
+ const auto start = static_cast<size_t>(cu_seqlens[i - 1]);
+ const auto end = static_cast<size_t>(cu_seqlens[i]);
+ for (size_t row = start; row < end; ++row) {
+ for (size_t col = start; col < end; ++col) {
+ data[row * seq_len + col] = ov::float16(0.0f);
+ }
+ }
+ }
+ } else if (element_type == ov::element::f32) {
+ auto* data = mask.data<float>();
+ std::fill(data, data + mask.get_size(), -std::numeric_limits<float>::infinity());
+ for (size_t i = 1; i < cu_seqlens.size(); ++i) {
+ const auto start = static_cast<size_t>(cu_seqlens[i - 1]);
+ const auto end = static_cast<size_t>(cu_seqlens[i]);
+ for (size_t row = start; row < end; ++row) {
+ for (size_t col = start; col < end; ++col) {
+ data[row * seq_len + col] = 0.0f;
+ }
+ }
+ }
+ } else {
+ throw std::runtime_error("Unsupported attention mask element type");
+ }
+
+ return mask;
+ }
+
+ void generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) override {
+ inputs.clear();
+ inputs_ref.clear();
+
+ const auto& compiled_inputs = compiledModel.inputs();
+ const auto& ref_inputs = functionRefs->inputs();
+
+ std::map<std::string, ov::Tensor> compiled_tensors_by_name;
+
+ for (size_t i = 0lu; i < compiled_inputs.size(); ++i) {
+ const auto& funcInput = compiled_inputs[i];
+ const auto input_name = funcInput.get_node_shared_ptr()->get_friendly_name();
+ ov::Tensor tensor;
+ if (input_name == "cu_seq_lens") {
+ tensor = ov::Tensor(funcInput.get_element_type(), targetInputStaticShapes[i]);
+ auto* data = tensor.data<int32_t>();
+ for (size_t j = 0; j < m_cu_seqlens.size(); ++j) {
+ data[j] = m_cu_seqlens[j];
+ }
+ } else {
+ tensor = ov::Tensor(funcInput.get_element_type(), targetInputStaticShapes[i]);
+ fill_tensor_with_non_zero_pattern(tensor);
+ }
+
+ inputs.insert({std::const_pointer_cast<Node>(funcInput.get_node_shared_ptr()), tensor});
+ compiled_tensors_by_name.emplace(input_name, tensor);
+ }
+
+ // Build reference inputs in reference-model order, but reuse the compiled-model tensors
+ // for the shared qkv/cos/sin inputs and only create a dedicated attention mask for the
+ // reference-only SDPA branch.
+ for (size_t i = 0lu; i < ref_inputs.size(); ++i) {
+ const auto& ref_input = ref_inputs[i];
+ const auto input_name = ref_input.get_node_shared_ptr()->get_friendly_name();
+ ov::Tensor tensor;
+ if (input_name == "attention_mask") {
+ tensor = create_attention_mask_from_cu_seqlens(m_cu_seqlens, ref_input.get_element_type());
+ } else {
+ auto it = compiled_tensors_by_name.find(input_name);
+ if (it != compiled_tensors_by_name.end()) {
+ tensor = it->second;
+ } else {
+ tensor = ov::Tensor(ref_input.get_element_type(), targetInputStaticShapes[i]);
+ }
+ }
+ inputs_ref.emplace_back(std::move(tensor));
+ }
+ }
+
+ std::vector<ov::Tensor> calculate_refs() override {
+ if (is_report_stages) {
+ std::cout << "[ REFERENCE ] `SubgraphBaseTest::calculate_refs()` is started"<< std::endl;
+ }
+ auto start_time = std::chrono::system_clock::now();
+
+ // Use Template plugin for reference - it doesn't have TransposeSplitMatcher
+ // This keeps the original Transpose+Split pattern intact
+ auto outputs = ov::test::utils::infer_on_template(functionRefs, inputs_ref);
+
+ if (is_report_stages) {
+ auto end_time = std::chrono::system_clock::now();
+ std::chrono::duration<double> duration = end_time - start_time;
+ std::cout << "[ REFERENCE ] `SubgraphBaseTest::calculate_refs()` is finished successfully. Duration is " << duration.count() << "s" << std::endl;
+ }
+ return outputs;
+ }
+
+ void compare(const std::vector<ov::Tensor>& expected, const std::vector<ov::Tensor>& actual) override {
+ ASSERT_EQ(expected.size(), actual.size());
+ ASSERT_EQ(expected.size(), function->get_results().size());
+
+ for (size_t j = 0; j < expected.size(); ++j) {
+ utils::compare(expected[j], actual[j], abs_threshold, rel_threshold);
+ }
+ }
+
+private:
+ std::vector<int32_t> m_cu_seqlens;
+ AttentionType m_attn_type;
+ ov::TensorVector inputs_ref;
+};
+
+TEST_P(TransposeSplitVLSDPATestOnGPU, CompareWithRefs) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+ ElementType inType;
+ ov::Dimension::value_type num_head, head_size;
+ std::vector<int32_t> cu_seqlens;
+ std::tie(inType, num_head, head_size, cu_seqlens) = GetParam();
+ if (inType != ElementType::f16) // VLSDPA CM kernel supports half precision only
+ GTEST_SKIP();
+
+ if (!check_vlsdpa_available())
+ GTEST_SKIP() << "CM JIT support is required for VLSDPA tests, and the device must be Xe1 or later";
+
+ try {
+ run();
+ } catch (const std::exception& e) {
+ const std::string message = e.what();
+ if (message.find("Kernel for {vlsdpa:vlsdpa} is not found in the kernel cache") != std::string::npos ||
+ message.find("ProgramBuilder build failed") != std::string::npos) {
+ GTEST_SKIP() << "VLSDPA CM kernel is unavailable in this environment: " << message;
+ }
+ throw;
+ }
+}
+
+namespace {
+
+// cu_seqlens starts from 0, ends with seqlen.
+const std::vector<std::vector<int32_t>> input_cu_seqlens = {
+ {0, 4},
+ {0, 16, 32},
+ {0, 64, 128, 192, 256}
+};
+
+INSTANTIATE_TEST_SUITE_P(smoke_TransposeSplitVLSDPATest,
+ TransposeSplitVLSDPATestOnGPU,
+ ::testing::Combine(::testing::Values(ov::element::f16),
+ ::testing::Values(1, 2), // num_heads
+ ::testing::Values(16, 64), // head_size
+ ::testing::ValuesIn(input_cu_seqlens)),
+ TransposeSplitVLSDPATestOnGPU::getTestCaseName);
+
+} // namespace
+
+} // namespace test
+} // namespace ov
diff --git a/src/plugins/intel_gpu/tests/unit/module_tests/layout_test.cpp b/src/plugins/intel_gpu/tests/unit/module_tests/layout_test.cpp
index 0b491f83e4e..404831ddbbe 100644
--- a/src/plugins/intel_gpu/tests/unit/module_tests/layout_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/module_tests/layout_test.cpp
@@ -182,7 +182,7 @@ TEST_P(weights_layout_test, size_check) {
ASSERT_EQ(ordered_dims[i], p.size[p.expected_order[i]]);
}
- if (p.expected_pitches.size() > 0)
+ if (!p.expected_pitches.empty())
ASSERT_EQ(l.get_pitches(), p.expected_pitches);
else {
l.get_pitches();
@@ -209,6 +209,14 @@ struct layouts_cmp_test_params {
class layout_cmp_test : public testing::TestWithParam<layouts_cmp_test_params> { };
+TEST(layout_test, to_short_string_contains_padding_details) {
+ const auto l = layout{ov::PartialShape{1, 2, 3, 4}, data_types::f32, format::bfyx, padding{{1, 2, 3, 4}, {5, 6, 7, 8}}};
+ const auto str = l.to_short_string();
+
+ EXPECT_NE(str.find(":pad_l[1,2,3,4]"), std::string::npos);
+ EXPECT_NE(str.find(":pad_u[5,6,7,8]"), std::string::npos);
+}
+
TEST_P(layout_cmp_test, basic) {
auto p = GetParam();
diff --git a/src/plugins/intel_gpu/tests/unit/passes/prepare_buffer_fusing_test.cpp b/src/plugins/intel_gpu/tests/unit/passes/prepare_buffer_fusing_test.cpp
index dda55912df3..23440abfc0f 100644
--- a/src/plugins/intel_gpu/tests/unit/passes/prepare_buffer_fusing_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/passes/prepare_buffer_fusing_test.cpp
@@ -7,6 +7,10 @@
#include "test_utils.h"
#include "random_generator.hpp"
+#include <intel_gpu/primitives/vl_sdpa.hpp>
+#include "vl_sdpa_inst.h"
+#include "graph/impls/ocl/kernel_selector_helper.h"
+
#include "intel_gpu/runtime/engine.hpp"
#include "intel_gpu/graph/program.hpp"
@@ -974,6 +978,42 @@ TEST(prepare_buffer_fusing, in_place_crop_dynamic) {
ASSERT_EQ(output_ptr_3[i], out3[i]);
}
+TEST(prepare_buffer_fusing, do_runtime_in_place_crop_skips_non_propagatable_reshape_when_reshape_was_preupdated) {
+ auto& engine = get_test_engine();
+
+ auto in_layout = layout{ov::PartialShape{1, 1, 4}, data_types::f32, format::bfyx};
+ auto axis_mem = engine.allocate_memory({{}, data_types::i64, format::bfyx});
+ auto splits_length_mem = engine.allocate_memory({{2}, data_types::i64, format::bfyx});
+ set_values<int64_t>(axis_mem, {2});
+ set_values<int64_t>(splits_length_mem, {2, 2});
+
+ topology topology(
+ input_layout("input", in_layout),
+ data("axis", axis_mem),
+ data("splits_length", splits_length_mem),
+ crop("crop", {input_info("input"), input_info("axis"), input_info("splits_length")},
+ cldnn::tensor(1), cldnn::tensor(0), cldnn::crop_ngraph_op_mode::variadic_split, 0, 2),
+ reshape("reshape", input_info("crop"), false, {}, ov::PartialShape{-1, -1, 4}, cldnn::reshape::reshape_mode::base),
+ reorder("output", input_info("reshape"), format::bfyx, data_types::f32));
+
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ network network(engine, topology, config);
+
+ auto input_inst = network.get_primitive("input");
+ auto crop_inst = network.get_primitive("crop");
+ auto reshape_inst = network.get_primitive("reshape");
+
+ crop_inst->set_can_be_optimized(true);
+ const_cast<cldnn::program_node&>(crop_inst->get_node()).can_be_optimized(true);
+ PrimitiveInstTestHelper::set_update_shape_done_by_other(reshape_inst, true);
+
+ PrimitiveInstTestHelper::do_runtime_in_place_crop(input_inst);
+
+ ASSERT_FALSE(crop_inst->can_be_optimized());
+}
+
TEST(prepare_buffer_fusing, in_place_crop_dynamic_reshape_unsqueeze) {
auto& engine = get_test_engine();
@@ -1370,7 +1410,7 @@ TEST(prepare_buffer_fusing, test_implicit_crop_and_outerpadding) {
// For conv, Check padded input and weight propagated by implicit crop are handled properly
TEST(prepare_buffer_fusing, test_implicit_crop_and_outerpadding_conv) {
auto& engine = get_test_engine();
- const std::string no_bias = "";
+ const std::string no_bias;
auto input = engine.allocate_memory({ data_types::f32, format::bfyx, { 2, 1, 5, 4 } });
auto weights = engine.allocate_memory({ data_types::f32, format::bfyx, { 2, 1, 3, 2 } });
@@ -1431,7 +1471,7 @@ TEST(prepare_buffer_fusing, test_implicit_crop_and_outerpadding_conv) {
// For deconv, Check padded input and weight propagated by implicit crop are handled properly
TEST(prepare_buffer_fusing, test_implicit_crop_and_outerpadding_deconv) {
auto& engine = get_test_engine();
- const std::string no_bias = "";
+ const std::string no_bias;
auto input = engine.allocate_memory({ data_types::f32, format::bfyx, { 4, 1, 2, 2 } });
auto weights = engine.allocate_memory({ data_types::f32, format::bfyx, { 2, 1, 2, 2 } });
auto biases = engine.allocate_memory({ data_types::f32, format::bfyx, { 1, 1, 1, 1 } });
@@ -2386,6 +2426,776 @@ TEST(prepare_buffer_fusing, in_place_crop_static_output_with_dynamic_predecessor
}
}
+// Runtime along-feature contract for the TransposeSplitMatcher pattern is covered
+// by `in_place_crop_along_feature_runtime_updates_reshape_padding` below. That
+// test uses the same shape family (input `[-1, 3, H, S]`, variadic_split axis=1,
+// splits `{1,1,1}`) but drives it end-to-end through `network::execute()` and
+// asserts the physically-correct padding contract on all three reshape outputs:
+// _lower_size[1] == k*H, _upper_size[1] == (F-1-k)*H,
+// get_pitches()[0] == F*H*S, get_linear_offset() == k*H*S.
+// A former build-time-only variant of this test asserted arbitrary
+// `_lower_size[1] == 1` / `_upper_size[1] == 1` values that the build-time
+// `simple_data_format` dynamic branch never actually writes (that branch sets
+// only the dynamic pad mask, not concrete sizes), so it has been dropped in
+// favor of the runtime test.
+
+// =============================================================================
+// UNIT TEST: runtime along-feature path must propagate the crop's feature-axis
+// padding into the reshape output layout.
+// -----------------------------------------------------------------------------
+// Contract under test:
+// When do_runtime_in_place_crop picks the along-feature branch (because the
+// crop preserves batch/spatial dims and only cuts on the feature axis) and
+// the crop's user is a rank-reducing reshape flagged as
+// is_runtime_propagatable_padding(), the reshape output layout MUST end up
+// with a non-empty data_padding at runtime. Otherwise downstream consumers
+// (eltwise, RoPE, vl_sdpa, ...) read the wrong region of the parent buffer.
+//
+// Failure mode under current code (before fix):
+// The along-feature helper only updates crop_layout.data_padding, and the
+// caller relies on reshape_inst->update_shape() to re-derive the reshape
+// output padding. But reshape_inst::calc_output_layouts explicitly resets
+// the padding to padding() for reshape_mode::base (see reshape.cpp), so the
+// reshape observes no padding at all -> optimization is silently broken
+// for the TransposeSplitMatcher pattern.
+//
+// Setup (TransposeSplitMatcher pattern):
+// Build a topology with a dynamic input [-1, 3, H, S] so the build-time
+// crop optimization goes through simple_data_format (build-time dynamic
+// branch, which stamps a dyn pad mask on the reshape output). Then run
+// with a concrete static [L, 3, H, S] so that do_runtime_in_place_crop's
+// along-feature branch fires (can_crop_be_optimized_along_feature is true
+// because batch/H/S are preserved). Three crops on axis=1 of size 1
+// feed rank-reducing reshapes (base mode, [-1, 1, H, S] -> [-1, H, S]),
+// each followed by an eltwise producer so the network can execute.
+//
+// Expectations after execute():
+// 1) All three crops are optimized in-place (can_be_optimized() == true).
+// 2) Each reshape*'s runtime output layout carries a dynamic pad mask on
+// at least one axis.
+// 3) The total padding (sum of lower + upper across all axes) on each
+// reshape output equals 2 — the crop takes 1 slot out of 3, so 2 slots
+// of padding remain regardless of which slice we're looking at
+// (slice 0: 0 + 2, slice 1: 1 + 1, slice 2: 2 + 0).
+// =============================================================================
+TEST(prepare_buffer_fusing, in_place_crop_along_feature_runtime_updates_reshape_padding) {
+ auto& engine = get_test_engine();
+ tests::random_generator rg(GET_SUITE_NAME);
+
+ const int64_t L = 32, H = 4, S = 8;
+
+ auto in_layout_dyn = layout{ov::PartialShape{-1, 3, H, S}, data_types::f16, format::bfyx};
+ auto input_mem = engine.allocate_memory({{L, 3, H, S}, data_types::f16, format::bfyx});
+ auto axis_mem = engine.allocate_memory({{}, data_types::i64, format::bfyx});
+ auto splits_len_mem = engine.allocate_memory({{3}, data_types::i64, format::bfyx});
+ auto scale_mem = engine.allocate_memory({{1}, data_types::f16, format::bfyx});
+
+ auto input_data = rg.generate_random_1d<ov::float16>(L * 3 * H * S, -1.f, 1.f);
+ set_values(input_mem, input_data);
+ set_values<int64_t>(axis_mem, {1});
+ set_values<int64_t>(splits_len_mem, {1, 1, 1});
+ set_values<ov::float16>(scale_mem, {ov::float16(1.f)});
+
+ const auto op_mode = cldnn::crop_ngraph_op_mode::variadic_split;
+ const int64_t axis = 1;
+ // Use an explicit output_pattern so reshape's shape inference can resolve
+ // the dynamic batch dim at runtime; special_zero=false with -1 tells
+ // ov::op::v1::Reshape to infer this dim from the total element count.
+ // Without a resolvable output shape, downstream nodes would trip
+ // "[GPU] Count is called for dynamic shape" during execute().
+ const std::vector<int64_t> rs_pattern = {-1, H, S};
+ const auto rs_shape_dyn = ov::PartialShape{-1, H, S};
+
+ topology topo(
+ input_layout("input", in_layout_dyn),
+ data("axis", axis_mem),
+ data("splits_len", splits_len_mem),
+ data("scale", scale_mem),
+ crop("crop0", {input_info("input"), input_info("axis"), input_info("splits_len")},
+ cldnn::tensor(1), cldnn::tensor(0), op_mode, 0, axis),
+ reshape("reshape0", input_info("crop0"), false, rs_pattern, rs_shape_dyn, cldnn::reshape::reshape_mode::base),
+ eltwise("out0", {input_info("reshape0"), input_info("scale")}, eltwise_mode::prod),
+ crop("crop1", {input_info("input"), input_info("axis"), input_info("splits_len")},
+ cldnn::tensor(1), cldnn::tensor(0), op_mode, 1, axis),
+ reshape("reshape1", input_info("crop1"), false, rs_pattern, rs_shape_dyn, cldnn::reshape::reshape_mode::base),
+ eltwise("out1", {input_info("reshape1"), input_info("scale")}, eltwise_mode::prod),
+ crop("crop2", {input_info("input"), input_info("axis"), input_info("splits_len")},
+ cldnn::tensor(1), cldnn::tensor(0), op_mode, 2, axis),
+ reshape("reshape2", input_info("crop2"), false, rs_pattern, rs_shape_dyn, cldnn::reshape::reshape_mode::base),
+ eltwise("out2", {input_info("reshape2"), input_info("scale")}, eltwise_mode::prod)
+ );
+
+ ExecutionConfig config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+
+ network net(engine, topo, config);
+ net.set_input_data("input", input_mem);
+ net.execute();
+
+ ASSERT_TRUE(net.get_primitive("crop0")->can_be_optimized()) << "crop0 must be in-place at runtime";
+ ASSERT_TRUE(net.get_primitive("crop1")->can_be_optimized()) << "crop1 must be in-place at runtime";
+ ASSERT_TRUE(net.get_primitive("crop2")->can_be_optimized()) << "crop2 must be in-place at runtime";
+
+ // Physically-correct reshape padding contract:
+ // The reshape output layout must view the parent QKV buffer with:
+ // get_pitches()[0] == F * H * S (per-token stride in parent)
+ // get_linear_offset() == k * H * S (slice-k start offset)
+ // The helper achieves this by placing scaled padding on the reshape's
+ // dim 1 (bfyx feature position = pshape H):
+ // _lower_size[1] = k * H
+ // _upper_size[1] = (F-1-k) * H
+ // Both values are asserted precisely so any regression that reintroduces
+ // the empty / raw-`k` padding will fail the test immediately.
+ constexpr int64_t F = 3;
+ const int64_t expected_pitch = F * H * S;
+ auto assert_reshape_padded = [&](const std::string& id, int64_t k) {
+ const auto inst = net.get_primitive(id);
+ ASSERT_NE(inst, nullptr) << id << " instance not found";
+ const auto& lo = inst->get_output_layout();
+ const auto& pad = lo.data_padding;
+
+ const int64_t expected_lower = k * H;
+ const int64_t expected_upper = (F - 1 - k) * H;
+ const int64_t expected_offset = k * H * S;
+
+ ASSERT_TRUE(pad._dynamic_dims_mask[1])
+ << id << ": dynamic pad mask must be attached to the H axis (dim 1)";
+ ASSERT_EQ(pad._lower_size[1], expected_lower)
+ << id << ": _lower_size[1] must equal k * H = " << expected_lower;
+ ASSERT_EQ(pad._upper_size[1], expected_upper)
+ << id << ": _upper_size[1] must equal (F-1-k) * H = " << expected_upper;
+ ASSERT_EQ(static_cast<int64_t>(lo.get_pitches()[0]), expected_pitch)
+ << id << ": get_pitches()[0] must equal F * H * S = " << expected_pitch;
+ ASSERT_EQ(static_cast<int64_t>(lo.get_linear_offset()), expected_offset)
+ << id << ": get_linear_offset() must equal k * H * S = " << expected_offset;
+ };
+
+ assert_reshape_padded("reshape0", 0);
+ assert_reshape_padded("reshape1", 1);
+ assert_reshape_padded("reshape2", 2);
+}
+
+// =============================================================================
+// UNIT TEST: build-time and runtime must agree on which axis carries the
+// dyn-pad mask for the TransposeSplitMatcher pattern.
+// -----------------------------------------------------------------------------
+// Contract under test:
+// OCL consumers (RoPE, eltwise, MVN, ...) JIT-compile against the layout
+// snapshot produced by prepare_buffer_fusing at build time. The JIT bakes in
+// which shape_info slot to read pad_before / pad_after from — that slot is
+// fixed for the lifetime of the compiled kernel. fill_shape_info_data then
+// writes the runtime _lower_size / _upper_size into that fixed slot.
+//
+// If the along-feature runtime helper places the mask on a DIFFERENT axis
+// than the build-time simple_data_format algorithm, three things break:
+// 1. The JIT'd kernel reads pad_before from the wrong shape_info slot.
+// 2. fill_shape_info_data pulls _lower_size / _upper_size from an axis
+// that carries 0 at runtime (because the actual padding migrated).
+// 3. The consumer walks memory as if the input had no padding, silently
+// addressing the wrong slice.
+//
+// Setup: same TransposeSplitMatcher pattern as
+// in_place_crop_along_feature_runtime_updates_reshape_padding — dynamic
+// input [-1, 3, H, S], variadic_split axis=1 with 3 unit slices, each crop
+// followed by a rank-reducing reshape to [-1, H, S] (base mode).
+//
+// Expectations:
+// For every reshape output, the dyn-pad mask axis chosen by the build-time
+// simple_data_format branch MUST match the axis on which the runtime
+// along-feature helper writes the concrete _lower/_upper values (bfyx dim
+// 1, i.e. the H axis). Otherwise the runtime fix is invisible to any
+// consumer that reads shape_info instead of taking the layout directly.
+// =============================================================================
+TEST(prepare_buffer_fusing, in_place_crop_along_feature_reshape_pad_axis_matches_between_build_and_runtime) {
+ auto& engine = get_test_engine();
+ tests::random_generator rg(GET_SUITE_NAME);
+
+ const int64_t L = 32, H = 4, S = 8;
+
+ auto in_layout_dyn = layout{ov::PartialShape{-1, 3, H, S}, data_types::f16, format::bfyx};
+ auto input_mem = engine.allocate_memory({{L, 3, H, S}, data_types::f16, format::bfyx});
+ auto axis_mem = engine.allocate_memory({{}, data_types::i64, format::bfyx});
+ auto splits_len_mem = engine.allocate_memory({{3}, data_types::i64, format::bfyx});
+ auto scale_mem = engine.allocate_memory({{1}, data_types::f16, format::bfyx});
+
+ auto input_data = rg.generate_random_1d<ov::float16>(L * 3 * H * S, -1.f, 1.f);
+ set_values(input_mem, input_data);
+ set_values<int64_t>(axis_mem, {1});
+ set_values<int64_t>(splits_len_mem, {1, 1, 1});
+ set_values<ov::float16>(scale_mem, {ov::float16(1.f)});
+
+ const auto op_mode = cldnn::crop_ngraph_op_mode::variadic_split;
+ const int64_t axis = 1;
+ const std::vector<int64_t> rs_pattern = {-1, H, S};
+ const auto rs_shape_dyn = ov::PartialShape{-1, H, S};
+
+ topology topo(
+ input_layout("input", in_layout_dyn),
+ data("axis", axis_mem),
+ data("splits_len", splits_len_mem),
+ data("scale", scale_mem),
+ crop("crop0", {input_info("input"), input_info("axis"), input_info("splits_len")},
+ cldnn::tensor(1), cldnn::tensor(0), op_mode, 0, axis),
+ reshape("reshape0", input_info("crop0"), false, rs_pattern, rs_shape_dyn, cldnn::reshape::reshape_mode::base),
+ eltwise("out0", {input_info("reshape0"), input_info("scale")}, eltwise_mode::prod),
+ crop("crop1", {input_info("input"), input_info("axis"), input_info("splits_len")},
+ cldnn::tensor(1), cldnn::tensor(0), op_mode, 1, axis),
+ reshape("reshape1", input_info("crop1"), false, rs_pattern, rs_shape_dyn, cldnn::reshape::reshape_mode::base),
+ eltwise("out1", {input_info("reshape1"), input_info("scale")}, eltwise_mode::prod),
+ crop("crop2", {input_info("input"), input_info("axis"), input_info("splits_len")},
+ cldnn::tensor(1), cldnn::tensor(0), op_mode, 2, axis),
+ reshape("reshape2", input_info("crop2"), false, rs_pattern, rs_shape_dyn, cldnn::reshape::reshape_mode::base),
+ eltwise("out2", {input_info("reshape2"), input_info("scale")}, eltwise_mode::prod)
+ );
+
+ ExecutionConfig config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+
+ auto prog = program::build_program(engine, topo, config, false, false);
+ ASSERT_NE(prog, nullptr);
+
+ // Runtime along-feature helper writes concrete padding on the H axis
+ // (bfyx dim 1). Build-time simple_data_format MUST place the dyn-pad mask
+ // on the same axis so downstream OCL consumers JIT'd from the build-time
+ // layout read the right shape_info slot at runtime.
+ auto assert_build_time_mask_on_h_axis = [&](const std::string& id) {
+ const auto& lo = prog->get_node(id).get_output_layout();
+ const auto& mask = lo.data_padding._dynamic_dims_mask;
+ ASSERT_TRUE(mask[1])
+ << id << ": build-time dyn-pad mask must be attached to the H axis (dim 1) "
+ << "to match the runtime along-feature helper";
+ ASSERT_FALSE(mask[2])
+ << id << ": build-time dyn-pad mask must NOT sit on dim 2 (S axis); "
+ << "otherwise consumers JIT'd against dim 2 will read 0 padding at runtime "
+ << "while the actual padding migrates to dim 1";
+ };
+ assert_build_time_mask_on_h_axis("reshape0");
+ assert_build_time_mask_on_h_axis("reshape1");
+ assert_build_time_mask_on_h_axis("reshape2");
+
+ // Execute and verify that the runtime mask location is IDENTICAL to the
+ // build-time one — no silent migration between axes.
+ network net(prog, 0);
+ net.set_input_data("input", input_mem);
+ net.execute();
+
+ auto assert_masks_agree = [&](const std::string& id) {
+ const auto& build_mask = prog->get_node(id).get_output_layout().data_padding._dynamic_dims_mask;
+ const auto& runtime_mask = net.get_primitive(id)->get_output_layout().data_padding._dynamic_dims_mask;
+ ASSERT_EQ(build_mask, runtime_mask)
+ << id << ": build-time and runtime dyn-pad masks must sit on the same axis; "
+ << "otherwise fill_shape_info_data writes 0 into the JIT-baked slot";
+ };
+ assert_masks_agree("reshape0");
+ assert_masks_agree("reshape1");
+ assert_masks_agree("reshape2");
+}
+
+// =============================================================================
+// UNIT TEST: end-to-end addressing regression through an OCL consumer that
+// reads the reshape's shape_info.
+// -----------------------------------------------------------------------------
+// Contract under test:
+// The full build → JIT → runtime-fill → kernel-arithmetic pipeline for the
+// TransposeSplitMatcher pattern must produce numerically-correct outputs.
+// Downstream consumers walk the padded reshape output using shape_info's
+// pad_before / pad_after slots; if any link in the chain is wrong (build
+// picks a different mask axis than runtime, fill_shape_info_data writes 0
+// into the JIT-baked slot, kernel template picks the wrong slot, etc.),
+// the consumer walks wrong memory and produces wrong data.
+//
+// The other tests in this family assert layout properties in isolation
+// (masks, sizes, pitches, offsets). This one is a *behavior* test: it checks
+// that an eltwise OCL consumer — which is exactly the class of kernel
+// affected by the shape_info axis mismatch documented in the verbose log —
+// reads the correct slice of the parent QKV buffer.
+//
+// The consumer here is `eltwise(reshape, bias, mode=sum)` where `bias` has
+// shape `[L, 1, 1]` with a distinct value per token index. That construction
+// makes any wrong token pitch, wrong linear offset, or shape_info-slot
+// mismatch fail immediately in the numerical comparison against a
+// host-computed golden reference for the correct slice (as opposed to the
+// `scale=1.0f` variant used by sibling tests, which multiplies garbage by
+// 1.0 and silently masks address-walking bugs).
+//
+// Failure mode this catches (pre-fix history):
+// Build-time simple_data_format placed the mask on the S axis (dim 2)
+// while runtime along-feature helper wrote _lower_size / _upper_size on
+// the H axis (dim 1). fill_shape_info_data pulled 0 from the S slot the
+// JIT'd eltwise kernel expected, so the kernel walked the input as if
+// there were no padding: q_start * H * S instead of q_start * F * H * S,
+// plus no k * H * S slice offset. Slice 0 accidentally worked (offset 0),
+// slices 1 and 2 read wrong tokens.
+// =============================================================================
+TEST(prepare_buffer_fusing, in_place_crop_along_feature_end_to_end_addressing_through_ocl_consumer) {
+ auto& engine = get_test_engine();
+ tests::random_generator rg(GET_SUITE_NAME);
+
+ const int64_t L = 32, H = 4, S = 8;
+ constexpr int64_t F = 3;
+
+ auto in_layout_dyn = layout{ov::PartialShape{-1, F, H, S}, data_types::f32, format::bfyx};
+ auto input_mem = engine.allocate_memory({{L, F, H, S}, data_types::f32, format::bfyx});
+ auto axis_mem = engine.allocate_memory({{}, data_types::i64, format::bfyx});
+ auto splits_len_mem = engine.allocate_memory({{F}, data_types::i64, format::bfyx});
+ // Per-token bias broadcast over [H, S]. Distinct value per token so any
+ // wrong token stride / slice offset shows up in the numerical output.
+ auto bias_mem = engine.allocate_memory({{L, 1, 1}, data_types::f32, format::bfyx});
+
+ auto input_data = rg.generate_random_1d<float>(L * F * H * S, -1.f, 1.f);
+ std::vector<float> bias_data(L);
+ for (int64_t t = 0; t < L; t++)
+ bias_data[t] = static_cast<float>(t + 1);
+
+ set_values(input_mem, input_data);
+ set_values<int64_t>(axis_mem, {1});
+ set_values<int64_t>(splits_len_mem, {1, 1, 1});
+ set_values(bias_mem, bias_data);
+
+ const auto op_mode = cldnn::crop_ngraph_op_mode::variadic_split;
+ const int64_t axis = 1;
+ const std::vector<int64_t> rs_pattern = {-1, H, S};
+ const auto rs_shape_dyn = ov::PartialShape{-1, H, S};
+
+ topology topo(
+ input_layout("input", in_layout_dyn),
+ data("axis", axis_mem),
+ data("splits_len", splits_len_mem),
+ data("bias", bias_mem),
+ crop("crop0", {input_info("input"), input_info("axis"), input_info("splits_len")},
+ cldnn::tensor(1), cldnn::tensor(0), op_mode, 0, axis),
+ reshape("reshape0", input_info("crop0"), false, rs_pattern, rs_shape_dyn, cldnn::reshape::reshape_mode::base),
+ eltwise("out0", {input_info("reshape0"), input_info("bias")}, eltwise_mode::sum),
+ crop("crop1", {input_info("input"), input_info("axis"), input_info("splits_len")},
+ cldnn::tensor(1), cldnn::tensor(0), op_mode, 1, axis),
+ reshape("reshape1", input_info("crop1"), false, rs_pattern, rs_shape_dyn, cldnn::reshape::reshape_mode::base),
+ eltwise("out1", {input_info("reshape1"), input_info("bias")}, eltwise_mode::sum),
+ crop("crop2", {input_info("input"), input_info("axis"), input_info("splits_len")},
+ cldnn::tensor(1), cldnn::tensor(0), op_mode, 2, axis),
+ reshape("reshape2", input_info("crop2"), false, rs_pattern, rs_shape_dyn, cldnn::reshape::reshape_mode::base),
+ eltwise("out2", {input_info("reshape2"), input_info("bias")}, eltwise_mode::sum)
+ );
+
+ ExecutionConfig config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+
+ network net(engine, topo, config);
+ net.set_input_data("input", input_mem);
+ auto outputs = net.execute();
+
+ // Sanity: all three crops must be in-place, otherwise the test would
+ // not exercise the shape_info addressing path we care about.
+ ASSERT_TRUE(net.get_primitive("crop0")->can_be_optimized());
+ ASSERT_TRUE(net.get_primitive("crop1")->can_be_optimized());
+ ASSERT_TRUE(net.get_primitive("crop2")->can_be_optimized());
+
+ // Per-slice golden reference computed on the CORRECT slice of the parent
+ // buffer: out_k[t, h, s] = input[t, k, h, s] + bias[t].
+ // Any wrong token stride, wrong linear offset, or shape_info-slot
+ // mismatch will fail one of these comparisons with a diagnostic that
+ // points directly at the offending (k, t, h, s) coordinates.
+ auto check_slice = [&](const std::string& id, int64_t k) {
+ auto out_mem = outputs.at(id).get_memory();
+ cldnn::mem_lock<float> out(out_mem, get_test_stream());
+ ASSERT_EQ(out.size(), static_cast<size_t>(L * H * S)) << id;
+ for (int64_t t = 0; t < L; t++) {
+ for (int64_t h = 0; h < H; h++) {
+ for (int64_t s = 0; s < S; s++) {
+ const size_t in_idx = static_cast<size_t>(((t * F + k) * H + h) * S + s);
+ const size_t out_idx = static_cast<size_t>((t * H + h) * S + s);
+ const float expected = input_data[in_idx] + bias_data[t];
+ ASSERT_FLOAT_EQ(out[out_idx], expected)
+ << id << " mismatch: k=" << k
+ << " t=" << t << " h=" << h << " s=" << s;
+ }
+ }
+ }
+ };
+ check_slice("out0", 0);
+ check_slice("out1", 1);
+ check_slice("out2", 2);
+}
+
+// =============================================================================
+// UNIT TEST: runtime along-feature path with no reshape user (regression guard).
+// -----------------------------------------------------------------------------
+// Contract under test:
+// After the along-feature helper is extended to take a user_info parameter,
+// the crop-only path (no reshape user) must still work: user_info.first
+// stays null, the helper must not dereference it, and the crop must still
+// be optimized in-place.
+//
+// Setup:
+// Dynamic input [-1, 3, H, S]; a single crop on axis=1 slice 1 feeds
+// directly into a reorder (no reshape between crop and consumer). At
+// runtime, do_runtime_in_place_crop sees crop_users.size() == 1 but the
+// user is not a reshape, so user_info.first stays null through the helper.
+//
+// Expectations after execute():
+// 1) crop is optimized in-place (can_be_optimized() == true).
+// 2) The extended helper signature does not crash with a null user_info.
+// =============================================================================
+TEST(prepare_buffer_fusing, in_place_crop_along_feature_no_reshape_user) {
+ auto& engine = get_test_engine();
+ tests::random_generator rg(GET_SUITE_NAME);
+
+ const int64_t L = 8, H = 4, S = 8;
+
+ auto in_layout_dyn = layout{ov::PartialShape{-1, 3, H, S}, data_types::f16, format::bfyx};
+ auto input_mem = engine.allocate_memory({{L, 3, H, S}, data_types::f16, format::bfyx});
+ auto axis_mem = engine.allocate_memory({{}, data_types::i64, format::bfyx});
+ auto splits_len_mem = engine.allocate_memory({{3}, data_types::i64, format::bfyx});
+
+ auto input_data = rg.generate_random_1d<ov::float16>(L * 3 * H * S, -1.f, 1.f);
+ set_values(input_mem, input_data);
+ set_values<int64_t>(axis_mem, {1});
+ set_values<int64_t>(splits_len_mem, {1, 1, 1});
+
+ topology topo(
+ input_layout("input", in_layout_dyn),
+ data("axis", axis_mem),
+ data("splits_len", splits_len_mem),
+ crop("crop", {input_info("input"), input_info("axis"), input_info("splits_len")},
+ cldnn::tensor(1), cldnn::tensor(0), cldnn::crop_ngraph_op_mode::variadic_split, 1, 1),
+ reorder("out", input_info("crop"), format::bfyx, data_types::f16)
+ );
+
+ ExecutionConfig config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+
+ network net(engine, topo, config);
+ net.set_input_data("input", input_mem);
+ net.execute();
+
+ ASSERT_TRUE(net.get_primitive("crop")->can_be_optimized())
+ << "crop with no reshape user must still be optimized in-place along the feature axis";
+}
+
+// =============================================================================
+// TransposeSplitMatcher: Split(axis=1) with 3 crops -> Reshape -> eltwise
+//
+// Pattern: Input[-1, 3, H, S]
+// crop0(axis=1, slice=0) [-1,1,H,S] -> reshape[-1,H,S] -> eltwise(scale) -> out0
+// crop1(axis=1, slice=1) [-1,1,H,S] -> reshape[-1,H,S] -> eltwise(scale) -> out1
+// crop2(axis=1, slice=2) [-1,1,H,S] -> reshape[-1,H,S] -> eltwise(scale) -> out2
+//
+// All 3 crops must have can_be_optimized=1 at runtime:
+// axis=1, input[1]==1 (static), output rank = input rank - 1
+// reshape.is_runtime_propagatable_padding() == true for all three
+// downstream consumer is eltwise (no further block)
+// =============================================================================
+TEST(prepare_buffer_fusing, in_place_crop_split_axis1_three_crops_eltwise_consumer) {
+ auto& engine = get_test_engine();
+ tests::random_generator rg(GET_SUITE_NAME);
+
+ const int64_t H = 4, S = 8;
+ const int64_t L = 16; // batch (sequence length)
+
+ // Use a STATIC input layout so that the GPU runtime can allocate output buffers.
+ // The dynamic propagation (is_runtime_propagatable_padding) is verified at
+ // program-build level below; runtime can_be_optimized is verified after execute().
+ auto in_layout = layout{{L, 3, H, S}, data_types::f16, format::bfyx};
+ auto in_layout_dyn = layout{ov::PartialShape{-1, 3, H, S}, data_types::f16, format::bfyx};
+ auto input_mem = engine.allocate_memory(in_layout);
+ auto axis_mem = engine.allocate_memory({{}, data_types::i64, format::bfyx});
+ auto splits_len_mem = engine.allocate_memory({{3}, data_types::i64, format::bfyx});
+
+ auto input_data = rg.generate_random_1d<ov::float16>(L * 3 * H * S, -1.f, 1.f);
+ set_values(input_mem, input_data);
+ set_values<int64_t>(axis_mem, {1});
+ set_values<int64_t>(splits_len_mem, {1, 1, 1});
+
+ auto op_mode = cldnn::crop_ngraph_op_mode::variadic_split;
+ const int64_t axis = 1;
+ // Reshape output shape: static for proper buffer allocation
+ auto rs_shape = ov::PartialShape{L, H, S};
+ auto rs_shape_dyn = ov::PartialShape{-1, H, S};
+
+ // Build topology with the DYNAMIC layout for the is_runtime_propagatable_padding check
+ topology topo_dyn(
+ input_layout("input", in_layout_dyn),
+ data("axis", axis_mem),
+ data("splits_len", splits_len_mem),
+ crop("crop0", {input_info("input"), input_info("axis"), input_info("splits_len")},
+ cldnn::tensor(1), cldnn::tensor(0), op_mode, 0, axis),
+ reshape("reshape0", input_info("crop0"), false, {}, rs_shape_dyn, cldnn::reshape::reshape_mode::base),
+ reorder("out0", input_info("reshape0"), format::bfyx, data_types::f16,
+ std::vector<float>(), reorder_mean_mode::subtract, padding(), true),
+ crop("crop1", {input_info("input"), input_info("axis"), input_info("splits_len")},
+ cldnn::tensor(1), cldnn::tensor(0), op_mode, 1, axis),
+ reshape("reshape1", input_info("crop1"), false, {}, rs_shape_dyn, cldnn::reshape::reshape_mode::base),
+ reorder("out1", input_info("reshape1"), format::bfyx, data_types::f16,
+ std::vector<float>(), reorder_mean_mode::subtract, padding(), true),
+ crop("crop2", {input_info("input"), input_info("axis"), input_info("splits_len")},
+ cldnn::tensor(1), cldnn::tensor(0), op_mode, 2, axis),
+ reshape("reshape2", input_info("crop2"), false, {}, rs_shape_dyn, cldnn::reshape::reshape_mode::base),
+ reorder("out2", input_info("reshape2"), format::bfyx, data_types::f16,
+ std::vector<float>(), reorder_mean_mode::subtract, padding(), true)
+ );
+ ExecutionConfig config_dyn = get_test_default_config(engine);
+ config_dyn.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config_dyn.set_property(ov::intel_gpu::optimize_data(true));
+
+ // Check static optimization decision: all 3 reshapes must be is_runtime_propagatable_padding
+ auto prog = program::build_program(engine, topo_dyn, config_dyn, false, true);
+ ASSERT_NE(prog, nullptr);
+ ASSERT_TRUE(prog->get_node("reshape0").as<reshape>().is_runtime_propagatable_padding())
+ << "reshape0 must be runtime-propagatable";
+ ASSERT_TRUE(prog->get_node("reshape1").as<reshape>().is_runtime_propagatable_padding())
+ << "reshape1 must be runtime-propagatable";
+ ASSERT_TRUE(prog->get_node("reshape2").as<reshape>().is_runtime_propagatable_padding())
+ << "reshape2 must be runtime-propagatable";
+
+ // For runtime check, use the dynamic topology. The reorder output marker nodes
+ // allow observing can_be_optimized at runtime without triggering count() errors.
+ network net(engine, topo_dyn, config_dyn);
+ net.set_input_data("input", input_mem);
+
+ // Verify can_be_optimized BEFORE execute so we check the compile-time decision
+ // (prepare_buffer_fusing sets can_be_optimized statically for dynamic crops too
+ // when is_runtime_propagatable_padding() returns true and the simple_data_format
+ // path fires at build time)
+ ASSERT_TRUE(net.get_primitive("crop0")->can_be_optimized()) << "crop0 should be in-place";
+ ASSERT_TRUE(net.get_primitive("crop1")->can_be_optimized()) << "crop1 should be in-place";
+ ASSERT_TRUE(net.get_primitive("crop2")->can_be_optimized()) << "crop2 should be in-place";
+}
+
+// =============================================================================
+// TransposeSplitMatcher: Split(axis=1) with 3 crops -> vl_sdpa consumer.
+// -----------------------------------------------------------------------------
+// vl_sdpa-specific coverage. General "3 crops in-place" for the
+// TransposeSplitMatcher axis=1 pattern is covered by the sibling test
+// `in_place_crop_split_axis1_three_crops_eltwise_consumer`; the reshape
+// padding contract (mask axis / _lower / _upper / pitches / offset) is
+// covered by `in_place_crop_along_feature_runtime_updates_reshape_padding`.
+// This test focuses on what only the vl_sdpa consumer path can verify:
+//
+// 1. `is_runtime_propagatable_padding()` returns true for a reshape whose
+// downstream is `vl_sdpa` (the vl_sdpa branch of the predicate in
+// reshape_inst.h). Every other test in the family exercises the
+// eltwise/reorder branches; if someone tightens or reverts the vl_sdpa
+// branch, no other test would notice.
+//
+// 2. Layout asymmetry — V retains the crop-derived padded parent view
+// (F*H*S token pitch) while Q/K went through eltwise and got fresh
+// contiguous buffers (H*S token pitch). Q_pitch == K_pitch != V_pitch.
+// Regresses if reshape2 loses its padded view for the direct-to-vl_sdpa
+// path.
+//
+// 3. End-to-end numerical correctness of the CM kernel's
+// `token_offset_v` / `v_token_pitch` scalar-based addressing. The V
+// input has non-zero linear_offset and non-standard pitch; the CM
+// kernel dispatch reads `params.input_layouts[2].get_linear_offset()`
+// and `.get_pitches()[0]` to compute those scalars, and then the
+// kernel body walks V using them. If any link in that chain is wrong,
+// the numerical comparison against a host-side SDPA reference fails.
+//
+// Pattern: Input[-1, 3, H, S]
+// crop0(axis=1, slice=0) → reshape → eltwise (Q proxy) ────────►
+// crop1(axis=1, slice=1) → reshape → eltwise (K proxy) ────────► vl_sdpa
+// crop2(axis=1, slice=2) → reshape (V, direct) ──────────────►
+//
+// NOTE: vl_sdpa is a CM kernel available only on XMX (systolic) GPU devices.
+// Skipped on non-XMX or non-CM-capable devices.
+// =============================================================================
+TEST(prepare_buffer_fusing, in_place_crop_split_axis1_three_crops_vlsdpa_consumer) {
+ auto& engine = get_test_engine();
+
+ ExecutionConfig check_config = get_test_default_config(engine);
+ if (!engine.get_device_info().supports_immad ||
+ !cldnn::check_cm_jit_support(engine, check_config))
+ GTEST_SKIP() << "vl_sdpa CM kernel not available on this device";
+
+ tests::random_generator rg(GET_SUITE_NAME);
+
+ const int32_t H = 2, S = 64;
+ const std::vector<int32_t> cu_seqlens = {0, 16};
+ const int32_t L = cu_seqlens.back();
+ constexpr int32_t F = 3;
+
+ auto in_layout = layout{ov::PartialShape{-1, F, H, S}, data_types::f16, format::bfyx};
+ auto input_mem = engine.allocate_memory({{L, F, H, S}, data_types::f16, format::bfyx});
+ auto cu_seqlens_mem = engine.allocate_memory({{static_cast<ov::Dimension::value_type>(cu_seqlens.size())}, data_types::i32, format::bfyx});
+ auto axis_mem = engine.allocate_memory({{}, data_types::i64, format::bfyx});
+ auto splits_len_mem = engine.allocate_memory({{F}, data_types::i64, format::bfyx});
+ auto scale_mem = engine.allocate_memory({{1}, data_types::f16, format::bfyx});
+
+ auto input_data = rg.generate_random_1d<ov::float16>(L * F * H * S, -0.5f, 0.5f);
+ set_values(input_mem, input_data);
+ set_values(cu_seqlens_mem, cu_seqlens);
+ set_values<int64_t>(axis_mem, {1});
+ set_values<int64_t>(splits_len_mem, {1, 1, 1});
+ set_values<ov::float16>(scale_mem, {ov::float16(1.f)});
+
+ auto op_mode = cldnn::crop_ngraph_op_mode::variadic_split;
+ const int64_t axis = 1;
+ const std::vector<int64_t> rs_pattern = {-1, H, S};
+ const auto rs_shape = ov::PartialShape{-1, H, S};
+
+ // vl_sdpa transpose order: raw memory is [L, H, S] but the kernel extracts
+ // num_heads / head_size from dim 1 / dim 2 of the logical view. Order
+ // {1, 0, 2} maps raw dims [L, H, S] to logical [H, L, S] so that
+ // num_heads = raw[1] = H and head_size = raw[2] = S. This matches the
+ // functional test in transpose_split_vlsdpa.cpp. Using identity order
+ // here silently mis-computes num_heads as L.
+ const std::vector<int64_t> order{1, 0, 2};
+
+ topology topo(
+ input_layout("input", in_layout),
+ input_layout("cu_seqlens", layout{ov::PartialShape{-1}, data_types::i32, format::bfyx}),
+ data("axis", axis_mem),
+ data("splits_len", splits_len_mem),
+ data("scale", scale_mem),
+ // Q path: crop0 → reshape → eltwise*1.0 (contiguous fresh buffer).
+ crop("crop0", {input_info("input"), input_info("axis"), input_info("splits_len")},
+ cldnn::tensor(1), cldnn::tensor(0), op_mode, 0, axis),
+ reshape("reshape0", input_info("crop0"), false, rs_pattern, rs_shape, cldnn::reshape::reshape_mode::base),
+ eltwise("eltwise0", {input_info("reshape0"), input_info("scale")}, eltwise_mode::prod),
+ // K path: crop1 → reshape → eltwise*1.0 (contiguous fresh buffer).
+ crop("crop1", {input_info("input"), input_info("axis"), input_info("splits_len")},
+ cldnn::tensor(1), cldnn::tensor(0), op_mode, 1, axis),
+ reshape("reshape1", input_info("crop1"), false, rs_pattern, rs_shape, cldnn::reshape::reshape_mode::base),
+ eltwise("eltwise1", {input_info("reshape1"), input_info("scale")}, eltwise_mode::prod),
+ // V path: crop2 → reshape (padded view straight into vl_sdpa).
+ crop("crop2", {input_info("input"), input_info("axis"), input_info("splits_len")},
+ cldnn::tensor(1), cldnn::tensor(0), op_mode, 2, axis),
+ reshape("reshape2", input_info("crop2"), false, rs_pattern, rs_shape, cldnn::reshape::reshape_mode::base),
+ vl_sdpa("vlsdpa",
+ {input_info("eltwise0"), input_info("eltwise1"),
+ input_info("reshape2"), input_info("cu_seqlens")},
+ order, order, order, order),
+ reorder("output", input_info("vlsdpa"), format::bfyx, data_types::f16)
+ );
+
+ ExecutionConfig config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+
+ // (1) Build-time predicate: all 3 reshapes must be runtime-propagatable,
+ // including reshape2 whose downstream is vl_sdpa (the branch unique
+ // to this test).
+ {
+ auto prog = program::build_program(engine, topo, config, false, true);
+ ASSERT_NE(prog, nullptr);
+ ASSERT_TRUE(prog->get_node("reshape0").as<reshape>().is_runtime_propagatable_padding())
+ << "reshape0 (Q→eltwise) must be runtime-propagatable";
+ ASSERT_TRUE(prog->get_node("reshape1").as<reshape>().is_runtime_propagatable_padding())
+ << "reshape1 (K→eltwise) must be runtime-propagatable";
+ ASSERT_TRUE(prog->get_node("reshape2").as<reshape>().is_runtime_propagatable_padding())
+ << "reshape2 (V→vl_sdpa) must be runtime-propagatable (vl_sdpa-specific guard)";
+ }
+
+ // Execute with optimizations enabled.
+ network net(engine, topo, config);
+ net.set_input_data("input", input_mem);
+ net.set_input_data("cu_seqlens", cu_seqlens_mem);
+ auto outputs = net.execute();
+ auto out_mem = outputs.at("output").get_memory();
+ ASSERT_NE(out_mem, nullptr);
+
+ // (2) Layout asymmetry: V still carries crop-derived padding (F*H*S
+ // token pitch); Q/K went through eltwise and are contiguous (H*S).
+ // If reshape2 loses its padded view for the vl_sdpa path, v_pitch
+ // collapses to q_pitch.
+ const auto q_pitch = net.get_primitive("eltwise0")->get_output_layout().get_pitches()[0];
+ const auto k_pitch = net.get_primitive("eltwise1")->get_output_layout().get_pitches()[0];
+ const auto v_pitch = net.get_primitive("reshape2")->get_output_layout().get_pitches()[0];
+ ASSERT_EQ(q_pitch, k_pitch)
+ << "Q and K flow through eltwise, so their pitches must match";
+ ASSERT_NE(v_pitch, q_pitch)
+ << "V must keep the crop-derived padded pitch (F*H*S) — regression if it collapses to H*S";
+
+ // (3) End-to-end numerical: host-side SDPA reference against vl_sdpa
+ // output. This is the only automated check that the CM kernel's
+ // token_offset_v / v_token_pitch scalar dispatch actually addresses
+ // the correct V slice of the parent QKV buffer.
+ //
+ // Reference: for each sequence [seq_start, seq_end) and each query
+ // token q in that range, each head h computes
+ // scores[k] = (Q[q, h] · K[seq_start+k, hkv]) * scale
+ // P[k] = softmax(scores)
+ // out[q, h] = sum_k P[k] * V[seq_start+k, hkv]
+ // with scale = 1 / sqrt(head_size). No causal mask (vl_sdpa
+ // wrapper passes use_causal_mask=false). Q, K, V come from the
+ // three F-slices of the parent input: Q = input[:, 0, :, :],
+ // K = input[:, 1, :, :], V = input[:, 2, :, :].
+ const size_t num_heads = static_cast<size_t>(H);
+ const size_t num_kv_heads = static_cast<size_t>(H);
+ const size_t head_ratio = num_heads / num_kv_heads;
+ const float scale = 1.0f / std::sqrt(static_cast<float>(S));
+
+ auto qkv_at = [&](size_t token, int32_t f, size_t head, size_t d) -> float {
+ const size_t off = ((token * static_cast<size_t>(F) + static_cast<size_t>(f)) * num_heads + head) * static_cast<size_t>(S) + d;
+ return static_cast<float>(input_data[off]);
+ };
+
+ std::vector<float> ref_output(static_cast<size_t>(L) * num_heads * static_cast<size_t>(S), 0.f);
+ for (size_t s = 0; s + 1 < cu_seqlens.size(); s++) {
+ const int32_t seq_start = cu_seqlens[s];
+ const int32_t seq_end = cu_seqlens[s + 1];
+ const int32_t seq_len = seq_end - seq_start;
+ ASSERT_GT(seq_len, 0);
+
+ std::vector<float> scores(static_cast<size_t>(seq_len));
+ for (int32_t q = 0; q < seq_len; q++) {
+ const size_t q_idx = static_cast<size_t>(seq_start + q);
+ for (size_t h = 0; h < num_heads; h++) {
+ const size_t hkv = h / head_ratio;
+ // dot-products Q·K, scaled.
+ for (int32_t k = 0; k < seq_len; k++) {
+ const size_t k_idx = static_cast<size_t>(seq_start + k);
+ float acc = 0.f;
+ for (size_t d = 0; d < static_cast<size_t>(S); d++) {
+ acc += qkv_at(q_idx, 0, h, d) * qkv_at(k_idx, 1, hkv, d);
+ }
+ scores[static_cast<size_t>(k)] = acc * scale;
+ }
+ // softmax
+ float max_s = scores[0];
+ for (int32_t k = 1; k < seq_len; k++)
+ max_s = std::max(max_s, scores[static_cast<size_t>(k)]);
+ float denom = 0.f;
+ for (int32_t k = 0; k < seq_len; k++) {
+ scores[static_cast<size_t>(k)] = std::exp(scores[static_cast<size_t>(k)] - max_s);
+ denom += scores[static_cast<size_t>(k)];
+ }
+ const float inv_denom = 1.f / denom;
+ for (int32_t k = 0; k < seq_len; k++)
+ scores[static_cast<size_t>(k)] *= inv_denom;
+ // weighted sum with V.
+ for (size_t d = 0; d < static_cast<size_t>(S); d++) {
+ float acc = 0.f;
+ for (int32_t k = 0; k < seq_len; k++) {
+ const size_t k_idx = static_cast<size_t>(seq_start + k);
+ acc += scores[static_cast<size_t>(k)] * qkv_at(k_idx, 2, hkv, d);
+ }
+ ref_output[(q_idx * num_heads + h) * static_cast<size_t>(S) + d] = acc;
+ }
+ }
+ }
+ }
+
+ cldnn::mem_lock<ov::float16> observed(out_mem, get_test_stream());
+ ASSERT_EQ(observed.size(), ref_output.size());
+ // f16 + softmax tolerance. Values stay in a well-behaved range because
+ // the inputs are in [-0.5, 0.5] and the head_size normalization keeps
+ // pre-softmax scores modest.
+ const float tol = 5e-2f;
+ for (size_t i = 0; i < ref_output.size(); i++) {
+ const float got = static_cast<float>(observed[i]);
+ ASSERT_NEAR(got, ref_output[i], tol)
+ << "vl_sdpa output mismatch at flat index " << i
+ << " (token=" << (i / (num_heads * S))
+ << " head=" << ((i / S) % num_heads)
+ << " dim=" << (i % S) << ")"
+ << " — CM kernel likely addressed wrong V slice via token_offset_v / v_token_pitch";
+ }
+}
+
// A concat with one predecessor inside a shape-of subgraph (a crop lowered from VariadicSplit,
// running on a CPU impl that can't produce padded output) and one outside must NOT be optimized
// in place: implicit concat would force offset padding on the CPU crop output and assert at
diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/vlsdpa_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/vlsdpa_gpu_test.cpp
index e45ca319ca8..e956937048b 100644
--- a/src/plugins/intel_gpu/tests/unit/test_cases/vlsdpa_gpu_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/test_cases/vlsdpa_gpu_test.cpp
@@ -348,6 +348,173 @@ struct vlsdpa_gpu_test : public ::testing::TestWithParam<vlsdpa_test_params> {
const std::vector<uint16_t> order_o2 = {1, 0, 2}; // primitive permute constructor asks "ushort"
};
+struct mixed_pitch_case_params {
+ int32_t num_heads;
+ int32_t head_size;
+ std::vector<int32_t> cu_seqlens;
+ int32_t q_lower_pad_heads;
+ int32_t k_lower_pad_heads;
+ int32_t v_lower_pad_heads;
+};
+
+static void run_mixed_pitch_case(const mixed_pitch_case_params& p,
+ const bool strict_elementwise = false) {
+ if (!vlsdpa_gpu_test::check_vlsdpa_available())
+ GTEST_SKIP();
+
+ auto& engine = get_test_engine();
+ tests::random_generator rg(GET_SUITE_NAME);
+ rg.set_seed(GET_SUITE_NAME);
+
+ const int32_t H = p.num_heads;
+ const int32_t S = p.head_size;
+ const int32_t L = p.cu_seqlens.back();
+
+ const std::vector<int64_t> order_q = {1, 0, 2};
+ const std::vector<int64_t> order_k = {1, 0, 2};
+ const std::vector<int64_t> order_v = {1, 0, 2};
+ const std::vector<int64_t> order_o = {1, 0, 2};
+ const std::vector<uint16_t> order_o2 = {1, 0, 2};
+
+ layout q_dyn({-1, H, S}, data_types::f16, format::bfyx);
+ layout k_dyn({-1, H, S}, data_types::f16, format::bfyx);
+ layout v_dyn({-1, H, S}, data_types::f16, format::bfyx);
+ layout attn_mask_dyn({1, -1, -1}, data_types::f16, format::bfyx);
+ layout cu_dyn({-1}, data_types::i32, format::bfyx);
+
+ layout q_static({L, H, S}, data_types::f16, format::bfyx);
+ layout k_static({L, H, S}, data_types::f16, format::bfyx);
+ layout v_static({L, H, S}, data_types::f16, format::bfyx);
+ layout attn_mask_static({1, L, L}, data_types::f16, format::bfyx);
+ layout cu_static({static_cast<ov::Dimension::value_type>(p.cu_seqlens.size())}, data_types::i32, format::bfyx);
+
+ // Per-input lower feature padding emulates independent runtime base offsets / token pitches.
+ layout q_padded_static({L, H, S}, data_types::f16, format::bfyx,
+ padding({0, p.q_lower_pad_heads, 0, 0}, {0, 0, 0, 0}));
+ layout k_padded_static({L, H, S}, data_types::f16, format::bfyx,
+ padding({0, p.k_lower_pad_heads, 0, 0}, {0, 0, 0, 0}));
+ layout v_padded_static({L, H, S}, data_types::f16, format::bfyx,
+ padding({0, p.v_lower_pad_heads, 0, 0}, {0, 0, 0, 0}));
+
+ topology ref_topo;
+ ref_topo.add(input_layout("q", q_dyn));
+ ref_topo.add(input_layout("k", k_dyn));
+ ref_topo.add(input_layout("v", v_dyn));
+ ref_topo.add(input_layout("attn", attn_mask_dyn));
+ ref_topo.add(scaled_dot_product_attention("sdpa",
+ {input_info("q"), input_info("k"), input_info("v"), input_info("attn")},
+ false, -1, order_q, order_k, order_v, {0, 1, 2}, {}, false));
+ ref_topo.add(permute("permute_o", input_info("sdpa"), order_o2));
+ ref_topo.add(reorder("result", input_info("permute_o"), format::bfyx, data_types::f16));
+
+ topology opt_topo;
+ opt_topo.add(input_layout("q_in", q_dyn));
+ opt_topo.add(input_layout("k_in", k_dyn));
+ opt_topo.add(input_layout("v_in", v_dyn));
+ opt_topo.add(input_layout("attn", cu_dyn));
+
+ const std::string q_name = p.q_lower_pad_heads > 0 ? "q_padded" : "q_in";
+ const std::string k_name = p.k_lower_pad_heads > 0 ? "k_padded" : "k_in";
+ const std::string v_name = p.v_lower_pad_heads > 0 ? "v_padded" : "v_in";
+
+ if (p.q_lower_pad_heads > 0) {
+ opt_topo.add(reorder("q_padded", input_info("q_in"), q_padded_static));
+ }
+ if (p.k_lower_pad_heads > 0) {
+ opt_topo.add(reorder("k_padded", input_info("k_in"), k_padded_static));
+ }
+ if (p.v_lower_pad_heads > 0) {
+ opt_topo.add(reorder("v_padded", input_info("v_in"), v_padded_static));
+ }
+
+ opt_topo.add(vl_sdpa("vlsdpa",
+ {input_info(q_name), input_info(k_name), input_info(v_name), input_info("attn")},
+ order_q, order_k, order_v, order_o));
+ opt_topo.add(reorder("result", input_info("vlsdpa"), format::bfyx, data_types::f16));
+
+ auto q_mem = engine.allocate_memory(q_static);
+ auto k_mem = engine.allocate_memory(k_static);
+ auto v_mem = engine.allocate_memory(v_static);
+ auto attn_mask_mem = engine.allocate_memory(attn_mask_static);
+ auto cu_mem = engine.allocate_memory(cu_static);
+
+ auto q_data = rg.generate_random_1d<ov::float16>(L * H * S, -0.5f, 0.5f);
+ auto k_data = rg.generate_random_1d<ov::float16>(L * H * S, -0.5f, 0.5f);
+ auto v_data = rg.generate_random_1d<ov::float16>(L * H * S, -0.5f, 0.5f);
+ set_values(q_mem, q_data);
+ set_values(k_mem, k_data);
+ set_values(v_mem, v_data);
+
+ std::vector<ov::float16> attn_mask_data(static_cast<size_t>(L) * static_cast<size_t>(L), -std::numeric_limits<ov::float16>::infinity());
+ for (size_t i = 1; i < p.cu_seqlens.size(); ++i) {
+ size_t start = static_cast<size_t>(p.cu_seqlens[i - 1]);
+ size_t end = static_cast<size_t>(p.cu_seqlens[i]);
+ for (size_t r = start; r < end; ++r) {
+ for (size_t c = start; c < end; ++c) {
+ attn_mask_data[r * static_cast<size_t>(L) + c] = ov::float16(0.0f);
+ }
+ }
+ }
+ set_values(attn_mask_mem, attn_mask_data);
+ set_values(cu_mem, p.cu_seqlens);
+
+ ExecutionConfig config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+
+ auto ref_net = get_network(engine, ref_topo, config, get_test_stream_ptr(), false);
+ ref_net->set_input_data("q", q_mem);
+ ref_net->set_input_data("k", k_mem);
+ ref_net->set_input_data("v", v_mem);
+ ref_net->set_input_data("attn", attn_mask_mem);
+ auto ref_out = ref_net->execute().at("result").get_memory();
+
+ auto opt_net = get_network(engine, opt_topo, config, get_test_stream_ptr(), false);
+ opt_net->set_input_data("q_in", q_mem);
+ opt_net->set_input_data("k_in", k_mem);
+ opt_net->set_input_data("v_in", v_mem);
+ opt_net->set_input_data("attn", cu_mem);
+ auto opt_out = opt_net->execute().at("result").get_memory();
+
+ const auto q_layout_runtime = opt_net->get_primitive(q_name)->get_output_layout();
+ const auto k_layout_runtime = opt_net->get_primitive(k_name)->get_output_layout();
+ const auto v_layout_runtime = opt_net->get_primitive(v_name)->get_output_layout();
+
+ ASSERT_EQ(static_cast<int32_t>(q_layout_runtime.get_linear_offset()), p.q_lower_pad_heads * S);
+ ASSERT_EQ(static_cast<int32_t>(k_layout_runtime.get_linear_offset()), p.k_lower_pad_heads * S);
+ ASSERT_EQ(static_cast<int32_t>(v_layout_runtime.get_linear_offset()), p.v_lower_pad_heads * S);
+
+ const int32_t expected_q_pitch = (p.q_lower_pad_heads + H) * S;
+ const int32_t expected_k_pitch = (p.k_lower_pad_heads + H) * S;
+ const int32_t expected_v_pitch = (p.v_lower_pad_heads + H) * S;
+ ASSERT_EQ(static_cast<int32_t>(q_layout_runtime.get_pitches()[0]), expected_q_pitch);
+ ASSERT_EQ(static_cast<int32_t>(k_layout_runtime.get_pitches()[0]), expected_k_pitch);
+ ASSERT_EQ(static_cast<int32_t>(v_layout_runtime.get_pitches()[0]), expected_v_pitch);
+
+ cldnn::mem_lock<ov::float16, mem_lock_type::read> ref_data(ref_out, get_test_stream());
+ cldnn::mem_lock<ov::float16, mem_lock_type::read> opt_data(opt_out, get_test_stream());
+
+ ASSERT_EQ(ref_data.size(), opt_data.size())
+ << "Mismatched output element count between reference and VLSDPA paths";
+
+ const float ref_magnitude = std::sqrt(std::inner_product(ref_data.begin(), ref_data.end(), ref_data.begin(), 0.0f));
+ const float opt_magnitude = std::sqrt(std::inner_product(opt_data.begin(), opt_data.end(), opt_data.begin(), 0.0f));
+ ASSERT_GT(ref_magnitude, 0.0f) << "Reference output has zero magnitude";
+ ASSERT_GT(opt_magnitude, 0.0f) << "VLSDPA output has zero magnitude";
+
+ float max_abs_diff = 0.0f;
+ for (size_t idx = 0; idx < ref_data.size(); ++idx) {
+ const float ref_val = static_cast<float>(ref_data[idx]);
+ const float opt_val = static_cast<float>(opt_data[idx]);
+ ASSERT_FALSE(std::isnan(ref_val) || std::isnan(opt_val)) << "NaN found at index " << idx;
+ max_abs_diff = std::max(max_abs_diff, std::abs(ref_val - opt_val));
+ }
+
+ ASSERT_GE(cosineSimilarity(ref_data, opt_data), 0.95f);
+ if (strict_elementwise) {
+ ASSERT_LE(max_abs_diff, 0.10f) << "Max abs diff is too large for strict mixed-pitch check";
+ }
+}
+
TEST_P(vlsdpa_gpu_test, basic) {
if (!check_vlsdpa_available())
GTEST_SKIP();
@@ -398,4 +565,51 @@ INSTANTIATE_TEST_SUITE_P(smoke_vlsdpa_gpu_test,
vlsdpa_gpu_test::PrintToStringParamName
);
+TEST(vlsdpa_gpu_test, mixed_input_runtime_pitches_v_padded) {
+ run_mixed_pitch_case({2 /*H*/, 72 /*S*/, {0, 16} /*cu_seqlens*/,
+ 0 /*q_lower_pad_heads*/, 0 /*k_lower_pad_heads*/, 4 /*v_lower_pad_heads*/});
+}
+
+TEST(vlsdpa_gpu_test, mixed_input_runtime_pitches_control_contiguous) {
+ run_mixed_pitch_case({2 /*H*/, 72 /*S*/, {0, 16} /*cu_seqlens*/,
+ 0 /*q_lower_pad_heads*/, 0 /*k_lower_pad_heads*/, 0 /*v_lower_pad_heads*/});
+}
+
+TEST(vlsdpa_gpu_test, mixed_input_runtime_pitches_q_padded) {
+ run_mixed_pitch_case({2 /*H*/, 72 /*S*/, {0, 16} /*cu_seqlens*/,
+ 4 /*q_lower_pad_heads*/, 0 /*k_lower_pad_heads*/, 0 /*v_lower_pad_heads*/});
+}
+
+TEST(vlsdpa_gpu_test, mixed_input_runtime_pitches_k_padded) {
+ run_mixed_pitch_case({2 /*H*/, 72 /*S*/, {0, 16} /*cu_seqlens*/,
+ 0 /*q_lower_pad_heads*/, 4 /*k_lower_pad_heads*/, 0 /*v_lower_pad_heads*/});
+}
+
+TEST(vlsdpa_gpu_test, mixed_input_runtime_pitches_qkv_all_padded) {
+ // Distinct lower pads per input enforce different base offsets for all three streams.
+ run_mixed_pitch_case({2 /*H*/, 72 /*S*/, {0, 16} /*cu_seqlens*/,
+ 2 /*q_lower_pad_heads*/, 4 /*k_lower_pad_heads*/, 6 /*v_lower_pad_heads*/}, true);
+}
+
+TEST(vlsdpa_gpu_test, mixed_input_runtime_pitches_qk_equal_v_diff_dynamic_l) {
+ run_mixed_pitch_case({2 /*H*/, 72 /*S*/, {0, 16} /*cu_seqlens*/,
+ 0 /*q_lower_pad_heads*/, 0 /*k_lower_pad_heads*/, 4 /*v_lower_pad_heads*/});
+ run_mixed_pitch_case({2 /*H*/, 72 /*S*/, {0, 16, 32} /*cu_seqlens*/,
+ 0 /*q_lower_pad_heads*/, 0 /*k_lower_pad_heads*/, 4 /*v_lower_pad_heads*/});
+}
+
+TEST(vlsdpa_gpu_test, mixed_input_runtime_pitches_headsize_param) {
+ const std::vector<mixed_pitch_case_params> cases = {
+ {1, 64, {0, 16}, 0, 0, 2},
+ {1, 72, {0, 16}, 0, 0, 2},
+ {2, 64, {0, 16}, 0, 0, 4},
+ {2, 72, {0, 16}, 0, 0, 4},
+ {2, 128, {0, 16}, 0, 0, 4},
+ };
+
+ for (const auto& test_case : cases) {
+ run_mixed_pitch_case(test_case);
+ }
+}
+
} // namespace
diff --git a/src/plugins/intel_gpu/tests/unit/test_utils/primitive_inst_test_helper.h b/src/plugins/intel_gpu/tests/unit/test_utils/primitive_inst_test_helper.h
index 2332930a034..93c11c03c92 100644
--- a/src/plugins/intel_gpu/tests/unit/test_utils/primitive_inst_test_helper.h
+++ b/src/plugins/intel_gpu/tests/unit/test_utils/primitive_inst_test_helper.h
@@ -14,6 +14,12 @@ public:
static void set_allocation_done_by_other(const std::shared_ptr<primitive_inst>& inst, bool val) {
inst->_allocation_done_by_other = val;
}
+ static void set_update_shape_done_by_other(const std::shared_ptr<primitive_inst>& inst, bool val) {
+ inst->_update_shape_done_by_other = val;
+ }
+ static void do_runtime_in_place_crop(const std::shared_ptr<primitive_inst>& inst) {
+ inst->do_runtime_in_place_crop();
+ }
static bool need_reset_output_memory(const std::shared_ptr<primitive_inst>& inst) {
return inst->need_reset_output_memory();
}
diff --git a/src/plugins/intel_gpu/tests/unit/transformations/transpose_split_fusion_test.cpp b/src/plugins/intel_gpu/tests/unit/transformations/transpose_split_fusion_test.cpp
new file mode 100644
index 00000000000..681aad213a4
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/unit/transformations/transpose_split_fusion_test.cpp
@@ -0,0 +1,187 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "common_test_utils/ov_test_utils.hpp"
+
+#include <openvino/runtime/core.hpp>
+#include "openvino/core/model.hpp"
+#include "openvino/opsets/opset13.hpp"
+#include "openvino/pass/manager.hpp"
+
+#include "plugin/transformations/transpose_fusion.hpp"
+
+#include "ov_ops/vl_sdpa.hpp"
+#include "intel_gpu/op/sdpa.hpp"
+
+#include <openvino/pass/serialize.hpp>
+
+#include <memory>
+
+using namespace testing;
+using namespace ov::intel_gpu;
+using namespace ov;
+using namespace ov::opset13;
+
+namespace ov {
+namespace test {
+namespace intel_gpu {
+
+namespace {
+
+enum class AttentionType {
+ SDPA, // ScaledDotProductAttention
+ VLSDPA // Vision Language SDPA (for Qwen-VL models)
+};
+
+// Build the original model with Transpose + Split pattern
+// This pattern appears in Qwen-VL models (Qwen2-VL, Qwen2.5-VL, Qwen3-VL, etc.)
+// Pattern: Parameter[-1, 3, H, S] -> Transpose[3, -1, H, S] -> Split(axis=0) -> Reshape -> Attention
+std::shared_ptr<ov::Model> build_model_with_transpose_split(AttentionType attn_type) {
+ const int64_t num_head = 8;
+ const int64_t head_size = 32;
+
+ // Parameter with shape [-1, 3, num_head, head_size]
+ auto qkv = std::make_shared<Parameter>(element::f16, PartialShape{-1, 3, num_head, head_size});
+ qkv->set_friendly_name("qkv");
+ qkv->get_output_tensor(0).set_names({"qkv"});
+
+ // Transpose: [-1, 3, H, S] -> [3, -1, H, S]
+ auto transpose_order = Constant::create(element::i64, Shape{4}, std::vector<int64_t>{1, 0, 2, 3});
+ auto transpose = std::make_shared<Transpose>(qkv, transpose_order);
+ transpose->set_friendly_name("transpose_qkv");
+
+ // Split along axis 0: [3, -1, H, S] -> 3x [1, -1, H, S]
+ auto split_axis = Constant::create(element::i64, Shape{}, std::vector<int64_t>{0});
+ auto split = std::make_shared<Split>(transpose, split_axis, 3);
+ split->set_friendly_name("split_qkv");
+
+ // Reshape each split output: [1, -1, H, S] -> [-1, H, S]
+ auto reshape_pattern = Constant::create(element::i64, Shape{3}, std::vector<int64_t>{-1, num_head, head_size});
+
+ auto reshape_q = std::make_shared<Reshape>(split->output(0), reshape_pattern, false);
+ reshape_q->set_friendly_name("reshape_q");
+
+ auto reshape_k = std::make_shared<Reshape>(split->output(1), reshape_pattern, false);
+ reshape_k->set_friendly_name("reshape_k");
+
+ auto reshape_v = std::make_shared<Reshape>(split->output(2), reshape_pattern, false);
+ reshape_v->set_friendly_name("reshape_v");
+
+ // RoPE for q and k (simplified using Multiply for testing)
+ auto rope_cos_sin = Constant::create(element::f16, Shape{1, num_head, head_size}, {1.0f});
+
+ auto rope_q = std::make_shared<Multiply>(reshape_q, rope_cos_sin);
+ rope_q->set_friendly_name("rope_q");
+
+ auto rope_k = std::make_shared<Multiply>(reshape_k, rope_cos_sin);
+ rope_k->set_friendly_name("rope_k");
+
+ // Create attention node based on type
+ if (attn_type == AttentionType::VLSDPA) {
+ // Create VLSDPA for Qwen-VL models
+ auto cu_seq_lens = std::make_shared<Parameter>(element::i32, PartialShape{-1});
+ cu_seq_lens->set_friendly_name("cu_seq_lens");
+ cu_seq_lens->get_output_tensor(0).set_names({"cu_seq_lens"});
+
+ auto vlsdpa = std::make_shared<ov::op::internal::VLSDPA>(OutputVector{rope_q, rope_k, reshape_v, cu_seq_lens});
+ vlsdpa->set_friendly_name("vlsdpa");
+
+ return std::make_shared<ov::Model>(OutputVector{vlsdpa}, ParameterVector{qkv, cu_seq_lens});
+ } else {
+ // Create standard SDPA
+ auto sdpa = std::make_shared<ScaledDotProductAttention>(rope_q, rope_k, reshape_v, false);
+ sdpa->set_friendly_name("sdpa");
+
+ return std::make_shared<ov::Model>(OutputVector{sdpa}, ParameterVector{qkv});
+ }
+}
+
+// Build the target model after TransposeSplitMatcher transformation
+// Pattern: Parameter[-1, 3, H, S] -> Split(axis=1) -> Reshape
+std::shared_ptr<ov::Model> build_target_model_with_optimized_split(AttentionType attn_type) {
+ const int64_t num_head = 8;
+ const int64_t head_size = 32;
+
+ // Parameter with shape [-1, 3, num_head, head_size]
+ auto qkv = std::make_shared<Parameter>(element::f16, PartialShape{-1, 3, num_head, head_size});
+ qkv->set_friendly_name("qkv");
+ qkv->get_output_tensor(0).set_names({"qkv"});
+
+ // Split along axis 1: [-1, 3, H, S] -> 3x [-1, 1, H, S]
+ auto split_axis = Constant::create(element::i64, Shape{}, std::vector<int64_t>{1});
+ auto split = std::make_shared<Split>(qkv, split_axis, 3);
+ split->set_friendly_name("split_qkv");
+
+ // Reshape each split output: [-1, 1, H, S] -> [-1, H, S]
+ auto reshape_pattern = Constant::create(element::i64, Shape{3}, std::vector<int64_t>{-1, num_head, head_size});
+
+ auto reshape_q = std::make_shared<Reshape>(split->output(0), reshape_pattern, false);
+ reshape_q->set_friendly_name("reshape_q");
+
+ auto reshape_k = std::make_shared<Reshape>(split->output(1), reshape_pattern, false);
+ reshape_k->set_friendly_name("reshape_k");
+
+ auto reshape_v = std::make_shared<Reshape>(split->output(2), reshape_pattern, false);
+ reshape_v->set_friendly_name("reshape_v");
+
+ // RoPE for q and k (simplified using Multiply for testing)
+ auto rope_cos_sin = Constant::create(element::f16, Shape{1, num_head, head_size}, {1.0f});
+
+ auto rope_q = std::make_shared<Multiply>(reshape_q, rope_cos_sin);
+ rope_q->set_friendly_name("rope_q");
+
+ auto rope_k = std::make_shared<Multiply>(reshape_k, rope_cos_sin);
+ rope_k->set_friendly_name("rope_k");
+
+ // Create attention node based on type
+ if (attn_type == AttentionType::VLSDPA) {
+ // Create VLSDPA for Qwen-VL models
+ auto cu_seq_lens = std::make_shared<Parameter>(element::i32, PartialShape{-1});
+ cu_seq_lens->set_friendly_name("cu_seq_lens");
+ cu_seq_lens->get_output_tensor(0).set_names({"cu_seq_lens"});
+
+ auto vlsdpa = std::make_shared<ov::op::internal::VLSDPA>(OutputVector{rope_q, rope_k, reshape_v, cu_seq_lens});
+ vlsdpa->set_friendly_name("vlsdpa");
+
+ return std::make_shared<ov::Model>(OutputVector{vlsdpa}, ParameterVector{qkv, cu_seq_lens});
+ } else {
+ // Create GPU-specific SDPA (TransposeSDPAMatcher converts to this)
+ std::vector<int64_t> default_order = {0, 1, 2}; // Default order for 3D tensors
+ auto sdpa = std::make_shared<ov::intel_gpu::op::SDPA>(
+ OutputVector{rope_q, rope_k, reshape_v},
+ false, // not causal
+ default_order, default_order, default_order, default_order);
+ sdpa->set_friendly_name("sdpa");
+
+ return std::make_shared<ov::Model>(OutputVector{sdpa}, ParameterVector{qkv});
+ }
+}
+
+} // namespace
+
+// Parameterized test for TransposeSplitMatcher with both SDPA and VLSDPA
+class TransposeSplitFusionTest : public TransformationTestsF,
+ public ::testing::WithParamInterface<AttentionType> {
+};
+
+TEST_P(TransposeSplitFusionTest, TransposeSplitWithAttention) {
+ AttentionType attn_type = GetParam();
+ disable_rt_info_check();
+ {
+ model = build_model_with_transpose_split(attn_type);
+ manager.register_pass<TransposeFusion>();
+ }
+ { model_ref = build_target_model_with_optimized_split(attn_type); }
+}
+
+INSTANTIATE_TEST_SUITE_P(TransposeSplitFusion,
+ TransposeSplitFusionTest,
+ ::testing::Values(AttentionType::SDPA, AttentionType::VLSDPA),
+ [](const testing::TestParamInfo<AttentionType>& info) {
+ return info.param == AttentionType::SDPA ? "SDPA" : "VLSDPA";
+ });
+
+} // namespace intel_gpu
+} // namespace test
+} // namespace ov