Skip to content

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

[MOE] Fuse expert subgraph weights in offline transformation pass (#32199)

Mateusz Mikolajczyk7b7fde86a57b
diff --git a/src/common/transformations/include/transformations/common_optimizations/fuse_moe_experts.hpp b/src/common/transformations/include/transformations/common_optimizations/fuse_moe_experts.hpp
new file mode 100644
index 00000000000..40a434e9cdd
--- /dev/null
+++ b/src/common/transformations/include/transformations/common_optimizations/fuse_moe_experts.hpp
@@ -0,0 +1,57 @@
+// Copyright (C) 2018-2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/pass/manager.hpp"
+#include "openvino/pass/pattern/multi_matcher.hpp"
+#include "transformations_visibility.hpp"
+
+namespace ov {
+namespace pass {
+
+/**
+ * @brief Data structure representing a single expert's weight parameters and metadata.
+ *
+ * Used during MoE fusion to track and organize expert-specific information across
+ * the pattern matching and transformation process.
+ */
+struct expert_data {
+ std::shared_ptr<Node> gate_proj_weight; ///< Gate projection weight matrix
+ std::shared_ptr<Node> up_proj_weight; ///< Up projection weight matrix
+ std::shared_ptr<Node> down_proj_weight; ///< Down projection weight matrix
+ size_t expert_id; ///< Expert identifier (0-based index)
+ std::shared_ptr<Node> permute_node; ///< Associated permute/transpose node for MoE layer grouping
+};
+
+/**
+ * @brief Detects decomposed Mixture-of-Experts (MoE) layers whose experts are expressed
+ * as independent SWIGLU 3-GEMM pipelines with scatter-based accumulation, and replaces
+ * them with a single fused representation.
+ *
+ * The pass traverses each matched MoE layer, extracts per-expert gate/up/down weights,
+ * preserves optional fp16->fp32 decompression Converts, concatenates the parameters into
+ * expert-major tensors, and rebuilds the batched 3-GEMM computation together with the
+ * routing weights tensor. The resulting fused subgraph mirrors the structure expected by
+ * vectorized MoE passes.
+ */
+class TRANSFORMATIONS_API FuseMOEExperts : public ov::pass::MultiMatcher {
+public:
+ OPENVINO_RTTI("FuseMOEExperts");
+ FuseMOEExperts();
+};
+
+/**
+ * @brief High-level MoE transformation that invokes @c FuseMOEExperts across the
+ * entire model, replacing decomposed expert blocks with the fused 3-GEMM
+ * representation compatible with vectorized MoE passes.
+ */
+class TRANSFORMATIONS_API FuseMOE : public ModelPass {
+public:
+ OPENVINO_MODEL_PASS_RTTI("FuseMOE");
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+};
+
+} // namespace pass
+} // namespace ov
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
new file mode 100644
index 00000000000..cbe4b036cc0
--- /dev/null
+++ b/src/common/transformations/src/transformations/common_optimizations/fuse_moe_experts.cpp
@@ -0,0 +1,525 @@
+// Copyright (C) 2018-2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "transformations/common_optimizations/fuse_moe_experts.hpp"
+
+#include <algorithm>
+#include <cstddef>
+#include <cstdint>
+#include <limits>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+#include "itt.hpp"
+#include "openvino/core/graph_util.hpp"
+#include "openvino/core/node.hpp"
+#include "openvino/op/add.hpp"
+#include "openvino/op/broadcast.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/divide.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/non_zero.hpp"
+#include "openvino/op/one_hot.hpp"
+#include "openvino/op/reduce_sum.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/scatter_elements_update.hpp"
+#include "openvino/op/shape_of.hpp"
+#include "openvino/op/slice.hpp"
+#include "openvino/op/softmax.hpp"
+#include "openvino/op/split.hpp"
+#include "openvino/op/squeeze.hpp"
+#include "openvino/op/swish.hpp"
+#include "openvino/op/tile.hpp"
+#include "openvino/op/topk.hpp"
+#include "openvino/op/transpose.hpp"
+#include "openvino/op/unsqueeze.hpp"
+#include "openvino/op/util/shape_of_base.hpp"
+#include "openvino/pass/manager.hpp"
+#include "openvino/pass/pattern/matcher.hpp"
+#include "openvino/pass/pattern/op/block.hpp"
+#include "openvino/pass/pattern/op/pattern.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "transformations/rt_info/decompression.hpp"
+#include "transformations/utils/utils.hpp"
+namespace ov {
+namespace pass {
+
+using namespace ov::pass;
+using namespace ov::pass::pattern;
+
+namespace {
+
+// Check if a Slice operation's end parameter matches one found in model.
+// The pattern expects a 2-element constant [1, MAX] where.
+// This pattern matches Slice operations like: Slice(input, [0,0], [1,INT_MAX], [1,1], [0,1])
+// index_add__Slice_2 = makeOP<opset8::Slice>({index_add__ScatterElementsUpdate_5, {0,0}, {1,INT_MAX}, {1,1}, {0,1}});
+bool is_slice_to_end(const std::shared_ptr<Node>& node) {
+ auto constant = ov::as_type_ptr<ov::op::v0::Constant>(node);
+ if (!constant || !constant->get_element_type().is_integral_number()) {
+ return false;
+ }
+
+ const auto values = constant->cast_vector<int64_t>();
+ // Expect exactly 2 values: [1, MAX] where first dimension ends at 1
+ if (values.size() != 2 || values[0] != 1) {
+ return false;
+ }
+
+ // Second dimension should use maximum value to indicate slicing to the end
+ const auto end_value = values[1];
+ if (constant->get_element_type() == element::i32) {
+ return end_value == std::numeric_limits<int32_t>::max();
+ }
+
+ if (constant->get_element_type() == element::i64) {
+ return end_value == std::numeric_limits<int64_t>::max();
+ }
+
+ return false;
+}
+
+// Pattern matching for individual expert computation block with SwiGLU activation
+std::shared_ptr<pattern::op::Block> mlp3_no_bias_swiglu_block(
+ const Output<Node>& permute_Transpose, // Transpose -> OneHot -> TopK -> Softmax -> MatMul -> Hidden States
+ const Output<Node>& unsqueeze_Unsqueeze, // Unsqueeze -> Reshape -> Hidden States
+ const Output<Node>&
+ index_Split_out_1, // Split -> Unsqueeze -> Divide -> TopK -> Softmax -> MatMul -> Hidden States
+ const Output<Node>& index_Reshape // Reshape -> Divide -> TopK -> Softmax -> MatMul -> Hidden States
+) {
+ auto index_add__ScatterElementsUpdate_2 = pattern::any_input();
+ auto shape_const = wrap_type<ov::op::v0::Constant>();
+ auto expert_id = wrap_type<ov::op::v0::Constant>();
+ auto slice_end_const = wrap_type<ov::op::v0::Constant>();
+ auto select_Gather_1 = wrap_type<ov::op::v8::Gather>(
+ {permute_Transpose, expert_id, wrap_type<ov::op::v0::Constant>(pattern::value_matches("0"))},
+ {{"batch_dims", 0}});
+ auto squeeze_Squeeze_1 =
+ wrap_type<ov::op::v0::Squeeze>({select_Gather_1, wrap_type<ov::op::v0::Constant>(pattern::value_matches("0"))});
+ // NonZero output_type relaxed to accept both i32 and i64
+ auto ListUnpack_NonZero_1 = wrap_type<ov::op::v3::NonZero>({squeeze_Squeeze_1});
+ auto ListUnpack_Split_1 = wrap_type<ov::op::v1::Split>(
+ {ListUnpack_NonZero_1, wrap_type<ov::op::v0::Constant>(pattern::value_matches("0"))},
+ {{"num_splits", 2}});
+ ListUnpack_Split_1->set_output_size(2);
+ auto ListUnpack_Squeeze_0_1 = wrap_type<ov::op::v0::Squeeze>(
+ {ListUnpack_Split_1->output(1), wrap_type<ov::op::v0::Constant>(pattern::value_matches("0"))});
+ // Convert is optional - pattern matches both with and without type conversion
+ auto index_add__Convert_1 = wrap_type<ov::op::v0::Convert>({ListUnpack_Squeeze_0_1}) | ListUnpack_Squeeze_0_1;
+ auto index_add__Reshape_1 = wrap_type<ov::op::v1::Reshape>(
+ {index_add__Convert_1, wrap_type<ov::op::v0::Constant>(pattern::value_matches("-1, 1"))},
+ {{"special_zero", false}});
+ auto index_add__Slice_1 =
+ wrap_type<ov::op::v8::Slice>({index_add__ScatterElementsUpdate_2,
+ wrap_type<ov::op::v0::Constant>(pattern::value_matches("0, 0")),
+ slice_end_const,
+ wrap_type<ov::op::v0::Constant>(pattern::value_matches("1, 1")),
+ wrap_type<ov::op::v0::Constant>(pattern::value_matches("0, 1"))});
+ auto index_add__ShapeOf_14 = wrap_type<ov::op::v3::ShapeOf>({index_add__Slice_1}, {{"output_type", "i32"}});
+ auto index_add__Broadcast_16 =
+ wrap_type<ov::op::v3::Broadcast>({index_add__Reshape_1, index_add__ShapeOf_14}, {{"mode", "bidirectional"}});
+ auto unsqueeze_Unsqueeze_reshape =
+ wrap_type<ov::op::v1::Reshape>({unsqueeze_Unsqueeze, pattern::any_input()}, {{"special_zero", false}});
+ auto index_Gather_2 = wrap_type<ov::op::v8::Gather>({unsqueeze_Unsqueeze_reshape,
+ index_add__Convert_1,
+ wrap_type<ov::op::v0::Constant>(pattern::value_matches("0"))},
+ {{"batch_dims", 0}});
+ auto reshape_Reshape_1_0 =
+ wrap_type<ov::op::v1::Reshape>({index_Gather_2, pattern::any_input()}, {{"special_zero", true}});
+ auto reshape_Reshape_1_1 =
+ wrap_type<ov::op::v1::Reshape>({reshape_Reshape_1_0, pattern::any_input()}, {{"special_zero", true}});
+ auto reshape_Reshape_1_2 =
+ wrap_type<ov::op::v1::Reshape>({reshape_Reshape_1_1, pattern::any_input()}, {{"special_zero", true}});
+
+ auto reshape_Reshape_1 =
+ wrap_type<ov::op::v1::Reshape>({reshape_Reshape_1_2, shape_const}, {{"special_zero", true}});
+ auto gate_proj_weight = pattern::any_input(pattern::rank_equals(2));
+ auto linear_MatMul_gate = wrap_type<ov::op::v0::MatMul>({reshape_Reshape_1, gate_proj_weight},
+ {{"transpose_a", false}, {"transpose_b", true}});
+ auto silu_Swish = wrap_type<ov::op::v4::Swish>({linear_MatMul_gate});
+ auto up_proj_weight = pattern::any_input(pattern::rank_equals(2));
+ auto linear_MatMul_up = wrap_type<ov::op::v0::MatMul>({reshape_Reshape_1, up_proj_weight},
+ {{"transpose_a", false}, {"transpose_b", true}});
+ auto mul_Multiply = wrap_type<ov::op::v1::Multiply>({silu_Swish, linear_MatMul_up}, {{"auto_broadcast", "numpy"}});
+ auto down_proj_weight = pattern::any_input(pattern::rank_equals(2));
+ auto linear_MatMul_down = wrap_type<ov::op::v0::MatMul>({mul_Multiply, down_proj_weight},
+ {{"transpose_a", false}, {"transpose_b", true}});
+ auto ListUnpack_Squeeze_1 = wrap_type<ov::op::v0::Squeeze>(
+ {ListUnpack_Split_1->output(0), wrap_type<ov::op::v0::Constant>(pattern::value_matches("0"))});
+ // Convert is optional - pattern matches both with and without type conversion
+ auto index_Convert_4 = wrap_type<ov::op::v0::Convert>({ListUnpack_Squeeze_1}) | ListUnpack_Squeeze_1;
+ auto index_Multiply_1 =
+ wrap_type<ov::op::v1::Multiply>({index_add__Convert_1, index_Split_out_1}, {{"auto_broadcast", "numpy"}});
+ auto index_Add_1 = wrap_type<ov::op::v1::Add>({index_Convert_4, index_Multiply_1}, {{"auto_broadcast", "numpy"}});
+ auto index_Gather_3 = wrap_type<ov::op::v8::Gather>(
+ {index_Reshape, index_Add_1, wrap_type<ov::op::v0::Constant>(pattern::value_matches("0"))},
+ {{"batch_dims", 0}});
+ auto index_Reshape_8_1 = wrap_type<ov::op::v1::Reshape>(
+ {index_Gather_3, wrap_type<ov::op::v0::Constant>(pattern::value_matches("0, 1"))},
+ {{"special_zero", true}});
+ auto mul_Multiply_2 =
+ wrap_type<ov::op::v1::Multiply>({linear_MatMul_down, index_Reshape_8_1}, {{"auto_broadcast", "numpy"}});
+ auto index_add__Broadcast_17 =
+ wrap_type<ov::op::v3::Broadcast>({mul_Multiply_2, index_add__ShapeOf_14}, {{"mode", "bidirectional"}});
+ auto index_add__ScatterElementsUpdate_5 =
+ wrap_type<ov::op::v12::ScatterElementsUpdate>({index_add__ScatterElementsUpdate_2,
+ index_add__Broadcast_16,
+ index_add__Broadcast_17,
+ wrap_type<ov::op::v0::Constant>(pattern::value_matches("0"))},
+ {{"reduction", "sum"}, {"use_init_val", true}});
+ auto block = std::make_shared<pattern::op::Block>(
+ ov::OutputVector{permute_Transpose, unsqueeze_Unsqueeze, index_Split_out_1, index_Reshape},
+ ov::OutputVector{index_add__ScatterElementsUpdate_5},
+ "expert_block");
+ REGISTER_ANCHORS(block,
+ expert_id,
+ gate_proj_weight,
+ up_proj_weight,
+ down_proj_weight,
+ permute_Transpose,
+ slice_end_const);
+ return block;
+}
+
+// Helper function to create commonly used axis constants
+struct AxisPatterns {
+ std::shared_ptr<Node> axis0 = wrap_type<ov::op::v0::Constant>(pattern::value_matches("0"));
+ std::shared_ptr<Node> axis1 = wrap_type<ov::op::v0::Constant>(pattern::value_matches("1"));
+ std::shared_ptr<Node> axis2 = wrap_type<ov::op::v0::Constant>(pattern::value_matches("2"));
+};
+
+// Helper function to extract a dimension from a tensor shape
+// Returns ShapeOf -> Gather(axis_index) -> Unsqueeze as a dimension vector
+std::shared_ptr<Node> extract_shape_dim(const Output<Node>& input, size_t axis_index) {
+ auto shape_of = std::make_shared<ov::op::v3::ShapeOf>(input, element::i64);
+ auto axis_scalar = ov::op::v0::Constant::create(element::i64, Shape{}, {static_cast<int64_t>(axis_index)});
+ auto axis0_scalar = ov::op::v0::Constant::create(element::i64, Shape{}, {0});
+ auto dim_scalar = std::make_shared<ov::op::v8::Gather>(shape_of, axis_scalar, axis0_scalar);
+ auto axis0_vector = ov::op::v0::Constant::create(element::i64, Shape{1}, {0});
+ return std::make_shared<ov::op::v0::Unsqueeze>(dim_scalar, axis0_vector);
+}
+
+// Helper function to create router pattern (Softmax -> TopK -> OneHot -> Transpose)
+// This pattern identifies the expert selection logic from router logits
+std::pair<std::shared_ptr<Node>, std::shared_ptr<Node>> create_router_pattern() {
+ auto linear_MatMul = pattern::any_input();
+ auto expert_num = wrap_type<ov::op::v0::Constant>();
+ auto num_topk = wrap_type<ov::op::v0::Constant>();
+ auto one_hot_on = wrap_type<ov::op::v0::Constant>(pattern::value_matches("1"));
+ auto one_hot_off = wrap_type<ov::op::v0::Constant>(pattern::value_matches("0"));
+ auto transpose_perm = wrap_type<ov::op::v0::Constant>(pattern::value_matches("2, 1, 0"));
+
+ auto softmax = wrap_type<ov::op::v8::Softmax>({linear_MatMul}, {{"axis", 1}});
+ auto topk = wrap_type<ov::op::v11::TopK>(
+ {softmax, num_topk},
+ {{"axis", -1}, {"mode", "max"}, {"sort", "value"}, {"index_element_type", "i64"}, {"stable", false}});
+ topk->set_output_size(2);
+ auto one_hot = wrap_type<ov::op::v1::OneHot>({topk->output(1), expert_num, one_hot_on, one_hot_off}, {{"axis", 2}});
+ auto permute = wrap_type<ov::op::v1::Transpose>({one_hot, transpose_perm});
+
+ return {topk, permute};
+}
+
+// Helper function to create expert indexing pattern (NonZero -> Split -> Convert)
+// This extracts indices of tokens assigned to each expert
+std::shared_ptr<Node> create_expert_indexing_pattern(const std::shared_ptr<Node>& permute_transpose,
+ const AxisPatterns& axes) {
+ auto select_gather =
+ wrap_type<ov::op::v8::Gather>({permute_transpose, axes.axis0, axes.axis0}, {{"batch_dims", 0}});
+ auto squeeze = wrap_type<ov::op::v0::Squeeze>({select_gather, axes.axis0});
+ // NonZero output_type relaxed to accept both i32 and i64
+ auto non_zero = wrap_type<ov::op::v3::NonZero>({squeeze});
+ auto split = wrap_type<ov::op::v1::Split>({non_zero, axes.axis0}, {{"num_splits", 2}});
+ split->set_output_size(2);
+ auto squeeze_indices = wrap_type<ov::op::v0::Squeeze>({split->output(1), axes.axis0});
+ // Convert is optional - pattern matches both with and without type conversion
+ auto convert = wrap_type<ov::op::v0::Convert>({squeeze_indices}) | squeeze_indices;
+ return convert;
+}
+
+// Helper function to create routing weights pattern
+// This normalizes TopK values and prepares them for weighting expert outputs
+std::tuple<std::shared_ptr<Node>, std::shared_ptr<Node>> create_routing_weights_pattern(
+ const std::shared_ptr<Node>& topk,
+ const AxisPatterns& axes) {
+ auto reduce_neg1 = wrap_type<ov::op::v0::Constant>(pattern::value_matches("-1"));
+ auto sum_reduce = wrap_type<ov::op::v1::ReduceSum>({topk->output(0), reduce_neg1}, {{"keep_dims", true}});
+ auto normalized = wrap_type<ov::op::v1::Divide>({topk->output(0), sum_reduce},
+ {{"auto_broadcast", "numpy"}, {"m_pythondiv", true}});
+ auto unsqueeze = wrap_type<ov::op::v0::Unsqueeze>({normalized, axes.axis2});
+ auto shape_of = wrap_type<ov::op::v3::ShapeOf>({unsqueeze}, {{"output_type", "i32"}});
+ auto split = wrap_type<ov::op::v1::Split>({shape_of, axes.axis0}, {{"num_splits", 3}});
+ split->set_output_size(3);
+ auto reshape = wrap_type<ov::op::v1::Reshape>({unsqueeze, pattern::any_input()}, {{"special_zero", true}});
+
+ return {split, reshape};
+}
+
+} // namespace
+
+ov::pass::FuseMOEExperts::FuseMOEExperts() : MultiMatcher("FuseMOEExperts") {
+ // Create axis patterns
+ AxisPatterns axes;
+
+ // Create router pattern: Softmax -> TopK -> OneHot -> Transpose
+ auto router_result = create_router_pattern();
+ auto topk_TopK = router_result.first;
+ auto permute_Transpose = router_result.second;
+
+ // Create expert indexing pattern for the first expert (used in outer loop)
+ auto index_add__Convert = create_expert_indexing_pattern(permute_Transpose, axes);
+
+ // Prepare additional patterns for expert computation
+ auto view_Reshape = pattern::any_input();
+ auto slice_end = wrap_type<ov::op::v0::Constant>(); // Used in callback for slice validation
+
+ // Pattern for hidden states preparation
+ auto unsqueeze_Unsqueeze = wrap_type<ov::op::v0::Unsqueeze>({view_Reshape, axes.axis0});
+
+ // Create routing weights pattern
+ auto routing_result = create_routing_weights_pattern(topk_TopK, axes);
+ auto index_Split = std::get<0>(routing_result);
+ auto index_Reshape = std::get<1>(routing_result);
+
+ // Create expert computation pattern (3-GEMM SwiGLU block)
+ auto expert_scatter =
+ mlp3_no_bias_swiglu_block(permute_Transpose, unsqueeze_Unsqueeze, index_Split->output(1), index_Reshape);
+
+ // Match the final reshape and residual add after all expert computations
+ auto original_shape = pattern::any_input();
+ auto last_reshape = wrap_type<ov::op::v1::Reshape>({expert_scatter, original_shape}, {{"special_zero", false}});
+ auto residual_input = pattern::any_input();
+ auto last_add = wrap_type<ov::op::v1::Add>({residual_input, last_reshape}, {{"auto_broadcast", "numpy"}});
+
+ auto callback = [=](const std::unordered_map<std::shared_ptr<Node>, std::vector<PatternValueMap>>& matches) {
+ auto num_last_add = matches.at(last_add).size();
+
+ // Collect expert data from all matched patterns
+ std::vector<expert_data> all_experts;
+ all_experts.reserve(matches.at(expert_scatter).size());
+ for (const auto& pm : matches.at(expert_scatter)) {
+ auto slice_end_anchor = expert_scatter->get_anchor("slice_end_const", pm);
+ if (!slice_end_anchor.has_value() || !is_slice_to_end(slice_end_anchor.value().get_node_shared_ptr())) {
+ return false;
+ }
+ auto gate_proj_node = expert_scatter->get_anchor("gate_proj_weight", pm).value().get_node_shared_ptr();
+ auto up_proj_node = expert_scatter->get_anchor("up_proj_weight", pm).value().get_node_shared_ptr();
+ auto down_proj_node = expert_scatter->get_anchor("down_proj_weight", pm).value().get_node_shared_ptr();
+ auto expert_id_node = expert_scatter->get_anchor("expert_id", pm).value().get_node_shared_ptr();
+ auto expert_id_const = ov::as_type_ptr<ov::op::v0::Constant>(expert_id_node);
+ auto permute_node = expert_scatter->get_anchor("permute_Transpose", pm).value().get_node_shared_ptr();
+ auto expert_id_values = expert_id_const->cast_vector<int64_t>();
+ all_experts.push_back({gate_proj_node,
+ up_proj_node,
+ down_proj_node,
+ static_cast<std::size_t>(expert_id_values.at(0)),
+ permute_node});
+ }
+
+ // Group experts by their permute node to identify which MoE layer they belong to
+ std::unordered_map<const ov::Node*, std::vector<expert_data>> experts_by_permute;
+ for (const auto& expert : all_experts) {
+ experts_by_permute[expert.permute_node.get()].push_back(expert);
+ }
+
+ // Create shared constants (used across all MoE layers)
+ auto const_0 = ov::op::v0::Constant::create(element::i64, Shape{1}, {0});
+ auto const_1 = ov::op::v0::Constant::create(element::i64, Shape{1}, {1});
+ auto const_minus_1 = ov::op::v0::Constant::create(element::i64, Shape{1}, {-1});
+ auto transpose_perm = ov::op::v0::Constant::create(element::i64, Shape{2}, {1, 0});
+
+ // Process each MoE layer separately
+ for (size_t moe_idx = 0; moe_idx < num_last_add; moe_idx++) {
+ const auto& last_add_match = matches.at(last_add)[moe_idx];
+ std::shared_ptr<Node> slice_end_node = nullptr;
+ auto slice_end_it = last_add_match.find(slice_end);
+ if (slice_end_it != last_add_match.end()) {
+ slice_end_node = slice_end_it->second.get_node_shared_ptr();
+ } else if (auto slice_end_anchor = expert_scatter->get_anchor("slice_end_const", last_add_match)) {
+ slice_end_node = slice_end_anchor.value().get_node_shared_ptr();
+ }
+ if (slice_end_node && !is_slice_to_end(slice_end_node)) {
+ continue;
+ }
+ auto last_add_node = last_add_match.at(last_add).get_node_shared_ptr();
+ auto last_reshape_node = last_add_match.at(last_reshape).get_node_shared_ptr();
+
+ auto permute_node =
+ expert_scatter->get_anchor("permute_Transpose", last_add_match).value().get_node_shared_ptr();
+ auto experts_it = experts_by_permute.find(permute_node.get());
+ if (experts_it == experts_by_permute.end() || experts_it->second.empty()) {
+ continue;
+ }
+
+ auto& experts = experts_it->second;
+ std::sort(experts.begin(), experts.end(), [](const expert_data& a, const expert_data& b) {
+ return a.expert_id < b.expert_id;
+ });
+
+ // Build fused weight tensors by concatenating individual expert weights along expert dimension
+
+ // Detect if weights have decompression pattern and extract original compressed weights
+ auto get_original_weight_and_decompress_info =
+ [](const std::shared_ptr<Node>& weight) -> std::pair<std::shared_ptr<Node>, bool> {
+ if (auto convert_op = ov::as_type_ptr<ov::op::v0::Convert>(weight)) {
+ if (ov::is_decompression(convert_op)) {
+ auto convert_input = convert_op->get_input_node_shared_ptr(0);
+ if (ov::as_type_ptr<ov::op::v0::Constant>(convert_input)) {
+ return {convert_input, true};
+ }
+ }
+ }
+ return {weight, false};
+ };
+ // Build concatenated weight tensor for all experts, preserving decompression if present
+ auto build_fused_weight =
+ [&](const std::function<std::shared_ptr<Node>(const expert_data&)>& getter) -> Output<Node> {
+ OutputVector inputs;
+ bool needs_decompress = false;
+ auto target_type = getter(experts.front())->get_output_element_type(0);
+
+ for (const auto& expert : experts) {
+ auto weight = getter(expert);
+ auto [original_weight, decompress] = get_original_weight_and_decompress_info(weight);
+
+ if (decompress) {
+ needs_decompress = true;
+ target_type = weight->get_output_element_type(0);
+ }
+
+ inputs.emplace_back(ov::op::util::make_try_fold<ov::op::v0::Unsqueeze>(original_weight, const_0));
+ }
+
+ auto fused = ov::op::util::make_try_fold<ov::op::v0::Concat>(inputs, 0);
+ if (needs_decompress) {
+ auto convert = std::make_shared<ov::op::v0::Convert>(fused, target_type);
+ ov::mark_as_decompression(convert);
+ return convert->output(0);
+ }
+
+ return fused;
+ };
+
+ auto fused_gate_weights = build_fused_weight([](const expert_data& expert) {
+ return expert.gate_proj_weight;
+ });
+ auto fused_up_weights = build_fused_weight([](const expert_data& expert) {
+ return expert.up_proj_weight;
+ });
+ auto fused_down_weights = build_fused_weight([](const expert_data& expert) {
+ return expert.down_proj_weight;
+ });
+
+ // Extract input and residual nodes from the pattern match
+ auto view_reshape_node = last_add_match.at(view_Reshape).get_node_shared_ptr();
+ auto residual_input_node = last_add_match.at(residual_input).get_node_shared_ptr();
+
+ // Build the fused MoE computation
+ const size_t num_experts = experts.size();
+
+ // Extract dimensions from shapes
+ auto hidden_dim = extract_shape_dim(experts[0].gate_proj_weight, 1);
+
+ auto topk = last_add_match.at(topk_TopK).get_node_shared_ptr();
+ auto topk_indices_output = topk->output(1);
+ auto batch_dim = extract_shape_dim(topk_indices_output, 0);
+
+ auto num_experts_const =
+ ov::op::v0::Constant::create(element::i64, Shape{}, {static_cast<int64_t>(num_experts)});
+ auto num_experts_dim = std::make_shared<ov::op::v0::Unsqueeze>(num_experts_const, const_0);
+
+ // Tile and reshape input to prepare for batched expert computation
+ auto tile_shape =
+ ov::op::v0::Constant::create(element::i64,
+ Shape{2},
+ {static_cast<int64_t>(num_experts), static_cast<int64_t>(1)});
+
+ auto view_reshape_shape = std::make_shared<ov::op::v0::Concat>(OutputVector{const_minus_1, hidden_dim}, 0);
+ auto view_reshape = std::make_shared<ov::op::v1::Reshape>(view_reshape_node, view_reshape_shape, false);
+ auto repeated_input = std::make_shared<ov::op::v0::Tile>(view_reshape, tile_shape);
+
+ auto batched_shape =
+ std::make_shared<ov::op::v0::Concat>(OutputVector{num_experts_dim, batch_dim, hidden_dim}, 0);
+ auto batched_input = std::make_shared<ov::op::v1::Reshape>(repeated_input, batched_shape, false);
+
+ // Execute three-GEMM SwiGLU pattern: gate_proj, up_proj, and down_proj
+ auto gate_bmm = std::make_shared<ov::op::v0::MatMul>(batched_input, fused_gate_weights, false, true);
+ auto gate_swish = std::make_shared<ov::op::v4::Swish>(gate_bmm);
+
+ auto up_bmm = std::make_shared<ov::op::v0::MatMul>(batched_input, fused_up_weights, false, true);
+ auto swiglu_mul = std::make_shared<ov::op::v1::Multiply>(gate_swish, up_bmm);
+
+ auto down_bmm = std::make_shared<ov::op::v0::MatMul>(swiglu_mul, fused_down_weights, false, true);
+
+ auto minus_one_vec = ov::op::v0::Constant::create(element::i64, Shape{1}, {-1});
+ auto expert_output_shape = std::make_shared<ov::op::v0::Concat>(
+ OutputVector{num_experts_dim, batch_dim, minus_one_vec, hidden_dim},
+ 0);
+ auto expert_outputs = std::make_shared<ov::op::v1::Reshape>(down_bmm, expert_output_shape, false);
+
+ // Build routing weights tensor from TopK outputs
+ auto topk_values = topk->output(0);
+ auto sum_reduce =
+ std::make_shared<ov::op::v1::ReduceSum>(topk_values,
+ ov::op::v0::Constant::create(element::i64, Shape{1}, {-1}),
+ true);
+ auto normalized_topk = std::make_shared<ov::op::v1::Divide>(topk_values, sum_reduce);
+
+ auto scatter_shape = std::make_shared<ov::op::v0::Concat>(OutputVector{batch_dim, num_experts_dim}, 0);
+ auto zeros_scalar = ov::op::v0::Constant::create(normalized_topk->get_element_type(), Shape{}, {0});
+ auto zeros_tensor = std::make_shared<ov::op::v3::Broadcast>(zeros_scalar, scatter_shape);
+
+ auto scatter = std::make_shared<ov::op::v12::ScatterElementsUpdate>(zeros_tensor,
+ topk_indices_output,
+ normalized_topk,
+ const_1);
+ auto router_transpose = std::make_shared<ov::op::v1::Transpose>(scatter, transpose_perm);
+ auto router_shape =
+ std::make_shared<ov::op::v0::Concat>(OutputVector{num_experts_dim, batch_dim, minus_one_vec}, 0);
+ auto router_reshape = std::make_shared<ov::op::v1::Reshape>(router_transpose, router_shape, true);
+ auto routing_weights = std::make_shared<ov::op::v0::Unsqueeze>(router_reshape, const_minus_1);
+
+ // Apply routing weights and reduce across expert dimension
+ auto weighted_outputs = std::make_shared<ov::op::v1::Multiply>(expert_outputs, routing_weights);
+ auto final_output = std::make_shared<ov::op::v1::ReduceSum>(weighted_outputs, const_0, false);
+
+ // Reshape back to original shape and add residual connection
+ auto target_shape = std::make_shared<ov::op::v3::ShapeOf>(view_reshape_node, element::i64);
+ auto final_reshape = std::make_shared<ov::op::v1::Reshape>(final_output, target_shape, false);
+ auto final_add = std::make_shared<ov::op::v1::Add>(residual_input_node, final_reshape);
+
+ if (last_reshape_node && !last_reshape_node->get_friendly_name().empty()) {
+ final_reshape->set_friendly_name(last_reshape_node->get_friendly_name());
+ }
+ final_add->set_friendly_name(last_add_node->get_friendly_name());
+
+ if (last_reshape_node) {
+ ov::copy_runtime_info(ov::NodeVector{last_reshape_node}, ov::NodeVector{final_reshape});
+ }
+ ov::copy_runtime_info(ov::NodeVector{last_add_node}, ov::NodeVector{final_add});
+
+ ov::replace_node(last_add_node, final_add);
+ }
+
+ return true;
+ };
+
+ register_patterns(std::vector<std::shared_ptr<Node>>{expert_scatter, last_add}, callback, true);
+}
+
+bool ov::pass::FuseMOE::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ RUN_ON_MODEL_SCOPE(FuseMOE);
+ ov::pass::Manager manager(get_pass_config(), "FuseMOE");
+
+ manager.register_pass<ov::pass::FuseMOEExperts>();
+ manager.run_passes(model);
+ return false;
+}
+
+} // namespace pass
+} // namespace ov
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 5ff07b5fa46..585a7d0a747 100644
--- a/src/common/transformations/src/transformations/common_optimizations/moc_transformations.cpp
+++ b/src/common/transformations/src/transformations/common_optimizations/moc_transformations.cpp
@@ -35,6 +35,7 @@
#include "transformations/common_optimizations/fold_subgraph_empty_inputs.hpp"
#include "transformations/common_optimizations/fq_mul_fusion.hpp"
#include "transformations/common_optimizations/fq_reshape_fusion.hpp"
+#include "transformations/common_optimizations/fuse_moe_experts.hpp"
#include "transformations/common_optimizations/gelu_fusion.hpp"
#include "transformations/common_optimizations/gru_cell_fusion.hpp"
#include "transformations/common_optimizations/hsigmoid_fusion.hpp"
@@ -289,6 +290,11 @@ bool ov::pass::MOCTransformations::run_on_model(const std::shared_ptr<ov::Model>
REGISTER_PASS(manager, ConstantFolding)
REGISTER_PASS(manager, SymbolicOptimizations)
REGISTER_PASS(manager, ResolveNameCollisions, true);
+ // todo: enable after plugin support for MoE
+ // Remove pytestmark to enable e2e test:
+ // tests/model_hub_tests/transformation_tests/test_moe_transformation.py
+ // REGISTER_PASS(manager, FuseMOE)
+
manager.run_passes(f);
if (!m_use_shapes) {
diff --git a/src/common/transformations/tests/common_optimizations/fuse_moe_test.cpp b/src/common/transformations/tests/common_optimizations/fuse_moe_test.cpp
new file mode 100644
index 00000000000..6baaf9e794a
--- /dev/null
+++ b/src/common/transformations/tests/common_optimizations/fuse_moe_test.cpp
@@ -0,0 +1,439 @@
+// Copyright (C) 2018-2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <gtest/gtest.h>
+
+#include <memory>
+
+#include "common_test_utils/ov_test_utils.hpp"
+#include "openvino/op/moe.hpp"
+#include "openvino/opsets/opset1.hpp"
+#include "openvino/opsets/opset11.hpp"
+#include "openvino/opsets/opset12.hpp"
+#include "openvino/opsets/opset3.hpp"
+#include "openvino/opsets/opset4.hpp"
+#include "openvino/opsets/opset6.hpp"
+#include "openvino/opsets/opset8.hpp"
+#include "transformations/common_optimizations/fuse_moe_experts.hpp"
+#include "transformations/common_optimizations/matmul_experts_fusion.hpp"
+#include "transformations/rt_info/decompression.hpp"
+#include "transformations/utils/gen_pattern.hpp"
+
+using namespace testing;
+using namespace ov::gen_pattern;
+using namespace ov;
+
+std::shared_ptr<ov::Model> BuildMOE(int expert_num, int topk) {
+ ov::element::Type inType = ov::element::f32;
+ // param1: [batch*seq, 2048]
+ auto final_hidden_states_ = std::make_shared<ov::opset1::Parameter>(inType, ov::PartialShape{-1, 2048});
+ // f32[?,128]
+ auto router_logits = std::make_shared<ov::opset1::Parameter>(inType, ov::PartialShape{-1, expert_num});
+ auto softmax_Softmax = makeOP<opset8::Softmax>({router_logits}, {{"axis", 1}});
+ auto topk_TopK = makeOP<opset11::TopK>(
+ {softmax_Softmax, topk},
+ {{"axis", -1}, {"mode", "max"}, {"sort", "value"}, {"index_element_type", "i64"}, {"stable", false}});
+ auto axis_minus_one = makeConst(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{-1});
+ auto sum_ReduceSum = makeOP<opset1::ReduceSum>({topk_TopK->output(0), axis_minus_one}, {{"keep_dims", true}});
+ auto div__Divide = makeOP<opset1::Divide>({topk_TopK->output(0), sum_ReduceSum},
+ {{"auto_broadcast", "numpy"}, {"m_pythondiv", true}});
+ auto one_hot_OneHot = makeOP<opset1::OneHot>({topk_TopK->output(1), expert_num, 1, 0}, {{"axis", 2}});
+ // param2: expert_mask: [128, 8, batch]
+ auto permute_Transpose = makeOP<opset1::Transpose>({one_hot_OneHot, {2, 1, 0}});
+
+ // hidden_states_2d: f32[-1, 2048]
+ // auto view_Reshape = makeOP(ov::Rank(2));
+ auto hidden_states_2d = std::make_shared<ov::opset1::Parameter>(inType, ov::PartialShape{-1, 2048});
+ auto hidden_states_ = makeOP<opset1::Convert>({hidden_states_2d}, {{"destination_type", "f32"}});
+ auto target_shape = makeOP<opset3::ShapeOf>({hidden_states_}, {{"output_type", "i64"}});
+ // param3: hidden_states: f32[1, -1, 2048]
+ auto axis0_scalar = makeConst(ov::element::i64, ov::Shape{}, std::vector<int64_t>{0});
+ auto axis0_vector_const = makeConst(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{0});
+ auto axis0_vector = makeConst(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{0});
+ auto axis2_vector = makeConst(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{2});
+ auto reduce_axis1 = makeConst(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{1});
+ auto transpose_axes = makeConst(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{1, 0});
+
+ auto hidden_states = makeOP<opset1::Unsqueeze>({hidden_states_, axis0_scalar});
+ auto hidden_states_reshape_shape = makeConst(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{-1, 2048});
+ auto hidden_states_reshaped =
+ makeOP<opset1::Reshape>({hidden_states, hidden_states_reshape_shape}, {{"special_zero", false}});
+
+ auto unsqueeze_Unsqueeze_1 = makeOP<opset1::Unsqueeze>({div__Divide, 2});
+ auto index_ShapeOf_1 = makeOP<opset3::ShapeOf>({unsqueeze_Unsqueeze_1}, {{"output_type", "i32"}});
+ auto index_Slice = makeOP<opset8::Slice>({index_ShapeOf_1, {0}, {2}, {1}, {0}});
+ auto index_ReduceProd = makeOP<opset1::ReduceProd>({index_Slice, 0}, {{"keep_dims", true}});
+ auto index_Concat = makeOP<opset1::Concat>({index_ReduceProd, {-1}}, {{"axis", 0}});
+ auto index_Split = makeOP<opset1::Split>({index_ShapeOf_1, 0}, {{"num_splits", 3}});
+ index_Split->set_output_size(3);
+ // routing weights: [self.topk * batch, 1]
+ auto index_Reshape = makeOP<opset1::Reshape>({unsqueeze_Unsqueeze_1, index_Concat}, {{"special_zero", true}});
+
+ // shape: [expert_number, topk, batch]
+ auto expert_mask = permute_Transpose;
+ auto squeeze_axis_const = makeConst(element::i64, ov::Shape{}, {0});
+ // shape: [self.topk * batch, 1]
+ auto routing_weights = index_Reshape;
+
+ auto residual_input = makeOP<opset1::Convert>({final_hidden_states_}, {{"destination_type", "f32"}});
+ std::shared_ptr<ov::Node> final_hidden_states = residual_input;
+ std::shared_ptr<ov::Node> original_shape_node;
+
+ for (int i = 0; i < expert_num; i++) {
+ // expert_mask[expert_idx]
+ std::shared_ptr<Node> select_Gather_2;
+
+ select_Gather_2 = makeOP<opset8::Gather>({expert_mask, i, 0}, {{"batch_dims", 0}});
+ auto squeeze_Squeeze_7 = makeOP<opset1::Squeeze>(
+ {select_Gather_2,
+ squeeze_axis_const}); // tensor_array<i64[2,?]>
+ // __module.model.layers.1.mlp/aten::squeeze/Squeeze_7(__module.model.layers.1.mlp/aten::select/Gather_7,
+ // 60)
+
+ // x = torch.where(expert_mask[expert_idx]), x shape: [2, nonzero], dim0: topk, dim1: batch
+ auto ListUnpack_NonZero_2 = makeOP<opset3::NonZero>({squeeze_Squeeze_7}, {{"output_type", "i64"}});
+ // topk, batch = torch.where(expert_mask[expert_idx])
+ auto ListUnpack_Split_2 = makeOP<opset1::Split>({ListUnpack_NonZero_2, 0}, {{"num_splits", 2}});
+ // batch
+ auto ListUnpack_Squeeze_0_2 =
+ makeOP<opset1::Squeeze>({ListUnpack_Split_2->output(1), squeeze_axis_const}, {{"special_zero", false}});
+ auto index_add__Convert_2 = makeOP<opset1::Convert>({ListUnpack_Squeeze_0_2}, {{"destination_type", "i32"}});
+ auto index_add__Reshape_2 = makeOP<opset1::Reshape>({index_add__Convert_2, {-1, 1}}, {{"special_zero", false}});
+ auto index_add__Slice_2 = makeOP<opset8::Slice>({final_hidden_states, {0, 0}, {1, INT_MAX}, {1, 1}, {0, 1}});
+ auto index_add__ShapeOf_22 = makeOP<opset3::ShapeOf>({index_add__Slice_2}, {{"output_type", "i32"}});
+ original_shape_node = index_add__ShapeOf_22;
+ auto index_add__Broadcast_25 =
+ makeOP<opset3::Broadcast>({index_add__Reshape_2, index_add__ShapeOf_22}, {{"mode", "bidirectional"}});
+ auto index_Gather_4 =
+ makeOP<opset8::Gather>({hidden_states_reshaped /*unsqueeze_Unsqueeze_reshape*/, index_add__Convert_2, 0},
+ {{"batch_dims", 0}});
+ auto reshape_Reshape_2_0 = makeOP<opset1::Reshape>({index_Gather_4, {-1, 2048}}, {{"special_zero", true}});
+ auto reshape_Reshape_2_1 = makeOP<opset1::Reshape>({reshape_Reshape_2_0, {-1, 2048}}, {{"special_zero", true}});
+ auto reshape_Reshape_2_2 = makeOP<opset1::Reshape>({reshape_Reshape_2_1, {-1, 2048}}, {{"special_zero", true}});
+ auto reshape_Reshape_2 = makeOP<opset1::Reshape>({reshape_Reshape_2_2, {-1, 2048}}, {{"special_zero", true}});
+ std::shared_ptr<ov::Node> gate_linear_Convert, up_linear_Convert, down_linear_Convert;
+ // FP16 weights only
+ auto self_model_model_layers_0_mlp_experts_2_gate_proj_weight =
+ makeConst(element::f16, ov::Shape({768, 16 * 128}), {0});
+ gate_linear_Convert = makeOP<opset1::Convert>({self_model_model_layers_0_mlp_experts_2_gate_proj_weight},
+ {{"destination_type", "f32"}});
+ ov::mark_as_decompression(gate_linear_Convert);
+ auto self_model_model_layers_0_mlp_experts_2_up_proj_weight = makeConst(element::f16,
+ ov::Shape({
+ 768,
+ 16 * 128,
+ }),
+ {0});
+
+ up_linear_Convert = makeOP<opset1::Convert>({self_model_model_layers_0_mlp_experts_2_up_proj_weight},
+ {{"destination_type", "f32"}});
+ ov::mark_as_decompression(up_linear_Convert);
+ auto self_model_model_layers_0_mlp_experts_2_down_proj_weight = makeConst(element::f16,
+ ov::Shape({
+ 2048,
+ 6 * 128,
+ }),
+ {0});
+ down_linear_Convert = makeOP<opset1::Convert>({self_model_model_layers_0_mlp_experts_2_down_proj_weight},
+ {{"destination_type", "f32"}});
+ ov::mark_as_decompression(down_linear_Convert);
+ auto gate_linear_MatMul = makeOP<opset1::MatMul>({reshape_Reshape_2, gate_linear_Convert},
+ {{"transpose_a", false}, {"transpose_b", true}});
+ auto silu_Swish = makeOP<opset4::Swish>({gate_linear_MatMul});
+
+ auto up_linear_MatMul = makeOP<opset1::MatMul>({reshape_Reshape_2, up_linear_Convert},
+ {{"transpose_a", false}, {"transpose_b", true}});
+ auto mul_Multiply = makeOP<opset1::Multiply>({silu_Swish, up_linear_MatMul}, {{"auto_broadcast", "numpy"}});
+
+ auto down_linear_MatMul = makeOP<opset1::MatMul>({mul_Multiply, down_linear_Convert},
+ {{"transpose_a", false}, {"transpose_b", true}});
+ auto ListUnpack_Squeeze_2 =
+ makeOP<opset1::Squeeze>({ListUnpack_Split_2->output(0), squeeze_axis_const}, {{"special_zero", false}});
+ auto index_Convert_6 = makeOP<opset1::Convert>({ListUnpack_Squeeze_2}, {{"destination_type", "i32"}});
+ // self.topk * batch, index_split=shapeof(routing_weights), shape: [batch, self.topk, 1]
+ auto index_Multiply_2 =
+ makeOP<opset1::Multiply>({index_add__Convert_2, index_Split->output(1)}, {{"auto_broadcast", "numpy"}});
+ // self.topk * batch + topk
+ auto index_Add_2 = makeOP<opset1::Add>({index_Convert_6, index_Multiply_2}, {{"auto_broadcast", "numpy"}});
+ // routing_weights', shape[self.topk * batch, 1]
+ auto index_Gather_5 =
+ makeOP<opset8::Gather>({routing_weights /*index_Reshape*/, index_Add_2, 0}, {{"batch_dims", 0}});
+ auto index_Reshape_8_2 = makeOP<opset1::Reshape>({index_Gather_5, {0, 1}}, {{"special_zero", true}});
+ auto mul_Multiply_3 =
+ makeOP<opset1::Multiply>({down_linear_MatMul, index_Reshape_8_2}, {{"auto_broadcast", "numpy"}});
+ auto index_add__Broadcast_26 =
+ makeOP<opset3::Broadcast>({mul_Multiply_3, index_add__ShapeOf_22}, {{"mode", "bidirectional"}});
+ auto index_add__ScatterElementsUpdate_8 =
+ makeOP<opset12::ScatterElementsUpdate>({final_hidden_states /*index_add__ScatterElementsUpdate_5*/,
+ index_add__Broadcast_25,
+ index_add__Broadcast_26,
+ 0},
+ {{"reduction", "sum"}, {"use_init_val", true}});
+ final_hidden_states = index_add__ScatterElementsUpdate_8;
+ }
+ auto final_reshape = makeOP<opset1::Reshape>({final_hidden_states, original_shape_node}, {{"special_zero", false}});
+ auto final_add = makeOP<opset1::Add>({residual_input, final_reshape}, {{"auto_broadcast", "numpy"}});
+
+ return std::make_shared<ov::Model>(ov::OutputVector{final_add},
+ ov::ParameterVector{final_hidden_states_, router_logits, hidden_states_2d});
+}
+
+static std::shared_ptr<ov::Model> BuildFusedMOE(const int expert_num, const int topk) {
+ constexpr int64_t hidden_size = 2048;
+ constexpr int64_t intermediate_size = 768;
+
+ ov::element::Type inType = ov::element::f32;
+ auto final_hidden_states_ = std::make_shared<ov::opset1::Parameter>(inType, ov::PartialShape{-1, hidden_size});
+ auto router_logits = std::make_shared<ov::opset1::Parameter>(inType, ov::PartialShape{-1, expert_num});
+ auto hidden_states_2d = std::make_shared<ov::opset1::Parameter>(inType, ov::PartialShape{-1, hidden_size});
+
+ auto residual_input = makeOP<opset1::Convert>({final_hidden_states_}, {{"destination_type", "f32"}});
+ auto hidden_states_ = makeOP<opset1::Convert>({hidden_states_2d}, {{"destination_type", "f32"}});
+
+ auto single_gate_weight_f16 =
+ makeConst(ov::element::f16,
+ ov::Shape{static_cast<size_t>(intermediate_size), static_cast<size_t>(hidden_size)},
+ {0});
+ auto single_gate_weight_convert = makeOP<opset1::Convert>({single_gate_weight_f16}, {{"destination_type", "f32"}});
+ ov::mark_as_decompression(single_gate_weight_convert);
+
+ auto softmax_Softmax = makeOP<opset8::Softmax>({router_logits}, {{"axis", 1}});
+ auto topk_TopK = makeOP<opset11::TopK>(
+ {softmax_Softmax, topk},
+ {{"axis", -1}, {"mode", "max"}, {"sort", "value"}, {"index_element_type", "i64"}, {"stable", false}});
+ auto axis_minus_one = makeConst(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{-1});
+ auto sum_ReduceSum = makeOP<opset1::ReduceSum>({topk_TopK->output(0), axis_minus_one}, {{"keep_dims", true}});
+ auto div__Divide = makeOP<opset1::Divide>({topk_TopK->output(0), sum_ReduceSum},
+ {{"auto_broadcast", "numpy"}, {"m_pythondiv", true}});
+
+ auto target_shape = makeOP<opset3::ShapeOf>({hidden_states_}, {{"output_type", "i64"}});
+
+ // Create fused weights with f16 constants and decompression Converts to match transformation output
+ auto fused_gate_weights_f16 = makeConst(ov::element::f16,
+ ov::Shape{static_cast<size_t>(expert_num),
+ static_cast<size_t>(intermediate_size),
+ static_cast<size_t>(hidden_size)},
+ {0});
+ auto fused_gate_weights_convert = std::make_shared<ov::op::v0::Convert>(fused_gate_weights_f16, ov::element::f32);
+ ov::mark_as_decompression(fused_gate_weights_convert);
+ auto fused_gate_weights = fused_gate_weights_convert;
+
+ auto fused_up_weights_f16 = makeConst(ov::element::f16,
+ ov::Shape{static_cast<size_t>(expert_num),
+ static_cast<size_t>(intermediate_size),
+ static_cast<size_t>(hidden_size)},
+ {0});
+ auto fused_up_weights_convert = std::make_shared<ov::op::v0::Convert>(fused_up_weights_f16, ov::element::f32);
+ ov::mark_as_decompression(fused_up_weights_convert);
+ auto fused_up_weights = fused_up_weights_convert;
+
+ auto fused_down_weights_f16 = makeConst(ov::element::f16,
+ ov::Shape{static_cast<size_t>(expert_num),
+ static_cast<size_t>(hidden_size),
+ static_cast<size_t>(intermediate_size)},
+ {0});
+ auto fused_down_weights_convert = std::make_shared<ov::op::v0::Convert>(fused_down_weights_f16, ov::element::f32);
+ ov::mark_as_decompression(fused_down_weights_convert);
+ auto fused_down_weights = fused_down_weights_convert;
+
+ // Create simple batched computation
+ auto axis0_scalar = makeConst(ov::element::i64, ov::Shape{}, std::vector<int64_t>{0});
+ auto axis1_scalar = makeConst(ov::element::i64, ov::Shape{}, std::vector<int64_t>{1});
+ auto axis0_vector = makeConst(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{0});
+ auto axis1_vector = makeConst(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{1});
+ auto axis_minus_one_vector = makeConst(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{-1});
+ auto transpose_axes = makeConst(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{1, 0});
+ auto minus_one = makeConst(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{-1});
+ auto axes0_i64 = makeConst(ov::element::i64, ov::Shape{}, std::vector<int64_t>{0});
+ auto gate_weight_shape = makeOP<opset3::ShapeOf>({single_gate_weight_convert}, {{"output_type", "i64"}});
+ auto gather_index_one = makeConst(ov::element::i64, ov::Shape{}, std::vector<int64_t>{1});
+ auto hidden_dim_scalar =
+ makeOP<opset8::Gather>({gate_weight_shape, gather_index_one, axes0_i64}, {{"batch_dims", 0}});
+ auto hidden_dim_unsqueeze = makeOP<opset1::Unsqueeze>({hidden_dim_scalar, axis0_vector});
+ auto topk_indices_shape = makeOP<opset3::ShapeOf>({topk_TopK->output(1)}, {{"output_type", "i64"}});
+ auto batch_dim_scalar =
+ makeOP<opset8::Gather>({topk_indices_shape, axis0_scalar, axis0_scalar}, {{"batch_dims", 0}});
+ auto batch_dim_unsqueeze = makeOP<opset1::Unsqueeze>({batch_dim_scalar, axis0_vector});
+
+ auto num_experts_const = makeConst(ov::element::i64, ov::Shape{}, {static_cast<int64_t>(expert_num)});
+ auto num_experts_unsqueeze = makeOP<opset1::Unsqueeze>({num_experts_const, axis0_vector});
+ auto tile_shape_vec = std::vector<int64_t>{static_cast<int64_t>(expert_num), 1};
+ auto tile_shape = makeConst(ov::element::i64, ov::Shape{2}, tile_shape_vec);
+ auto view_reshape_shape = makeOP<opset1::Concat>({axis_minus_one_vector, hidden_dim_unsqueeze}, {{"axis", 0}});
+ auto view_reshape = makeOP<opset1::Reshape>({hidden_states_, view_reshape_shape}, {{"special_zero", false}});
+ auto repeated_input = makeOP<opset6::Tile>({view_reshape, tile_shape});
+ auto batched_shape =
+ makeOP<opset1::Concat>({num_experts_unsqueeze, batch_dim_unsqueeze, hidden_dim_unsqueeze}, {{"axis", 0}});
+ auto batched_input = makeOP<opset1::Reshape>({repeated_input, batched_shape}, {{"special_zero", false}});
+
+ // Apply fused expert computation
+ auto gate_bmm = makeOP<opset1::MatMul>({batched_input, fused_gate_weights->output(0)},
+ {{"transpose_a", false}, {"transpose_b", true}});
+ auto gate_swish = makeOP<opset4::Swish>({gate_bmm});
+ auto up_bmm = makeOP<opset1::MatMul>({batched_input, fused_up_weights->output(0)},
+ {{"transpose_a", false}, {"transpose_b", true}});
+ auto swiglu_mul = makeOP<opset1::Multiply>({gate_swish, up_bmm}, {{"auto_broadcast", "numpy"}});
+ auto down_bmm = makeOP<opset1::MatMul>({swiglu_mul, fused_down_weights->output(0)},
+ {{"transpose_a", false}, {"transpose_b", true}});
+
+ auto expert_output_shape =
+ makeOP<opset1::Concat>({num_experts_unsqueeze, batch_dim_unsqueeze, minus_one, hidden_dim_unsqueeze},
+ {{"axis", 0}});
+ auto expert_outputs = makeOP<opset1::Reshape>({down_bmm, expert_output_shape}, {{"special_zero", false}});
+
+ // Create routing weights via scatter to match 3-GEMM pattern
+ auto topk_values = topk_TopK->output(0);
+ auto sum_reduce = makeOP<opset1::ReduceSum>({topk_values, axis_minus_one}, {{"keep_dims", true}});
+ auto normalized_topk =
+ makeOP<opset1::Divide>({topk_values, sum_reduce}, {{"auto_broadcast", "numpy"}, {"m_pythondiv", true}});
+ auto zeros_scalar = makeConst(ov::element::f32, ov::Shape{}, std::vector<float>{0.0f});
+ auto scatter_shape =
+ std::make_shared<ov::op::v0::Concat>(ov::OutputVector{batch_dim_unsqueeze, num_experts_unsqueeze}, 0);
+ auto zeros_tensor = std::make_shared<ov::op::v3::Broadcast>(zeros_scalar, scatter_shape);
+ auto scatter = std::make_shared<ov::op::v12::ScatterElementsUpdate>(zeros_tensor,
+ topk_TopK->output(1),
+ normalized_topk,
+ axis1_vector);
+ auto router_transpose = std::make_shared<ov::op::v1::Transpose>(scatter, transpose_axes);
+ auto router_shape =
+ std::make_shared<ov::op::v0::Concat>(ov::OutputVector{num_experts_unsqueeze, batch_dim_unsqueeze, minus_one},
+ 0);
+ auto router_reshape = std::make_shared<ov::op::v1::Reshape>(router_transpose, router_shape, true);
+ auto routing_unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(router_reshape, axis_minus_one_vector);
+
+ // Apply routing and sum
+ auto weighted_outputs = std::make_shared<ov::op::v1::Multiply>(expert_outputs, routing_unsqueeze);
+ auto final_output = std::make_shared<ov::op::v1::ReduceSum>(weighted_outputs, axis0_vector, false);
+
+ auto final_reshape = std::make_shared<ov::op::v1::Reshape>(final_output, target_shape, false);
+ auto final_add = std::make_shared<ov::op::v1::Add>(residual_input, final_reshape);
+ final_add->set_friendly_name("moe_decomposed");
+
+ return std::make_shared<ov::Model>(final_add,
+ ov::ParameterVector{final_hidden_states_, router_logits, hidden_states_2d});
+}
+
+static std::shared_ptr<ov::Model> BuildFusedMOEWithInternalOp(const int expert_num, const int topk) {
+ constexpr int64_t hidden_size = 2048;
+ constexpr int64_t intermediate_size = 768;
+
+ ov::element::Type inType = ov::element::f32;
+ auto final_hidden_states_ = std::make_shared<ov::opset1::Parameter>(inType, ov::PartialShape{-1, hidden_size});
+ auto router_logits = std::make_shared<ov::opset1::Parameter>(inType, ov::PartialShape{-1, expert_num});
+ auto hidden_states_2d = std::make_shared<ov::opset1::Parameter>(inType, ov::PartialShape{-1, hidden_size});
+
+ auto residual_input = makeOP<opset1::Convert>({final_hidden_states_}, {{"destination_type", "f32"}});
+ auto hidden_states_ = makeOP<opset1::Convert>({hidden_states_2d}, {{"destination_type", "f32"}});
+
+ auto softmax_Softmax = makeOP<opset8::Softmax>({router_logits}, {{"axis", 1}});
+ auto topk_TopK = makeOP<opset11::TopK>(
+ {softmax_Softmax, topk},
+ {{"axis", -1}, {"mode", "max"}, {"sort", "value"}, {"index_element_type", "i64"}, {"stable", false}});
+
+ auto target_shape = makeOP<opset3::ShapeOf>({hidden_states_}, {{"output_type", "i64"}});
+
+ auto axis_minus_one = makeConst(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{-1});
+ auto topk_values = topk_TopK->output(0);
+ auto sum_reduce = makeOP<opset1::ReduceSum>({topk_values, axis_minus_one}, {{"keep_dims", true}});
+ auto normalized_topk =
+ makeOP<opset1::Divide>({topk_values, sum_reduce}, {{"auto_broadcast", "numpy"}, {"m_pythondiv", true}});
+
+ auto axis0_scalar = makeConst(ov::element::i64, ov::Shape{}, std::vector<int64_t>{0});
+ auto axis0_vector = makeConst(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{0});
+ auto axis1_vector = makeConst(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{1});
+ auto transpose_axes = makeConst(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{1, 0});
+ auto axis_minus_one_vector = makeConst(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{-1});
+ auto minus_one = makeConst(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{-1});
+
+ auto router_topk_indices = topk_TopK->output(1);
+ auto topk_indices_shape = makeOP<opset3::ShapeOf>({router_topk_indices}, {{"output_type", "i64"}});
+ auto batch_dim_scalar =
+ makeOP<opset8::Gather>({topk_indices_shape, axis0_scalar, axis0_scalar}, {{"batch_dims", 0}});
+ auto batch_dim_unsqueeze = makeOP<opset1::Unsqueeze>({batch_dim_scalar, axis0_vector});
+
+ auto num_experts_const =
+ makeConst(ov::element::i64, ov::Shape{}, std::vector<int64_t>{static_cast<int64_t>(expert_num)});
+ auto num_experts_unsqueeze = makeOP<opset1::Unsqueeze>({num_experts_const, axis0_vector});
+
+ auto zeros_scalar = makeConst(ov::element::f32, ov::Shape{}, std::vector<float>{0.0f});
+ auto scatter_shape =
+ std::make_shared<ov::op::v0::Concat>(ov::OutputVector{batch_dim_unsqueeze, num_experts_unsqueeze}, 0);
+ auto zeros_tensor = std::make_shared<ov::op::v3::Broadcast>(zeros_scalar, scatter_shape);
+ auto scatter = std::make_shared<ov::op::v12::ScatterElementsUpdate>(zeros_tensor,
+ router_topk_indices,
+ normalized_topk,
+ axis1_vector);
+ auto router_transpose = std::make_shared<ov::op::v1::Transpose>(scatter, transpose_axes);
+ auto router_shape =
+ std::make_shared<ov::op::v0::Concat>(ov::OutputVector{num_experts_unsqueeze, batch_dim_unsqueeze, minus_one},
+ 0);
+ auto router_reshape = std::make_shared<ov::op::v1::Reshape>(router_transpose, router_shape, true);
+ auto routing_weights = std::make_shared<ov::op::v0::Unsqueeze>(router_reshape, axis_minus_one_vector);
+
+ auto fused_gate_weights_f16 = makeConst(ov::element::f16,
+ ov::Shape{static_cast<size_t>(expert_num),
+ static_cast<size_t>(intermediate_size),
+ static_cast<size_t>(hidden_size)},
+ {0});
+ auto fused_gate_weights = makeOP<opset1::Convert>({fused_gate_weights_f16}, {{"destination_type", "f32"}});
+ ov::mark_as_decompression(fused_gate_weights);
+
+ auto fused_up_weights_f16 = makeConst(ov::element::f16,
+ ov::Shape{static_cast<size_t>(expert_num),
+ static_cast<size_t>(intermediate_size),
+ static_cast<size_t>(hidden_size)},
+ {0});
+ auto fused_up_weights = makeOP<opset1::Convert>({fused_up_weights_f16}, {{"destination_type", "f32"}});
+ ov::mark_as_decompression(fused_up_weights);
+
+ auto fused_down_weights_f16 = makeConst(ov::element::f16,
+ ov::Shape{static_cast<size_t>(expert_num),
+ static_cast<size_t>(hidden_size),
+ static_cast<size_t>(intermediate_size)},
+ {0});
+ auto fused_down_weights = makeOP<opset1::Convert>({fused_down_weights_f16}, {{"destination_type", "f32"}});
+ ov::mark_as_decompression(fused_down_weights);
+
+ ov::OutputVector moe_inputs = {hidden_states_,
+ routing_weights,
+ router_topk_indices,
+ fused_gate_weights,
+ fused_up_weights,
+ fused_down_weights};
+
+ ov::op::internal::MOE::Config config;
+ config.expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU;
+
+ auto moe = std::make_shared<ov::op::internal::MOE>(moe_inputs, config);
+ auto final_reshape = std::make_shared<ov::op::v1::Reshape>(moe, target_shape, false);
+ auto final_add = std::make_shared<ov::op::v1::Add>(residual_input, final_reshape);
+
+ return std::make_shared<ov::Model>(ov::OutputVector{final_add},
+ ov::ParameterVector{final_hidden_states_, router_logits, hidden_states_2d});
+}
+
+TEST_F(TransformationTestsF, ConvertMOEToFuseMOE_FP16) {
+ disable_rt_info_check();
+ disable_result_friendly_names_check();
+
+ int expert_num = 16;
+ int topk = 8;
+
+ model = BuildMOE(expert_num, topk);
+ ov::pass::FuseMOE().run_on_model(model);
+ model_ref = BuildFusedMOE(expert_num, topk);
+}
+
+TEST_F(TransformationTestsF, FuseMOEExperts_to_FuseVectorizedMOE3GEMM_Integration) {
+ disable_rt_info_check();
+ disable_result_friendly_names_check();
+
+ int expert_num = 16;
+ int topk = 8;
+
+ model = BuildMOE(expert_num, topk);
+ ov::pass::FuseMOE().run_on_model(model);
+ manager.register_pass<ov::pass::FuseVectorizedMOE3GEMM>();
+ model_ref = BuildFusedMOEWithInternalOp(expert_num, topk);
+}
\ No newline at end of file
diff --git a/src/core/src/pattern/op/block.cpp b/src/core/src/pattern/op/block.cpp
index cac68a69bc2..1b6c969473d 100644
--- a/src/core/src/pattern/op/block.cpp
+++ b/src/core/src/pattern/op/block.cpp
@@ -50,7 +50,9 @@ bool Block::match_value(Matcher* matcher, const Output<Node>& pattern_value, con
pattern_map.merge(local_pm);
for (const auto& matched_node : local_matcher->get_matched_nodes()) {
- matcher->add_node(matched_node);
+ for (const auto& matched_node_out : matched_node->outputs()) {
+ matcher->add_node(matched_node_out);
+ }
}
return true;
}
\ No newline at end of file
diff --git a/tests/model_hub_tests/transformation_tests/models/hf-tiny-random-moe-models-precommit b/tests/model_hub_tests/transformation_tests/models/hf-tiny-random-moe-models-precommit
new file mode 100644
index 00000000000..c21897d0e0f
--- /dev/null
+++ b/tests/model_hub_tests/transformation_tests/models/hf-tiny-random-moe-models-precommit
@@ -0,0 +1 @@
+optimum-internal-testing/tiny-random-qwen3_moe,https://huggingface.co/optimum-internal-testing/tiny-random-qwen3_moe
diff --git a/tests/model_hub_tests/transformation_tests/test_moe_transformation.py b/tests/model_hub_tests/transformation_tests/test_moe_transformation.py
new file mode 100644
index 00000000000..8b6200081f5
--- /dev/null
+++ b/tests/model_hub_tests/transformation_tests/test_moe_transformation.py
@@ -0,0 +1,329 @@
+# Copyright (C) 2018-2025 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+from huggingface_hub import snapshot_download
+from optimum.intel import OVModelForCausalLM
+import openvino as ov
+from models_hub_common.utils import retry
+import models_hub_common.utils as utils
+import pytest
+import os
+from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
+import torch
+import numpy as np
+
+pytestmark = pytest.mark.skip(reason="FuseMOE transformation temporarily disabled in moc_transformations.cpp")
+
+
+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).
+
+ Returns:
+ int: Number of fused MoE layers detected
+ """
+ # 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 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
+
+ return 0
+
+
+def verify_fused_moe_pattern(ov_model: ov.Model,
+ model_id: str,
+ ie_device: str):
+ """
+ Verify that the model has the fused MoE pattern.
+
+ Since MOC transformations (including FuseMOE) are applied during model loading,
+ we don't need to apply them again. Instead, we verify that the loaded model
+ already contains the characteristic fused MoE subgraph with 3D weight tensors.
+
+ This function:
+ 1. Verifies MoE fusion by checking for 3D fused weight tensors
+ 2. Compiles the model to ensure validity
+ """
+ # Verify that MoE fusion is present in the loaded model
+ num_experts = verify_moe_fusion(ov_model, model_id)
+ assert num_experts > 0, "Model does not contain fused MoE pattern with 3D weight tensors"
+
+ # Compile to ensure the model is valid
+ ov.Core().compile_model(ov_model, ie_device)
+
+
+def create_synthetic_moe_model(tmp_path, num_layers, num_experts, dtype="float32", hidden_size=512, intermediate_size=192):
+ """
+ Create a synthetic Qwen3 MoE model from config for testing.
+
+ Args:
+ tmp_path: Temporary directory path
+ num_layers: Number of hidden layers (MoE layers)
+ num_experts: Number of experts per MoE layer
+ dtype: Model dtype (float32, bfloat16, float16)
+ hidden_size: Hidden dimension size
+ intermediate_size: MoE intermediate size
+
+ Returns:
+ str: Path to the saved model
+ """
+ # Load config from cache to avoid HuggingFace rate limits
+ config_cache = snapshot_download("optimum-internal-testing/tiny-random-qwen3_moe")
+ config = AutoConfig.from_pretrained(config_cache)
+ config.num_hidden_layers = num_layers
+ config.decoder_sparse_step = 1
+ config.num_experts = num_experts
+ config.torch_dtype = dtype
+ config.hidden_size = hidden_size
+ config.moe_intermediate_size = intermediate_size
+
+ model = AutoModelForCausalLM.from_config(config)
+ model_path = os.path.join(tmp_path, f"synthetic_qwen3_moe_l{num_layers}_e{num_experts}_{dtype}")
+ model.save_pretrained(model_path)
+
+ return model_path
+
+
+@retry(3, exceptions=(OSError,), delay=1)
+def run_moe(tmp_path,
+ model_id,
+ model_link,
+ ie_device):
+ """
+ Test that MoE models are loaded with fused expert subgraphs.
+
+ MOC transformations (including FuseMOE) are automatically applied during
+ model loading with from_pretrained, so we verify that the loaded model
+ contains the characteristic fused MoE pattern.
+
+ Additionally verifies output correctness by comparing with original PyTorch model.
+ """
+ model_cached = snapshot_download(model_id) # required to avoid HF rate limits
+
+ # Load original PyTorch model and tokenizer for comparison (from cache to avoid rate limits)
+ pt_model = AutoModelForCausalLM.from_pretrained(model_cached, trust_remote_code=True)
+ tokenizer = AutoTokenizer.from_pretrained(model_cached, trust_remote_code=True)
+
+ # Prepare test input
+ test_text = "Test input for MoE model verification"
+ inputs = tokenizer(test_text, return_tensors="pt")
+
+ # Get PyTorch output
+ with torch.no_grad():
+ pt_outputs = pt_model(**inputs)
+ pt_logits = pt_outputs.logits.numpy()
+
+ # Clean up PyTorch model to free memory
+ del pt_model
+ del pt_outputs
+
+ # Load the OpenVINO model - MOC transformations are applied during loading
+ ov_model = OVModelForCausalLM.from_pretrained(
+ model_cached,
+ export=True,
+ trust_remote_code=True,
+ compile=False # Don't compile yet, but transformations are still applied
+ )
+
+ # Verify that the loaded model has the fused MoE pattern
+ verify_fused_moe_pattern(ov_model.model, model_id, ie_device)
+
+ # Get OpenVINO output and compare with PyTorch
+ ov_outputs = ov_model(**inputs)
+ ov_logits = ov_outputs.logits.numpy()
+
+ # Compare outputs (allow small numerical differences due to precision)
+ max_diff = np.abs(pt_logits - ov_logits).max()
+ mean_diff = np.abs(pt_logits - ov_logits).mean()
+
+ print(f"Output comparison: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}")
+
+ # Verify outputs are close
+ # Tolerances: rtol=1e-3, atol=1e-3 account for OpenVINO IR conversion and execution differences
+ assert np.allclose(pt_logits, ov_logits, rtol=1e-3, atol=1e-3), \
+ f"Output mismatch between PyTorch and OpenVINO fused model: max_diff={max_diff}, mean_diff={mean_diff}"
+
+
+@retry(3, exceptions=(OSError,), delay=1)
+def run_moe_synthetic(tmp_path,
+ num_layers,
+ num_experts,
+ dtype,
+ ie_device):
+ """
+ Test MoE fusion on synthetically generated models.
+
+ Creates a model from config with specified parameters and verifies
+ that MoE fusion produces the expected fused pattern.
+
+ Additionally verifies output correctness by comparing with original PyTorch model.
+ """
+ model_path = create_synthetic_moe_model(tmp_path, num_layers, num_experts, dtype)
+
+ # Load original PyTorch model for comparison (from local path)
+ pt_model = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True)
+ # Load tokenizer from cache to avoid HuggingFace rate limits
+ tokenizer_cache = snapshot_download("optimum-internal-testing/tiny-random-qwen3_moe")
+ tokenizer = AutoTokenizer.from_pretrained(tokenizer_cache, trust_remote_code=True)
+
+ # Prepare test input
+ test_text = "Test input for synthetic MoE model"
+ inputs = tokenizer(test_text, return_tensors="pt")
+
+ # Get PyTorch output
+ with torch.no_grad():
+ pt_outputs = pt_model(**inputs)
+ pt_logits = pt_outputs.logits.numpy()
+
+ # Clean up PyTorch model to free memory
+ del pt_model
+ del pt_outputs
+
+ # Load and export the OpenVINO model with MoE fusion
+ ov_model = OVModelForCausalLM.from_pretrained(
+ model_path,
+ export=True,
+ trust_remote_code=True,
+ compile=False
+ )
+
+ # 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 the expected number of experts
+ detected_experts = verify_moe_fusion(ov_model.model, f"synthetic_l{num_layers}_e{num_experts}_{dtype}")
+ assert detected_experts == num_experts, \
+ f"Expected {num_experts} experts, but detected {detected_experts}"
+
+ # Get OpenVINO output and compare with PyTorch
+ ov_outputs = ov_model(**inputs)
+ ov_logits = ov_outputs.logits.numpy()
+
+ # Compare outputs (allow small numerical differences)
+ max_diff = np.abs(pt_logits - ov_logits).max()
+ mean_diff = np.abs(pt_logits - ov_logits).mean()
+
+ print(f"Synthetic ({num_layers}L, {num_experts}E, {dtype}): max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}")
+
+ # Adjust tolerances based on dtype
+ # FP16/BF16 have lower precision, so allow larger numerical differences
+ rtol = 1e-2 if dtype in ["float16", "bfloat16"] else 1e-3
+ atol = 1e-2 if dtype in ["float16", "bfloat16"] else 1e-3
+
+ assert np.allclose(pt_logits, ov_logits, rtol=rtol, atol=atol), \
+ f"Output mismatch for {num_layers}L, {num_experts}E, {dtype}: max_diff={max_diff}, mean_diff={mean_diff}"
+
+
+MOE_PRECOMMIT_TEST_CASES = [
+ (OVModelForCausalLM, *model_info_tuple)
+ for model_info_tuple in utils.get_models_list(
+ os.path.join(os.path.dirname(__file__), "models", "hf-tiny-random-moe-models-precommit")
+ )
+]
+
+
+def moe_test_idfn(entry):
+ """Generate test ID from model info."""
+ retval = "moe-"
+ if entry[0] is OVModelForCausalLM:
+ retval += "text-"
+ else:
+ raise ValueError(f"Unknown model class {entry[0]}")
+ retval += entry[1]
+ return retval
+
+
[email protected]("model_info_tuple", MOE_PRECOMMIT_TEST_CASES, ids=moe_test_idfn)
+def test_moe_precommit(tmp_path, model_info_tuple, ie_device):
+ """Test MoE fusion transformation on precommit models."""
+ model_class, model_name, model_link, mark, reason = model_info_tuple
+ assert mark is None or mark == 'skip' or mark == 'xfail', \
+ "Incorrect test case: {}, {}".format(model_name, model_link)
+ if mark == 'skip':
+ pytest.skip(reason)
+ elif mark == 'xfail':
+ pytest.xfail(reason)
+
+ run_moe(tmp_path, model_name, model_link, ie_device)
+
+
+# Synthetic test cases with different configurations
+MOE_SYNTHETIC_TEST_CASES = [
+ # (num_layers, num_experts, dtype)
+ # Test different numbers of MoE layers
+ (1, 4, "float32"), # Single MoE layer
+ (2, 4, "float32"), # Two MoE layers
+ (3, 4, "float32"), # Three MoE layers
+
+ # Test different numbers of experts
+ (1, 2, "float32"), # Minimal: 2 experts
+ (1, 8, "float32"), # More experts: 8
+ (1, 16, "float32"), # Many experts: 16
+
+ # Test different dtypes (important for decompression pattern testing)
+ (1, 4, "float16"), # FP16 - may have decompression
+ (1, 4, "bfloat16"), # BF16 - may have decompression
+
+ # Combined variations
+ (2, 8, "float16"), # Multiple layers + more experts + FP16
+ (3, 16, "bfloat16"), # Multiple layers + many experts + BF16
+]
+
+
+def synthetic_test_idfn(entry):
+ """Generate test ID for synthetic test cases."""
+ num_layers, num_experts, dtype = entry
+ return f"synthetic-l{num_layers}-e{num_experts}-{dtype}"
+
+
[email protected]("test_params", MOE_SYNTHETIC_TEST_CASES, ids=synthetic_test_idfn)
+def test_moe_synthetic(tmp_path, test_params, ie_device):
+ """
+ Test MoE fusion with synthetically generated models.
+
+ This tests various configurations:
+ - Different numbers of MoE layers (1, 2, 3)
+ - Different numbers of experts (2, 4, 8, 16)
+ - Different dtypes (float32, float16, bfloat16) to validate decompression handling
+ """
+ num_layers, num_experts, dtype = test_params
+ run_moe_synthetic(tmp_path, num_layers, num_experts, dtype, ie_device)