OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[GPU] Fuse multi-scale deformable attention into an MSDA primitive (#38038)
Bhavik Dhandhalyad0f8c495f670
diff --git a/src/common/transformations/include/ov_ops/msda.hpp b/src/common/transformations/include/ov_ops/msda.hppnew file mode 100644index 00000000000..d5ae4387525--- /dev/null+++ b/src/common/transformations/include/ov_ops/msda.hpp@@ -0,0 +1,47 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/op/op.hpp"+#include "transformations_visibility.hpp"++namespace ov {+namespace op {+namespace internal {+/// @brief Multi-scale deformable attention of Deformable-DETR style detectors.+///+/// Inputs:+/// value [B, S, H, D] float: the keys of all feature levels, level after level;+/// value_spatial_shapes [L, 2] integer: (h, w) of every level, with S = sum(h * w);+/// level_start_index [L] integer: index of the first key of every level in S;+/// sampling_locations [B, Q, H, L, P, 2] float: (x, y) of every sampling point in level-normalized+/// coordinates: [0, 1] spans the level, points outside it read zeros;+/// attention_weights [B, Q, H, L, P] float.+/// value, sampling_locations and attention_weights have one element type.+///+/// Output [B, Q, H * D]: out[b, q, h * D + d] = sum over l, p of+/// attention_weights[b, q, h, l, p] * sample_l(x * w_l - 0.5, y * h_l - 0.5)[b, h, d],+/// where sample_l is the bilinear interpolation of the level l keys of value with zeros outside the level, that is+/// GridSample with align_corners=false and zero padding at the coordinates 2 * (x, y) - 1.+class TRANSFORMATIONS_API MSDA : public ov::op::Op {+public:+ OPENVINO_OP("MSDA", "ie_internal_opset", ov::op::Op);++ MSDA() = default;++ MSDA(const Output<Node>& value,+ const Output<Node>& value_spatial_shapes,+ const Output<Node>& level_start_index,+ const Output<Node>& sampling_locations,+ const Output<Node>& attention_weights);++ bool visit_attributes(AttributeVisitor& visitor) override;+ void validate_and_infer_types() override;+ std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& new_args) const override;+};++} // namespace internal+} // namespace op+} // namespace ovdiff --git a/src/common/transformations/include/sources.cmake b/src/common/transformations/include/sources.cmakeindex a8cd2ac43ba..f7f90f0fdd4 100644--- a/src/common/transformations/include/sources.cmake+++ b/src/common/transformations/include/sources.cmake@@ -24,6 +24,7 @@ set(OV_OPS_HEADERS${CMAKE_CURRENT_LIST_DIR}/ov_ops/grouped_matmul_compressed.hpp${CMAKE_CURRENT_LIST_DIR}/ov_ops/lora_subgraph.hpp${CMAKE_CURRENT_LIST_DIR}/ov_ops/moe_compressed.hpp+ ${CMAKE_CURRENT_LIST_DIR}/ov_ops/msda.hpp${CMAKE_CURRENT_LIST_DIR}/ov_ops/multiclass_nms_ie_internal.hpp${CMAKE_CURRENT_LIST_DIR}/ov_ops/nms_ie_internal.hpp${CMAKE_CURRENT_LIST_DIR}/ov_ops/nms_static_shape_ie.hpp@@ -114,6 +115,7 @@ set(COMMON_OPTIMIZATIONS_HEADERS${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/move_fc_reshape_to_weights.hpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/mul_conv_fusion.hpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/mul_fake_quantize_fusion.hpp+ ${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/multi_scale_deformable_attn_grid_sample_fusion.hpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/mvn_fusion.hpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/nearest_neighbor_upsampling_fusion.hpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/nonzero_horizontal_fusion.hppdiff --git a/src/common/transformations/include/transformations/common_optimizations/multi_scale_deformable_attn_grid_sample_fusion.hpp b/src/common/transformations/include/transformations/common_optimizations/multi_scale_deformable_attn_grid_sample_fusion.hppnew file mode 100644index 00000000000..c07480a381c--- /dev/null+++ b/src/common/transformations/include/transformations/common_optimizations/multi_scale_deformable_attn_grid_sample_fusion.hpp@@ -0,0 +1,85 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/matcher_pass.hpp"+#include "transformations_visibility.hpp"++namespace ov::pass {+class TRANSFORMATIONS_API MultiScaleDeformableAttnGridSampleFusion;+} // namespace ov::pass++/**+ * @ingroup ov_transformation_common_api+ * @brief Fuses the GridSample based multi-scale deformable attention subgraph into the internal MSDA operation.+ *+ * Deformable-DETR style models (Deformable-DETR, GroundingDINO, RT-DETR) exported through the PyTorch frontend+ * sample every feature level with its own GridSample and reduce the samples with the attention weights. MSDA+ * computes the same result in one operation, without materializing the [B*H, D, Q, L, P] samples tensor.+ * Dimensions: B batch, S keys, H heads, D channels per head, Q queries, L levels, P points, h x w level size.+ *+ * Before (one chain per level l = 0 .. L-1; [ ] marks optional nodes):+ *+ * value [B,S,H,D] locations [B,Q,H,L,P,2]+ * | |+ * VariadicSplit(axis 1), output l Multiply(2) -> Add(-1)+ * | |+ * Reshape [B,h*w,H*D] Gather(l, axis 3)+ * | |+ * Transpose(0,2,1) [Squeeze or Reshape]+ * | |+ * Reshape [B*H,D,h,w] Transpose(0,2,1,3,4)+ * | |+ * | Reshape [B*H,Q,P,2]+ * | |+ * +-------------- GridSample ----------------++ * |+ * Unsqueeze/Reshape [B*H,D,Q,1,P]+ * |+ * Concat(axis -2) of the L levels weights [B,Q,H,L,P]+ * | |+ * Reshape [B*H,D,Q,L*P] Transpose(0,2,1,3,4)+ * | |+ * | Reshape [B*H,1,Q,L*P]+ * | |+ * +----------- Multiply -------------++ * |+ * ReduceSum(axis -1) [B*H,D,Q]+ * |+ * Reshape [B,H*D,Q]+ * |+ * [Convert]+ * |+ * Transpose(0,2,1) [B,Q,H*D]+ *+ * The constants 2 and -1 may come through a decompression Convert. The ReduceSum may also come as+ * Multiply(AvgPool(kernel 1 x L*P, strides 1, no pads), L*P) -> [Reshape], the form ConvertReduceToPooling produces+ * (the GPU plugin runs it before this pass for f16 on devices without XMX).+ *+ * After:+ *+ * value spatial_shapes [L,2] level_start_index [L] locations weights+ * | (Constant) (Constant) | |+ * +--------------+----------------------+------ MSDA -------+----------++ * |+ * [B,Q,H*D]+ * |+ * [Convert], when the original graph has one+ *+ * The rewrite is applied when:+ * - value, locations and weights have static shapes: the matcher checks the products B*H, H*D and the sum of the+ * level sizes on static dimension values, and the GPU MSDA primitive has a static-shape implementation only;+ * - GridSample is bilinear with zero padding and align_corners=false, and its coordinates are 2 * x - 1 of the+ * level-normalized locations x, which is the sampling MSDA implements (see ov_ops/msda.hpp);+ * - level l reads output l of one VariadicSplit and locations[:, :, :, l], all levels share one value and one+ * locations tensor of the same element type, and the level sizes add up to S;+ * - every Transpose has the order and every Reshape the output shape shown above, so the element order matches+ * the MSDA layout.+ */+class ov::pass::MultiScaleDeformableAttnGridSampleFusion : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("MultiScaleDeformableAttnGridSampleFusion");+ MultiScaleDeformableAttnGridSampleFusion();+};diff --git a/src/common/transformations/src/ov_ops/msda.cpp b/src/common/transformations/src/ov_ops/msda.cppnew file mode 100644index 00000000000..dce324a7292--- /dev/null+++ b/src/common/transformations/src/ov_ops/msda.cpp@@ -0,0 +1,131 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "ov_ops/msda.hpp"++#include "itt.hpp"++namespace ov {+namespace op {+namespace internal {++MSDA::MSDA(const Output<Node>& value,+ const Output<Node>& value_spatial_shapes,+ const Output<Node>& level_start_index,+ const Output<Node>& sampling_locations,+ const Output<Node>& attention_weights)+ : Op({value, value_spatial_shapes, level_start_index, sampling_locations, attention_weights}) {+ constructor_validate_and_infer_types();+}++std::shared_ptr<ov::Node> MSDA::clone_with_new_inputs(const ov::OutputVector& new_args) const {+ INTERNAL_OP_SCOPE(internal_MSDA_clone_with_new_inputs);+ check_new_args_count(this, new_args);+ return std::make_shared<MSDA>(new_args.at(0), new_args.at(1), new_args.at(2), new_args.at(3), new_args.at(4));+}++bool MSDA::visit_attributes(ov::AttributeVisitor& visitor) {+ INTERNAL_OP_SCOPE(internal_MSDA_visit_attributes);+ return true;+}++// The inputs and the output are described in ov_ops/msda.hpp.+void MSDA::validate_and_infer_types() {+ INTERNAL_OP_SCOPE(internal_MSDA_validate_and_infer_types);+ NODE_VALIDATION_CHECK(this, get_input_size() == 5, "MSDA must have 5 inputs whereas it has ", get_input_size());++ // value, sampling_locations and attention_weights share one floating type;+ // value_spatial_shapes and level_start_index are integer.+ auto data_type = get_input_element_type(0);+ NODE_VALIDATION_CHECK(this,+ ov::element::Type::merge(data_type, data_type, get_input_element_type(3)) &&+ ov::element::Type::merge(data_type, data_type, get_input_element_type(4)),+ "MSDA value, sampling_locations and attention_weights must have the same element type, got ",+ get_input_element_type(0),+ ", ",+ get_input_element_type(3),+ " and ",+ get_input_element_type(4));+ NODE_VALIDATION_CHECK(this,+ data_type.is_dynamic() || data_type.is_real(),+ "MSDA value must have a floating point element type, got ",+ data_type);+ for (size_t i : {1, 2}) {+ const auto& index_type = get_input_element_type(i);+ NODE_VALIDATION_CHECK(this,+ index_type.is_dynamic() || index_type.is_integral_number(),+ "MSDA value_spatial_shapes and level_start_index must have an integer element type, got ",+ index_type);+ }++ const auto& value = get_input_partial_shape(0);+ const auto& spatial_shapes = get_input_partial_shape(1);+ const auto& level_start_index = get_input_partial_shape(2);+ const auto& locations = get_input_partial_shape(3);+ const auto& weights = get_input_partial_shape(4);+ NODE_VALIDATION_CHECK(this,+ value.rank().compatible(4),+ "MSDA value input must be 4D (bs, num_keys, num_heads, embed_dims), got ",+ value);+ NODE_VALIDATION_CHECK(+ this,+ spatial_shapes.rank().compatible(2) && (spatial_shapes.rank().is_dynamic() || spatial_shapes[1].compatible(2)),+ "MSDA value_spatial_shapes input must have shape (num_levels, 2), got ",+ spatial_shapes);+ NODE_VALIDATION_CHECK(this,+ level_start_index.rank().compatible(1),+ "MSDA level_start_index input must be 1D (num_levels), got ",+ level_start_index);+ NODE_VALIDATION_CHECK(+ this,+ locations.rank().compatible(6) && (locations.rank().is_dynamic() || locations[5].compatible(2)),+ "MSDA sampling_locations input must have shape (bs, num_queries, num_heads, num_levels, "+ "num_points, 2), got ",+ locations);+ NODE_VALIDATION_CHECK(+ this,+ weights.rank().compatible(5),+ "MSDA attention_weights input must be 5D (bs, num_queries, num_heads, num_levels, num_points), "+ "got ",+ weights);++ // Every dimension must agree between the inputs that carry it.+ ov::Dimension batch, num_queries, num_heads, embed_dims, num_levels, num_points;+ const auto merge = [this](ov::Dimension& dim, const ov::PartialShape& shape, size_t axis, const char* name) {+ NODE_VALIDATION_CHECK(this,+ shape.rank().is_dynamic() || ov::Dimension::merge(dim, dim, shape[axis]),+ "MSDA inputs have inconsistent ",+ name,+ ": value ",+ get_input_partial_shape(0),+ ", value_spatial_shapes ",+ get_input_partial_shape(1),+ ", level_start_index ",+ get_input_partial_shape(2),+ ", sampling_locations ",+ get_input_partial_shape(3),+ ", attention_weights ",+ get_input_partial_shape(4));+ };+ for (const auto* shape : {&value, &locations, &weights})+ merge(batch, *shape, 0, "batch size");+ merge(num_queries, locations, 1, "number of queries");+ merge(num_queries, weights, 1, "number of queries");+ merge(num_heads, value, 2, "number of heads");+ merge(num_heads, locations, 2, "number of heads");+ merge(num_heads, weights, 2, "number of heads");+ merge(embed_dims, value, 3, "number of channels");+ merge(num_levels, spatial_shapes, 0, "number of levels");+ merge(num_levels, level_start_index, 0, "number of levels");+ merge(num_levels, locations, 3, "number of levels");+ merge(num_levels, weights, 3, "number of levels");+ merge(num_points, locations, 4, "number of points");+ merge(num_points, weights, 4, "number of points");++ set_output_type(0, data_type, ov::PartialShape{batch, num_queries, num_heads * embed_dims});+}++} // namespace internal+} // namespace op+} // namespace ovdiff --git a/src/common/transformations/src/sources.cmake b/src/common/transformations/src/sources.cmakeindex b6828b79625..ef3bd902ada 100644--- a/src/common/transformations/src/sources.cmake+++ b/src/common/transformations/src/sources.cmake@@ -76,6 +76,7 @@ set(COMMON_OPTIMIZATIONS_SOURCES${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/move_eltwise_up_data_movement.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/mul_conv_fusion.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/mul_fake_quantize_fusion.cpp+ ${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/multi_scale_deformable_attn_grid_sample_fusion.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/mvn_fusion.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/nearest_neighbor_upsampling_fusion.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/nonzero_horizontal_fusion.cpp@@ -353,6 +354,7 @@ set(OV_OPS_SOURCES${CMAKE_CURRENT_LIST_DIR}/ov_ops/grouped_matmul_compressed.cpp${CMAKE_CURRENT_LIST_DIR}/ov_ops/lora_subgraph.cpp${CMAKE_CURRENT_LIST_DIR}/ov_ops/moe_compressed.cpp+ ${CMAKE_CURRENT_LIST_DIR}/ov_ops/msda.cpp${CMAKE_CURRENT_LIST_DIR}/ov_ops/multiclass_nms_ie_internal.cpp${CMAKE_CURRENT_LIST_DIR}/ov_ops/nms_ie_internal.cpp${CMAKE_CURRENT_LIST_DIR}/ov_ops/nms_static_shape_ie.cppdiff --git a/src/common/transformations/src/transformations/common_optimizations/multi_scale_deformable_attn_grid_sample_fusion.cpp b/src/common/transformations/src/transformations/common_optimizations/multi_scale_deformable_attn_grid_sample_fusion.cppnew file mode 100644index 00000000000..dcc5b67b453--- /dev/null+++ b/src/common/transformations/src/transformations/common_optimizations/multi_scale_deformable_attn_grid_sample_fusion.cpp@@ -0,0 +1,230 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "transformations/common_optimizations/multi_scale_deformable_attn_grid_sample_fusion.hpp"++#include <cstdint>+#include <memory>+#include <optional>+#include <string>+#include <vector>++#include "itt.hpp"+#include "openvino/core/graph_util.hpp"+#include "openvino/core/rt_info.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/avg_pool.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/grid_sample.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/reduce_sum.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/squeeze.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/op/unsqueeze.hpp"+#include "openvino/op/variadic_split.hpp"+#include "openvino/pass/pattern/matcher.hpp"+#include "openvino/pass/pattern/op/optional.hpp"+#include "openvino/pass/pattern/op/pattern.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "ov_ops/msda.hpp"++namespace {++namespace v0 = ov::op::v0;+namespace v1 = ov::op::v1;+namespace v8 = ov::op::v8;+namespace v9 = ov::op::v9;+using namespace ov::pass::pattern;++// One feature level: GridSample of VariadicSplit output l of value, sampled at+// the coordinates 2 * locations[:, :, :, l] - 1.+struct LevelPattern {+ std::shared_ptr<ov::Node> value, image_flat, locations, gather, root;++ LevelPattern() {+ value = any_input(has_static_shape() && shape_matches("B, S, H, D"));+ auto split = wrap_type<v1::VariadicSplit>({value, 1, any_input()});+ image_flat = wrap_type<v1::Reshape>({split, any_input()}, shape_matches("B, HW, HD"));+ auto image_transpose = wrap_type<v1::Transpose>({image_flat, {0, 2, 1}});+ auto image = wrap_type<v1::Reshape>({image_transpose, any_input()}, shape_matches("BH, D, h, w"));++ locations = any_input(has_static_shape() && shape_matches("B, Q, H, L, P, 2"));+ auto two = ov::pass::pattern::optional<v0::Convert>(wrap_type<v0::Constant>(value_matches("2")));+ auto minus_one = ov::pass::pattern::optional<v0::Convert>(wrap_type<v0::Constant>(value_matches("-1")));+ auto coords = wrap_type<v1::Add>({wrap_type<v1::Multiply>({locations, two}), minus_one});+ gather = wrap_type<v8::Gather>(+ {coords, wrap_const(), wrap_type<v0::Constant>(value_matches("3") || value_matches("-3"))},+ {{"batch_dims", 0}});+ // A [1] shaped Gather index keeps the level axis until a Squeeze (or an+ // equivalent Reshape) removes it.+ auto level_coords = ov::pass::pattern::optional<v0::Squeeze, v1::Reshape>({gather, any_input()});+ auto coords_transpose =+ wrap_type<v1::Transpose>({level_coords, {0, 2, 1, 3, 4}}, shape_matches("B, H, Q, P, 2"));+ auto grid_coords = wrap_type<v1::Reshape>({coords_transpose, any_input()}, shape_matches("BH, Q, P, 2"));+ // MSDA takes value and locations of one element type.+ auto grid = wrap_type<v9::GridSample>(+ {image, grid_coords},+ attrs_match({{"align_corners", false}, {"mode", "bilinear"}, {"padding_mode", "zeros"}}) &&+ ov::pass::pattern::op::Predicate(+ [](const ov::Output<ov::Node>& output) {+ const auto node = output.get_node();+ return node->get_input_element_type(0) == node->get_input_element_type(1);+ },+ "same_data_and_grid_type"));+ root = wrap_type<v0::Unsqueeze, v1::Reshape>({grid, any_input()}, shape_matches("BH, D, Q, 1, P"));+ }+};++struct Level {+ const ov::Node* split;+ ov::Output<ov::Node> value, locations;+ int64_t h, w;+ ov::NodeVector nodes;+};++bool same_value(const PatternSymbolMap& symbols, const std::string& name, const PatternSymbolValue& value) {+ const auto it = symbols.find(name);+ return it == symbols.end() || it->second == value;+}++// Matches every input of the Concat against the level pattern. The checks+// below relate several levels or multiply dimensions, which the shape notation+// cannot express: level l reads output l of one VariadicSplit and+// locations[:, :, :, l], all levels share the value and locations tensors, the+// level sizes add up to the S keys, BH = B * H and HD = H * D. The dimension+// names shared with the aggregation pattern are added to `symbols`, so that+// pattern checks them as well; h, w and HW are bound per level only.+std::optional<std::vector<Level>> match_levels(const LevelPattern& pattern,+ const ov::Output<ov::Node>& concat_output,+ PatternSymbolMap& symbols) {+ const auto concat = ov::as_type_ptr<v0::Concat>(concat_output.get_node_shared_ptr());+ // The levels are concatenated along axis 3 (-2) of the [B*H, D, Q, 1, P] samples.+ if (!concat || concat->get_output_partial_shape(0).rank() != 5 ||+ (concat->get_axis() < 0 ? concat->get_axis() + 5 : concat->get_axis()) != 3)+ return std::nullopt;++ std::vector<Level> levels;+ PatternSymbolMap level_dims;+ int64_t keys = 0;+ for (size_t l = 0; l < concat->get_input_size(); ++l) {+ Matcher matcher(pattern.root, "MultiScaleDeformableAttnGridSampleFusionLevel");+ if (!matcher.match(concat->input_value(l)))+ return std::nullopt;+ const auto& pm = matcher.get_pattern_value_map();+ const auto& dims = matcher.get_symbols();+ const auto split_output = pm.at(pattern.image_flat).get_node()->input_value(0);+ Level level{split_output.get_node(),+ pm.at(pattern.value),+ pm.at(pattern.locations),+ dims.at("h").i(),+ dims.at("w").i(),+ matcher.get_matched_nodes()};+ const auto index =+ ov::as_type_ptr<v0::Constant>(pm.at(pattern.gather).get_node()->get_input_node_shared_ptr(1));+ if (!index || split_output.get_index() != l ||+ index->cast_vector<int64_t>() != std::vector<int64_t>{static_cast<int64_t>(l)} ||+ dims.at("HW").i() != level.h * level.w ||+ (!levels.empty() && (level.split != levels.front().split || level.value != levels.front().value ||+ level.locations != levels.front().locations)))+ return std::nullopt;+ for (const char* name : {"B", "S", "H", "D", "Q", "L", "P", "BH", "HD"}) {+ if (!same_value(level_dims, name, dims.at(name)) || !same_value(symbols, name, dims.at(name)))+ return std::nullopt;+ level_dims.emplace(name, dims.at(name));+ }+ keys += level.h * level.w;+ levels.push_back(std::move(level));+ }+ const auto dim = [&level_dims](const std::string& name) {+ return level_dims.at(name).i();+ };+ if (levels.empty() || dim("L") != static_cast<int64_t>(levels.size()) || dim("S") != keys ||+ dim("BH") != dim("B") * dim("H") || dim("HD") != dim("H") * dim("D"))+ return std::nullopt;+ symbols.insert(level_dims.begin(), level_dims.end());+ return levels;+}++} // namespace++ov::pass::MultiScaleDeformableAttnGridSampleFusion::MultiScaleDeformableAttnGridSampleFusion() {+ MATCHER_SCOPE(MultiScaleDeformableAttnGridSampleFusion);++ const auto level_pattern = std::make_shared<LevelPattern>();+ auto concat_m =+ wrap_type<v0::Concat>(shape_matches("BH, D, Q, L, P") &&+ ov::pass::pattern::op::Predicate(+ [level_pattern](PatternSymbolMap& symbols, const ov::Output<ov::Node>& output) {+ return match_levels(*level_pattern, output, symbols).has_value();+ },+ "msda_levels_match"));+ auto values_m = wrap_type<v1::Reshape>({concat_m, any_input()}, shape_matches("BH, D, Q, LP"));+ auto weights_m = any_input(has_static_shape() && shape_matches("B, Q, H, L, P"));+ auto weights_transpose_m = wrap_type<v1::Transpose>({weights_m, {0, 2, 1, 3, 4}});+ auto weights_reshape_m = wrap_type<v1::Reshape>({weights_transpose_m, any_input()}, shape_matches("BH, 1, Q, LP"));+ auto weighted_m = wrap_type<v1::Multiply>({values_m, weights_reshape_m});+ auto reduce_m = wrap_type<v1::ReduceSum>({weighted_m, -1}, {{"keep_dims", false}});+ // On GPUs without XMX, ConvertReduceToPooling has already turned an f16+ // ReduceSum into AvgPool over the last axis times the number of samples.+ auto pool_m = wrap_type<v1::AvgPool>({weighted_m},+ attrs_match({{"strides", std::vector<int64_t>{1, 1}},+ {"pads_begin", std::vector<int64_t>{0, 0}},+ {"pads_end", std::vector<int64_t>{0, 0}}}) &&+ shape_matches("BH, D, Q, 1"));+ auto pool_sum_m = wrap_type<v1::Multiply>({pool_m, wrap_type<v0::Constant>(value_matches("LP"))});+ auto sum_m = reduce_m | ov::pass::pattern::optional<v1::Reshape>({pool_sum_m, any_input()});+ auto heads_m = wrap_type<v1::Reshape>({sum_m, any_input()}, shape_matches("B, HD, Q"));+ // When the subgraph is a model output that f16 inference keeps in f32, the+ // GPU pipeline reaches this pass with a Convert before the last Transpose.+ auto heads_convert_m = ov::pass::pattern::optional<v0::Convert>({heads_m});+ auto output_m = wrap_type<v1::Transpose>({heads_convert_m, {0, 2, 1}});++ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](Matcher& m) {+ const auto& pattern_map = m.get_pattern_value_map();+ const auto output = pattern_map.at(output_m).get_node_shared_ptr();+ if (transformation_callback(output))+ return false;++ auto symbols = m.get_symbols();+ const auto levels = match_levels(*level_pattern, pattern_map.at(concat_m), symbols);+ if (!levels)+ return false;++ std::vector<int32_t> spatial_shapes, level_starts;+ int64_t start = 0;+ ov::NodeVector fused = m.get_matched_nodes();+ for (const auto& level : *levels) {+ spatial_shapes.push_back(static_cast<int32_t>(level.h));+ spatial_shapes.push_back(static_cast<int32_t>(level.w));+ level_starts.push_back(static_cast<int32_t>(start));+ start += level.h * level.w;+ fused.insert(fused.end(), level.nodes.begin(), level.nodes.end());+ }+ const auto num_levels = levels->size();+ auto shapes = v0::Constant::create(ov::element::i32, ov::Shape{num_levels, 2}, spatial_shapes);+ auto starts = v0::Constant::create(ov::element::i32, ov::Shape{num_levels}, level_starts);+ auto msda = std::make_shared<ov::op::internal::MSDA>(levels->front().value,+ shapes,+ starts,+ levels->front().locations,+ pattern_map.at(weights_m));+ ov::NodeVector created{shapes, starts, msda};+ std::shared_ptr<ov::Node> result = msda;+ if (pattern_map.count(heads_convert_m)) {+ result = std::make_shared<v0::Convert>(msda, output->get_output_element_type(0));+ created.push_back(result);+ }+ result->set_friendly_name(output->get_friendly_name());+ ov::copy_runtime_info(fused, created);+ ov::replace_node(output, result);+ return true;+ };++ auto m = std::make_shared<Matcher>(output_m, matcher_name);+ register_matcher(m, callback);+}diff --git a/src/common/transformations/src/transformations/paged_attention/paged_selective_ssm_fusion.cpp b/src/common/transformations/src/transformations/paged_attention/paged_selective_ssm_fusion.cppindex 3076fec9696..8bb075012f0 100644--- a/src/common/transformations/src/transformations/paged_attention/paged_selective_ssm_fusion.cpp+++ b/src/common/transformations/src/transformations/paged_attention/paged_selective_ssm_fusion.cpp@@ -26,7 +26,6 @@#include "transformations/rt_info/keep_const_precision.hpp"using ov::pass::pattern::any_input;-using ov::pass::pattern::optional;using ov::pass::pattern::wrap_type;namespace v0 = ov::op::v0;@@ -86,7 +85,7 @@ PagedSelectiveSSMFusion::PagedSelectiveSSMFusion(ov::pass::paged_attention::PaPaauto cache_param = any_input();auto read_value = wrap_type<ov::op::util::ReadValueBase>({cache_param});- auto gathered_state = optional<ov::op::util::GatherBase>({read_value, any_input(), any_input()});+ auto gathered_state = ov::pass::pattern::optional<ov::op::util::GatherBase>({read_value, any_input(), any_input()});auto ssm = wrap_type<ov::op::internal::SelectiveSSM>({a, dt, b, x, c, gathered_state});ov::matcher_pass_callback callback =diff --git a/src/common/transformations/tests/common_optimizations/multi_scale_deformable_attn_grid_sample_fusion_test.cpp b/src/common/transformations/tests/common_optimizations/multi_scale_deformable_attn_grid_sample_fusion_test.cppnew file mode 100644index 00000000000..1eeb9488e0a--- /dev/null+++ b/src/common/transformations/tests/common_optimizations/multi_scale_deformable_attn_grid_sample_fusion_test.cpp@@ -0,0 +1,436 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "transformations/common_optimizations/multi_scale_deformable_attn_grid_sample_fusion.hpp"++#include <gtest/gtest.h>++#include <memory>+#include <sstream>+#include <string>+#include <tuple>+#include <vector>++#include "common_test_utils/ov_test_utils.hpp"+#include "openvino/core/model.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/avg_pool.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/grid_sample.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/reduce_sum.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/squeeze.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/op/variadic_split.hpp"+#include "ov_ops/msda.hpp"++using namespace ov;++namespace {++namespace v0 = ov::op::v0;+namespace v1 = ov::op::v1;+namespace v8 = ov::op::v8;+namespace v9 = ov::op::v9;++// Shape constants: element type and length follow the vector, so heterogeneous+// literal lists deduce cleanly.+std::shared_ptr<v0::Constant> i64_const(std::vector<int64_t> v) {+ return v0::Constant::create(element::i64, ov::Shape{v.size()}, v);+}++struct PatternParams {+ size_t levels = 4;+ size_t points = 4;+ size_t heads = 2;+ size_t embed = 32;+ size_t batch = 1;+ size_t queries = 5;+ bool dynamic_value = false;+ bool align_corners = false;+ v9::GridSample::InterpolationMode mode = v9::GridSample::InterpolationMode::BILINEAR;+ bool foreign_second_level_value = false;+ bool wrong_normalization = false;+ // Shape-compatible graphs whose element order differs from MSDA.+ bool wrong_coords_order = false;+ bool wrong_weights_order = false;+ bool swapped_level_locations = false;+ // Gather with a [1] index followed by Squeeze, as in the StridedSlice+ // based exports after GroupedStridedSliceOptimizer.+ bool squeezed_level_index = false;+ // Level 1 reads output 1 of a second VariadicSplit of value with other split lengths.+ bool levels_read_different_splits = false;+ // Element type of value and weights, and of locations when it differs.+ element::Type data_type = element::f32;+ element::Type locations_type = element::dynamic;+ // A Convert to f32 between the last Reshape and Transpose, as the GPU+ // pipeline leaves it when f16 inference keeps the model output in f32.+ bool converted_output = false;+ // The sum as ConvertReduceToPooling leaves it: AvgPool over the samples times+ // their count (pooled_sum_scale; 0 means the count), then a Reshape back to+ // [B*H, D, Q] unless a later pass folds it into the next Reshape.+ bool pooled_sum = false;+ bool pooled_sum_reshape = true;+ float pooled_sum_scale = 0.f;+};++element::Type locations_type(const PatternParams& p) {+ return p.locations_type == element::dynamic ? p.data_type : p.locations_type;+}++// Spatial size of level l: h = 4 + 2 * l, w = 5 + l.+size_t level_h(size_t l) {+ return 4 + 2 * l;+}+size_t level_w(size_t l) {+ return 5 + l;+}++// Builds the GridSample based multi-scale deformable attention pattern as it+// reaches the GPU plugin pipeline: VariadicSplit(value) per-level image+// chains, Gather per-level location slices, GridSample, Concat, broadcast+// Multiply and last-axis ReduceSum followed by the final Transpose([0,2,1]).+// Parameters: [0] value, [1] locations, [2] weights, [3] optional second value+// source.+std::shared_ptr<ov::Model> getModel(const PatternParams& p) {+ size_t keys = 0;+ for (size_t l = 0; l < p.levels; ++l)+ keys += level_h(l) * level_w(l);++ PartialShape value_ps(Shape{p.batch, keys, p.heads, p.embed});+ if (p.dynamic_value)+ value_ps[0] = Dimension::dynamic();+ auto value = std::make_shared<v0::Parameter>(p.data_type, value_ps);+ value->set_friendly_name("value");+ auto weights = std::make_shared<v0::Parameter>(p.data_type, Shape{p.batch, p.queries, p.heads, p.levels, p.points});+ weights->set_friendly_name("weights");++ // Locations: Add(Multiply(x, 2), -1) normalizes [0,1] locations to the+ // [-1,1] coordinates GridSample consumes.+ std::shared_ptr<v0::Parameter> loc_param =+ std::make_shared<v0::Parameter>(locations_type(p), Shape{p.batch, p.queries, p.heads, p.levels, p.points, 2});+ auto scale = v0::Constant::create(locations_type(p), Shape{1}, {p.wrong_normalization ? 3.f : 2.f});+ auto minus_one = v0::Constant::create(locations_type(p), Shape{1}, {-1.f});+ std::shared_ptr<ov::Node> normalized =+ std::make_shared<v1::Add>(std::make_shared<v1::Multiply>(loc_param, scale), minus_one);+ loc_param->set_friendly_name("locations");++ ParameterVector params{value, loc_param, weights};+ std::shared_ptr<v0::Parameter> foreign_value;+ if (p.foreign_second_level_value) {+ foreign_value = std::make_shared<v0::Parameter>(p.data_type, Shape{p.batch, keys, p.heads, p.embed});+ foreign_value->set_friendly_name("foreign_value");+ params.push_back(foreign_value);+ }++ std::vector<std::shared_ptr<v1::VariadicSplit>> splits;+ std::vector<int64_t> split_sizes;+ for (size_t l = 0; l < p.levels; ++l)+ split_sizes.push_back(static_cast<int64_t>(level_h(l) * level_w(l)));+ auto axis_one = v0::Constant::create(element::i64, Shape{}, {1});+ splits.push_back(+ std::make_shared<v1::VariadicSplit>(value,+ axis_one,+ v0::Constant::create(element::i64, Shape{p.levels}, split_sizes)));+ if (foreign_value)+ splits.push_back(+ std::make_shared<v1::VariadicSplit>(foreign_value,+ axis_one,+ v0::Constant::create(element::i64, Shape{p.levels}, split_sizes)));+ if (p.levels_read_different_splits) {+ // Output 1 keeps its size but starts one key later, and the sizes still add up to the keys.+ auto shifted_sizes = split_sizes;+ shifted_sizes[0] += 1;+ shifted_sizes[2] -= 1;+ splits.push_back(+ std::make_shared<v1::VariadicSplit>(value,+ axis_one,+ v0::Constant::create(element::i64, Shape{p.levels}, shifted_sizes)));+ }++ OutputVector level_outputs;+ for (size_t l = 0; l < p.levels; ++l) {+ const size_t h = level_h(l), w = level_w(l), s = h * w;+ const bool second_split = (p.foreign_second_level_value || p.levels_read_different_splits) && l == 1;+ const auto& split = second_split ? splits[1] : splits[0];++ // Image chain: Reshape -> Transpose -> Reshape -> GridSample input 0.+ auto image_flat =+ std::make_shared<v1::Reshape>(split->output(l),+ i64_const({int64_t(p.batch), int64_t(s), int64_t(p.heads * p.embed)}),+ true);+ auto image_transpose = std::make_shared<v1::Transpose>(image_flat, i64_const({0, 2, 1}));+ auto image = std::make_shared<v1::Reshape>(+ image_transpose,+ i64_const({int64_t(p.batch * p.heads), int64_t(p.embed), int64_t(h), int64_t(w)}),+ true);++ // Locations chain: Gather -> Transpose -> Reshape -> GridSample input 1.+ const auto level_index = int64_t(p.swapped_level_locations ? p.levels - 1 - l : l);+ std::shared_ptr<ov::Node> gathered = std::make_shared<v8::Gather>(+ normalized,+ v0::Constant::create(element::i64, p.squeezed_level_index ? Shape{1} : Shape{}, {level_index}),+ v0::Constant::create(element::i64, Shape{}, {3}));+ if (p.squeezed_level_index)+ gathered = std::make_shared<v0::Squeeze>(gathered, i64_const({3}));+ auto coords_transpose =+ std::make_shared<v1::Transpose>(gathered,+ i64_const(p.wrong_coords_order ? std::vector<int64_t>{0, 1, 2, 3, 4}+ : std::vector<int64_t>{0, 2, 1, 3, 4}));+ auto coords = std::make_shared<v1::Reshape>(+ coords_transpose,+ i64_const({int64_t(p.batch * p.heads), int64_t(p.queries), int64_t(p.points), 2}),+ true);++ v9::GridSample::Attributes attributes{p.align_corners, p.mode, v9::GridSample::PaddingMode::ZEROS};+ auto grid = std::make_shared<v9::GridSample>(image, coords, attributes);+ level_outputs.push_back(std::make_shared<v1::Reshape>(+ grid,+ i64_const({int64_t(p.batch * p.heads), int64_t(p.embed), int64_t(p.queries), 1, int64_t(p.points)}),+ true));+ }++ auto concat = std::make_shared<v0::Concat>(level_outputs, -2);+ auto values_reshape =+ std::make_shared<v1::Reshape>(concat, i64_const({0, int64_t(p.embed), 0, int64_t(p.levels * p.points)}), true);++ // Weights chain: Reshape -> Transpose -> Reshape -> broadcast operand.+ auto weights_value = std::make_shared<v1::Reshape>(+ weights,+ i64_const({int64_t(p.batch), int64_t(p.queries), int64_t(p.heads), int64_t(p.levels), int64_t(p.points)}),+ true);+ auto weights_transpose = std::make_shared<v1::Transpose>(+ weights_value,+ i64_const(p.wrong_weights_order ? std::vector<int64_t>{0, 1, 2, 3, 4} : std::vector<int64_t>{0, 2, 1, 3, 4}));+ auto weights_reshape = std::make_shared<v1::Reshape>(+ weights_transpose,+ i64_const({int64_t(p.batch * p.heads), 1, int64_t(p.queries), int64_t(p.levels * p.points)}),+ true);++ auto mul = std::make_shared<v1::Multiply>(values_reshape, weights_reshape);+ std::shared_ptr<ov::Node> reduce;+ if (p.pooled_sum) {+ const auto samples = p.levels * p.points;+ auto pool = std::make_shared<v1::AvgPool>(mul,+ Strides{1, 1},+ Shape{0, 0},+ Shape{0, 0},+ Shape{1, samples},+ true,+ ov::op::RoundingType::FLOOR);+ const float scale = p.pooled_sum_scale != 0.f ? p.pooled_sum_scale : static_cast<float>(samples);+ reduce = std::make_shared<v1::Multiply>(pool, v0::Constant::create(p.data_type, Shape{1}, {scale}));+ if (p.pooled_sum_reshape)+ reduce = std::make_shared<v1::Reshape>(+ reduce,+ i64_const({int64_t(p.batch * p.heads), int64_t(p.embed), int64_t(p.queries)}),+ true);+ } else {+ reduce = std::make_shared<v1::ReduceSum>(mul, i64_const({-1}), false);+ }+ std::shared_ptr<ov::Node> heads =+ std::make_shared<v1::Reshape>(reduce, i64_const({-1, int64_t(p.heads * p.embed), 0}), true);+ if (p.converted_output)+ heads = std::make_shared<v0::Convert>(heads, element::f32);+ auto output = std::make_shared<v1::Transpose>(heads, i64_const({0, 2, 1}));++ return std::make_shared<ov::Model>(OutputVector{output}, params, "MSDAPattern");+}++// The MSDA the fusion produces for getModel(p): value, the level sizes and+// start offsets, the [0,1] locations and the weights operand.+std::shared_ptr<ov::Model> getModelRef(const PatternParams& p) {+ size_t keys = 0;+ std::vector<int32_t> spatial_shapes, level_starts;+ for (size_t l = 0; l < p.levels; ++l) {+ spatial_shapes.push_back(static_cast<int32_t>(level_h(l)));+ spatial_shapes.push_back(static_cast<int32_t>(level_w(l)));+ level_starts.push_back(static_cast<int32_t>(keys));+ keys += level_h(l) * level_w(l);+ }+ auto value = std::make_shared<v0::Parameter>(p.data_type, Shape{p.batch, keys, p.heads, p.embed});+ auto locations =+ std::make_shared<v0::Parameter>(p.data_type, Shape{p.batch, p.queries, p.heads, p.levels, p.points, 2});+ auto weights = std::make_shared<v0::Parameter>(p.data_type, Shape{p.batch, p.queries, p.heads, p.levels, p.points});+ auto weights_value = std::make_shared<v1::Reshape>(+ weights,+ i64_const({int64_t(p.batch), int64_t(p.queries), int64_t(p.heads), int64_t(p.levels), int64_t(p.points)}),+ true);+ auto msda =+ std::make_shared<ov::op::internal::MSDA>(value,+ v0::Constant::create(element::i32, Shape{p.levels, 2}, spatial_shapes),+ v0::Constant::create(element::i32, Shape{p.levels}, level_starts),+ locations,+ weights_value);+ std::shared_ptr<ov::Node> output = msda;+ if (p.converted_output)+ output = std::make_shared<v0::Convert>(msda, element::f32);+ return std::make_shared<ov::Model>(OutputVector{output}, ParameterVector{value, locations, weights});+}++} // namespace++class MultiScaleDeformableAttnGridSampleFusionTest : public TransformationTestsF {+protected:+ void SetUp() override {+ TransformationTestsF::SetUp();+ manager.register_pass<ov::pass::MultiScaleDeformableAttnGridSampleFusion>();+ }+};++// batch, levels, points, heads, channels per head, Gather with a [1] index and Squeeze+using FusionParams = std::tuple<size_t, size_t, size_t, size_t, size_t, bool>;++class MultiScaleDeformableAttnGridSampleFusionFused : public MultiScaleDeformableAttnGridSampleFusionTest,+ public testing::WithParamInterface<FusionParams> {+public:+ MultiScaleDeformableAttnGridSampleFusionFused() {+ comparator.enable(FunctionsComparator::CONST_VALUES);+ }++ static std::string getTestCaseName(const testing::TestParamInfo<FusionParams>& info) {+ const auto& [batch, levels, points, heads, embed, squeezed] = info.param;+ std::ostringstream name;+ name << "batch=" << batch << "_levels=" << levels << "_points=" << points << "_heads=" << heads+ << "_embed=" << embed << (squeezed ? "_squeezed_index" : "_scalar_index");+ return name.str();+ }++protected:+ void SetUp() override {+ MultiScaleDeformableAttnGridSampleFusionTest::SetUp();+ PatternParams p;+ std::tie(p.batch, p.levels, p.points, p.heads, p.embed, p.squeezed_level_index) = GetParam();+ model = getModel(p);+ model_ref = getModelRef(p);+ }+};++TEST_P(MultiScaleDeformableAttnGridSampleFusionFused, Fused) {}++INSTANTIATE_TEST_SUITE_P(MultiScaleDeformableAttnGridSampleFusion,+ MultiScaleDeformableAttnGridSampleFusionFused,+ testing::Values(FusionParams{1, 4, 4, 2, 32, false},+ FusionParams{1, 3, 2, 3, 16, false},+ FusionParams{1, 1, 4, 2, 32, false},+ FusionParams{1, 4, 4, 2, 32, true},+ FusionParams{2, 4, 4, 4, 32, false},+ FusionParams{2, 3, 2, 3, 16, true}),+ MultiScaleDeformableAttnGridSampleFusionFused::getTestCaseName);++TEST_F(MultiScaleDeformableAttnGridSampleFusionTest, ConvertedOutput) {+ // f16 subgraph whose output the plugin keeps in f32.+ comparator.enable(FunctionsComparator::CONST_VALUES);+ PatternParams p;+ p.data_type = element::f16;+ p.converted_output = true;+ model = getModel(p);+ model_ref = getModelRef(p);+}++TEST_F(MultiScaleDeformableAttnGridSampleFusionTest, PooledSum) {+ comparator.enable(FunctionsComparator::CONST_VALUES);+ PatternParams p;+ p.pooled_sum = true;+ model = getModel(p);+ model_ref = getModelRef(p);+}++TEST_F(MultiScaleDeformableAttnGridSampleFusionTest, PooledSumWithoutReshape) {+ comparator.enable(FunctionsComparator::CONST_VALUES);+ PatternParams p;+ p.pooled_sum = true;+ p.pooled_sum_reshape = false;+ model = getModel(p);+ model_ref = getModelRef(p);+}++TEST_F(MultiScaleDeformableAttnGridSampleFusionTest, PooledSumWrongScale) {+ // AvgPool times half the number of samples is not their sum.+ PatternParams p;+ p.pooled_sum = true;+ p.pooled_sum_scale = static_cast<float>(p.levels * p.points / 2);+ model = getModel(p);+}++TEST_F(MultiScaleDeformableAttnGridSampleFusionTest, WrongNormalization) {+ // Add(Multiply(x, 3), -1) does not map [0,1] to the GridSample coordinate range.+ PatternParams p;+ p.wrong_normalization = true;+ model = getModel(p);+}++TEST_F(MultiScaleDeformableAttnGridSampleFusionTest, DynamicValue) {+ PatternParams p;+ p.dynamic_value = true;+ model = getModel(p);+}++TEST_F(MultiScaleDeformableAttnGridSampleFusionTest, AlignCorners) {+ PatternParams p;+ p.align_corners = true;+ model = getModel(p);+}++TEST_F(MultiScaleDeformableAttnGridSampleFusionTest, NearestMode) {+ PatternParams p;+ p.mode = ov::op::v9::GridSample::InterpolationMode::NEAREST;+ model = getModel(p);+}++TEST_F(MultiScaleDeformableAttnGridSampleFusionTest, LevelsSampleDifferentValues) {+ PatternParams p;+ p.foreign_second_level_value = true;+ model = getModel(p);+}++// The remaining graphs are shape compatible with the pattern but read the+// elements in a different order than MSDA.+TEST_F(MultiScaleDeformableAttnGridSampleFusionTest, WrongCoordsOrder) {+ // With as many queries as heads only the Transpose order differs.+ PatternParams p;+ p.queries = p.heads;+ p.wrong_coords_order = true;+ model = getModel(p);+}++TEST_F(MultiScaleDeformableAttnGridSampleFusionTest, WrongWeightsOrder) {+ PatternParams p;+ p.wrong_weights_order = true;+ model = getModel(p);+}++TEST_F(MultiScaleDeformableAttnGridSampleFusionTest, SwappedLevelLocations) {+ PatternParams p;+ p.levels = 2;+ p.points = 2;+ p.swapped_level_locations = true;+ model = getModel(p);+}++TEST_F(MultiScaleDeformableAttnGridSampleFusionTest, SwappedLevelLocationsSqueezedIndex) {+ PatternParams p;+ p.squeezed_level_index = true;+ p.swapped_level_locations = true;+ model = getModel(p);+}++TEST_F(MultiScaleDeformableAttnGridSampleFusionTest, LevelsReadDifferentSplits) {+ // Level 1 reads a split output of the right size at another offset of value.+ PatternParams p;+ p.levels = 3;+ p.levels_read_different_splits = true;+ model = getModel(p);+}++TEST_F(MultiScaleDeformableAttnGridSampleFusionTest, LocationsTypeDiffersFromValue) {+ PatternParams p;+ p.locations_type = element::f16;+ model = getModel(p);+}diff --git a/src/common/transformations/tests/sources.cmake b/src/common/transformations/tests/sources.cmakeindex c95b19aa89c..f4e591759aa 100644--- a/src/common/transformations/tests/sources.cmake+++ b/src/common/transformations/tests/sources.cmake@@ -93,6 +93,7 @@ set(COMMON_OPTIMIZATIONS_TESTS_SRCS${CMAKE_CURRENT_LIST_DIR}/common_optimizations/moe_transpose_weights_test.cpp${CMAKE_CURRENT_LIST_DIR}/common_optimizations/move_eltwise_up_data_movement_test.cpp${CMAKE_CURRENT_LIST_DIR}/common_optimizations/mul_fake_quantize_fusion.cpp+ ${CMAKE_CURRENT_LIST_DIR}/common_optimizations/multi_scale_deformable_attn_grid_sample_fusion_test.cpp${CMAKE_CURRENT_LIST_DIR}/common_optimizations/mvn_fusion_test.cpp${CMAKE_CURRENT_LIST_DIR}/common_optimizations/nearest_neighbor_upsampling_fusion_test.cpp${CMAKE_CURRENT_LIST_DIR}/common_optimizations/ngraph_fq_transpose_test.cppdiff --git a/src/core/tests/type_prop/msda.cpp b/src/core/tests/type_prop/msda.cppnew file mode 100644index 00000000000..f8c1eccafb0--- /dev/null+++ b/src/core/tests/type_prop/msda.cpp@@ -0,0 +1,250 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "ov_ops/msda.hpp"++#include <gtest/gtest.h>++#include "common_test_utils/test_assertions.hpp"+#include "openvino/openvino.hpp"++namespace ov::test {+namespace {++std::shared_ptr<op::internal::MSDA> make_msda(const element::Type& et,+ const PartialShape& value,+ const PartialShape& spatial_shapes,+ const PartialShape& level_start_index,+ const PartialShape& locations,+ const PartialShape& weights,+ const element::Type& index_et = element::i32,+ const element::Type& locations_et = element::dynamic) {+ return std::make_shared<op::internal::MSDA>(+ std::make_shared<op::v0::Parameter>(et, value),+ std::make_shared<op::v0::Parameter>(index_et, spatial_shapes),+ std::make_shared<op::v0::Parameter>(index_et, level_start_index),+ std::make_shared<op::v0::Parameter>(locations_et == element::dynamic ? et : locations_et, locations),+ std::make_shared<op::v0::Parameter>(et, weights));+}++} // namespace++TEST(type_prop, msda_static_f32) {+ const auto op = make_msda(element::f32,+ Shape{2, 31, 4, 8},+ Shape{2, 2},+ Shape{2},+ Shape{2, 6, 4, 2, 3, 2},+ Shape{2, 6, 4, 2, 3});++ EXPECT_EQ(op->get_output_size(), 1);+ EXPECT_EQ(op->get_output_element_type(0), element::f32);+ EXPECT_EQ(op->get_output_partial_shape(0), PartialShape({2, 6, 32}));+}++TEST(type_prop, msda_static_f16_i64_indices) {+ const auto op = make_msda(element::f16,+ Shape{1, 20, 2, 16},+ Shape{1, 2},+ Shape{1},+ Shape{1, 9, 2, 1, 4, 2},+ Shape{1, 9, 2, 1, 4},+ element::i64);++ EXPECT_EQ(op->get_output_element_type(0), element::f16);+ EXPECT_EQ(op->get_output_partial_shape(0), PartialShape({1, 9, 32}));+}++TEST(type_prop, msda_dims_resolved_from_other_inputs) {+ const auto op = make_msda(element::f32,+ PartialShape{-1, -1, 4, 8},+ PartialShape{-1, 2},+ PartialShape{-1},+ PartialShape{2, -1, -1, 2, 3, 2},+ PartialShape{-1, 6, 4, -1, -1});++ EXPECT_EQ(op->get_output_partial_shape(0), PartialShape({2, 6, 32}));+}++TEST(type_prop, msda_interval_dims) {+ const auto op = make_msda(element::f32,+ PartialShape{{1, 4}, -1, 4, 8},+ PartialShape{2, 2},+ PartialShape{2},+ PartialShape{{2, 8}, {10, 20}, 4, 2, 3, 2},+ PartialShape{-1, {15, 30}, 4, 2, 3});++ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{{2, 4}, {15, 20}, 32}));+}++TEST(type_prop, msda_dynamic_rank_inputs) {+ const auto op = make_msda(element::f32,+ PartialShape::dynamic(),+ PartialShape::dynamic(),+ PartialShape::dynamic(),+ PartialShape::dynamic(),+ PartialShape{1, 7, 2, 1, 4});++ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{1, 7, -1}));+}++TEST(type_prop, msda_invalid_value_rank) {+ OV_EXPECT_THROW(std::ignore = make_msda(element::f32,+ Shape{1, 20, 16},+ Shape{1, 2},+ Shape{1},+ Shape{1, 7, 2, 1, 4, 2},+ Shape{1, 7, 2, 1, 4}),+ NodeValidationFailure,+ testing::HasSubstr("MSDA value input must be 4D"));+}++TEST(type_prop, msda_invalid_spatial_shapes) {+ OV_EXPECT_THROW(std::ignore = make_msda(element::f32,+ Shape{1, 20, 2, 8},+ Shape{1, 3},+ Shape{1},+ Shape{1, 7, 2, 1, 4, 2},+ Shape{1, 7, 2, 1, 4}),+ NodeValidationFailure,+ testing::HasSubstr("value_spatial_shapes input must have shape (num_levels, 2)"));+}++TEST(type_prop, msda_invalid_data_type) {+ OV_EXPECT_THROW(std::ignore = make_msda(element::i32,+ Shape{1, 20, 2, 8},+ Shape{1, 2},+ Shape{1},+ Shape{1, 7, 2, 1, 4, 2},+ Shape{1, 7, 2, 1, 4}),+ NodeValidationFailure,+ testing::HasSubstr("MSDA value must have a floating point element type"));+}++TEST(type_prop, msda_mismatched_data_types) {+ OV_EXPECT_THROW(std::ignore = make_msda(element::f32,+ Shape{1, 20, 2, 8},+ Shape{1, 2},+ Shape{1},+ Shape{1, 7, 2, 1, 4, 2},+ Shape{1, 7, 2, 1, 4},+ element::i32,+ element::f16),+ NodeValidationFailure,+ testing::HasSubstr("must have the same element type"));+}++TEST(type_prop, msda_invalid_index_type) {+ OV_EXPECT_THROW(std::ignore = make_msda(element::f32,+ Shape{1, 20, 2, 8},+ Shape{1, 2},+ Shape{1},+ Shape{1, 7, 2, 1, 4, 2},+ Shape{1, 7, 2, 1, 4},+ element::f32),+ NodeValidationFailure,+ testing::HasSubstr("must have an integer element type"));+}++TEST(type_prop, msda_batch_mismatch) {+ OV_EXPECT_THROW(std::ignore = make_msda(element::f32,+ Shape{2, 20, 2, 8},+ Shape{1, 2},+ Shape{1},+ Shape{1, 7, 2, 1, 4, 2},+ Shape{1, 7, 2, 1, 4}),+ NodeValidationFailure,+ testing::HasSubstr("inconsistent batch size"));+}++TEST(type_prop, msda_heads_mismatch) {+ OV_EXPECT_THROW(std::ignore = make_msda(element::f32,+ Shape{1, 20, 4, 8},+ Shape{1, 2},+ Shape{1},+ Shape{1, 7, 2, 1, 4, 2},+ Shape{1, 7, 2, 1, 4}),+ NodeValidationFailure,+ testing::HasSubstr("inconsistent number of heads"));+}++TEST(type_prop, msda_levels_mismatch) {+ OV_EXPECT_THROW(std::ignore = make_msda(element::f32,+ Shape{1, 20, 2, 8},+ Shape{2, 2},+ Shape{2},+ Shape{1, 7, 2, 1, 4, 2},+ Shape{1, 7, 2, 1, 4}),+ NodeValidationFailure,+ testing::HasSubstr("inconsistent number of levels"));+}++TEST(type_prop, msda_queries_mismatch) {+ OV_EXPECT_THROW(std::ignore = make_msda(element::f32,+ Shape{1, 20, 2, 8},+ Shape{1, 2},+ Shape{1},+ Shape{1, 7, 2, 1, 4, 2},+ Shape{1, 5, 2, 1, 4}),+ NodeValidationFailure,+ testing::HasSubstr("inconsistent number of queries"));+}++TEST(type_prop, msda_points_mismatch) {+ OV_EXPECT_THROW(std::ignore = make_msda(element::f32,+ Shape{1, 20, 2, 8},+ Shape{1, 2},+ Shape{1},+ Shape{1, 7, 2, 1, 4, 2},+ Shape{1, 7, 2, 1, 3}),+ NodeValidationFailure,+ testing::HasSubstr("inconsistent number of points"));+}++TEST(type_prop, msda_invalid_locations_last_dim) {+ OV_EXPECT_THROW(std::ignore = make_msda(element::f32,+ Shape{1, 20, 2, 8},+ Shape{1, 2},+ Shape{1},+ Shape{1, 7, 2, 1, 4, 3},+ Shape{1, 7, 2, 1, 4}),+ NodeValidationFailure,+ testing::HasSubstr("MSDA sampling_locations input must have shape"));+}++TEST(type_prop, msda_invalid_weights_rank) {+ OV_EXPECT_THROW(std::ignore = make_msda(element::f32,+ Shape{1, 20, 2, 8},+ Shape{1, 2},+ Shape{1},+ Shape{1, 7, 2, 1, 4, 2},+ Shape{1, 7, 2, 4}),+ NodeValidationFailure,+ testing::HasSubstr("MSDA attention_weights input must be 5D"));+}++TEST(type_prop, msda_invalid_level_start_index_rank) {+ OV_EXPECT_THROW(std::ignore = make_msda(element::f32,+ Shape{1, 20, 2, 8},+ Shape{1, 2},+ Shape{1, 1},+ Shape{1, 7, 2, 1, 4, 2},+ Shape{1, 7, 2, 1, 4}),+ NodeValidationFailure,+ testing::HasSubstr("MSDA level_start_index input must be 1D"));+}++TEST(type_prop, msda_wrong_input_count) {+ const auto value = std::make_shared<op::v0::Parameter>(element::f32, Shape{1, 20, 2, 8});+ const auto spatial_shapes = std::make_shared<op::v0::Parameter>(element::i32, Shape{1, 2});+ const auto level_start_index = std::make_shared<op::v0::Parameter>(element::i32, Shape{1});+ const auto locations = std::make_shared<op::v0::Parameter>(element::f32, Shape{1, 7, 2, 1, 4, 2});+ const auto op = std::make_shared<op::internal::MSDA>();+ op->set_arguments(OutputVector{value, spatial_shapes, level_start_index, locations});+ OV_EXPECT_THROW(op->validate_and_infer_types(),+ NodeValidationFailure,+ testing::HasSubstr("MSDA must have 5 inputs"));+}++} // namespace ov::testdiff --git a/src/core/tests/type_prop/sources.cmake b/src/core/tests/type_prop/sources.cmakeindex 5636ca696a8..7585d2596bd 100644--- a/src/core/tests/type_prop/sources.cmake+++ b/src/core/tests/type_prop/sources.cmake@@ -124,6 +124,7 @@ set(OV_CORE_TESTS_TYPE_PROP_SRCS${CMAKE_CURRENT_LIST_DIR}/minimum.cpp${CMAKE_CURRENT_LIST_DIR}/mish.cpp${CMAKE_CURRENT_LIST_DIR}/mod.cpp+ ${CMAKE_CURRENT_LIST_DIR}/msda.cpp${CMAKE_CURRENT_LIST_DIR}/multiclass_nms.cpp${CMAKE_CURRENT_LIST_DIR}/multinomial.cpp${CMAKE_CURRENT_LIST_DIR}/multiply.cppdiff --git a/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp b/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hppindex ea5ee898f1f..2a84a83eea8 100644--- a/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp@@ -323,6 +323,7 @@ REGISTER_FACTORY(internal, PagedGatedDeltaNet);REGISTER_FACTORY(internal, PagedSelectiveSSM);REGISTER_FACTORY(internal, LoraSubgraph);REGISTER_FACTORY(internal, LoraSubgraphFused);+REGISTER_FACTORY(internal, MSDA);REGISTER_FACTORY(internal, VLSDPA);REGISTER_FACTORY(internal, MOECompressed);REGISTER_FACTORY(internal, MoERouterFused);diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/msda.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/msda.hppnew file mode 100644index 00000000000..cb778f88205--- /dev/null+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/msda.hpp@@ -0,0 +1,38 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once+#include <vector>++#include "primitive.hpp"++namespace cldnn {++/// @brief Multi-scale deformable attention, the GPU counterpart of ov::op::internal::MSDA.+/// @details Inputs: value, value_spatial_shapes, level_start_index, sampling_locations and attention_weights.+struct msda : public primitive_base<msda> {+ CLDNN_DECLARE_PRIMITIVE(msda)++ msda() : primitive_base("", {}) {}++ /// @brief Constructs msda primitive / layer.+ ///+ /// @param id An identifier of new primitive.+ /// @param inputs A list of Input primitive ids (inputs).+ msda(const primitive_id& id, const std::vector<input_info>& inputs) : primitive_base(id, inputs) {}++ bool operator==(const primitive& rhs) const override {+ return compare_common_params(rhs);+ }++ void save(BinaryOutputBuffer& ob) const override {+ primitive_base<msda>::save(ob);+ }++ void load(BinaryInputBuffer& ib) override {+ primitive_base<msda>::load(ib);+ }+};++} // namespace cldnndiff --git a/src/plugins/intel_gpu/sources.cmake b/src/plugins/intel_gpu/sources.cmakeindex 0092d03a0d8..e6471f78e95 100644--- a/src/plugins/intel_gpu/sources.cmake+++ b/src/plugins/intel_gpu/sources.cmake@@ -79,6 +79,7 @@ set(GPU_PLUGIN_OPS_SOURCES${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/moe.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/moe_offload_constant.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/moe_router_fused.cpp+ ${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/msda.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/multiclass_nms.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/multinomial.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/mvn.cppdiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/msda_opt.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/msda_opt.clnew file mode 100644index 00000000000..cfb957345d0--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/msda_opt.cl@@ -0,0 +1,80 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Multi-scale deformable attention. Every work item computes one output+// element (b, q, m, c): the sum over levels and points of the attention weight+// times value bilinearly sampled at the point location, with zero padding and+// align_corners=false, which is the GridSample sampling the fusion replaces.+//+// The pixel coordinates and the bilinear weights are float, as in+// grid_sample_opt_bilinear_zeros.cl; the samples are accumulated in+// ACCUMULATOR_TYPE (f32) and converted to OUTPUT_TYPE on store. One work item+// per output channel keeps the corner loads of neighboring work items+// contiguous along D.+//+// SPATIAL_SIZE, NUM_QUERY, NUM_HEADS, EMBED_DIMS, NUM_LEVELS and NUM_POINT are+// JIT constants; the inputs are plain, so they are indexed linearly.++KERNEL(multi_scale_deformable_attn)(+ __global const INPUT0_TYPE* restrict data_value, // (bs, num_keys, NUM_HEADS, EMBED_DIMS)+ __global const int* restrict data_spatial_shapes, // (NUM_LEVELS, 2), (h, w) of every level+ __global const int* restrict data_level_start_index, // (NUM_LEVELS), first key of every level+ __global const INPUT3_TYPE* restrict data_sampling_loc, // (bs, num_queries, NUM_HEADS, NUM_LEVELS, NUM_POINT, 2), level-normalized (x, y)+ __global const INPUT4_TYPE* restrict data_attn_weight, // (bs, num_queries, NUM_HEADS, NUM_LEVELS, NUM_POINT)+ __global OUTPUT_TYPE* restrict output) { // (bs, num_queries, NUM_HEADS * EMBED_DIMS)+ const int index = get_global_id(2);+ const int c = index % EMBED_DIMS;+ const int sampling_index = index / EMBED_DIMS; // (b, q, m)+ const int m = sampling_index % NUM_HEADS;+ const int b = sampling_index / (NUM_HEADS * NUM_QUERY);++ const int key_stride = NUM_HEADS * EMBED_DIMS;+ __global const INPUT0_TYPE* batch_value = data_value + b * SPATIAL_SIZE * key_stride + m * EMBED_DIMS + c;+ int weight_index = sampling_index * NUM_LEVELS * NUM_POINT;++ ACCUMULATOR_TYPE acc = 0;+ for (int l = 0; l < NUM_LEVELS; ++l) {+ const int height = data_spatial_shapes[2 * l];+ const int width = data_spatial_shapes[2 * l + 1];+ __global const INPUT0_TYPE* level_value = batch_value + data_level_start_index[l] * key_stride;++ for (int p = 0; p < NUM_POINT; ++p, ++weight_index) {+ // GridSample unnormalizes the coordinate 2 * x - 1 to+ // ((2 * x - 1 + 1) * width - 1) / 2 = x * width - 0.5.+ const float x = (float)data_sampling_loc[2 * weight_index] * width - 0.5f;+ const float y = (float)data_sampling_loc[2 * weight_index + 1] * height - 0.5f;+ const ACCUMULATOR_TYPE attention = TO_ACCUMULATOR_TYPE(data_attn_weight[weight_index]);++ const int x0 = (int)floor(x);+ const int y0 = (int)floor(y);+ const float dx = x - x0;+ const float dy = y - y0;++ const bool x0_valid = x0 >= 0 && x0 < width;+ const bool x1_valid = x0 + 1 >= 0 && x0 + 1 < width;+ const bool y0_valid = y0 >= 0 && y0 < height;+ const bool y1_valid = y0 + 1 >= 0 && y0 + 1 < height;+ const int x0c = x0_valid ? x0 : 0;+ const int x1c = x1_valid ? x0 + 1 : 0;+ const int y0c = y0_valid ? y0 : 0;+ const int y1c = y1_valid ? y0 + 1 : 0;++ // The corners are loaded unconditionally from clamped, in-bounds+ // offsets and masked afterwards, which avoids divergent branches+ // around the loads (see LOAD_INPUT in grid_sample_opt_bilinear_zeros.cl).+ const INPUT0_TYPE v00_d = level_value[(y0c * width + x0c) * key_stride];+ const INPUT0_TYPE v01_d = level_value[(y0c * width + x1c) * key_stride];+ const INPUT0_TYPE v10_d = level_value[(y1c * width + x0c) * key_stride];+ const INPUT0_TYPE v11_d = level_value[(y1c * width + x1c) * key_stride];++ const ACCUMULATOR_TYPE v00 = (y0_valid && x0_valid) ? TO_ACCUMULATOR_TYPE(v00_d) * (1 - dx) : 0;+ const ACCUMULATOR_TYPE v01 = (y0_valid && x1_valid) ? TO_ACCUMULATOR_TYPE(v01_d) * dx : 0;+ const ACCUMULATOR_TYPE v10 = (y1_valid && x0_valid) ? TO_ACCUMULATOR_TYPE(v10_d) * (1 - dx) : 0;+ const ACCUMULATOR_TYPE v11 = (y1_valid && x1_valid) ? TO_ACCUMULATOR_TYPE(v11_d) * dx : 0;++ acc += attention * ((1 - dy) * (v00 + v01) + dy * (v10 + v11));+ }+ }+ output[index] = TO_OUTPUT_TYPE(acc);+}diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/msda_opt.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/msda_opt.cppnew file mode 100644index 00000000000..6c8ba120ef3--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/msda_opt.cpp@@ -0,0 +1,75 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "msda_opt.hpp"++#include "common_utils/dispatch_utils.hpp"+#include "intel_gpu/primitives/msda.hpp"+#include "primitive_ocl_base.hpp"+#include "utils/jitter.hpp"+#include "utils/kernel_generator.hpp"++namespace ov::intel_gpu::ocl {+namespace {++class MSDAOptGenerator : public KernelGenerator {+public:+ MSDAOptGenerator() : KernelGenerator("msda_opt") {}++protected:+ // value [B, S, H, D], value_spatial_shapes [L, 2], level_start_index [L],+ // sampling_locations [B, Q, H, L, P, 2], attention_weights [B, Q, H, L, P].+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = KernelGenerator::get_jit_constants(params);+ const auto value = params.get_input_layout(0).get_shape();+ const auto weights = params.get_input_layout(4).get_shape();+ jit.make("SPATIAL_SIZE", value[1]);+ jit.make("NUM_HEADS", value[2]);+ jit.make("EMBED_DIMS", value[3]);+ jit.make("NUM_QUERY", weights[1]);+ jit.make("NUM_LEVELS", weights[3]);+ jit.make("NUM_POINT", weights[4]);+ // f32 for f16 data too: the sum over levels and points loses+ // precision when it is accumulated in f16.+ jit.add(make_type_jit_constants("ACCUMULATOR", ov::element::f32));+ return jit;+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {+ OPENVINO_ASSERT(!params.is_dynamic(), "MSDA kernel requires static shapes");+ auto& wgs = kd.params.workGroups;+ // One work item per output element (b, q, h, d).+ wgs.global = {1, 1, params.get_output_layout(0).count()};+ wgs.local = ov::intel_gpu::get_optimal_lws(wgs.global, params.get_device_info());+ }};+ }+};++class MSDAOptImpl : public PrimitiveImplOCL {+public:+ DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::ocl::MSDAOptImpl)++ Stage::Ptr msda = make_stage<MSDAOptGenerator>();++ MSDAOptImpl() : PrimitiveImplOCL(MSDAOpt::get_type_info_static()) {}+ MSDAOptImpl(const program_node& node, const RuntimeParams& params) : MSDAOptImpl() {+ add_stage(msda, params);+ }+ [[nodiscard]] std::unique_ptr<primitive_impl> clone() const override {+ return make_deep_copy<MSDAOptImpl>(this);+ }+};++} // namespace++std::unique_ptr<primitive_impl> MSDAOpt::create_impl(const program_node& node, const RuntimeParams& params) const {+ OPENVINO_ASSERT(node.is_type<msda>(), "MSDAOpt expects an msda node");+ return std::make_unique<MSDAOptImpl>(node, params);+}++} // namespace ov::intel_gpu::ocl++BIND_BINARY_BUFFER_WITH_TYPE(cldnn::msda)+BIND_BINARY_BUFFER_WITH_TYPE(ov::intel_gpu::ocl::MSDAOptImpl)diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/msda_opt.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/msda_opt.hppnew file mode 100644index 00000000000..ba90e57cbb4--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/msda_opt.hpp@@ -0,0 +1,57 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <array>+#include <limits>+#include <memory>+#include <utility>++#include "msda_inst.h"+#include "program_node.h"+#include "registry/implementation_manager.hpp"++using namespace cldnn; // TODO: Remove once namespaces are aligned++namespace ov::intel_gpu::ocl {++struct MSDAOpt : public ImplementationManager {+ OV_GPU_PRIMITIVE_IMPL("ocl::msda::opt")+ explicit MSDAOpt(shape_types shape_type, ValidateFunc vf = nullptr) : ImplementationManager(impl_types::ocl, shape_type, std::move(vf)) {}+ [[nodiscard]] std::unique_ptr<primitive_impl> create_impl(const program_node& node, const RuntimeParams& params) const override;++ [[nodiscard]] in_out_fmts_t query_formats(const program_node& node) const override {+ std::vector<format::type> in_fmts;+ for (size_t i = 0; i < node.get_dependencies().size(); i++)+ in_fmts.push_back(format::get_default_format(node.get_input_layout(i).get_rank()));+ return {in_fmts, {format::get_default_format(node.get_output_layout(0).get_rank())}};+ }++ // The op validation guarantees the input ranks and dimensions; the kernel+ // needs plain layouts, f16/f32 data, i32 level sizes and offsets, and+ // element counts that fit its 32-bit offsets.+ [[nodiscard]] bool validate_impl(const program_node& node) const override {+ OPENVINO_ASSERT(node.is_type<msda>(), "MSDAOpt expects an msda node");+ static constexpr std::array supported_types = {ov::element::f16, ov::element::f32};+ const auto plain = [](const layout& l) {+ return l.format == format::get_default_format(l.get_rank()) && !l.get_padding();+ };+ const auto fits_int32 = [](const layout& l) {+ return l.count() <= static_cast<size_t>(std::numeric_limits<int32_t>::max());+ };+ for (size_t i = 0; i < node.get_dependencies().size(); i++) {+ const auto& in_layout = node.get_input_layout(i);+ const bool index_input = i == 1 || i == 2;+ if (!plain(in_layout) || !fits_int32(in_layout) ||+ (index_input ? in_layout.data_type != ov::element::i32 : !one_of(in_layout.data_type, supported_types))) {+ return false;+ }+ }+ const auto& out_layout = node.get_output_layout(0);+ return plain(out_layout) && fits_int32(out_layout) && one_of(out_layout.data_type, supported_types);+ }+};++} // namespace ov::intel_gpu::ocldiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sources.cmake b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sources.cmakeindex 61ae07f62ad..e738d3dfa5e 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sources.cmake+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sources.cmake@@ -55,6 +55,8 @@ set(GPU_OCL_V2_IMPL_SOURCES${CMAKE_CURRENT_LIST_DIR}/moe/moe_scatter_reduction_opt.hpp${CMAKE_CURRENT_LIST_DIR}/moe/moe_scatter_reduction_ref.cpp${CMAKE_CURRENT_LIST_DIR}/moe/moe_scatter_reduction_ref.hpp+ ${CMAKE_CURRENT_LIST_DIR}/msda_opt.cpp+ ${CMAKE_CURRENT_LIST_DIR}/msda_opt.hpp${CMAKE_CURRENT_LIST_DIR}/pa_kv_reorder.cpp${CMAKE_CURRENT_LIST_DIR}/pa_kv_reorder.hpp${CMAKE_CURRENT_LIST_DIR}/paged_causal_conv1d_ref.cpp@@ -132,6 +134,7 @@ set(GPU_OCL_V2_KERNEL_SOURCES${CMAKE_CURRENT_LIST_DIR}/moe_scatter_reduction_opt.cl${CMAKE_CURRENT_LIST_DIR}/moe_scatter_reduction_ref.cl${CMAKE_CURRENT_LIST_DIR}/moe_scatter_reduction_row_lut.cl+ ${CMAKE_CURRENT_LIST_DIR}/msda_opt.cl${CMAKE_CURRENT_LIST_DIR}/pa_adaptive_rkv_diversity_ref.cl${CMAKE_CURRENT_LIST_DIR}/pa_kv_cache_reorder_ref.cl${CMAKE_CURRENT_LIST_DIR}/pa_kv_cache_rotate_ref.cldiff --git a/src/plugins/intel_gpu/src/graph/include/msda_inst.h b/src/plugins/intel_gpu/src/graph/include/msda_inst.hnew file mode 100644index 00000000000..7bc206d8d9f--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/include/msda_inst.h@@ -0,0 +1,44 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once+#include <string>++#include "intel_gpu/primitives/msda.hpp"+#include "primitive_inst.h"++namespace cldnn {++template <>+struct typed_program_node<msda> : public typed_program_node_base<msda> {+ using parent = typed_program_node_base<msda>;++public:+ using parent::parent;++ std::vector<size_t> get_shape_infer_dependencies() const override {+ return {};+ }+};+using msda_node = typed_program_node<msda>;++template <>+class typed_primitive_inst<msda> : public typed_primitive_inst_base<msda> {+ using parent = typed_primitive_inst_base<msda>;+ using parent::parent;++public:+ template <typename ShapeType>+ static std::vector<layout> calc_output_layouts(const msda_node& /*node*/, const kernel_impl_params& impl_params);+ static layout calc_output_layout(const msda_node& node, const kernel_impl_params& impl_params) {+ return calc_output_layouts<ov::PartialShape>(node, impl_params)[0];+ }++ static std::string to_string(const msda_node& node);++ typed_primitive_inst(network& network, const msda_node& node);+};++using msda_inst = typed_primitive_inst<msda>;+} // namespace cldnndiff --git a/src/plugins/intel_gpu/src/graph/msda.cpp b/src/plugins/intel_gpu/src/graph/msda.cppnew file mode 100644index 00000000000..fe175f97e0d--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/msda.cpp@@ -0,0 +1,35 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "json_object.h"+#include "msda_inst.h"+#include "primitive_type_base.h"++namespace cldnn {+GPU_DEFINE_PRIMITIVE_TYPE_ID(msda);++template <typename ShapeType>+std::vector<layout> msda_inst::calc_output_layouts(const msda_node& /*node*/, const kernel_impl_params& impl_param) {+ // value [B, S, H, D] and attention_weights [B, Q, H, L, P] give the output [B, Q, H * D].+ const auto& value_layout = impl_param.get_input_layout(0);+ const auto value = value_layout.get_partial_shape();+ const auto weights = impl_param.get_input_layout(4).get_partial_shape();+ const ov::PartialShape output_shape{value[0], weights[1], value[2] * value[3]};+ return {layout{output_shape, value_layout.data_type, format::get_default_format(output_shape.size())}};+}++template std::vector<layout> msda_inst::calc_output_layouts<ov::PartialShape>(const msda_node& node, const kernel_impl_params& impl_param);++std::string msda_inst::to_string(const msda_node& node) {+ auto node_info = node.desc_to_json();++ std::stringstream primitive_description;+ node_info->dump(primitive_description);++ return primitive_description.str();+}++msda_inst::typed_primitive_inst(network& network, const msda_node& node) : parent(network, node) {}++} // namespace cldnndiff --git a/src/plugins/intel_gpu/src/graph/registry/msda_impls.cpp b/src/plugins/intel_gpu/src/graph/registry/msda_impls.cppnew file mode 100644index 00000000000..e16e3a5fb70--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/registry/msda_impls.cpp@@ -0,0 +1,27 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "intel_gpu/primitives/msda.hpp"+#include "primitive_inst.h"+#include "registry.hpp"++#if OV_GPU_WITH_OCL+# include "impls/ocl_v2/msda_opt.hpp"+#endif++namespace ov::intel_gpu {++using namespace cldnn;++const std::vector<std::shared_ptr<cldnn::ImplementationManager>>& Registry<msda>::get_implementations() {+ static const std::vector<std::shared_ptr<ImplementationManager>> impls = {+#if OV_GPU_WITH_OCL+ OV_GPU_CREATE_INSTANCE_OCL(ocl::MSDAOpt, shape_types::static_shape)+#endif+ };++ return impls;+}++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/graph/registry/registry.hpp b/src/plugins/intel_gpu/src/graph/registry/registry.hppindex 9b0a921264a..dce0ad23838 100644--- a/src/plugins/intel_gpu/src/graph/registry/registry.hpp+++ b/src/plugins/intel_gpu/src/graph/registry/registry.hpp@@ -182,6 +182,7 @@ REGISTER_IMPLS(shape_of);REGISTER_IMPLS(strided_slice);REGISTER_IMPLS(tile);REGISTER_IMPLS(col2im);+REGISTER_IMPLS(msda);REGISTER_IMPLS(vl_sdpa);REGISTER_IMPLS(moe_3gemm_fused_compressed);REGISTER_IMPLS(moe_router_fused);diff --git a/src/plugins/intel_gpu/src/graph/sources.cmake b/src/plugins/intel_gpu/src/graph/sources.cmakeindex d8077bcb218..14163985551 100644--- a/src/plugins/intel_gpu/src/graph/sources.cmake+++ b/src/plugins/intel_gpu/src/graph/sources.cmake@@ -168,6 +168,7 @@ set(GPU_GRAPH_SOURCES${CMAKE_CURRENT_LIST_DIR}/include/moe_mask_gen_inst.h${CMAKE_CURRENT_LIST_DIR}/include/moe_router_fused_inst.h${CMAKE_CURRENT_LIST_DIR}/include/moe_scatter_reduction_inst.h+ ${CMAKE_CURRENT_LIST_DIR}/include/msda_inst.h${CMAKE_CURRENT_LIST_DIR}/include/multiclass_nms_inst.h${CMAKE_CURRENT_LIST_DIR}/include/multinomial_inst.h${CMAKE_CURRENT_LIST_DIR}/include/mutable_data_inst.h@@ -254,6 +255,7 @@ set(GPU_GRAPH_SOURCES${CMAKE_CURRENT_LIST_DIR}/moe_mask_gen.cpp${CMAKE_CURRENT_LIST_DIR}/moe_router_fused.cpp${CMAKE_CURRENT_LIST_DIR}/moe_scatter_reduction.cpp+ ${CMAKE_CURRENT_LIST_DIR}/msda.cpp${CMAKE_CURRENT_LIST_DIR}/multiclass_nms.cpp${CMAKE_CURRENT_LIST_DIR}/multinomial.cpp${CMAKE_CURRENT_LIST_DIR}/mutable_data.cpp@@ -322,6 +324,7 @@ set(GPU_GRAPH_SOURCES${CMAKE_CURRENT_LIST_DIR}/registry/moe_mask_gen_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/moe_router_fused_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/moe_scatter_reduction_impls.cpp+ ${CMAKE_CURRENT_LIST_DIR}/registry/msda_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/mvn_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/non_max_suppression_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/pa_kv_reorder_impls.cppdiff --git a/src/plugins/intel_gpu/src/plugin/ops/msda.cpp b/src/plugins/intel_gpu/src/plugin/ops/msda.cppnew file mode 100644index 00000000000..dc5c7a10e28--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/ops/msda.cpp@@ -0,0 +1,25 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "intel_gpu/primitives/msda.hpp"++#include "intel_gpu/plugin/common_utils.hpp"+#include "intel_gpu/plugin/program_builder.hpp"+#include "ov_ops/msda.hpp"++namespace ov::intel_gpu {++static void CreateMSDAOp(ProgramBuilder& p, const std::shared_ptr<op::internal::MSDA>& op) {+ validate_inputs_count(op, {5});+ auto inputs = p.GetInputInfo(op);++ const std::string layerName = layer_type_name_ID(op);+ const cldnn::msda msda_prim(layerName, inputs);++ p.add_primitive(*op, msda_prim);+}++REGISTER_FACTORY_IMPL(internal, MSDA);++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cppindex 4f26c385ccd..81401993622 100644--- a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp+++ b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp@@ -153,6 +153,7 @@#include "transformations/common_optimizations/lora_subgraph_fusion.hpp"#include "transformations/common_optimizations/lstm_cell_fusion.hpp"#include "transformations/common_optimizations/move_eltwise_up_data_movement.hpp"+#include "transformations/common_optimizations/multi_scale_deformable_attn_grid_sample_fusion.hpp"#include "transformations/common_optimizations/mvn_fusion.hpp"#include "transformations/common_optimizations/convert_tiled_moe_block_to_gather_matmuls.hpp"#include "transformations/op_conversions/convert_grouped_matmul_to_gather_matmul.hpp"@@ -1956,6 +1957,7 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {manager.register_pass<ov::pass::EliminatePad>();manager.register_pass<ov::pass::ConstantsReduce>();+ manager.register_pass<ov::pass::MultiScaleDeformableAttnGridSampleFusion>();manager.register_pass<ov::intel_gpu::PreserveSingleSelectiveSSMOutput>();diff --git a/src/plugins/intel_gpu/tests/functional/shared_tests_instances/subgraph_tests/msda_pattern.cpp b/src/plugins/intel_gpu/tests/functional/shared_tests_instances/subgraph_tests/msda_pattern.cppnew file mode 100644index 00000000000..2676cd1c5f0--- /dev/null+++ b/src/plugins/intel_gpu/tests/functional/shared_tests_instances/subgraph_tests/msda_pattern.cpp@@ -0,0 +1,30 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "subgraph_tests/msda_pattern.hpp"++namespace {++using ov::test::MSDAForm;+using ov::test::MSDAPattern;+using ov::test::MSDAShapes;++const std::vector<MSDAShapes> shapes = {+ // GroundingDINO levels at 800x1333 with fewer queries than the 900 of the decoder.+ {{{100, 167}, {50, 84}, {25, 42}, {13, 21}}, 1, 50, 8, 32, 4},+ // Encoder style: the queries are the keys.+ {{{8, 10}, {4, 5}}, 1, 100, 2, 16, 4},+ {{{4, 5}, {6, 6}, {8, 7}}, 1, 6, 2, 8, 2},+ {{{6, 6}, {3, 3}}, 2, 7, 4, 16, 2},+};++INSTANTIATE_TEST_SUITE_P(smoke_MSDAPattern,+ MSDAPattern,+ ::testing::Combine(::testing::ValuesIn(shapes),+ ::testing::Values(MSDAForm::VariadicSplit, MSDAForm::StridedSlice),+ ::testing::Values(ov::element::f32, ov::element::f16),+ ::testing::Values(ov::test::utils::DEVICE_GPU)),+ MSDAPattern::getTestCaseName);++} // namespacediff --git a/src/plugins/intel_gpu/tests/functional/sources.cmake b/src/plugins/intel_gpu/tests/functional/sources.cmakeindex 99f2e6375ef..348656847b4 100644--- a/src/plugins/intel_gpu/tests/functional/sources.cmake+++ b/src/plugins/intel_gpu/tests/functional/sources.cmake@@ -245,6 +245,7 @@ set(GPU_FUNCTIONAL_TEST_SOURCES${CMAKE_CURRENT_LIST_DIR}/shared_tests_instances/subgraph_tests/matmul_conversion.cpp${CMAKE_CURRENT_LIST_DIR}/shared_tests_instances/subgraph_tests/matmul_squeeze_add.cpp${CMAKE_CURRENT_LIST_DIR}/shared_tests_instances/subgraph_tests/matmul_transpose_to_reshape.cpp+ ${CMAKE_CURRENT_LIST_DIR}/shared_tests_instances/subgraph_tests/msda_pattern.cpp${CMAKE_CURRENT_LIST_DIR}/shared_tests_instances/subgraph_tests/multiply_add.cpp${CMAKE_CURRENT_LIST_DIR}/shared_tests_instances/subgraph_tests/perm_conv_perm_concat.cpp${CMAKE_CURRENT_LIST_DIR}/shared_tests_instances/subgraph_tests/preprocess.cppdiff --git a/src/plugins/intel_gpu/tests/unit/sources.cmake b/src/plugins/intel_gpu/tests/unit/sources.cmakeindex db36ba66b55..aa7d4e50863 100644--- a/src/plugins/intel_gpu/tests/unit/sources.cmake+++ b/src/plugins/intel_gpu/tests/unit/sources.cmake@@ -229,6 +229,7 @@ set(GPU_UNIT_TESTS_SRCS${CMAKE_CURRENT_LIST_DIR}/test_cases/moe_offload_weight_provider_test.cpp${CMAKE_CURRENT_LIST_DIR}/test_cases/moe_router_fused_gpu_test.cpp${CMAKE_CURRENT_LIST_DIR}/test_cases/moe_scatter_reduction_gpu_test.cpp+ ${CMAKE_CURRENT_LIST_DIR}/test_cases/msda_gpu_test.cpp${CMAKE_CURRENT_LIST_DIR}/test_cases/multiclass_nms_gpu_test.cpp${CMAKE_CURRENT_LIST_DIR}/test_cases/multiple_streams_gpu_test.cpp${CMAKE_CURRENT_LIST_DIR}/test_cases/mvn_gpu_test.cppdiff --git a/src/plugins/intel_gpu/tests/unit/test_cases/msda_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/msda_gpu_test.cppnew file mode 100644index 00000000000..3aad23ce3d8--- /dev/null+++ b/src/plugins/intel_gpu/tests/unit/test_cases/msda_gpu_test.cpp@@ -0,0 +1,221 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <algorithm>+#include <cmath>+#include <sstream>+#include <tuple>+#include <vector>++#include "intel_gpu/primitives/input_layout.hpp"+#include "intel_gpu/primitives/msda.hpp"+#include "test_utils.h"++using namespace cldnn;+using namespace ::tests;++namespace {++struct MsdaCase {+ size_t batch, queries, heads, embed, levels, points;+ std::vector<std::pair<int, int>> spatial; // (h, w) per level+ size_t keys() const {+ size_t k = 0;+ for (const auto& hw : spatial)+ k += static_cast<size_t>(hw.first) * hw.second;+ return k;+ }+};++// Host model of the MSDA semantics: per (b, q, h, d) accumulate over levels and+// points the attention-weighted bilinear sample of value at the pixel+// coordinates x * W - 0.5, y * H - 0.5 of the normalized location (x, y), with+// zero padding outside the feature map.+std::vector<float> msda_reference(const MsdaCase& c, const std::vector<float>& value, const std::vector<float>& loc, const std::vector<float>& weights) {+ const size_t B = c.batch, Q = c.queries, H = c.heads, D = c.embed, L = c.levels, P = c.points;+ const size_t K = c.keys();+ std::vector<int32_t> starts;+ int32_t position = 0;+ for (const auto& hw : c.spatial) {+ starts.push_back(position);+ position += hw.first * hw.second;+ }+ std::vector<float> out(B * Q * H * D, 0.f);+ for (size_t b = 0; b < B; ++b) {+ for (size_t q = 0; q < Q; ++q) {+ for (size_t h = 0; h < H; ++h) {+ for (size_t d = 0; d < D; ++d) {+ float col = 0.f;+ for (size_t l = 0; l < L; ++l) {+ const int Hl = c.spatial[l].first, Wl = c.spatial[l].second;+ for (size_t p = 0; p < P; ++p) {+ const size_t widx = (((b * Q + q) * H + h) * L + l) * P + p;+ const size_t lidx = 2 * widx;+ const float loc_w = loc[lidx], loc_h = loc[lidx + 1];+ const float weight = weights[widx];+ const float h_im = loc_h * Hl - 0.5f;+ const float w_im = loc_w * Wl - 0.5f;+ if (h_im > -1.f && w_im > -1.f && h_im < Hl && w_im < Wl) {+ const int h_low = static_cast<int>(std::floor(h_im));+ const int w_low = static_cast<int>(std::floor(w_im));+ const int h_high = h_low + 1, w_high = w_low + 1;+ const float lh = h_im - h_low, lw = w_im - w_low;+ const float hh = 1.f - lh, hw = 1.f - lw;+ const auto at = [&](int y, int x) -> float {+ if (y < 0 || x < 0 || y >= Hl || x >= Wl)+ return 0.f;+ const size_t key = starts[l] + static_cast<size_t>(y) * Wl + x;+ return value[((b * K + key) * H + h) * D + d];+ };+ col += (hh * hw * at(h_low, w_low) + hh * lw * at(h_low, w_high) + lh * hw * at(h_high, w_low) + lh * lw * at(h_high, w_high)) *+ weight;+ }+ }+ }+ out[((b * Q + q) * H + h) * D + d] = col;+ }+ }+ }+ }+ return out;+}++// Rounds to the precision the kernel reads, so the host reference sees the+// same inputs as the device.+std::vector<float> round_to(data_types type, std::vector<float> values) {+ if (type == data_types::f16) {+ for (auto& v : values)+ v = static_cast<float>(ov::float16(v));+ }+ return values;+}++template <typename T>+memory::ptr make_input(engine& engine, const ov::PartialShape& shape, data_types type, const std::vector<float>& values) {+ auto memory = engine.allocate_memory({shape, type, format::get_default_format(shape.size())});+ std::vector<T> converted(values.begin(), values.end());+ set_values(memory, converted);+ return memory;+}++template <typename T>+void run_msda_case(const MsdaCase& c, data_types type, bool is_caching_test) {+ auto& engine = get_test_engine();+ const size_t K = c.keys();++ std::vector<float> value_vec(c.batch * K * c.heads * c.embed);+ for (size_t i = 0; i < value_vec.size(); ++i)+ value_vec[i] = 0.125f * static_cast<float>(i % 97) - 3.0f;+ std::vector<float> loc_vec(c.batch * c.queries * c.heads * c.levels * c.points * 2);+ // Locations from -0.3 to 1.3 put samples inside the levels, on their+ // borders and fully outside them.+ for (size_t i = 0; i < loc_vec.size(); ++i)+ loc_vec[i] = -0.3f + 0.1f * static_cast<float>(i % 17);+ std::vector<float> weight_vec(c.batch * c.queries * c.heads * c.levels * c.points);+ for (size_t i = 0; i < weight_vec.size(); ++i)+ weight_vec[i] = static_cast<float>((i % 7) + 1) / 8.f;+ value_vec = round_to(type, value_vec);+ loc_vec = round_to(type, loc_vec);+ weight_vec = round_to(type, weight_vec);++ std::vector<int32_t> spatial_flat;+ for (const auto& hw : c.spatial)+ spatial_flat.insert(spatial_flat.end(), {hw.first, hw.second});+ std::vector<int32_t> starts;+ int32_t position = 0;+ for (const auto& hw : c.spatial) {+ starts.push_back(position);+ position += hw.first * hw.second;+ }++ const auto B = int64_t(c.batch), Q = int64_t(c.queries), H = int64_t(c.heads), L = int64_t(c.levels), P = int64_t(c.points);+ auto data_value = make_input<T>(engine, ov::PartialShape{B, int64_t(K), H, int64_t(c.embed)}, type, value_vec);+ auto data_spatial_shapes = engine.allocate_memory({ov::PartialShape{L, 2}, data_types::i32, format::bfyx});+ auto data_level_start = engine.allocate_memory({ov::PartialShape{L}, data_types::i32, format::bfyx});+ auto data_sampling_loc = make_input<T>(engine, ov::PartialShape{B, Q, H, L, P, 2}, type, loc_vec);+ auto data_attn_weight = make_input<T>(engine, ov::PartialShape{B, Q, H, L, P}, type, weight_vec);+ set_values(data_spatial_shapes, spatial_flat);+ set_values(data_level_start, starts);++ topology topology;+ topology.add(input_layout("data_value", data_value->get_layout()));+ topology.add(input_layout("data_spatial_shapes", data_spatial_shapes->get_layout()));+ topology.add(input_layout("data_level_start_idx", data_level_start->get_layout()));+ topology.add(input_layout("data_sampling_loc", data_sampling_loc->get_layout()));+ topology.add(input_layout("data_attn_weight", data_attn_weight->get_layout()));+ topology.add(msda("msda",+ {input_info("data_value"),+ input_info("data_spatial_shapes"),+ input_info("data_level_start_idx"),+ input_info("data_sampling_loc"),+ input_info("data_attn_weight")}));++ cldnn::network::ptr network = get_network(engine, topology, get_test_default_config(engine), get_test_stream_ptr(), is_caching_test);+ network->set_input_data("data_value", data_value);+ network->set_input_data("data_spatial_shapes", data_spatial_shapes);+ network->set_input_data("data_level_start_idx", data_level_start);+ network->set_input_data("data_sampling_loc", data_sampling_loc);+ network->set_input_data("data_attn_weight", data_attn_weight);+ auto outputs = network->execute();+ ASSERT_EQ(outputs.count("msda"), size_t(1));++ auto output_memory = outputs.at("msda").get_memory();+ cldnn::mem_lock<T> output_ptr(output_memory, get_test_stream());+ const auto ref = msda_reference(c, value_vec, loc_vec, weight_vec);+ ASSERT_EQ(output_memory->count(), ref.size());+ // The kernel computes in float for both types; f16 only adds the rounding+ // of the stored result.+ for (size_t i = 0; i < ref.size(); ++i) {+ const float tolerance = type == data_types::f16 ? 1e-3f * std::max(1.f, std::abs(ref[i])) : 2e-4f;+ ASSERT_NEAR(static_cast<float>(output_ptr[i]), ref[i], tolerance) << "index " << i;+ }+}++// Shape case, data type and whether the network goes through export and import.+using MsdaTestParams = std::tuple<MsdaCase, data_types, bool>;++const std::vector<MsdaCase> msda_cases = {+ {1, 2, 2, 4, 2, 2, {{2, 2}, {2, 4}}},+ {2, 3, 1, 8, 1, 3, {{5, 3}}},+ // On 3x3 and 1x4 levels most samples touch a border or fall outside.+ {1, 4, 1, 2, 2, 1, {{3, 3}, {1, 4}}},+ // GroundingDINO 800x1333 stride-8 level: pixel coordinates up to 167 need+ // more precision than f16 offers for the bilinear weights.+ {1, 8, 2, 8, 2, 4, {{100, 167}, {50, 84}}},+};++} // namespace++class msda_gpu_test : public ::testing::TestWithParam<MsdaTestParams> {+public:+ static std::string get_test_case_name(const testing::TestParamInfo<MsdaTestParams>& info) {+ const auto& [c, type, is_caching_test] = info.param;+ std::ostringstream name;+ name << "B" << c.batch << "_Q" << c.queries << "_H" << c.heads << "_D" << c.embed << "_P" << c.points << "_levels";+ for (const auto& [h, w] : c.spatial)+ name << "_" << h << "x" << w;+ name << "_" << ov::element::Type(type) << (is_caching_test ? "_cached" : "");+ return name.str();+ }+};++TEST_P(msda_gpu_test, reference) {+ const auto& [c, type, is_caching_test] = GetParam();+ if (type == data_types::f16)+ run_msda_case<ov::float16>(c, type, is_caching_test);+ else+ run_msda_case<float>(c, type, is_caching_test);+}++INSTANTIATE_TEST_SUITE_P(smoke_msda_gpu_test,+ msda_gpu_test,+ ::testing::Combine(::testing::ValuesIn(msda_cases), ::testing::Values(data_types::f32, data_types::f16), ::testing::Values(false)),+ msda_gpu_test::get_test_case_name);++INSTANTIATE_TEST_SUITE_P(smoke_msda_gpu_test_cached,+ msda_gpu_test,+ ::testing::Combine(::testing::Values(msda_cases.front()),+ ::testing::Values(data_types::f32, data_types::f16),+ ::testing::Values(true)),+ msda_gpu_test::get_test_case_name);diff --git a/src/tests/functional/plugin/shared/include/shared_test_classes/subgraph/msda_pattern.hpp b/src/tests/functional/plugin/shared/include/shared_test_classes/subgraph/msda_pattern.hppnew file mode 100644index 00000000000..7e965331261--- /dev/null+++ b/src/tests/functional/plugin/shared/include/shared_test_classes/subgraph/msda_pattern.hpp@@ -0,0 +1,49 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+#pragma once++#include <string>+#include <tuple>+#include <utility>+#include <vector>++#include "shared_test_classes/base/ov_subgraph.hpp"++namespace ov {+namespace test {++// Multi-scale deformable attention geometry: feature level sizes {h, w},+// batch, queries, heads, channels per head and sampling points per level.+struct MSDAShapes {+ std::vector<std::pair<size_t, size_t>> levels;+ size_t batch;+ size_t queries;+ size_t heads;+ size_t embed;+ size_t points;+};++// How the exported graph takes the keys and the locations of a level:+// VariadicSplit outputs of value and a scalar Gather index (Deformable-DETR,+// GroundingDINO, RT-DETR exports), or StridedSlice slices of value and a [1]+// shaped Gather index followed by Squeeze.+enum class MSDAForm { VariadicSplit, StridedSlice };++// Shapes, form, inference precision and target device.+using MSDAPatternParams = std::tuple<MSDAShapes, MSDAForm, ov::element::Type, std::string>;++// GridSample based multi-scale deformable attention that the plugin fuses into+// a single MSDA primitive.+class MSDAPattern : public SubgraphBaseTest, public testing::WithParamInterface<MSDAPatternParams> {+public:+ static std::string getTestCaseName(const testing::TestParamInfo<MSDAPatternParams>& obj);++protected:+ void SetUp() override;+ void generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) override;+ void validate() override;+};++} // namespace test+} // namespace ovdiff --git a/src/tests/functional/plugin/shared/include/subgraph_tests/msda_pattern.hpp b/src/tests/functional/plugin/shared/include/subgraph_tests/msda_pattern.hppnew file mode 100644index 00000000000..913db02aedd--- /dev/null+++ b/src/tests/functional/plugin/shared/include/subgraph_tests/msda_pattern.hpp@@ -0,0 +1,17 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "shared_test_classes/subgraph/msda_pattern.hpp"++namespace ov {+namespace test {++TEST_P(MSDAPattern, CompareWithRefs) {+ run();+}++} // namespace test+} // namespace ovdiff --git a/src/tests/functional/plugin/shared/src/subgraph/msda_pattern.cpp b/src/tests/functional/plugin/shared/src/subgraph/msda_pattern.cppnew file mode 100644index 00000000000..272995e3517--- /dev/null+++ b/src/tests/functional/plugin/shared/src/subgraph/msda_pattern.cpp@@ -0,0 +1,162 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "shared_test_classes/subgraph/msda_pattern.hpp"++#include <memory>+#include <sstream>+#include <vector>++#include "common_test_utils/ov_tensor_utils.hpp"+#include "openvino/core/model.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/grid_sample.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/reduce_sum.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/squeeze.hpp"+#include "openvino/op/strided_slice.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/op/variadic_split.hpp"++namespace ov {+namespace test {++namespace {++std::shared_ptr<ov::op::v0::Constant> i64_const(const std::vector<int64_t>& v) {+ return ov::op::v0::Constant::create(element::i64, ov::Shape{v.size()}, v);+}++} // namespace++std::string MSDAPattern::getTestCaseName(const testing::TestParamInfo<MSDAPatternParams>& obj) {+ const auto& [shapes, form, precision, device] = obj.param;+ std::ostringstream result;+ result << "levels=";+ for (size_t l = 0; l < shapes.levels.size(); ++l)+ result << (l ? "_" : "") << shapes.levels[l].first << "x" << shapes.levels[l].second;+ result << ",B=" << shapes.batch << ",Q=" << shapes.queries << ",H=" << shapes.heads << ",D=" << shapes.embed+ << ",P=" << shapes.points << ",form=" << (form == MSDAForm::VariadicSplit ? "VariadicSplit" : "StridedSlice")+ << ",inference_precision=" << precision << ",targetDevice=" << device;+ return result.str();+}++void MSDAPattern::generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) {+ // value and weights in [-1, 1]; locations in [-0.5, 1.5], so samples land+ // inside the levels, on their borders and fully outside them. Multiples of+ // 1/1024 in these ranges are exact in f16, so the f16 instances compare the+ // kernel arithmetic, not the rounding of the inputs.+ const std::vector<utils::InputGenerateData> data = {{-1, 2, 1024, 1}, {-0.5, 2, 1024, 2}, {-1, 2, 1024, 3}};+ const auto& params = function->inputs();+ inputs.clear();+ for (size_t i = 0; i < params.size(); ++i) {+ inputs.insert(+ {params[i].get_node_shared_ptr(),+ utils::create_and_fill_tensor(params[i].get_element_type(), targetInputStaticShapes[i], data[i])});+ }+}++void MSDAPattern::validate() {+ SubgraphBaseTest::validate();+ CheckNumberOfNodesWithType(compiledModel, "msda", 1);+}++void MSDAPattern::SetUp() {+ const auto& [shapes, form, precision, device] = GetParam();+ targetDevice = device;+ configuration[ov::hint::inference_precision.name()] = precision;+ // The inputs are exact in f16 (see generate_inputs), so the differences to+ // the f32 reference come from the arithmetic: on a B60 the maximum was+ // 1.2e-7 for f32 and 4.8e-4 for f16, the rounding of the stored f16 result.+ // Computing the sampling in f16 instead would differ by about 4e-2.+ abs_threshold = precision == ov::element::f16 ? 2e-3f : 1e-5f;+ rel_threshold = abs_threshold;++ const auto Q = static_cast<int64_t>(shapes.queries), H = static_cast<int64_t>(shapes.heads);+ const auto D = static_cast<int64_t>(shapes.embed), P = static_cast<int64_t>(shapes.points);+ const auto L = static_cast<int64_t>(shapes.levels.size());+ std::vector<int64_t> level_keys;+ int64_t keys = 0;+ for (const auto& [h, w] : shapes.levels) {+ level_keys.push_back(static_cast<int64_t>(h * w));+ keys += level_keys.back();+ }++ const ov::Shape value_shape{shapes.batch, static_cast<size_t>(keys), shapes.heads, shapes.embed};+ const ov::Shape locations_shape{shapes.batch, shapes.queries, shapes.heads, shapes.levels.size(), shapes.points, 2};+ const ov::Shape weights_shape{shapes.batch, shapes.queries, shapes.heads, shapes.levels.size(), shapes.points};+ auto value = std::make_shared<ov::op::v0::Parameter>(element::f32, value_shape);+ auto locations = std::make_shared<ov::op::v0::Parameter>(element::f32, locations_shape);+ auto weights = std::make_shared<ov::op::v0::Parameter>(element::f32, weights_shape);++ // GridSample takes the [-1, 1] coordinates 2 * x - 1 of the [0, 1] locations x.+ auto scaled =+ std::make_shared<ov::op::v1::Multiply>(locations, ov::op::v0::Constant::create(element::f32, Shape{1}, {2.f}));+ auto coords =+ std::make_shared<ov::op::v1::Add>(scaled, ov::op::v0::Constant::create(element::f32, Shape{1}, {-1.f}));+ auto split = std::make_shared<ov::op::v1::VariadicSplit>(+ value,+ ov::op::v0::Constant::create(element::i64, Shape{}, {1}),+ ov::op::v0::Constant::create(element::i64, Shape{level_keys.size()}, level_keys));++ ov::OutputVector level_outputs;+ int64_t start = 0;+ for (int64_t l = 0; l < L; ++l) {+ const auto& [h_size, w_size] = shapes.levels[static_cast<size_t>(l)];+ const auto h = static_cast<int64_t>(h_size), w = static_cast<int64_t>(w_size);++ ov::Output<ov::Node> level_value, level_coords;+ if (form == MSDAForm::VariadicSplit) {+ level_value = split->output(static_cast<size_t>(l));+ level_coords =+ std::make_shared<ov::op::v8::Gather>(coords,+ ov::op::v0::Constant::create(element::i64, Shape{}, {l}),+ ov::op::v0::Constant::create(element::i64, Shape{}, {3}));+ } else {+ level_value = std::make_shared<ov::op::v1::StridedSlice>(value,+ i64_const({0, start}),+ i64_const({0, start + h * w}),+ i64_const({1, 1}),+ std::vector<int64_t>{1, 0},+ std::vector<int64_t>{1, 0});+ auto gathered = std::make_shared<ov::op::v8::Gather>(coords, i64_const({l}), i64_const({3}), 0);+ level_coords = std::make_shared<ov::op::v0::Squeeze>(gathered, i64_const({3}));+ }+ start += h * w;++ auto image_flat = std::make_shared<ov::op::v1::Reshape>(level_value, i64_const({0, 0, H * D}), true);+ auto image_transpose = std::make_shared<ov::op::v1::Transpose>(image_flat, i64_const({0, 2, 1}));+ auto image = std::make_shared<ov::op::v1::Reshape>(image_transpose, i64_const({-1, D, h, w}), true);+ auto coords_transpose = std::make_shared<ov::op::v1::Transpose>(level_coords, i64_const({0, 2, 1, 3, 4}));+ auto grid_coords = std::make_shared<ov::op::v1::Reshape>(coords_transpose, i64_const({-1, Q, P, 2}), true);++ ov::op::v9::GridSample::Attributes attributes{false,+ ov::op::v9::GridSample::InterpolationMode::BILINEAR,+ ov::op::v9::GridSample::PaddingMode::ZEROS};+ auto grid = std::make_shared<ov::op::v9::GridSample>(image, grid_coords, attributes);+ level_outputs.push_back(std::make_shared<ov::op::v1::Reshape>(grid, i64_const({-1, D, Q, 1, P}), false));+ }++ auto concat = std::make_shared<ov::op::v0::Concat>(level_outputs, -2);+ auto values = std::make_shared<ov::op::v1::Reshape>(concat, i64_const({0, D, 0, L * P}), true);+ auto weights_transpose = std::make_shared<ov::op::v1::Transpose>(weights, i64_const({0, 2, 1, 3, 4}));+ auto weights_reshape = std::make_shared<ov::op::v1::Reshape>(weights_transpose, i64_const({-1, 1, 0, L * P}), true);+ auto weighted = std::make_shared<ov::op::v1::Multiply>(values, weights_reshape);+ auto reduce = std::make_shared<ov::op::v1::ReduceSum>(weighted, i64_const({-1}), false);+ auto heads_output = std::make_shared<ov::op::v1::Reshape>(reduce, i64_const({-1, H * D, 0}), true);+ auto output = std::make_shared<ov::op::v1::Transpose>(heads_output, i64_const({0, 2, 1}));++ function = std::make_shared<ov::Model>(ov::OutputVector{output},+ ov::ParameterVector{value, locations, weights},+ "MSDAPattern");+ init_input_shapes(static_shapes_to_test_representation({value_shape, locations_shape, weights_shape}));+}++} // namespace test+} // namespace ov