Skip to content

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

[Transformations] Add BroadcastMatMulFusion common optimization (#36756)

Mikhail Ryzhov8c3b94331fea
diff --git a/src/common/transformations/include/sources.cmake b/src/common/transformations/include/sources.cmake
index 119b8e62bb3..3f277c9a037 100644
--- a/src/common/transformations/include/sources.cmake
+++ b/src/common/transformations/include/sources.cmake
@@ -51,6 +51,7 @@ set(COMMON_OPTIMIZATIONS_HEADERS
${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/batch_to_space_fusion.hpp
${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/binarize_weights.hpp
${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/broadcast_elementwise_fusion.hpp
+ ${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/broadcast_matmul_fusion.hpp
${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/broadcast_transition.hpp
${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/change_placeholder_types.hpp
${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/clamp_fusion.hpp
diff --git a/src/common/transformations/include/transformations/common_optimizations/broadcast_matmul_fusion.hpp b/src/common/transformations/include/transformations/common_optimizations/broadcast_matmul_fusion.hpp
new file mode 100644
index 00000000000..2aef0244f98
--- /dev/null
+++ b/src/common/transformations/include/transformations/common_optimizations/broadcast_matmul_fusion.hpp
@@ -0,0 +1,70 @@
+// 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 {
+namespace pass {
+
+class TRANSFORMATIONS_API BroadcastMatMulFusion;
+
+} // namespace pass
+} // namespace ov
+
+/**
+ * @ingroup ov_transformation_common_api
+ * @brief Removes a redundant Broadcast that expands one MatMul input's batch dimensions.
+ *
+ * Matches the Data -> Broadcast -> MatMul pattern, with the Broadcast on either MatMul
+ * input and Data being an arbitrary input (not necessarily a Constant). MatMul broadcasts
+ * the batch (leading) dimensions of its operands implicitly, so an explicit Broadcast that
+ * only expands those dimensions is redundant. The Broadcast is detached and Data is
+ * connected to the MatMul directly; the now-dangling Broadcast and its target-shape
+ * subgraph are left unreferenced and removed by later clean-up.
+ *
+ * A common source is the rotary-embedding branch, where a constant (e.g. inv_freq) is
+ * expanded to the batch dimension taken from another input's shape. Detaching the
+ * Broadcast also lets that shape-providing input become removable when it has no other
+ * consumers (for example attention_mask during PagedAttention conversion).
+ *
+ * Before:
+ *
+ * Data Other
+ * │ │
+ * ┌───┴─────┐ │
+ * │Broadcast│ │
+ * └───┬─────┘ │
+ * │ │
+ * └──────┬──────┘
+ * ┌──┴───┐
+ * │MatMul│
+ * └──────┘
+ *
+ * After:
+ *
+ * Data Other
+ * │ │
+ * └──────┬──────┘
+ * ┌──┴───┐
+ * │MatMul│
+ * └──────┘
+ *
+ * The Broadcast is removed only when it does not change the MatMul result:
+ * - the matrix (last two) dimensions are left intact by the Broadcast;
+ * - for every expanded batch dimension, the other MatMul operand carries the same
+ * dimension, proven equal by static value or by shape symbol; an unlabeled dynamic
+ * dimension is never assumed compatible, since that could hide a runtime batch mismatch
+ * the Broadcast would have rejected.
+ *
+ * The Broadcast node itself is not removed and may keep other consumers; only the matched
+ * MatMul input is rewired to Data directly.
+ */
+class ov::pass::BroadcastMatMulFusion : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("BroadcastMatMulFusion");
+ BroadcastMatMulFusion();
+};
diff --git a/src/common/transformations/src/sources.cmake b/src/common/transformations/src/sources.cmake
index 7c520239265..fb7b9a9ea6f 100644
--- a/src/common/transformations/src/sources.cmake
+++ b/src/common/transformations/src/sources.cmake
@@ -14,6 +14,7 @@ set(COMMON_OPTIMIZATIONS_SOURCES
${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/batch_to_space_fusion.cpp
${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/binarize_weights.cpp
${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/broadcast_elementwise_fusion.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/broadcast_matmul_fusion.cpp
${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/broadcast_transition.cpp
${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/change_placeholder_types.cpp
${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/clamp_fusion.cpp
diff --git a/src/common/transformations/src/transformations/common_optimizations/broadcast_matmul_fusion.cpp b/src/common/transformations/src/transformations/common_optimizations/broadcast_matmul_fusion.cpp
new file mode 100644
index 00000000000..07fae63f5f6
--- /dev/null
+++ b/src/common/transformations/src/transformations/common_optimizations/broadcast_matmul_fusion.cpp
@@ -0,0 +1,105 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "transformations/common_optimizations/broadcast_matmul_fusion.hpp"
+
+#include "itt.hpp"
+#include "openvino/core/rt_info.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/util/broadcast_base.hpp"
+#include "openvino/pass/pattern/op/or.hpp"
+#include "openvino/pass/pattern/op/pattern.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "transformations/symbolic_transformations/utils.hpp"
+
+namespace v0 = ov::op::v0;
+
+namespace ov::pass {
+
+namespace {
+
+// Verifies batch dims compatibility: every batch dimension the Broadcast expands must be
+// carried by the other MatMul operand, so MatMul reproduces it via implicit (NumPy-style)
+// batch broadcasting. Equality is accepted only when provable, never assumed for unlabeled
+// dynamic dimensions.
+bool can_remove_broadcast(const ov::PartialShape& data_shape,
+ const ov::PartialShape& broadcast_shape,
+ const ov::PartialShape& other_shape) {
+ const int64_t data_rank = data_shape.rank().get_length();
+ const int64_t broadcast_rank = broadcast_shape.rank().get_length();
+ const int64_t other_rank = other_shape.rank().get_length();
+
+ const int64_t broadcast_batch = broadcast_rank - 2;
+ for (int64_t offset = 0; offset < broadcast_batch; ++offset) {
+ const ov::Dimension& broadcast_dim = broadcast_shape[broadcast_batch - 1 - offset];
+
+ const int64_t data_idx = (data_rank - 2) - 1 - offset;
+ if (data_idx >= 0 && ov::symbol::util::dims_are_equal(data_shape[data_idx], broadcast_dim)) {
+ continue;
+ }
+
+ const int64_t other_idx = (other_rank - 2) - 1 - offset;
+ if (other_idx < 0 || !ov::symbol::util::dims_are_equal(other_shape[other_idx], broadcast_dim)) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+} // namespace
+
+BroadcastMatMulFusion::BroadcastMatMulFusion() {
+ MATCHER_SCOPE(BroadcastMatMulFusion);
+
+ // Only NumPy-style broadcasting (including its symmetric BIDIRECTIONAL variant) matches
+ // MatMul's implicit batch broadcasting.
+ auto is_numpy_or_bidirectional_mode =
+ pattern::attrs_match({{"mode", "numpy"}}) || pattern::attrs_match({{"mode", "bidirectional"}});
+
+ // Match any input (Constant or otherwise) -> Broadcast -> MatMul, with the Broadcast on
+ // either MatMul input. The shared "M, N" names require the Broadcast to leave the matrix
+ // dimensions of its data input intact, otherwise removing it would change the contraction.
+ // A Broadcast with other consumers is still detached from the MatMul input: only that one
+ // input edge is rewired.
+ auto data = pattern::any_input(pattern::shape_matches("DataBatches..., M, N"));
+ auto broadcast_shape_and_mode =
+ pattern::shape_matches("BroadcastBatches..., M, N") && is_numpy_or_bidirectional_mode;
+ auto broadcast_without_axes_mapping =
+ pattern::wrap_type<ov::op::util::BroadcastBase>({data, pattern::any_input()}, broadcast_shape_and_mode);
+ auto broadcast_with_axes_mapping =
+ pattern::wrap_type<ov::op::util::BroadcastBase>({data, pattern::any_input(), pattern::any_input()},
+ broadcast_shape_and_mode);
+ auto broadcast = broadcast_without_axes_mapping | broadcast_with_axes_mapping;
+ auto other = pattern::any_input(pattern::has_static_rank() && pattern::rank_more_than(1));
+ auto matmul_lhs = pattern::wrap_type<v0::MatMul>({broadcast, other});
+ auto matmul_rhs = pattern::wrap_type<v0::MatMul>({other, broadcast});
+ auto matmul = matmul_lhs | matmul_rhs;
+
+ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](pattern::Matcher& m) {
+ const auto& pattern_map = m.get_pattern_value_map();
+
+ const auto broadcast_value = pattern_map.at(broadcast);
+ const auto matmul_node = m.get_match_root();
+
+ const size_t broadcast_port = matmul_node->input_value(0) == broadcast_value ? 0 : 1;
+ const auto data_value = pattern_map.at(data);
+ const auto other_value = pattern_map.at(other);
+
+ if (!can_remove_broadcast(data_value.get_partial_shape(),
+ broadcast_value.get_partial_shape(),
+ other_value.get_partial_shape())) {
+ return false;
+ }
+
+ copy_runtime_info(broadcast_value.get_node_shared_ptr(), matmul_node);
+ matmul_node->input(broadcast_port).replace_source_output(data_value);
+ return true;
+ };
+
+ auto m = std::make_shared<pattern::Matcher>(matmul, matcher_name);
+ register_matcher(m, callback);
+}
+
+} // namespace ov::pass
diff --git a/src/common/transformations/src/transformations/common_optimizations/fuse_moe_experts.cpp b/src/common/transformations/src/transformations/common_optimizations/fuse_moe_experts.cpp
index 1c51efc9575..fe4e794a5d8 100644
--- a/src/common/transformations/src/transformations/common_optimizations/fuse_moe_experts.cpp
+++ b/src/common/transformations/src/transformations/common_optimizations/fuse_moe_experts.cpp
@@ -397,6 +397,9 @@ ov::pass::FuseMOEExperts::FuseMOEExperts() : MultiMatcher("FuseMOEExperts") {
}
auto fused = std::make_shared<v0::Concat>(inputs, 0);
+ // Tag the fused expert weight so it can be identified directly, e.g. by tests,
+ // instead of being guessed from its rank and shape.
+ fused->set_friendly_name(fused->get_friendly_name() + "/FusedMOEWeights");
if (std::all_of(inputs.begin(), inputs.end(), [](const auto& input) {
return op_util::is_constant(input.get_node());
})) {
diff --git a/src/common/transformations/src/transformations/common_optimizations/moc_transformations.cpp b/src/common/transformations/src/transformations/common_optimizations/moc_transformations.cpp
index 771744fc7d9..d081e281fc3 100644
--- a/src/common/transformations/src/transformations/common_optimizations/moc_transformations.cpp
+++ b/src/common/transformations/src/transformations/common_optimizations/moc_transformations.cpp
@@ -16,6 +16,7 @@
#include "transformations/common_optimizations/batch_to_space_fusion.hpp"
#include "transformations/common_optimizations/binarize_weights.hpp"
#include "transformations/common_optimizations/broadcast_elementwise_fusion.hpp"
+#include "transformations/common_optimizations/broadcast_matmul_fusion.hpp"
#include "transformations/common_optimizations/broadcast_transition.hpp"
#include "transformations/common_optimizations/clamp_fusion.hpp"
#include "transformations/common_optimizations/concat_to_broadcast.hpp"
@@ -195,6 +196,7 @@ bool ov::pass::MOCTransformations::run_on_model(const std::shared_ptr<ov::Model>
REGISTER_PASS(manager, ConvertNmsGatherPathToUnsigned)
REGISTER_PASS(manager, StridedSliceOptimization, m_use_shapes)
REGISTER_PASS(manager, BroadcastElementwiseFusion)
+ REGISTER_PASS(manager, BroadcastMatMulFusion)
REGISTER_PASS(manager, BroadcastTransition)
REGISTER_PASS(manager, PullThroughReduce)
diff --git a/src/common/transformations/tests/common_optimizations/broadcast_matmul_fusion_test.cpp b/src/common/transformations/tests/common_optimizations/broadcast_matmul_fusion_test.cpp
new file mode 100644
index 00000000000..850f39b0a62
--- /dev/null
+++ b/src/common/transformations/tests/common_optimizations/broadcast_matmul_fusion_test.cpp
@@ -0,0 +1,231 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "transformations/common_optimizations/broadcast_matmul_fusion.hpp"
+
+#include <gtest/gtest.h>
+
+#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/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"
+
+using namespace ov;
+
+namespace {
+
+namespace v0 = ov::op::v0;
+namespace v1 = ov::op::v1;
+namespace v3 = ov::op::v3;
+namespace v8 = ov::op::v8;
+
+std::shared_ptr<v0::Constant> make_const(const Shape& shape) {
+ return v0::Constant::create(element::f32, shape, std::vector<float>(shape_size(shape), 1.0f));
+}
+
+// Data [-> Broadcast(static target)] -> MatMul. Broadcast sits on the left or right MatMul
+// input; passing an empty `target` omits the Broadcast, producing the fused reference graph.
+// Data is a Constant unless `data_is_parameter` is set, in which case it is an extra Parameter,
+// exercising that the pass is not limited to constant data inputs.
+std::shared_ptr<ov::Model> buildModel(const Shape& data_shape,
+ const std::vector<int64_t>& target,
+ const PartialShape& other_shape,
+ bool broadcast_on_lhs,
+ bool transpose_b = false,
+ bool data_is_parameter = false) {
+ auto other = std::make_shared<v0::Parameter>(element::f32, other_shape);
+ ParameterVector params{other};
+ std::shared_ptr<Node> data_input;
+ if (data_is_parameter) {
+ auto data_param = std::make_shared<v0::Parameter>(element::f32, data_shape);
+ params.push_back(data_param);
+ data_input = data_param;
+ } else {
+ data_input = make_const(data_shape);
+ }
+ if (!target.empty()) {
+ auto target_shape = v0::Constant::create(element::i64, Shape{target.size()}, target);
+ data_input = std::make_shared<v3::Broadcast>(data_input, target_shape, op::BroadcastType::BIDIRECTIONAL);
+ }
+ std::shared_ptr<Node> matmul = broadcast_on_lhs
+ ? std::make_shared<v0::MatMul>(data_input, other, false, transpose_b)
+ : std::make_shared<v0::MatMul>(other, data_input, false, transpose_b);
+ auto result = std::make_shared<v0::Result>(matmul);
+ return std::make_shared<ov::Model>(ResultVector{result}, params);
+}
+
+struct PositiveCase {
+ std::string name;
+ Shape const_shape;
+ std::vector<int64_t> target;
+ PartialShape other_shape;
+ bool broadcast_on_lhs;
+ bool transpose_b = false;
+ bool data_is_parameter = false;
+};
+
+} // namespace
+
+class BroadcastMatMulFusionTest : public TransformationTestsF {
+protected:
+ void SetUp() override {
+ TransformationTestsF::SetUp();
+ manager.register_pass<ov::pass::BroadcastMatMulFusion>();
+ }
+};
+
+// ----------------------------- Positive: parametrized static-shape cases -----------------------------
+
+class BroadcastMatMulFusionPositive : public TransformationTestsF, public testing::WithParamInterface<PositiveCase> {
+protected:
+ void SetUp() override {
+ TransformationTestsF::SetUp();
+ comparator.enable(FunctionsComparator::ATTRIBUTES);
+ manager.register_pass<ov::pass::BroadcastMatMulFusion>();
+ }
+};
+
+TEST_P(BroadcastMatMulFusionPositive, RemovesBroadcast) {
+ const auto& p = GetParam();
+ model = buildModel(p.const_shape, p.target, p.other_shape, p.broadcast_on_lhs, p.transpose_b, p.data_is_parameter);
+ model_ref = buildModel(p.const_shape, {}, p.other_shape, p.broadcast_on_lhs, p.transpose_b, p.data_is_parameter);
+}
+
+INSTANTIATE_TEST_SUITE_P(
+ BroadcastMatMulFusion,
+ BroadcastMatMulFusionPositive,
+ testing::Values(
+ // Broadcast on the left input; other operand carries the expanded batch (4).
+ PositiveCase{"lhs_static_batch", Shape{1, 32, 8}, {4, 32, 8}, PartialShape{4, 8, 16}, true},
+ // Broadcast on the right input; contraction dim on the shared axis (32).
+ PositiveCase{"rhs_static_batch", Shape{1, 32, 8}, {4, 32, 8}, PartialShape{4, 16, 32}, false},
+ // 4D: two batch dims (2,4), both carried by the other operand.
+ PositiveCase{"lhs_4d_two_batch_dims", Shape{1, 1, 32, 8}, {2, 4, 32, 8}, PartialShape{2, 4, 8, 16}, true},
+ // transpose_b only reinterprets the (unchanged) matrix dims, so removal is still valid.
+ PositiveCase{"transposed_matmul", Shape{1, 32, 8}, {4, 32, 8}, PartialShape{4, 16, 8}, true, true},
+ // Broadcast does not change the batch dim (already 4) — still a no-op that can be detached.
+ PositiveCase{"data_already_carries_batch", Shape{4, 32, 8}, {4, 32, 8}, PartialShape{4, 8, 16}, true},
+ // Broadcast target already matches data's batch (4): a no-op broadcast.
+ PositiveCase{"no_op_bcast", Shape{4, 32, 8}, {4, 32, 8}, PartialShape{1, 8, 16}, true},
+ // Other operand carries an extra leading batch dim (2) beyond what the Broadcast expands (4).
+ PositiveCase{"other_has_extra_leading_batch_dim", Shape{1, 32, 8}, {4, 32, 8}, PartialShape{2, 4, 8, 16}, true},
+ // Data is a Parameter, not a Constant: the pass is not limited to constant data inputs.
+ PositiveCase{"non_constant_data", Shape{1, 32, 8}, {4, 32, 8}, PartialShape{4, 8, 16}, true, false, true}),
+ [](const testing::TestParamInfo<PositiveCase>& info) {
+ return info.param.name;
+ });
+
+// ----------------------------- Positive: standalone cases -----------------------------
+
+TEST_F(BroadcastMatMulFusionTest, RemovesBroadcastFromMatMulInputButKeepsBroadcastForOtherConsumer) {
+ // The Broadcast feeds both the MatMul and a second Result: only the MatMul input edge is
+ // rewired to the Constant directly, the Broadcast node itself stays for the other consumer.
+ auto other = std::make_shared<v0::Parameter>(element::f32, PartialShape{4, 8, 16});
+ auto data = make_const(Shape{1, 32, 8});
+ auto target = v0::Constant::create(element::i64, Shape{3}, {4, 32, 8});
+ auto broadcast = std::make_shared<v3::Broadcast>(data, target, op::BroadcastType::BIDIRECTIONAL);
+ auto matmul = std::make_shared<v0::MatMul>(broadcast, other);
+ model = std::make_shared<ov::Model>(
+ ResultVector{std::make_shared<v0::Result>(matmul), std::make_shared<v0::Result>(broadcast)},
+ ParameterVector{other});
+
+ auto other_ref = std::make_shared<v0::Parameter>(element::f32, PartialShape{4, 8, 16});
+ auto data_ref = make_const(Shape{1, 32, 8});
+ auto target_ref = v0::Constant::create(element::i64, Shape{3}, {4, 32, 8});
+ auto broadcast_ref = std::make_shared<v3::Broadcast>(data_ref, target_ref, op::BroadcastType::BIDIRECTIONAL);
+ auto matmul_ref = std::make_shared<v0::MatMul>(data_ref, other_ref);
+ model_ref = std::make_shared<ov::Model>(
+ ResultVector{std::make_shared<v0::Result>(matmul_ref), std::make_shared<v0::Result>(broadcast_ref)},
+ ParameterVector{other_ref});
+}
+
+TEST_F(BroadcastMatMulFusionTest, RemovesV1BroadcastWithAxesMapping) {
+ // v1::Broadcast in NUMPY mode always carries a 3rd (mocked) axes_mapping input, so the
+ // 3-input BroadcastBase form must be matched too, not just the 2-input v3::Broadcast one.
+ auto other = std::make_shared<v0::Parameter>(element::f32, PartialShape{4, 8, 16});
+ auto data = make_const(Shape{1, 32, 8});
+ auto target = v0::Constant::create(element::i64, Shape{3}, {4, 32, 8});
+ auto axes_mapping = v0::Constant::create(element::i64, Shape{3}, {0, 1, 2});
+ auto broadcast = std::make_shared<v1::Broadcast>(data, target, axes_mapping, op::AutoBroadcastType::NUMPY);
+ auto matmul = std::make_shared<v0::MatMul>(broadcast, other);
+ model = std::make_shared<ov::Model>(ResultVector{std::make_shared<v0::Result>(matmul)}, ParameterVector{other});
+
+ auto other_ref = std::make_shared<v0::Parameter>(element::f32, PartialShape{4, 8, 16});
+ auto data_ref = make_const(Shape{1, 32, 8});
+ auto matmul_ref = std::make_shared<v0::MatMul>(data_ref, other_ref);
+ model_ref =
+ std::make_shared<ov::Model>(ResultVector{std::make_shared<v0::Result>(matmul_ref)}, ParameterVector{other_ref});
+}
+
+// ----------------------------- Negative: transformation must NOT fire -----------------------------
+
+TEST_F(BroadcastMatMulFusionTest, KeepsBroadcastWhenOtherBatchDynamicWithoutSymbols) {
+ // Matrix dims stay static/equal, but both batch dims are dynamic and carry no shape symbol
+ // (no symbol propagation ran): equality is not provable, so the Broadcast must be kept.
+ auto other = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, 8, 16});
+ auto data = make_const(Shape{1, 32, 8});
+
+ auto batch = std::make_shared<v8::Gather>(std::make_shared<v3::ShapeOf>(other, element::i64),
+ v0::Constant::create(element::i64, Shape{1}, {0}),
+ v0::Constant::create(element::i64, Shape{}, {0}));
+ auto target = std::make_shared<v0::Concat>(OutputVector{batch,
+ v0::Constant::create(element::i64, Shape{1}, {32}),
+ v0::Constant::create(element::i64, Shape{1}, {8})},
+ 0);
+ auto broadcast = std::make_shared<v3::Broadcast>(data, target, op::BroadcastType::BIDIRECTIONAL);
+ auto matmul = std::make_shared<v0::MatMul>(broadcast, other);
+ model = std::make_shared<ov::Model>(ResultVector{std::make_shared<v0::Result>(matmul)}, ParameterVector{other});
+}
+
+TEST_F(BroadcastMatMulFusionTest, KeepsBroadcastWhenBatchNotCarriedByOther) {
+ // Other operand batch is a static 1, which cannot reproduce the broadcast batch of 4.
+ model = buildModel(Shape{1, 32, 8}, {4, 32, 8}, PartialShape{1, 8, 16}, /*broadcast_on_lhs=*/true);
+}
+
+TEST_F(BroadcastMatMulFusionTest, KeepsBroadcastWhenMatrixDimChanged) {
+ // Broadcast expands a matrix dim (1 -> 8): removing it would change the contraction.
+ model = buildModel(Shape{4, 1, 8}, {4, 8, 8}, PartialShape{4, 8, 16}, /*broadcast_on_lhs=*/true);
+}
+
+TEST_F(BroadcastMatMulFusionTest, KeepsBroadcastWhenConsumerNotMatMul) {
+ // The Broadcast feeds an elementwise Add, not a MatMul: the pattern must not match.
+ auto other = std::make_shared<v0::Parameter>(element::f32, PartialShape{4, 32, 8});
+ auto data = make_const(Shape{1, 32, 8});
+ auto target = v0::Constant::create(element::i64, Shape{3}, {4, 32, 8});
+ auto broadcast = std::make_shared<v3::Broadcast>(data, target, op::BroadcastType::BIDIRECTIONAL);
+ auto add = std::make_shared<ov::op::v1::Add>(broadcast, other);
+ model = std::make_shared<ov::Model>(ResultVector{std::make_shared<v0::Result>(add)}, ParameterVector{other});
+}
+
+TEST_F(BroadcastMatMulFusionTest, KeepsBroadcastWithPdpdMode) {
+ // PDPD broadcasting aligns dimensions differently from MatMul's NumPy-style batch
+ // broadcasting, so such a Broadcast must not be detached.
+ auto other = std::make_shared<v0::Parameter>(element::f32, PartialShape{4, 8, 16});
+ auto data = make_const(Shape{1, 32, 8});
+ auto target = v0::Constant::create(element::i64, Shape{3}, {4, 32, 8});
+ auto broadcast = std::make_shared<v3::Broadcast>(data, target, op::BroadcastModeSpec(op::BroadcastType::PDPD, 0));
+ auto matmul = std::make_shared<v0::MatMul>(broadcast, other);
+ model = std::make_shared<ov::Model>(ResultVector{std::make_shared<v0::Result>(matmul)}, ParameterVector{other});
+}
+
+TEST_F(BroadcastMatMulFusionTest, KeepsBroadcastWhenFixedExtentAndOtherDynamic) {
+ // Broadcast batch is a fixed 4, the other operand batch is dynamic: not provably equal,
+ // so removing the Broadcast could hide a runtime batch mismatch it would have rejected.
+ auto other = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, 8, 16});
+ auto data = make_const(Shape{1, 32, 8});
+ auto target = v0::Constant::create(element::i64, Shape{3}, {4, 32, 8});
+ auto broadcast = std::make_shared<v3::Broadcast>(data, target, op::BroadcastType::BIDIRECTIONAL);
+ auto matmul = std::make_shared<v0::MatMul>(broadcast, other);
+ model = std::make_shared<ov::Model>(ResultVector{std::make_shared<v0::Result>(matmul)}, ParameterVector{other});
+}
diff --git a/src/common/transformations/tests/sources.cmake b/src/common/transformations/tests/sources.cmake
index 6e195282f93..927bc3ce93e 100644
--- a/src/common/transformations/tests/sources.cmake
+++ b/src/common/transformations/tests/sources.cmake
@@ -25,6 +25,7 @@ set(COMMON_OPTIMIZATIONS_TESTS_SRCS
${CMAKE_CURRENT_LIST_DIR}/common_optimizations/batch_to_space_fusion.cpp
${CMAKE_CURRENT_LIST_DIR}/common_optimizations/binarize_weights.cpp
${CMAKE_CURRENT_LIST_DIR}/common_optimizations/broadcast_elementwise_fusion_test.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/common_optimizations/broadcast_matmul_fusion_test.cpp
${CMAKE_CURRENT_LIST_DIR}/common_optimizations/broadcast_transition_test.cpp
${CMAKE_CURRENT_LIST_DIR}/common_optimizations/change_placeholder_types_test.cpp
${CMAKE_CURRENT_LIST_DIR}/common_optimizations/clamp_fusion.cpp
diff --git a/tests/model_hub_tests/transformation_tests/test_moe_transformation.py b/tests/model_hub_tests/transformation_tests/test_moe_transformation.py
index fbc56ab8464..0749b0c076c 100644
--- a/tests/model_hub_tests/transformation_tests/test_moe_transformation.py
+++ b/tests/model_hub_tests/transformation_tests/test_moe_transformation.py
@@ -13,52 +13,47 @@ import torch
import numpy as np
import platform
+
+FUSED_MOE_WEIGHT_MARKER = "/FusedMOEWeights"
+
+
def verify_moe_fusion(ov_model: ov.Model, model_id: str):
"""
Verify that MoE fusion was applied correctly by checking for fused weight tensors.
- After MoE fusion, we expect to find MatMul operations with weights that have
- an expert dimension (first dimension should equal the number of experts).
+ FuseMOEExperts tags fused expert weight nodes (a Concat, possibly later constant-folded
+ to a Constant) with a "/FusedMOEWeights" friendly-name suffix, so they can be identified
+ directly instead of guessing from rank/shape (other rank-3 constants, e.g. RoPE's
+ inv_freq, can also end up directly on a MatMul input after other transformations run).
Returns:
- int: Number of fused MoE layers detected
+ int: Number of experts detected in the fused MoE weight tensors
"""
- # Get model configuration to determine number of experts
- # For tiny-random-qwen3_moe, we expect num_experts parameter in config
num_experts = None
for op in ov_model.get_ordered_ops():
- # Look for patterns indicating fused MoE:
- # - MatMul with 3D weight tensor [num_experts, hidden_dim, intermediate_dim]
- # - Tile operation that replicates input for all experts
- if op.get_type_name() == "MatMul":
- # Check if this MatMul has a 3D constant weight (indicating fused experts)
- for i in range(op.get_input_size()):
- input_node = op.input_value(i).get_node()
- if input_node.get_type_name() == "Constant":
- weight_shape = list(input_node.get_shape())
- # Fused expert weights should be 3D: [num_experts, in_dim, out_dim]
- if len(weight_shape) == 3:
- if num_experts is None:
- num_experts = weight_shape[0]
- else:
- assert weight_shape[0] == num_experts, \
- f"Inconsistent expert count: expected {num_experts}, got {weight_shape[0]}"
- # Check for Convert->Constant pattern (decompression)
- elif input_node.get_type_name() == "Convert":
- convert_input = input_node.input_value(0).get_node()
- if convert_input.get_type_name() == "Constant":
- weight_shape = list(convert_input.get_shape())
- if len(weight_shape) == 3:
- if num_experts is None:
- num_experts = weight_shape[0]
- else:
- assert weight_shape[0] == num_experts, \
- f"Inconsistent expert count: expected {num_experts}, got {weight_shape[0]}"
-
- # If we found fused weights, verify the number of experts makes sense
+ if op.get_type_name() != "MatMul":
+ continue
+ for i in range(op.get_input_size()):
+ input_node = op.input_value(i).get_node()
+ # Unwrap decompression Convert to reach the underlying weight constant
+ if input_node.get_type_name() == "Convert":
+ input_node = input_node.input_value(0).get_node()
+ # The marker is applied to the Concat produced by FuseMOEExperts; it may later be
+ # constant-folded into a Constant (e.g. on serialization), so accept either node type.
+ if input_node.get_type_name() not in ("Constant", "Concat") or \
+ FUSED_MOE_WEIGHT_MARKER not in input_node.get_friendly_name():
+ continue
+ weight_shape = list(input_node.get_shape())
+ assert len(weight_shape) == 3, \
+ f"Expected fused MoE weight to be 3D [num_experts, in_dim, out_dim], got {weight_shape}"
+ if num_experts is None:
+ num_experts = weight_shape[0]
+ else:
+ assert weight_shape[0] == num_experts, \
+ f"Inconsistent expert count: expected {num_experts}, got {weight_shape[0]}"
+
if num_experts is not None:
assert num_experts > 1, f"Expected multiple experts, found {num_experts}"
- # For tiny-random-qwen3_moe, we expect 4 experts
print(f"Detected {num_experts} experts in fused MoE layers")
return num_experts
@@ -231,6 +226,7 @@ def run_moe_synthetic(tmp_path,
del pt_outputs
# Load and export the OpenVINO model with MoE fusion
+ synthetic_id = f"synthetic_l{num_layers}_e{num_experts}_{dtype}"
ov_model = OVModelForCausalLM.from_pretrained(
model_path,
export=True,
@@ -239,10 +235,10 @@ def run_moe_synthetic(tmp_path,
)
# Verify that the loaded model has the fused MoE pattern
- verify_fused_moe_pattern(ov_model.model, f"synthetic_l{num_layers}_e{num_experts}_{dtype}", ie_device)
+ verify_fused_moe_pattern(ov_model.model, synthetic_id, ie_device)
# Verify the expected number of experts
- detected_experts = verify_moe_fusion(ov_model.model, f"synthetic_l{num_layers}_e{num_experts}_{dtype}")
+ detected_experts = verify_moe_fusion(ov_model.model, synthetic_id)
assert detected_experts == num_experts, \
f"Expected {num_experts} experts, but detected {detected_experts}"