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
[TRANSFORMATIONS][SDPA2PA] Added support of drop the batch dimension (#37013)
Mikhail Ryzhov6f0b752f9eec
diff --git a/src/common/transformations/include/transformations/paged_attention/position_ids_replacer.hpp b/src/common/transformations/include/transformations/paged_attention/position_ids_replacer.hppindex 9896190c8a0..4f0c8eef717 100644--- a/src/common/transformations/include/transformations/paged_attention/position_ids_replacer.hpp+++ b/src/common/transformations/include/transformations/paged_attention/position_ids_replacer.hpp@@ -4,6 +4,8 @@#pragma once+#include <memory>+#include "openvino/op/add.hpp"#include "openvino/op/parameter.hpp"#include "openvino/op/unsqueeze.hpp"@@ -19,6 +21,8 @@ class TRANSFORMATIONS_API PositionIDsReplacer;class TRANSFORMATIONS_API PositionIDsReplacerQwen;class TRANSFORMATIONS_API PositionIDsReplacerLFM2;class TRANSFORMATIONS_API PositionIDsReplacerCodeGen2;+class TRANSFORMATIONS_API EliminateDropBatch;+class TRANSFORMATIONS_API RoPEUnsqueezeAxisReplacer;} // namespace pass} // namespace ov@@ -102,3 +106,77 @@ public:OPENVINO_MATCHER_PASS_RTTI("PositionIDsReplacerLFM2");explicit PositionIDsReplacerLFM2(const Output<Node>& position_ids);};++/**+ * @brief After SDPAToPagedAttention flattens position_ids, the batch dimension no longer exists, so an+ * aten::select(dim=0, index=0) that dropped it (lowered to Gather(index=0, axis=0)) becomes redundant.+ *+ * This transformation detects Parameter(name == "position_ids") -> Unsqueeze(optional) -> Convert(optional) ->+ * Gather(index=0, axis=0) and replaces the Gather with a Reshape(-1), which flattens whatever shape is produced+ * by the optional Unsqueeze/Convert back to a 1D tensor. Since position_ids no longer carries a real batch+ * dimension to select from, this is equivalent to the original select but no longer depends on a batch axis+ * being present.+ *+ * We change from this: to this:+ *+ * ┌──────────────┐ ┌──────────────┐+ * │ position_ids │ │ position_ids │+ * └──────┬───────┘ └──────┬───────┘+ * │ │+ * ┌──────┴──────┐ ┌──────┴──────┐+ * │ Unsqueeze │ (optional) │ Unsqueeze │ (optional)+ * └──────┬──────┘ └──────┬──────┘+ * │ │+ * ┌──────┴──────┐ ┌──────┴──────┐+ * │ Convert │ (optional) │ Convert │ (optional)+ * └──────┬──────┘ └──────┬──────┘+ * │ │+ * ┌──────┴──────┐ ┌──────┴──────┐+ * │Gather(idx=0,│ │ Reshape │+ * │ axis=0) │ │ (-1) │+ * └─────────────┘ └─────────────┘+ */+class ov::pass::EliminateDropBatch : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("EliminateDropBatch");+ EliminateDropBatch();+};++/**+ * @brief Some models compute RoPE manually with an explicit outer product (position * inv_freq) followed by+ * Cos/Sin instead of using a fused rotary embedding op, producing cos/sin values in the original+ * [batch=1, tokens, ...] layout via a trailing Unsqueeze(axis=0). PagedAttention's Q/K arrive with tokens+ * flattened into the leading axis instead, so this transformation detects that RoPE outer-product tail+ * (MatMul(inv_freq) -> Cos/Sin -> Multiply(scale) -> Broadcast(optional) -> Unsqueeze(axis=0)) and+ * rewrites the trailing Unsqueeze's axis from 0 to 1, moving the flattened-tokens axis to index 0 to match+ * the layout Q/K arrive in. This is independent of how the per-token positions were derived (works whether+ * or not EliminateDropBatch has already collapsed a batch-drop select feeding into the outer product).+ *+ * We change from this: to this:+ *+ * ┌───────┐ ┌───────┐+ * │ MatMul│ │ MatMul│ (outer product with inv_freq)+ * └───┬───┘ └───┬───┘+ * │ │+ * ┌───┴───┐ ┌───┴───┐+ * │Cos/Sin│ │Cos/Sin│+ * └───┬───┘ └───┬───┘+ * │ │+ * ┌───┴────┐ ┌───┴────┐+ * │Multiply│ (scale) │Multiply│ (scale)+ * └───┬────┘ └───┬────┘+ * │ │+ * ┌───┴─────┐ ┌───┴─────┐+ * │Broadcast│ (optional) │Broadcast│ (optional)+ * └───┬─────┘ └───┬─────┘+ * │ │+ * ┌───┴──────┐ ┌───┴──────┐+ * │Unsqueeze │ │Unsqueeze │+ * │ (axis=0) │ │ (axis=1) │+ * └──────────┘ └──────────┘+ */+class ov::pass::RoPEUnsqueezeAxisReplacer : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("RoPEUnsqueezeAxisReplacer");+ RoPEUnsqueezeAxisReplacer();+};diff --git a/src/common/transformations/src/transformations/paged_attention/position_ids_replacer.cpp b/src/common/transformations/src/transformations/paged_attention/position_ids_replacer.cppindex 9767051b83b..32f53deb1fa 100644--- a/src/common/transformations/src/transformations/paged_attention/position_ids_replacer.cpp+++ b/src/common/transformations/src/transformations/paged_attention/position_ids_replacer.cpp@@ -4,9 +4,15 @@#include "transformations/paged_attention/position_ids_replacer.hpp"+#include <cstdint>+#include <vector>+#include "openvino/cc/pass/itt.hpp"#include "openvino/core/graph_util.hpp"+#include "openvino/core/rt_info.hpp"+#include "openvino/op/broadcast.hpp"#include "openvino/op/concat.hpp"+#include "openvino/op/convert.hpp"#include "openvino/op/cos.hpp"#include "openvino/op/einsum.hpp"#include "openvino/op/gather.hpp"@@ -26,15 +32,17 @@#include "openvino/pass/pattern/op/optional.hpp"#include "openvino/pass/pattern/op/or.hpp"#include "openvino/pass/pattern/op/wrap_type.hpp"-#include "transformations/utils/utils.hpp"using ov::pass::pattern::any_input;using ov::pass::pattern::Matcher;+using ov::pass::pattern::value_matches;using ov::pass::pattern::wrap_type;namespace v0 = ov::op::v0;namespace v1 = ov::op::v1;+namespace v3 = ov::op::v3;namespace v8 = ov::op::v8;+// TODO: Instead of using the following transformation that matches quite a specific place in a model graph in case when// position_ids parameter is missing, consider replacing always existing attention_mask parameter with a sub-graph using// a new slot_mapping parameter.@@ -56,6 +64,8 @@ ov::pass::PositionIDsReplacer::PositionIDsReplacer(const Output<Node>& position_ov::matcher_pass_callback callback = [=](Matcher& m) {const auto& pattern_map = m.get_pattern_value_map();+ // position_ids here is the shared Unsqueeze(-1) run_on_model already wired onto the parameter's consumers.+ // Reuse that existing node so an already-wired match resolves to a self-replacement no-op.replace_node(pattern_map.at(position_ids_pattern).get_node_shared_ptr(), position_ids.get_node_shared_ptr());return true;};@@ -155,7 +165,7 @@ ov::pass::PositionIDsReplacerLFM2::PositionIDsReplacerLFM2(const Output<Node>& p// Allow either the dequant-like start branch or a direct Parameter connection.auto p_start_subtract = wrap_type<v1::Subtract>({p_max_context_len, any_input()});auto p_start_dequant = wrap_type<v0::Convert>({p_start_subtract});- auto p_start = std::make_shared<ov::pass::pattern::op::Or>(OutputVector{p_start_dequant, p_max_context_len});+ auto p_start = p_start_dequant | p_max_context_len;auto p_end = wrap_type<v1::Add>({p_start, any_input()});auto p_range = wrap_type<ov::op::v4::Range>({p_start, p_end, ov::pass::pattern::wrap_const()});@@ -223,6 +233,70 @@ ov::pass::PositionIDsReplacerLFM2::PositionIDsReplacerLFM2(const Output<Node>& pregister_matcher(m, callback);}+ov::pass::EliminateDropBatch::EliminateDropBatch() {+ MATCHER_SCOPE(EliminateDropBatch);++ // Parameter(name == "position_ids") -> Unsqueeze(optional) -> Convert(optional) -> Gather(index=0, axis=0)+ auto p_position_ids = wrap_type<v0::Parameter>([](const Output<Node>& output) -> bool {+ return output.get_names().count("position_ids") != 0;+ });+ auto p_unsqueeze = ov::pass::pattern::optional<v0::Unsqueeze>({p_position_ids, any_input()});+ auto p_convert = ov::pass::pattern::optional<v0::Convert>({p_unsqueeze});++ auto p_index = wrap_type<v0::Constant>(value_matches("0"));+ auto p_axis = wrap_type<v0::Constant>(value_matches("0"));+ auto p_gather = wrap_type<ov::op::util::GatherBase>({p_convert, p_index, p_axis}, {{"batch_dims", 0}});++ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](Matcher& m) {+ const auto gather = m.get_match_root();++ auto reshape = std::make_shared<v1::Reshape>(gather->input_value(0),+ v0::Constant::create(element::i64, Shape{1}, {-1}),+ false);++ ov::replace_output_update_name(gather->output(0), reshape->output(0));+ return true;+ };++ auto m = std::make_shared<Matcher>(p_gather, matcher_name);+ register_matcher(m, callback);+}++// Handles models that compute RoPE manually via an explicit outer product (position * inv_freq) followed by+// Cos/Sin instead of a fused rotary embedding op, producing cos/sin values in the original+// [batch=1, tokens, ...] layout via a trailing Unsqueeze(axis=0). PagedAttention's Q/K arrive with tokens+// flattened into the leading axis instead, so this rewrites that trailing Unsqueeze's axis from 0 to 1,+// moving the flattened-tokens axis to index 0.+ov::pass::RoPEUnsqueezeAxisReplacer::RoPEUnsqueezeAxisReplacer() {+ MATCHER_SCOPE(RoPEUnsqueezeAxisReplacer);++ // MatMul(outer, with a constant inv_freq operand) -> Cos/Sin("polar") -> Multiply(scale) ->+ // Broadcast(optional) -> Unsqueeze(axis=0).+ auto p_outer_matmul = wrap_type<v0::MatMul>({any_input(), ov::pass::pattern::wrap_const()});+ auto p_trig = wrap_type<v0::Cos, v0::Sin>({p_outer_matmul});+ auto p_scaled = wrap_type<v1::Multiply>({any_input(), p_trig});+ auto p_broadcast = ov::pass::pattern::optional<op::util::BroadcastBase>({p_scaled, any_input()});+ auto p_concat = wrap_type<v0::Concat>({p_broadcast, p_broadcast});+ auto p_rope_out = p_broadcast | p_concat;+ auto p_axis = wrap_type<v0::Constant>(value_matches("0"));+ auto p_unsqueeze = wrap_type<v0::Unsqueeze>({p_rope_out, p_axis});++ ov::matcher_pass_callback callback = [=](Matcher& m) {+ const auto& pattern_map = m.get_pattern_value_map();++ const auto axis_const = ov::as_type_ptr<v0::Constant>(pattern_map.at(p_axis).get_node_shared_ptr());+ const auto unsqueeze = pattern_map.at(p_unsqueeze).get_node_shared_ptr();+ auto new_axis_const = v0::Constant::create(axis_const->get_element_type(), axis_const->get_shape(), {1});+ copy_runtime_info(axis_const, new_axis_const);+ unsqueeze->input(1).replace_source_output(new_axis_const);+ unsqueeze->validate_and_infer_types();+ return true;+ };++ auto m = std::make_shared<Matcher>(p_unsqueeze, matcher_name);+ register_matcher(m, callback);+}+ov::pass::PositionIDsReplacerCodeGen2::PositionIDsReplacerCodeGen2(const std::shared_ptr<v0::Parameter>& position_ids) {MATCHER_SCOPE(PositionIDsReplacerCodeGen2);@@ -261,4 +335,4 @@ ov::pass::PositionIDsReplacerCodeGen2::PositionIDsReplacerCodeGen2(const std::shauto m = std::make_shared<Matcher>(p_slice, matcher_name);register_matcher(m, callback);-}\ No newline at end of file+}diff --git a/src/common/transformations/tests/op_conversions/sdpa_to_paged_attention_test.cpp b/src/common/transformations/tests/op_conversions/sdpa_to_paged_attention_test.cppindex 45698f0ca73..07ee862ca50 100644--- a/src/common/transformations/tests/op_conversions/sdpa_to_paged_attention_test.cpp+++ b/src/common/transformations/tests/op_conversions/sdpa_to_paged_attention_test.cpp@@ -1466,6 +1466,329 @@ TEST_F(SDPAToPATest, SDPAToPA_PositionIDsReplacerLFM2_DirectParameterBranchRank4comparator.enable(FunctionsComparator::ATTRIBUTES);}+namespace {+// Whether the optional Unsqueeze/Convert wrappers sit between position_ids and the batch-drop select Gather.+struct EliminateDropBatchWrappers {+ bool has_unsqueeze;+ bool has_convert;+};++std::string test_name(const EliminateDropBatchWrappers& wrappers) {+ std::string name = "Select";+ name += wrappers.has_unsqueeze ? "_Unsqueeze" : "_NoUnsqueeze";+ name += wrappers.has_convert ? "_Convert" : "_NoConvert";+ return name;+}++std::shared_ptr<Node> wrap_optional(const std::shared_ptr<Node>& data, const EliminateDropBatchWrappers& wrappers) {+ std::shared_ptr<Node> result = data;+ if (wrappers.has_unsqueeze) {+ result = std::make_shared<v0::Unsqueeze>(result, v0::Constant::create(element::i32, Shape{}, {0}));+ }+ if (wrappers.has_convert) {+ result = std::make_shared<v0::Convert>(result, element::f32);+ }+ return result;+}+} // namespace++class SDPAToPAEliminateDropBatchTest : public TransformationTestsF,+ public ::testing::WithParamInterface<EliminateDropBatchWrappers> {};++TEST_P(SDPAToPAEliminateDropBatchTest, SDPAToPA_EliminateDropBatch_CollapsesToReshape) {+ // Parameter(position_ids) -> Unsqueeze(optional) -> Convert(optional) -> Gather(select dim=0, index=0)+ // collapses to Parameter(position_ids) -> Unsqueeze(optional) -> Convert(optional) -> Reshape([-1]),+ // regardless of which of the optional wrapper nodes are present.+ const auto wrappers = GetParam();+ {+ auto position_ids = make_param(PartialShape{DYN}, element::i64, "position_ids");+ auto data = wrap_optional(position_ids, wrappers);+ auto select = std::make_shared<v8::Gather>(data,+ v0::Constant::create(element::i64, Shape{}, {0}),+ v0::Constant::create(element::i64, Shape{}, {0}));+ model = std::make_shared<Model>(ResultVector{std::make_shared<v0::Result>(select)},+ nodes_to_params({position_ids}));+ manager.register_pass<pass::EliminateDropBatch>();+ }+ {+ auto position_ids = make_param(PartialShape{DYN}, element::i64, "position_ids");+ auto data = wrap_optional(position_ids, wrappers);+ auto reshape = std::make_shared<v1::Reshape>(data, v0::Constant::create(element::i64, Shape{1}, {-1}), false);+ model_ref = std::make_shared<Model>(ResultVector{std::make_shared<v0::Result>(reshape)},+ nodes_to_params({position_ids}));+ }++ comparator.enable(FunctionsComparator::ATTRIBUTES);+}++INSTANTIATE_TEST_SUITE_P(SDPAToPA,+ SDPAToPAEliminateDropBatchTest,+ ::testing::Values(EliminateDropBatchWrappers{false, false},+ EliminateDropBatchWrappers{false, true},+ EliminateDropBatchWrappers{true, false},+ EliminateDropBatchWrappers{true, true}),+ [](const ::testing::TestParamInfo<EliminateDropBatchWrappers>& info) {+ return test_name(info.param);+ });++TEST_F(SDPAToPATest, SDPAToPA_EliminateDropBatch_ReconnectsDownstreamConsumer) {+ // The replaced Gather's consumers must be reconnected to the new Reshape node.+ {+ auto position_ids = make_param(PartialShape{DYN}, element::i64, "position_ids");+ auto select = std::make_shared<v8::Gather>(position_ids,+ v0::Constant::create(element::i64, Shape{}, {0}),+ v0::Constant::create(element::i64, Shape{}, {0}));+ auto add = std::make_shared<v1::Add>(select, v0::Constant::create(element::i64, Shape{}, {1}));+ model =+ std::make_shared<Model>(ResultVector{std::make_shared<v0::Result>(add)}, nodes_to_params({position_ids}));+ manager.register_pass<pass::EliminateDropBatch>();+ }+ {+ auto position_ids = make_param(PartialShape{DYN}, element::i64, "position_ids");+ auto reshape =+ std::make_shared<v1::Reshape>(position_ids, v0::Constant::create(element::i64, Shape{1}, {-1}), false);+ auto add = std::make_shared<v1::Add>(reshape, v0::Constant::create(element::i64, Shape{}, {1}));+ model_ref =+ std::make_shared<Model>(ResultVector{std::make_shared<v0::Result>(add)}, nodes_to_params({position_ids}));+ }++ comparator.enable(FunctionsComparator::ATTRIBUTES);+}++namespace {+// A Gather that isn't the scalar select(dim=0, index=0) pattern on a Parameter named "position_ids": wrong+// index, wrong axis, non-zero batch_dims, a non-scalar indices tensor, or a differently-named Parameter.+struct EliminateDropBatchNegativeCase {+ std::vector<int64_t> indices;+ int64_t axis;+ int64_t batch_dims;+ std::string param_name;+ std::string name;+};+} // namespace++class SDPAToPAEliminateDropBatchNegativeTest : public TransformationTestsF,+ public ::testing::WithParamInterface<EliminateDropBatchNegativeCase> {};++TEST_P(SDPAToPAEliminateDropBatchNegativeTest, SDPAToPA_EliminateDropBatch_NotABatchDropSelect) {+ const auto& test_case = GetParam();+ auto position_ids = make_param(PartialShape{DYN, DYN}, element::i64, test_case.param_name);+ auto select = std::make_shared<v8::Gather>(+ position_ids,+ v0::Constant::create(element::i64, Shape{test_case.indices.size()}, test_case.indices),+ v0::Constant::create(element::i64, Shape{}, {test_case.axis}),+ test_case.batch_dims);+ model =+ std::make_shared<Model>(ResultVector{std::make_shared<v0::Result>(select)}, nodes_to_params({position_ids}));+ manager.register_pass<pass::EliminateDropBatch>();++ comparator.enable(FunctionsComparator::ATTRIBUTES);+}++INSTANTIATE_TEST_SUITE_P(+ SDPAToPA,+ SDPAToPAEliminateDropBatchNegativeTest,+ ::testing::Values(EliminateDropBatchNegativeCase{{1}, 0, 0, "position_ids", "WrongIndex"},+ EliminateDropBatchNegativeCase{{0}, 1, 0, "position_ids", "WrongAxis"},+ EliminateDropBatchNegativeCase{{0, 1}, 0, 0, "position_ids", "NonScalarIndices"},+ EliminateDropBatchNegativeCase{{0}, 0, 0, "input_ids", "NotPositionIdsParam"},+ EliminateDropBatchNegativeCase{{0}, 0, -1, "position_ids", "WrongBatchDims"}),+ [](const ::testing::TestParamInfo<EliminateDropBatchNegativeCase>& info) {+ return info.param.name;+ });++namespace {+// Builds the "manual RoPE" outer-product tail that RoPEUnsqueezeAxisReplacer requires before its trailing+// Unsqueeze(axis=0): Unsqueeze -> MatMul(inv_freq) -> Cos/Sin -> Multiply(scale) -> Broadcast(optional).+std::shared_ptr<Node> build_rope_broadcast(const Output<Node>& positions, bool use_sin, bool with_broadcast) {+ auto positions_unsqueeze =+ std::make_shared<v0::Unsqueeze>(positions, v0::Constant::create(element::i32, Shape{1}, {1}));+ auto inv_freq = v0::Constant::create(element::f32, Shape{4, 1}, std::vector<float>{0.1f, 0.2f, 0.3f, 0.4f});+ auto outer = std::make_shared<v0::MatMul>(positions_unsqueeze, inv_freq, false, true);+ std::shared_ptr<Node> trig;+ if (use_sin) {+ trig = std::make_shared<v0::Sin>(outer);+ } else {+ trig = std::make_shared<v0::Cos>(outer);+ }+ auto scale = v0::Constant::create(element::f32, Shape{}, {1.0f});+ std::shared_ptr<Node> scaled = std::make_shared<v1::Multiply>(scale, trig);+ if (with_broadcast) {+ auto broadcast_shape = v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{4, 4});+ scaled = std::make_shared<v3::Broadcast>(scaled, broadcast_shape);+ }+ return scaled;+}++// Whether the RoPE tail computes Sin (vs Cos), and whether the optional Broadcast is present before the+// trailing Unsqueeze.+struct RoPEUnsqueezeAxisCase {+ bool use_sin;+ bool with_broadcast;+};++std::string test_name(const RoPEUnsqueezeAxisCase& test_case) {+ std::string name = test_case.use_sin ? "Sin" : "Cos";+ name += test_case.with_broadcast ? "_Broadcast" : "_NoBroadcast";+ return name;+}+} // namespace++class SDPAToPARoPEUnsqueezeAxisReplacerTest : public TransformationTestsF,+ public ::testing::WithParamInterface<RoPEUnsqueezeAxisCase> {};++TEST_P(SDPAToPARoPEUnsqueezeAxisReplacerTest, SDPAToPA_RoPEUnsqueezeAxisReplacer_RewritesAxis) {+ // Manual RoPE outer-product tail ending in Unsqueeze(axis=0): the flattened-tokens axis must move from+ // index 1 to index 0 to match the layout PagedAttention's Q/K arrive in, so the trailing Unsqueeze's axis+ // is rewritten from 0 to 1. This holds for both the Cos and Sin branches, and regardless of whether the+ // optional Broadcast is present.+ const auto test_case = GetParam();+ {+ auto positions = make_param(PartialShape{DYN}, element::f32, "positions");+ auto broadcast = build_rope_broadcast(positions, test_case.use_sin, test_case.with_broadcast);+ auto unsqueeze = std::make_shared<v0::Unsqueeze>(broadcast, v0::Constant::create(element::i32, Shape{1}, {0}));+ model = std::make_shared<Model>(ResultVector{std::make_shared<v0::Result>(unsqueeze)},+ nodes_to_params({positions}));+ manager.register_pass<pass::RoPEUnsqueezeAxisReplacer>();+ }+ {+ auto positions = make_param(PartialShape{DYN}, element::f32, "positions");+ auto broadcast = build_rope_broadcast(positions, test_case.use_sin, test_case.with_broadcast);+ auto unsqueeze = std::make_shared<v0::Unsqueeze>(broadcast, v0::Constant::create(element::i32, Shape{1}, {1}));+ model_ref = std::make_shared<Model>(ResultVector{std::make_shared<v0::Result>(unsqueeze)},+ nodes_to_params({positions}));+ }++ comparator.enable(FunctionsComparator::ATTRIBUTES);+}++INSTANTIATE_TEST_SUITE_P(SDPAToPA,+ SDPAToPARoPEUnsqueezeAxisReplacerTest,+ ::testing::Values(RoPEUnsqueezeAxisCase{false, true},+ RoPEUnsqueezeAxisCase{false, false},+ RoPEUnsqueezeAxisCase{true, true},+ RoPEUnsqueezeAxisCase{true, false}),+ [](const ::testing::TestParamInfo<RoPEUnsqueezeAxisCase>& info) {+ return test_name(info.param);+ });++class SDPAToPARoPEUnsqueezeAxisReplacerNegativeTest : public TransformationTestsF,+ public ::testing::WithParamInterface<int64_t> {};++TEST_P(SDPAToPARoPEUnsqueezeAxisReplacerNegativeTest, SDPAToPA_RoPEUnsqueezeAxisReplacer_NonZeroAxisUnchanged) {+ // A trailing Unsqueeze with an axis other than 0 is not the tokens-to-batch reorientation this pass+ // targets (this includes axis=1, the value this pass itself rewrites axis=0 to), so the model must+ // remain unchanged.+ auto positions = make_param(PartialShape{DYN}, element::f32, "positions");+ auto broadcast = build_rope_broadcast(positions, false, true);+ auto unsqueeze =+ std::make_shared<v0::Unsqueeze>(broadcast, v0::Constant::create(element::i32, Shape{1}, {GetParam()}));+ model =+ std::make_shared<Model>(ResultVector{std::make_shared<v0::Result>(unsqueeze)}, nodes_to_params({positions}));+ manager.register_pass<pass::RoPEUnsqueezeAxisReplacer>();++ comparator.enable(FunctionsComparator::ATTRIBUTES);+}++INSTANTIATE_TEST_SUITE_P(SDPAToPA,+ SDPAToPARoPEUnsqueezeAxisReplacerNegativeTest,+ ::testing::Values(1, 2),+ [](const ::testing::TestParamInfo<int64_t>& info) {+ return "Axis" + std::to_string(info.param);+ });++namespace {+// Minimal embedding-sum graph PositionIDsReplacer targets: Add(input_embed, Gather(pos_weight,+// Convert(Add(<positions>, offset)), axis)), where <positions> is the node under test.+std::shared_ptr<Node> build_position_embedding_sum(const Output<Node>& positions) {+ auto embed_weight = v0::Constant::create(element::f32, Shape{10, 4}, std::vector<float>(40, 1.0f));+ auto input_ids = v0::Constant::create(element::i64, Shape{2}, {0, 1});+ auto axis = v0::Constant::create(element::i64, Shape{}, {0});+ auto input_embed = std::make_shared<v8::Gather>(embed_weight, input_ids, axis);++ auto pos_weight = v0::Constant::create(element::f32, Shape{10, 4}, std::vector<float>(40, 1.0f));+ auto offset = v0::Constant::create(element::i64, Shape{}, {2});+ auto add_offset = std::make_shared<v1::Add>(positions, offset);+ auto convert = std::make_shared<v0::Convert>(add_offset, element::i32);+ auto position_embed = std::make_shared<v8::Gather>(pos_weight, convert, axis);++ return std::make_shared<v1::Add>(input_embed, position_embed);+}+} // namespace++TEST_F(SDPAToPATest, SDPAToPA_PositionIDsReplacer_SkipsAlreadyWiredPositionIds) {+ // position_ids already reaches the embedding sum via the Unsqueeze(-1) SDPAToPagedAttention::run_on_model+ // splices onto its consumers; PositionIDsReplacer receives that same node, so the match resolves to a+ // self-replacement and the model must remain unchanged.+ auto position_ids = make_param(PartialShape{DYN}, element::i64, "position_ids");+ auto unsqueezed = std::make_shared<v0::Unsqueeze>(position_ids, v0::Constant::create(element::i32, Shape{}, {-1}));+ auto sum = build_position_embedding_sum(unsqueezed);+ model = std::make_shared<Model>(ResultVector{std::make_shared<v0::Result>(sum)}, nodes_to_params({position_ids}));+ manager.register_pass<pass::PositionIDsReplacer>(unsqueezed);++ comparator.enable(FunctionsComparator::ATTRIBUTES);+}++TEST_F(SDPAToPATest, SDPAToPA_PositionIDsReplacer_RedirectsDetachedPositions) {+ // The embedding sum is fed by positions computed internally (unrelated to the position_ids parameter), so+ // it must be redirected to the shared rank-restored position_ids node run_on_model wires onto the parameter.+ {+ auto position_ids = make_param(PartialShape{DYN}, element::i64, "position_ids");+ auto unsqueezed =+ std::make_shared<v0::Unsqueeze>(position_ids, v0::Constant::create(element::i32, Shape{}, {-1}));+ auto detached_positions = std::make_shared<v4::Range>(v0::Constant::create(element::i64, Shape{}, {0}),+ v0::Constant::create(element::i64, Shape{}, {2}),+ v0::Constant::create(element::i64, Shape{}, {1}),+ element::i64);+ auto sum = build_position_embedding_sum(detached_positions);+ model =+ std::make_shared<Model>(ResultVector{std::make_shared<v0::Result>(sum)}, nodes_to_params({position_ids}));+ manager.register_pass<pass::PositionIDsReplacer>(unsqueezed);+ }+ {+ auto position_ids = make_param(PartialShape{DYN}, element::i64, "position_ids");+ auto unsqueezed =+ std::make_shared<v0::Unsqueeze>(position_ids, v0::Constant::create(element::i32, Shape{}, {-1}));+ auto sum = build_position_embedding_sum(unsqueezed);+ model_ref =+ std::make_shared<Model>(ResultVector{std::make_shared<v0::Result>(sum)}, nodes_to_params({position_ids}));+ }++ comparator.enable(FunctionsComparator::ATTRIBUTES);+ disable_rt_info_check();+}++TEST_F(SDPAToPATest, SDPAToPA_RoPEUnsqueezeAxisReplacer_WithEliminateDropBatch) {+ // Full flow: EliminateDropBatch collapses the now-invalid batch-drop select to a Reshape, and+ // RoPEUnsqueezeAxisReplacer independently rewrites the RoPE outer-product tail's trailing Unsqueeze axis from 0+ // to 1. Neither pass depends on the other having run.+ {+ auto position_ids = make_param(PartialShape{DYN, DYN}, element::i64, "position_ids");+ auto convert = std::make_shared<v0::Convert>(position_ids, element::f32);+ auto select = std::make_shared<v8::Gather>(convert,+ v0::Constant::create(element::i64, Shape{}, {0}),+ v0::Constant::create(element::i64, Shape{}, {0}));+ auto broadcast = build_rope_broadcast(select, false, true);+ auto unsqueeze = std::make_shared<v0::Unsqueeze>(broadcast, v0::Constant::create(element::i32, Shape{1}, {0}));+ model = std::make_shared<Model>(ResultVector{std::make_shared<v0::Result>(unsqueeze)},+ nodes_to_params({position_ids}));+ manager.register_pass<pass::EliminateDropBatch>();+ manager.register_pass<pass::RoPEUnsqueezeAxisReplacer>();+ }+ {+ auto position_ids = make_param(PartialShape{DYN, DYN}, element::i64, "position_ids");+ auto convert = std::make_shared<v0::Convert>(position_ids, element::f32);+ auto reshape =+ std::make_shared<v1::Reshape>(convert, v0::Constant::create(element::i64, Shape{1}, {-1}), false);+ auto broadcast = build_rope_broadcast(reshape, false, true);+ auto unsqueeze = std::make_shared<v0::Unsqueeze>(broadcast, v0::Constant::create(element::i32, Shape{1}, {1}));+ model_ref = std::make_shared<Model>(ResultVector{std::make_shared<v0::Result>(unsqueeze)},+ nodes_to_params({position_ids}));+ }++ comparator.enable(FunctionsComparator::ATTRIBUTES);+}+// TODO: split the models in blocks the way it's done for Qwen and make the code not to be such a clutter// TODO: write a test for StateManagementPattern only (because changes for Alibi are inside it)// TODO: align precisions, check the copying of "fuse_names" attr in SDPAToPagedAttentiondiff --git a/src/core/src/pass/sdpa_to_paged_attention.cpp b/src/core/src/pass/sdpa_to_paged_attention.cppindex f5d9c1b587d..4e57b8c96c7 100644--- a/src/core/src/pass/sdpa_to_paged_attention.cpp+++ b/src/core/src/pass/sdpa_to_paged_attention.cpp@@ -115,36 +115,38 @@ bool ov::pass::SDPAToPagedAttention::run_on_model(const std::shared_ptr<ov::Modestd::unordered_set<std::string> var_ids_to_remove;- std::shared_ptr<v0::Parameter> position_ids = m_params.get("position_ids");+ // Get-or-create the flattened position_ids parameter and restore its rank at each existing consumer with a+ // single shared Unsqueeze(-1). The PositionIDsReplacer* passes below consume the raw parameter and add their+ // own rank-restoring nodes; EliminateDropBatch handles the batch-drop select branch separately.+ auto position_ids = m_params.get("position_ids");if (!position_ids) {position_ids = m_params.add("position_ids", element::i64, PartialShape{-1});} else {const auto& position_ids_shape = position_ids->get_partial_shape();-if (position_ids_shape.rank().is_static() && position_ids_shape.rank().get_length() == 2) {position_ids->set_partial_shape(PartialShape{-1});} else if (position_ids_shape.rank().is_static() && position_ids_shape.rank().get_length() == 3) {- // Qwen2.5 VL M-RoPE: set position_ids to [3, total_token_num] -> Unsqueeze(axis=-1) -> [3, total_token_num,- // 1]+ // Qwen2.5 VL M-RoPE: [3, total_token_num] -> Unsqueeze(axis=-1) -> [3, total_token_num, 1]position_ids->set_partial_shape(PartialShape{position_ids_shape[0], -1});} else {OPENVINO_THROW("Unexpected shape for position_ids input: expected rank 2 or 3, observed ",position_ids_shape.rank().is_static() ? position_ids_shape.rank().get_length() : -1);}-- position_ids->validate_and_infer_types();}- auto position_ids_target_inputs = position_ids->get_output_target_inputs(0);-- std::shared_ptr<ov::Node> unsqueezed_position_ids =+ const auto position_ids_target_inputs = position_ids->output(0).get_target_inputs();+ auto unsqueezed_position_ids =std::make_shared<v0::Unsqueeze>(position_ids, v0::Constant::create(element::i32, Shape{}, {-1}));-for (const auto& target : position_ids_target_inputs) {target.replace_source_output(unsqueezed_position_ids);}+ // Refresh shapes after the input_ids/position_ids changes above; per-pass validation is disabled below.+ model->validate_nodes_and_infer_types();+ov::pass::Manager manager("SDPA to PA");manager.set_per_pass_validation(false);+ manager.register_pass<EliminateDropBatch>();+ manager.register_pass<RoPEUnsqueezeAxisReplacer>();manager.register_pass<ov::pass::GatedDeltaNetFusion>(); // This pass is required to ensure that all GatedDeltaNet// nodes are in the expected form before running// PagedGatedDeltaNetFusion.