Skip to content

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

[Transformations][PagedAttention] Replace attention_mask used for broadcasting only (#36691)

Mikhail Ryzhov6c0b69473794
diff --git a/src/common/transformations/include/transformations/paged_attention/attention_mask_shape_replacer.hpp b/src/common/transformations/include/transformations/paged_attention/attention_mask_shape_replacer.hpp
new file mode 100644
index 00000000000..782837639fa
--- /dev/null
+++ b/src/common/transformations/include/transformations/paged_attention/attention_mask_shape_replacer.hpp
@@ -0,0 +1,101 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/core/node.hpp"
+#include "openvino/pass/matcher_pass.hpp"
+#include "transformations_visibility.hpp"
+
+namespace ov {
+namespace pass {
+
+class TRANSFORMATIONS_API AttentionMaskShapeReplacer;
+
+} // namespace pass
+} // namespace ov
+
+/**
+ * @ingroup ov_transformation_common_api
+ * @brief Replaces ShapeOf(attention_mask) with ShapeOf(input_source) in the
+ * broadcast-shape branch that feeds rotary MatMul.
+ *
+ * Some models build a Broadcast target shape from attention_mask and then use that
+ * Broadcast as the first input of MatMul, while the second input is derived from
+ * position_ids through an optional Unsqueeze/Convert chain.
+ * In PagedAttention mode, attention_mask is removed, therefore this shape branch
+ * must be rewired to an always-present source (input_ids or inputs_embeds).
+ *
+ * Matched topology:
+ *
+ * ┌─────────────────┐
+ * │ attention_mask │
+ * │ (Parameter) │
+ * └────────┬────────┘
+ * │
+ * ┌────┴────┐ ┌──────────────┐
+ * │ ShapeOf │ │ position_ids │
+ * └────┬────┘ │ (Parameter) │
+ * │ └──────┬───────┘
+ * ┌────┴────┐ ┌─────┴──────┐
+ * │ Gather │ │ Unsqueeze │ (optional)
+ * └────┬────┘ └─────┬──────┘
+ * │ ┌────┴────┐
+ * ┌────┴────┐ │ Convert │ (optional)
+ * │ Concat │ └────┬────┘
+ * └────┬────┘ │
+ * │ │
+ * ┌────┴────┐ │
+ * │Broadcast├───────────────┘
+ * └────┬────┘
+ * │
+ * ┌────┴────┐
+ * │ MatMul │
+ * └─────────┘
+ *
+ * Rewrite:
+ *
+ * Replace ShapeOf(attention_mask) with ShapeOf(input_source), where input_source
+ * is input_ids or inputs_embeds.
+ *
+ * After:
+ *
+ * ┌─────────────────┐
+ * │ input_source │
+ * │ (Parameter) │
+ * └────────┬────────┘
+ * │
+ * ┌────┴────┐ ┌──────────────┐
+ * │ ShapeOf │ │ position_ids │
+ * └────┬────┘ │ (Parameter) │
+ * │ └──────┬───────┘
+ * ┌────┴────┐ ┌─────┴──────┐
+ * │ Gather │ │ Unsqueeze │ (optional)
+ * └────┬────┘ └─────┬──────┘
+ * │ ┌────┴────┐
+ * ┌────┴────┐ │ Convert │ (optional)
+ * │ Concat │ └────┬────┘
+ * └────┬────┘ │
+ * │ │
+ * ┌────┴────┐ │
+ * │Broadcast├───────────────┘
+ * └────┬────┘
+ * │
+ * ┌────┴────┐
+ * │ MatMul │
+ * └─────────┘
+ *
+ * The rewrite is applied only when all of the following hold:
+ * 1) Gather axis is 0 (or -1 for a 1D ShapeOf output).
+ * 2) Gather indices are exactly {0}.
+ * 3) input_source rank is static and at least 1.
+ *
+ * These checks guarantee that the selected dimension is equivalent after rewiring
+ * and avoid altering unsupported shape semantics.
+ */
+class ov::pass::AttentionMaskShapeReplacer : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("AttentionMaskShapeReplacer");
+ explicit AttentionMaskShapeReplacer(const Output<Node>& input_source);
+};
diff --git a/src/common/transformations/src/transformations/paged_attention/attention_mask_shape_replacer.cpp b/src/common/transformations/src/transformations/paged_attention/attention_mask_shape_replacer.cpp
new file mode 100644
index 00000000000..04c7f268293
--- /dev/null
+++ b/src/common/transformations/src/transformations/paged_attention/attention_mask_shape_replacer.cpp
@@ -0,0 +1,97 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "transformations/paged_attention/attention_mask_shape_replacer.hpp"
+
+#include "itt.hpp"
+#include "openvino/core/rt_info.hpp"
+#include "openvino/core/validation_util.hpp"
+#include "openvino/op/broadcast.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/shape_of.hpp"
+#include "openvino/op/unsqueeze.hpp"
+#include "openvino/op/util/gather_base.hpp"
+#include "openvino/op/util/shape_of_base.hpp"
+#include "openvino/pass/pattern/op/optional.hpp"
+#include "openvino/pass/pattern/op/pattern.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+
+using ov::pass::pattern::any_input;
+using ov::pass::pattern::has_static_rank;
+using ov::pass::pattern::wrap_type;
+
+namespace v0 = ov::op::v0;
+namespace v3 = ov::op::v3;
+
+ov::pass::AttentionMaskShapeReplacer::AttentionMaskShapeReplacer(const Output<Node>& input_source) {
+ MATCHER_SCOPE(AttentionMaskShapeReplacer);
+
+ auto attn_mask = wrap_type<v0::Parameter>(has_static_rank() && [](const Output<Node>& output) {
+ return output.get_names().count("attention_mask") > 0;
+ });
+ auto shape_of = wrap_type<ov::op::util::ShapeOfBase>({attn_mask});
+ auto gather = wrap_type<ov::op::util::GatherBase>({shape_of, any_input(), any_input()});
+ auto concat = wrap_type<v0::Concat>({gather, any_input(), any_input()});
+ auto broadcast = wrap_type<v3::Broadcast>({any_input(), concat});
+ auto position_ids = wrap_type<v0::Parameter>(has_static_rank() && [](const Output<Node>& output) {
+ return output.get_names().count("position_ids") > 0;
+ });
+ auto position_ids_unsqueeze_0 = ov::pass::pattern::optional<v0::Unsqueeze>({position_ids, any_input()});
+ auto position_ids_unsqueeze_1 = ov::pass::pattern::optional<v0::Unsqueeze>({position_ids_unsqueeze_0, any_input()});
+ auto position_ids_convert = ov::pass::pattern::optional<v0::Convert>({position_ids_unsqueeze_1});
+ auto matmul = wrap_type<v0::MatMul>({broadcast, position_ids_convert});
+
+ ov::matcher_pass_callback callback = [=](ov::pass::pattern::Matcher& m) {
+ const auto& pattern_map = m.get_pattern_value_map();
+
+ // The batch dimension is read from ShapeOf(input_source) at index 0, so the source must
+ // expose it: a static rank of at least 1 is required for the rewrite to stay valid.
+ const auto source_rank = input_source.get_partial_shape().rank();
+ if (source_rank.is_dynamic() || source_rank.get_length() < 1) {
+ return false;
+ }
+
+ auto gather_node = pattern_map.at(gather).get_node_shared_ptr();
+ const auto indices_const = ov::util::get_constant_from_source(gather_node->input_value(1));
+ if (!indices_const) {
+ return false;
+ }
+
+ // The shape produced by ShapeOf is a 1D vector, so the Gather axis must select it (0, or the
+ // equivalent -1). Rewiring a Gather with an unexpected or dynamic axis could change behavior.
+ const auto axis_const = ov::util::get_constant_from_source(gather_node->input_value(2));
+ if (!axis_const) {
+ return false;
+ }
+ for (int64_t axis : axis_const->cast_vector<int64_t>()) {
+ if (axis != 0 && axis != -1) {
+ return false;
+ }
+ }
+
+ // Only the batch dimension (index 0) is guaranteed to coincide between attention_mask
+ // and the input source regardless of their ranks, so the rewrite is limited to it.
+ // This also keeps the same Gather index valid and avoids negative-index ambiguity.
+ for (int64_t index : indices_const->cast_vector<int64_t>()) {
+ if (index != 0) {
+ return false;
+ }
+ }
+
+ const auto old_shape_of = pattern_map.at(shape_of).get_node_shared_ptr();
+ auto new_shape_of = std::make_shared<v3::ShapeOf>(input_source, old_shape_of->get_output_element_type(0));
+ new_shape_of->set_friendly_name(old_shape_of->get_friendly_name());
+ ov::copy_runtime_info(old_shape_of, new_shape_of);
+
+ gather_node->input(0).replace_source_output(new_shape_of);
+ return true;
+ };
+
+ auto m = std::make_shared<ov::pass::pattern::Matcher>(matmul, matcher_name);
+ register_matcher(m, callback);
+}
diff --git a/src/common/transformations/tests/common_optimizations/attention_mask_shape_replacer.cpp b/src/common/transformations/tests/common_optimizations/attention_mask_shape_replacer.cpp
new file mode 100644
index 00000000000..0f7a3e68ffe
--- /dev/null
+++ b/src/common/transformations/tests/common_optimizations/attention_mask_shape_replacer.cpp
@@ -0,0 +1,146 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "transformations/paged_attention/attention_mask_shape_replacer.hpp"
+
+#include <gtest/gtest.h>
+
+#include <vector>
+
+#include "common_test_utils/ov_test_utils.hpp"
+#include "openvino/core/model.hpp"
+#include "openvino/op/broadcast.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/shape_of.hpp"
+#include "openvino/pass/manager.hpp"
+
+namespace {
+
+using namespace ov;
+namespace v0 = ov::op::v0;
+namespace v3 = ov::op::v3;
+namespace v8 = ov::op::v8;
+
+std::shared_ptr<v0::Parameter> make_attention_mask() {
+ auto attention_mask = std::make_shared<v0::Parameter>(element::i64, PartialShape{-1, -1});
+ attention_mask->set_friendly_name("attention_mask");
+ attention_mask->output(0).set_names({"attention_mask"});
+ return attention_mask;
+}
+
+// attention_mask -> ShapeOf -> Gather(indices, axis=0) -> Concat -> Broadcast -> MatMul(position_ids) -> Result
+std::shared_ptr<ov::Model> build_model(const Output<Node>& shape_source,
+ const std::shared_ptr<v0::Parameter>& attention_mask,
+ const std::shared_ptr<v0::Parameter>& input_source,
+ const std::shared_ptr<v0::Parameter>& position_ids,
+ const std::vector<int64_t>& gather_indices) {
+ auto shape_of = std::make_shared<v3::ShapeOf>(shape_source, element::i64);
+ auto indices = v0::Constant::create(element::i64, Shape{gather_indices.size()}, gather_indices);
+ auto axis = v0::Constant::create(element::i64, Shape{}, {0});
+ auto gather = std::make_shared<v8::Gather>(shape_of, indices, axis);
+
+ auto one = v0::Constant::create(element::i64, Shape{1}, {1});
+ auto four = v0::Constant::create(element::i64, Shape{1}, {4});
+ auto target_shape = std::make_shared<v0::Concat>(OutputVector{gather, one, four}, 0);
+
+ auto broadcast_data = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, 1, 4});
+ broadcast_data->set_friendly_name("broadcast_data");
+ auto broadcast = std::make_shared<v3::Broadcast>(broadcast_data, target_shape);
+
+ auto matmul = std::make_shared<v0::MatMul>(broadcast, position_ids, false, false);
+ auto result = std::make_shared<v0::Result>(matmul);
+ return std::make_shared<ov::Model>(ResultVector{result},
+ ParameterVector{attention_mask, input_source, position_ids, broadcast_data});
+}
+
+} // namespace
+
+class AttentionMaskShapeReplacerTest : public ::TransformationTestsF {};
+
+TEST_F(AttentionMaskShapeReplacerTest, ReplacesWithInputIdsBatchDim) {
+ auto attention_mask = make_attention_mask();
+ auto input_ids = std::make_shared<v0::Parameter>(element::i32, PartialShape{-1, -1});
+ input_ids->set_friendly_name("input_ids");
+ auto position_ids = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, 4, 1});
+ position_ids->set_friendly_name("position_ids");
+ position_ids->output(0).set_names({"position_ids"});
+ model = build_model(attention_mask, attention_mask, input_ids, position_ids, {0});
+
+ manager.register_pass<ov::pass::AttentionMaskShapeReplacer>(input_ids);
+
+ auto attention_mask_ref = make_attention_mask();
+ auto input_ids_ref = std::make_shared<v0::Parameter>(element::i32, PartialShape{-1, -1});
+ input_ids_ref->set_friendly_name("input_ids");
+ auto position_ids_ref = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, 4, 1});
+ position_ids_ref->set_friendly_name("position_ids");
+ position_ids_ref->output(0).set_names({"position_ids"});
+ model_ref = build_model(input_ids_ref, attention_mask_ref, input_ids_ref, position_ids_ref, {0});
+}
+
+TEST_F(AttentionMaskShapeReplacerTest, ReplacesWithInputsEmbedsBatchDim) {
+ auto attention_mask = make_attention_mask();
+ auto inputs_embeds = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, -1, 2048});
+ inputs_embeds->set_friendly_name("inputs_embeds");
+ auto position_ids = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, 4, 1});
+ position_ids->set_friendly_name("position_ids");
+ position_ids->output(0).set_names({"position_ids"});
+ model = build_model(attention_mask, attention_mask, inputs_embeds, position_ids, {0});
+
+ manager.register_pass<ov::pass::AttentionMaskShapeReplacer>(inputs_embeds);
+
+ auto attention_mask_ref = make_attention_mask();
+ auto inputs_embeds_ref = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, -1, 2048});
+ inputs_embeds_ref->set_friendly_name("inputs_embeds");
+ auto position_ids_ref = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, 4, 1});
+ position_ids_ref->set_friendly_name("position_ids");
+ position_ids_ref->output(0).set_names({"position_ids"});
+ model_ref = build_model(inputs_embeds_ref, attention_mask_ref, inputs_embeds_ref, position_ids_ref, {0});
+}
+
+TEST_F(AttentionMaskShapeReplacerTest, DoesNotReplaceNonBatchDim) {
+ auto attention_mask = make_attention_mask();
+ auto input_ids = std::make_shared<v0::Parameter>(element::i32, PartialShape{-1, -1});
+ input_ids->set_friendly_name("input_ids");
+ auto position_ids = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, 4, 1});
+ position_ids->set_friendly_name("position_ids");
+ position_ids->output(0).set_names({"position_ids"});
+ // Only the batch dimension (index 0) is rewired; the sequence dimension is left untouched.
+ model = build_model(attention_mask, attention_mask, input_ids, position_ids, {1});
+
+ manager.register_pass<ov::pass::AttentionMaskShapeReplacer>(input_ids);
+
+ auto attention_mask_ref = make_attention_mask();
+ auto input_ids_ref = std::make_shared<v0::Parameter>(element::i32, PartialShape{-1, -1});
+ input_ids_ref->set_friendly_name("input_ids");
+ auto position_ids_ref = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, 4, 1});
+ position_ids_ref->set_friendly_name("position_ids");
+ position_ids_ref->output(0).set_names({"position_ids"});
+ model_ref = build_model(attention_mask_ref, attention_mask_ref, input_ids_ref, position_ids_ref, {1});
+}
+
+TEST_F(AttentionMaskShapeReplacerTest, DoesNotReplaceNegativeIndex) {
+ auto attention_mask = make_attention_mask();
+ // A negative index would select a different dimension against the higher-rank source, so it is skipped.
+ auto inputs_embeds = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, -1, 2048});
+ inputs_embeds->set_friendly_name("inputs_embeds");
+ auto position_ids = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, 4, 1});
+ position_ids->set_friendly_name("position_ids");
+ position_ids->output(0).set_names({"position_ids"});
+ model = build_model(attention_mask, attention_mask, inputs_embeds, position_ids, {-2});
+
+ manager.register_pass<ov::pass::AttentionMaskShapeReplacer>(inputs_embeds);
+
+ auto attention_mask_ref = make_attention_mask();
+ auto inputs_embeds_ref = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, -1, 2048});
+ inputs_embeds_ref->set_friendly_name("inputs_embeds");
+ auto position_ids_ref = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, 4, 1});
+ position_ids_ref->set_friendly_name("position_ids");
+ position_ids_ref->output(0).set_names({"position_ids"});
+ model_ref = build_model(attention_mask_ref, attention_mask_ref, inputs_embeds_ref, position_ids_ref, {-2});
+}
diff --git a/src/core/src/pass/sdpa_to_paged_attention.cpp b/src/core/src/pass/sdpa_to_paged_attention.cpp
index c1480e92063..f5d9c1b587d 100644
--- a/src/core/src/pass/sdpa_to_paged_attention.cpp
+++ b/src/core/src/pass/sdpa_to_paged_attention.cpp
@@ -17,6 +17,7 @@
#include "transformations/common_optimizations/fuse_gated_delta_net.hpp"
#include "transformations/common_optimizations/sdpa_fusion.hpp"
#include "transformations/op_conversions/convert_slice_to_strided_slice.hpp"
+#include "transformations/paged_attention/attention_mask_shape_replacer.hpp"
#include "transformations/paged_attention/eliminate_conv_padding_mask_gating.hpp"
#include "transformations/paged_attention/paged_causal_conv1d_fusion.hpp"
#include "transformations/paged_attention/paged_gated_delta_net_fusion.hpp"
@@ -149,6 +150,7 @@ bool ov::pass::SDPAToPagedAttention::run_on_model(const std::shared_ptr<ov::Mode
// PagedGatedDeltaNetFusion.
manager.register_pass<StateManagementPattern>(m_params, m_results, m_options, var_ids_to_remove);
manager.register_pass<EliminateConvPaddingMaskGating>();
+ manager.register_pass<AttentionMaskShapeReplacer>(input_ids_node);
manager.register_pass<PagedCausalConv1DFusion>(m_params, var_ids_to_remove);
manager.register_pass<PagedGatedDeltaNetFusion>(m_params, var_ids_to_remove);
manager.register_pass<PrevSequenceLengthPattern>(processed_input_ids, max_context_len, position_ids);