OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[Core][CPU] Rename batch_gather_matmul to gather_matmul, move ops to common transformations (#34963)
Egor Duplenskii1c95c5b7a7dc
diff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul.hpp b/src/common/transformations/include/ov_ops/gather_matmul.hppsimilarity index 54%rename from src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul.hpprename to src/common/transformations/include/ov_ops/gather_matmul.hppindex 6a182eaa745..345e4a702da 100644--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul.hpp+++ b/src/common/transformations/include/ov_ops/gather_matmul.hpp@@ -10,21 +10,22 @@#include "openvino/core/node.hpp"#include "openvino/core/node_vector.hpp"#include "openvino/op/op.hpp"+#include "transformations_visibility.hpp"-namespace ov::intel_cpu {+namespace ov::op::internal {-class BatchGatherMatmul : public ov::op::Op {+class TRANSFORMATIONS_API GatherMatmul : public ov::op::Op {public:- OPENVINO_OP("BatchGatherMatmul", "cpu_plugin_opset");+ OPENVINO_OP("GatherMatmul");- BatchGatherMatmul() = default;+ GatherMatmul() = default;- BatchGatherMatmul(const ov::Output<Node>& A,- const ov::Output<Node>& B,- const ov::Output<Node>& indices,- const ov::Output<Node>& bias);+ GatherMatmul(const ov::Output<Node>& A,+ const ov::Output<Node>& B,+ const ov::Output<Node>& indices,+ const ov::Output<Node>& bias);- BatchGatherMatmul(const ov::Output<Node>& A, const ov::Output<Node>& B, const ov::Output<Node>& indices);+ GatherMatmul(const ov::Output<Node>& A, const ov::Output<Node>& B, const ov::Output<Node>& indices);std::shared_ptr<Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;@@ -36,4 +37,4 @@ private:static constexpr bool transp_b = true;};-} // namespace ov::intel_cpu\ No newline at end of file+} // namespace ov::op::internaldiff --git a/src/common/transformations/include/ov_ops/gather_matmul_compressed.hpp b/src/common/transformations/include/ov_ops/gather_matmul_compressed.hppnew file mode 100644index 00000000000..27bdd834b3e--- /dev/null+++ b/src/common/transformations/include/ov_ops/gather_matmul_compressed.hpp@@ -0,0 +1,35 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <memory>++#include "openvino/core/attribute_visitor.hpp"+#include "openvino/core/node.hpp"+#include "openvino/core/node_vector.hpp"+#include "openvino/op/op.hpp"+#include "ov_ops/gather_matmul.hpp"++namespace ov::op::internal {++class TRANSFORMATIONS_API GatherMatmulCompressed : public GatherMatmul {+public:+ OPENVINO_OP("GatherMatmulCompressed", "", GatherMatmul);++ GatherMatmulCompressed() = default;++ GatherMatmulCompressed(const ov::Output<Node>& A,+ const ov::Output<Node>& B,+ const ov::Output<Node>& indices,+ const ov::Output<Node>& bias,+ const ov::Output<Node>& weight_scales,+ const ov::Output<Node>& weight_zero_points);++ std::shared_ptr<Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;++ void validate_and_infer_types() override;+};++} // namespace ov::op::internaldiff --git a/src/common/transformations/include/ov_ops/moe_compressed.hpp b/src/common/transformations/include/ov_ops/moe_compressed.hppnew file mode 100644index 00000000000..d68ebd01e42--- /dev/null+++ b/src/common/transformations/include/ov_ops/moe_compressed.hpp@@ -0,0 +1,93 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/op/moe.hpp"+#include "openvino/op/op.hpp"+#include "transformations_visibility.hpp"++namespace ov::op::internal {++/// \brief MOECompressed experts that support compressed weights for GEMM3_SWIGLU MOE.+class TRANSFORMATIONS_API MOECompressed : public ov::op::internal::MOE {+public:+ OPENVINO_OP("MOECompressed", "", ov::op::internal::MOE);++ enum class RoutingType { SOFTMAX, SIGMOID_BIAS };++ struct Config : public MOE::Config {+ size_t hidden_size = 0;+ size_t inter_size = 0;+ size_t num_expert = 0;+ size_t num_shared_expert = 0;+ size_t top_k = 0;+ // numeric_limits<size_t>::max() means per_channel compression (single group).+ // other non-zero value means group compression with this given group_size.+ size_t group_size = 0;+ // In CB, intermediate shapes are expanded to {SeqLen, 1, HiddenSize}+ // In Non-CB, intermediate shapes are expanded to {Batch, SeqLen, HiddenSize}+ size_t has_batch_dim = 0;+ bool has_zp = false;+ ov::element::Type out_type = ov::element::dynamic;+ RoutingType routing_type = RoutingType::SOFTMAX;+ };++ /// \brief Constructs a MOECompressed operation with config only+ /// \param args The input tensors, in the following order:+ /// 0: hidden_states - input tensor with hidden representations+ /// 1: routing_weights - normalized routing weights for selected experts.+ /// Supports both:+ /// * legacy "scattered" layout: [num_experts, ...] (one slice per expert)+ /// * compact post-GatherMatmul layout, consistent with ov::op::MOE+ /// routing_weights as documented in openvino/op/moe.hpp.+ /// In all cases, the layout must be compatible with router_topk_output_indices+ /// and the MOE configuration (top_k, num_expert, etc.).+ /// 2: router_topk_output_indices - [..., topk] indices of selected top-k experts+ /// 3: w0_weight - expert weights for first projection,+ /// shape [num_experts, inter_size, group_num, group_size]+ /// 4: w0_scale - expert scale for first projection for compressed experts,+ /// shape [num_experts, inter_size, group_num, 1]+ /// 5: w0_zp - expert zp for first projection for compressed experts,+ /// shape [num_experts, inter_size, group_num, 1]+ /// 6: w1_weight - expert weights for second projection,+ /// shape [num_experts, inter_size, group_num, group_size]+ /// 7: w1_scale - expert scale for second projection for compressed experts,+ /// shape [num_experts, inter_size, group_num, 1]+ /// 8: w1_zp - expert zp for second projection for compressed experts,+ /// shape [num_experts, inter_size, group_num, 1]+ /// 9: w2_weight - expert weights for final projection,+ /// shape [num_experts, hidden_size, group_num, group_size]+ /// 10: w2_scale - expert scale for final projection for compressed experts,+ /// shape [num_experts, hidden_size, group_num, 1]+ /// 11: w2_zp - expert zp for final projection for compressed experts,+ /// shape [num_experts, hidden_size, group_num, 1]+ /// \param config Configuration for the MOE operation+ MOECompressed(const OutputVector& args, const Config& config);++ bool visit_attributes(AttributeVisitor& visitor) override;+ void validate_and_infer_types() override;+ std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& new_args) const override;++protected:+ Config m_config;+};++TRANSFORMATIONS_API std::ostream& operator<<(std::ostream& s, const MOECompressed::RoutingType& type);++} // namespace ov::op::internal++namespace ov {+template <>+class AttributeAdapter<ov::op::internal::MOECompressed::RoutingType>+ : public EnumAttributeAdapterBase<ov::op::internal::MOECompressed::RoutingType> {+public:+ AttributeAdapter(ov::op::internal::MOECompressed::RoutingType& value)+ : EnumAttributeAdapterBase<ov::op::internal::MOECompressed::RoutingType>(value) {}++ OPENVINO_RTTI("AttributeAdapter<ov::op::internal::MOECompressed::RoutingType>");+ ~AttributeAdapter() override = default;+};++} // namespace ovdiff --git a/src/common/transformations/include/transformations/common_optimizations/convert_tiled_moe_block_to_gather_matmuls.hpp b/src/common/transformations/include/transformations/common_optimizations/convert_tiled_moe_block_to_gather_matmuls.hppnew file mode 100644index 00000000000..c57fbeb2501--- /dev/null+++ b/src/common/transformations/include/transformations/common_optimizations/convert_tiled_moe_block_to_gather_matmuls.hpp@@ -0,0 +1,161 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/graph_rewrite.hpp"+#include "openvino/pass/matcher_pass.hpp"+#include "transformations_visibility.hpp"++namespace ov::pass {++// BGM-producing passes (IR → GatherMatmul)+class TRANSFORMATIONS_API ConvertTiledMoeBlockTo2GatherMatmuls;+class TRANSFORMATIONS_API ConvertTiledMoeBlockTo3GatherMatmuls;++class TRANSFORMATIONS_API ConvertTiledMoeBlockToGatherMatmuls;++} // namespace ov::pass++// ============================================================================+// ConvertTiledMoeBlockTo2GatherMatmuls+// ============================================================================+//+// Matches tiled MoE blocks where gate+up are fused into a single MatMul,+// then sliced apart (common in models with combined gate/up projection).+//+// BEFORE:+//+// experts_input+// |+// Reshape+// |+// Tile (replicate across experts)+// |+// Reshape [batch*seq*n_experts, hidden]+// |+// gate_up_MatMul (transpose_b) chosen_experts+// | |+// gate_up_Add (bias, 2 consumers) ScatterElementsUpdate+// / \ |+// Slice1 Slice2 Transpose+// | | |+// Clamp Minimum Reshape+// | | |+// Add Swish (Unsqueeze)+// \ / |+// Multiply |+// | |+// down_MatMul (transpose_b) |+// | |+// down_Add (bias) |+// | |+// Reshape |+// | |+// Multiply <-----------------------------++// |+// ReduceSum (experts dim)+//+//+// AFTER:+//+// experts_input+// |+// Unsqueeze(0) active_indices chosen_experts+// | | |+// GatherMatmul_1 (gate+up weights, bias) Transpose+// / \ |+// Slice1 Slice2 Unsqueeze+// | | |+// Clamp Minimum |+// | | |+// Add Swish |+// \ / |+// Multiply |+// | active_indices |+// | | |+// GatherMatmul_2 (down weights, bias) |+// | |+// Multiply <-----------------------------++// |+// ReduceSum+// |+// Reshape (remove experts dim)+//+// ============================================================================+class ov::pass::ConvertTiledMoeBlockTo2GatherMatmuls : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("ConvertTiledMoeBlockTo2GatherMatmuls");+ ConvertTiledMoeBlockTo2GatherMatmuls();+};++// ============================================================================+// ConvertTiledMoeBlockTo3GatherMatmuls+// ============================================================================+//+// Matches tiled MoE blocks with separate gate, up, and down MatMuls+// (SwiGLU architecture — no biases, no slicing).+//+// BEFORE:+//+// experts_input+// |+// Reshape+// |+// Tile (replicate across experts)+// |+// Reshape [batch*seq*n_experts, hidden]+// / |+// gate_MatMul up_MatMul chosen_experts+// | | |+// Swish | ScatterElementsUpdate+// \ / |+// Multiply (SwiGLU) Transpose+// | |+// down_MatMul Reshape+// | |+// Reshape (Unsqueeze)+// | |+// Multiply <--- router_weights -------++// |+// ReduceSum (experts dim)+//+//+// AFTER:+//+// experts_input+// |+// Unsqueeze(0) active_indices chosen_experts+// / \ | |+// GatherMatmul_1(gate) GatherMatmul_2(up) Transpose+// | | |+// Swish | Unsqueeze+// \ / |+// Multiply (SwiGLU) |+// | active_indices |+// | | |+// GatherMatmul_3 (down weights) |+// | |+// Multiply <--------------------------------++// |+// ReduceSum+// |+// Reshape (remove experts dim)+//+// ============================================================================+class ov::pass::ConvertTiledMoeBlockTo3GatherMatmuls : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("ConvertTiledMoeBlockTo3GatherMatmuls");+ ConvertTiledMoeBlockTo3GatherMatmuls();+};++// CPU uses BGM-producing passes only (stops at BGMs)+class ov::pass::ConvertTiledMoeBlockToGatherMatmuls : public ov::pass::GraphRewrite {+public:+ OPENVINO_GRAPH_REWRITE_RTTI("ConvertTiledMoeBlockToGatherMatmuls");+ ConvertTiledMoeBlockToGatherMatmuls() {+ add_matcher<ov::pass::ConvertTiledMoeBlockTo2GatherMatmuls>();+ add_matcher<ov::pass::ConvertTiledMoeBlockTo3GatherMatmuls>();+ }+};diff --git a/src/common/transformations/include/transformations/common_optimizations/moe_op_fusion.hpp b/src/common/transformations/include/transformations/common_optimizations/moe_op_fusion.hppnew file mode 100644index 00000000000..4077af934f4--- /dev/null+++ b/src/common/transformations/include/transformations/common_optimizations/moe_op_fusion.hpp@@ -0,0 +1,41 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/graph_rewrite.hpp"+#include "openvino/pass/matcher_pass.hpp"+#include "transformations_visibility.hpp"++namespace ov::pass {++// BGM→MOE passes (GatherMatmul graph → MOE op, used by GPU)+class TRANSFORMATIONS_API Convert2GatherMatmulMoeBlockToMoeOp;+class TRANSFORMATIONS_API Convert3GatherMatmulMoeBlockToMoeOp;+class TRANSFORMATIONS_API MoeOpFusion;++} // namespace ov::pass++// BGM→MOE passes — convert post-BGM graph (GatherMatmul + compact routing) to MOE op.+// When BGMCompressed nodes are present, produces MOECompressed instead of MOE.+class ov::pass::Convert2GatherMatmulMoeBlockToMoeOp : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("Convert2GatherMatmulMoeBlockToMoeOp");+ Convert2GatherMatmulMoeBlockToMoeOp(size_t has_batch_dim = 1);+};++class ov::pass::Convert3GatherMatmulMoeBlockToMoeOp : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("Convert3GatherMatmulMoeBlockToMoeOp");+ Convert3GatherMatmulMoeBlockToMoeOp(size_t has_batch_dim = 1);+};++class ov::pass::MoeOpFusion : public ov::pass::GraphRewrite {+public:+ OPENVINO_GRAPH_REWRITE_RTTI("MoeOpFusion");+ MoeOpFusion(size_t has_batch_dim = 1) {+ add_matcher<ov::pass::Convert2GatherMatmulMoeBlockToMoeOp>(has_batch_dim);+ add_matcher<ov::pass::Convert3GatherMatmulMoeBlockToMoeOp>(has_batch_dim);+ }+};diff --git a/src/common/transformations/include/transformations/op_conversions/convert_gather_matmul_to_compressed.hpp b/src/common/transformations/include/transformations/op_conversions/convert_gather_matmul_to_compressed.hppnew file mode 100644index 00000000000..3ae9b109e0d--- /dev/null+++ b/src/common/transformations/include/transformations/op_conversions/convert_gather_matmul_to_compressed.hpp@@ -0,0 +1,68 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <functional>+#include <memory>+#include <vector>++#include "openvino/pass/matcher_pass.hpp"+#include "ov_ops/gather_matmul_compressed.hpp"+#include "transformations_visibility.hpp"++namespace ov::pass {++// ============================================================================+// ConvertGatherMatmulToGatherMatmulCompressed+// ============================================================================+//+// Folds the compressed-weights dequantization subgraph on GatherMatmul's+// weight input into a single GatherMatmulCompressed op with explicit+// scale (and optional zero-point) inputs.+//+// BEFORE:+//+// activation weights(u4/u8/i4/i8) indices bias+// | | | |+// | Convert(f16/f32) | |+// | | | |+// | (Subtract(zp))? | |+// | | | |+// | Multiply(scale) | |+// | | | |+// | (Reshape)? | |+// | | | |+// | (Transpose)? | |+// | | | |+// | (Convert)? | |+// | | | |+// +------GatherMatmul---------------+--------++// |+// output+//+//+// AFTER:+//+// activation weights(u4/u8) indices bias scale (zp)?+// | | | | | |+// +----GatherMatmulCompressed---------+-------+-------++// |+// output+//+// ============================================================================+class TRANSFORMATIONS_API ConvertGatherMatmulToGatherMatmulCompressed : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("ConvertGatherMatmulToGatherMatmulCompressed");++ using SupportsPredicate =+ std::function<bool(const std::shared_ptr<ov::op::internal::GatherMatmulCompressed>&, size_t, size_t, size_t)>;++ ConvertGatherMatmulToGatherMatmulCompressed(const std::vector<ov::element::Type>& supported_activation_types,+ const std::vector<ov::element::Type>& supported_weights_types,+ const SupportsPredicate& supports_config = nullptr,+ bool convert_u4zp_to_u8 = false);+};++} // namespace ov::passdiff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul.cpp b/src/common/transformations/src/ov_ops/gather_matmul.cppsimilarity index 71%rename from src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul.cpprename to src/common/transformations/src/ov_ops/gather_matmul.cppindex 61d24cb325d..c1c4d2c43be 100644--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul.cpp+++ b/src/common/transformations/src/ov_ops/gather_matmul.cpp@@ -2,7 +2,7 @@// SPDX-License-Identifier: Apache-2.0//-#include "batch_gather_matmul.hpp"+#include "ov_ops/gather_matmul.hpp"#include <cstddef>#include <memory>@@ -17,35 +17,26 @@#include "openvino/op/constant.hpp"#include "openvino/op/matmul.hpp"#include "openvino/op/op.hpp"-#include "transformations/itt.hpp"-#include "transformations/utils/utils.hpp"-namespace ov::intel_cpu {+namespace ov::op::internal {-BatchGatherMatmul::BatchGatherMatmul(const ov::Output<Node>& A,- const ov::Output<Node>& B,- const ov::Output<Node>& indices,- const ov::Output<Node>& bias)+GatherMatmul::GatherMatmul(const ov::Output<Node>& A,+ const ov::Output<Node>& B,+ const ov::Output<Node>& indices,+ const ov::Output<Node>& bias): Op({A, B, indices, bias}) {validate_and_infer_types();}-BatchGatherMatmul::BatchGatherMatmul(const ov::Output<Node>& A,- const ov::Output<Node>& B,- const ov::Output<Node>& indices)- : BatchGatherMatmul(A, B, indices, std::make_shared<ov::op::v0::Constant>(element::dynamic, Shape{0})) {}+GatherMatmul::GatherMatmul(const ov::Output<Node>& A, const ov::Output<Node>& B, const ov::Output<Node>& indices)+ : GatherMatmul(A, B, indices, std::make_shared<ov::op::v0::Constant>(element::dynamic, Shape{0})) {}-std::shared_ptr<ov::Node> BatchGatherMatmul::clone_with_new_inputs(const ov::OutputVector& new_args) const {- INTERNAL_OP_SCOPE(GroupGatherMatmul_with_new_inputs);+std::shared_ptr<ov::Node> GatherMatmul::clone_with_new_inputs(const ov::OutputVector& new_args) const {check_new_args_count(this, new_args);- return std::make_shared<ov::intel_cpu::BatchGatherMatmul>(new_args.at(0),- new_args.at(1),- new_args.at(2),- new_args.at(3));+ return std::make_shared<GatherMatmul>(new_args.at(0), new_args.at(1), new_args.at(2), new_args.at(3));}-void BatchGatherMatmul::validate_and_infer_types() {- INTERNAL_OP_SCOPE(GroupGatherMatmul_validate_and_infer_types);+void GatherMatmul::validate_and_infer_types() {const auto input_size = get_input_size();NODE_VALIDATION_CHECK(this,input_size >= 4,@@ -53,11 +44,6 @@ void BatchGatherMatmul::validate_and_infer_types() {input_size,", expected at least 4.");- // Check input B is on constant path- NODE_VALIDATION_CHECK(this,- ov::op::util::is_on_path<ov::op::v0::Constant>(input_value(1)),- "Input B must be on constant path.");-const auto& a_shape = get_input_partial_shape(0);const auto& b_shape = get_input_partial_shape(1);const auto& indices_shape = get_input_partial_shape(2);@@ -74,7 +60,12 @@ void BatchGatherMatmul::validate_and_infer_types() {const size_t bias_rank = bias_shape.is_dynamic() ? 0 : bias_shape.size();NODE_VALIDATION_CHECK(this, a_rank == 3, "Input A rank must be exactly 3D. Got: ", a_rank, "D instead.");- NODE_VALIDATION_CHECK(this, b_rank == 3, "Input B rank must be exactly 3D. Got: ", b_rank, "D instead.");+ // 3D: [n_experts, N, K], 4D: [n_experts, N, group_num, group_size] (group-compressed)+ NODE_VALIDATION_CHECK(this,+ b_rank == 3 || b_rank == 4,+ "Input B rank must be 3D or 4D. Got: ",+ b_rank,+ "D instead.");NODE_VALIDATION_CHECK(this,indices_rank == 2,"Input indices rank must be exactly 2D. Got: ",@@ -120,12 +111,15 @@ void BatchGatherMatmul::validate_and_infer_types() {" instead.");}+ // For 4D group-compressed weights [n_experts, N, group_num, group_size], compute effective K+ const auto effective_k = (b_rank == 4) ? (b_shape[2] * b_shape[3]) : b_shape[2];+ov::op::v0::MatMul op;op.set_transpose_a(transp_a);op.set_transpose_b(transp_b);ov::PartialShape matmul_shape_a = {a_shape[1], a_shape[2]};- ov::PartialShape matmul_shape_b = {b_shape[1], b_shape[2]};+ ov::PartialShape matmul_shape_b = {b_shape[1], effective_k};auto out_matmul_shape =(ov::op::v0::shape_infer(&op, std::vector<ov::PartialShape>{matmul_shape_a, matmul_shape_b})).front();@@ -135,4 +129,4 @@ void BatchGatherMatmul::validate_and_infer_types() {set_output_type(0, get_input_element_type(0), output_shape);}-} // namespace ov::intel_cpu\ No newline at end of file+} // namespace ov::op::internaldiff --git a/src/common/transformations/src/ov_ops/gather_matmul_compressed.cpp b/src/common/transformations/src/ov_ops/gather_matmul_compressed.cppnew file mode 100644index 00000000000..196a1e12f5f--- /dev/null+++ b/src/common/transformations/src/ov_ops/gather_matmul_compressed.cpp@@ -0,0 +1,52 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "ov_ops/gather_matmul_compressed.hpp"++#include <memory>++#include "openvino/core/attribute_visitor.hpp"+#include "openvino/core/node.hpp"+#include "openvino/core/node_vector.hpp"+#include "openvino/core/type.hpp"+#include "openvino/op/constant.hpp"++namespace ov::op::internal {++GatherMatmulCompressed::GatherMatmulCompressed(const ov::Output<Node>& A,+ const ov::Output<Node>& B,+ const ov::Output<Node>& indices,+ const ov::Output<Node>& bias,+ const ov::Output<Node>& weight_scales,+ const ov::Output<Node>& weight_zero_points)+ : GatherMatmul(A, B, indices, bias) {+ set_argument(4, weight_scales);+ set_argument(5, weight_zero_points);+ validate_and_infer_types();+}++std::shared_ptr<ov::Node> GatherMatmulCompressed::clone_with_new_inputs(const ov::OutputVector& new_args) const {+ check_new_args_count(this, new_args);+ return std::make_shared<GatherMatmulCompressed>(new_args.at(0),+ new_args.at(1),+ new_args.at(2),+ new_args.at(3),+ new_args.at(4),+ new_args.at(5));+}++void GatherMatmulCompressed::validate_and_infer_types() {+ const auto input_size = get_input_size();+ NODE_VALIDATION_CHECK(this, input_size == 6, "Number of inputs is incorrect. Current value is: ", input_size);++ // Check weight_scales and weight_zero_points are on constant path+ NODE_VALIDATION_CHECK(this,+ ov::is_type<ov::op::v0::Constant>(get_input_node_shared_ptr(4)),+ "Input weight_scales must be a Constant node.");+ NODE_VALIDATION_CHECK(this,+ ov::is_type<ov::op::v0::Constant>(get_input_node_shared_ptr(5)),+ "Input weight_zero_points must be a Constant node.");+ GatherMatmul::validate_and_infer_types();+}+} // namespace ov::op::internaldiff --git a/src/common/transformations/src/ov_ops/moe_compressed.cpp b/src/common/transformations/src/ov_ops/moe_compressed.cppnew file mode 100644index 00000000000..743d484a4f0--- /dev/null+++ b/src/common/transformations/src/ov_ops/moe_compressed.cpp@@ -0,0 +1,58 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "ov_ops/moe_compressed.hpp"++namespace ov::op::internal {++MOECompressed::MOECompressed(const OutputVector& args, const Config& config) : MOE(args, config), m_config(config) {+ constructor_validate_and_infer_types();+}++std::shared_ptr<ov::Node> MOECompressed::clone_with_new_inputs(const ov::OutputVector& new_args) const {+ check_new_args_count(this, new_args);++ return std::make_shared<MOECompressed>(new_args, m_config);+}++void MOECompressed::validate_and_infer_types() {+ auto output_type = m_config.out_type == ov::element::dynamic ? get_input_element_type(0) : m_config.out_type;++ set_output_type(0, output_type, get_input_partial_shape(0));+}++bool MOECompressed::visit_attributes(ov::AttributeVisitor& visitor) {+ MOE::visit_attributes(visitor);+ visitor.on_attribute("hidden_size", m_config.hidden_size);+ visitor.on_attribute("inter_size", m_config.inter_size);+ visitor.on_attribute("num_expert", m_config.num_expert);+ visitor.on_attribute("num_shared_expert", m_config.num_shared_expert);+ visitor.on_attribute("top_k", m_config.top_k);+ visitor.on_attribute("group_size", m_config.group_size);+ visitor.on_attribute("has_batch_dim", m_config.has_batch_dim);+ visitor.on_attribute("has_zp", m_config.has_zp);+ visitor.on_attribute("out_type", m_config.out_type);+ visitor.on_attribute("routing_type", m_config.routing_type);+ return true;+}++std::ostream& operator<<(std::ostream& s, const MOECompressed::RoutingType& type) {+ return s << as_string(type);+}++} // namespace ov::op::internal++namespace ov {+using RoutingType = ov::op::internal::MOECompressed::RoutingType;+template <>+EnumNames<RoutingType>& EnumNames<RoutingType>::get() {+ static auto enum_names = EnumNames<RoutingType>("MOECompressed::RoutingType",+ {+ {"softmax", RoutingType::SOFTMAX},+ {"sigmoid_bias", RoutingType::SIGMOID_BIAS},+ });+ return enum_names;+}++} // namespace ovdiff --git a/src/common/transformations/src/transformations/common_optimizations/convert_tiled_moe_block_to_gather_matmuls.cpp b/src/common/transformations/src/transformations/common_optimizations/convert_tiled_moe_block_to_gather_matmuls.cppnew file mode 100644index 00000000000..900771a263d--- /dev/null+++ b/src/common/transformations/src/transformations/common_optimizations/convert_tiled_moe_block_to_gather_matmuls.cpp@@ -0,0 +1,359 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "transformations/common_optimizations/convert_tiled_moe_block_to_gather_matmuls.hpp"++#include <initializer_list>++#include "itt.hpp"+#include "openvino/core/graph_util.hpp"+#include "openvino/core/rt_info.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/clamp.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/minimum.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/reduce_sum.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/scatter_elements_update.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/op/swish.hpp"+#include "openvino/op/tile.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/op/unsqueeze.hpp"+#include "openvino/pass/pattern/matcher.hpp"+#include "openvino/pass/pattern/op/optional.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "ov_ops/gather_matmul.hpp"++namespace {+using namespace ov::pass;++namespace v0 = ov::op::v0;+namespace v1 = ov::op::v1;+namespace v3 = ov::op::v3;+namespace v4 = ov::op::v4;+namespace v8 = ov::op::v8;+namespace v12 = ov::op::v12;++// Note: intermediate nodes remain unchanged,+// but we need to explicitly call shape inference for them to keep shapes consistency+void validate_nodes(const pattern::PatternValueMap& map, const std::initializer_list<std::shared_ptr<ov::Node>> nodes) {+ for (const auto& node : nodes) {+ map.at(node).get_node_shared_ptr()->validate_and_infer_types();+ }+};++std::shared_ptr<ov::op::v0::Unsqueeze> introduce_n_experts_dim(const ov::Output<ov::Node>& data) {+ auto zero_const = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{}, 0);+ auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(data, zero_const);+ ov::copy_runtime_info(data.get_node_shared_ptr(), {unsqueeze, zero_const});+ return unsqueeze;+}++// --- Shared pattern node containers ---++struct MOE2GEMMPatternNodes {+ std::shared_ptr<ov::Node> experts_input, tile, after_tile_reshape;+ std::shared_ptr<ov::Node> gate_up_matmul, gate_up_add, gate_up_bias;+ std::shared_ptr<ov::Node> slice1, clamp, add1, slice2, minimum1, swish_beta, swish, multiply2;+ std::shared_ptr<ov::Node> down_proj_matmul, down_proj_bias, down_proj_add;+ std::shared_ptr<ov::Node> end_reshape_target_shape, end_reshape;+ std::shared_ptr<ov::Node> router_topk_indices, chosen_experts, scatter_elements_update;+ std::shared_ptr<ov::Node> router_transpose, router_reshape, optional_unsqueeze;+ std::shared_ptr<ov::Node> mul3, reduce_sum;+};++MOE2GEMMPatternNodes build_2gemm_pattern() {+ MOE2GEMMPatternNodes p;++ p.experts_input = pattern::wrap_type<v1::Reshape>({pattern::any_input(), pattern::any_input()});+ p.tile = pattern::wrap_type<v0::Tile>({p.experts_input, pattern::any_input()});+ p.after_tile_reshape = pattern::wrap_type<v1::Reshape>({p.tile, pattern::any_input()});+ p.gate_up_matmul = pattern::wrap_type<v0::MatMul>(+ {p.after_tile_reshape, pattern::any_input()},+ pattern::consumers_count(1) && pattern::attrs_match({{"transpose_a", false}, {"transpose_b", true}}));+ p.gate_up_bias = pattern::wrap_const();+ p.gate_up_add = pattern::wrap_type<v1::Add>({p.gate_up_matmul, p.gate_up_bias}, pattern::consumers_count(2));++ // Branch 1: Slice_1 -> Clamp -> Add_1+ p.slice1 = pattern::wrap_type<v8::Slice>(+ {p.gate_up_add, pattern::any_input(), pattern::any_input(), pattern::any_input(), pattern::any_input()});+ p.clamp = pattern::wrap_type<v0::Clamp>({p.slice1});+ p.add1 = pattern::wrap_type<v1::Add>({p.clamp, pattern::wrap_const()});++ // Branch 2: Slice_2 -> Minimum_1 -> Swish+ p.slice2 = pattern::wrap_type<v8::Slice>(+ {p.gate_up_add, pattern::any_input(), pattern::any_input(), pattern::any_input(), pattern::any_input()});+ p.minimum1 = pattern::wrap_type<v1::Minimum>({p.slice2, pattern::wrap_const()});+ p.swish_beta = pattern::wrap_const();+ p.swish = pattern::wrap_type<v4::Swish>({p.minimum1, p.swish_beta});++ // Join: Multiply_2+ p.multiply2 = pattern::wrap_type<v1::Multiply>({p.add1, p.swish});++ // Down projection+ p.down_proj_matmul = pattern::wrap_type<v0::MatMul>(+ {p.multiply2, pattern::any_input()},+ pattern::consumers_count(1) && pattern::attrs_match({{"transpose_a", false}, {"transpose_b", true}}));+ p.down_proj_bias = pattern::wrap_const();+ p.down_proj_add = pattern::wrap_type<v1::Add>({p.down_proj_matmul, p.down_proj_bias});+ p.end_reshape_target_shape = pattern::any_input();+ p.end_reshape = pattern::wrap_type<v1::Reshape>({p.down_proj_add, p.end_reshape_target_shape});++ // Routing weights/mask+ p.router_topk_indices = pattern::any_input();+ p.chosen_experts = pattern::any_input();+ p.scatter_elements_update = pattern::wrap_type<v3::ScatterElementsUpdate, v12::ScatterElementsUpdate>(+ {pattern::any_input(), p.router_topk_indices, p.chosen_experts, pattern::any_input()});++ p.router_transpose = pattern::wrap_type<v1::Transpose>({p.scatter_elements_update, pattern::any_input()});+ p.router_reshape = pattern::wrap_type<v1::Reshape>({p.router_transpose, pattern::any_input()});+ p.optional_unsqueeze = pattern::optional<v0::Unsqueeze>({p.router_reshape, pattern::any_input()});++ p.mul3 = pattern::wrap_type<v1::Multiply>({p.end_reshape, p.optional_unsqueeze});+ p.reduce_sum = pattern::wrap_type<v1::ReduceSum>({p.mul3, pattern::any_input()}, {{"keep_dims", false}});++ return p;+}++struct MOE3GEMMPatternNodes {+ std::shared_ptr<ov::Node> experts_input, tile, after_tile_reshape;+ std::shared_ptr<ov::Node> gate_matmul, swish, up_matmul, swiglu;+ std::shared_ptr<ov::Node> down_matmul;+ std::shared_ptr<ov::Node> end_reshape_target_shape, end_reshape;+ std::shared_ptr<ov::Node> router_topk_indices, chosen_experts, scatter_elements_update;+ std::shared_ptr<ov::Node> router_transpose, router_reshape, optional_unsqueeze;+ std::shared_ptr<ov::Node> mul3, reduce_sum;+};++MOE3GEMMPatternNodes build_3gemm_pattern() {+ MOE3GEMMPatternNodes p;++ p.experts_input = pattern::wrap_type<v1::Reshape>({pattern::any_input(), pattern::any_input()});+ p.tile = pattern::wrap_type<v0::Tile>({p.experts_input, pattern::any_input()});+ p.after_tile_reshape = pattern::wrap_type<v1::Reshape>({p.tile, pattern::any_input()});++ // First GEMM (activation gate)+ p.gate_matmul = pattern::wrap_type<v0::MatMul>(+ {p.after_tile_reshape, pattern::any_input()},+ pattern::consumers_count(1) && pattern::attrs_match({{"transpose_a", false}, {"transpose_b", true}}));+ p.swish = pattern::wrap_type<v4::Swish>({p.gate_matmul});+ // Second GEMM (up_projection)+ p.up_matmul = pattern::wrap_type<v0::MatMul>(+ {p.after_tile_reshape, pattern::any_input()},+ pattern::consumers_count(1) && pattern::attrs_match({{"transpose_a", false}, {"transpose_b", true}}));+ // Join: Multiply (SwiGLU)+ p.swiglu = pattern::wrap_type<v1::Multiply>({p.swish, p.up_matmul});++ // Third GEMM (down_projection)+ p.down_matmul = pattern::wrap_type<v0::MatMul>(+ {p.swiglu, pattern::any_input()},+ pattern::consumers_count(1) && pattern::attrs_match({{"transpose_a", false}, {"transpose_b", true}}));+ p.end_reshape_target_shape = pattern::any_input();+ p.end_reshape = pattern::wrap_type<v1::Reshape>({p.down_matmul, p.end_reshape_target_shape});++ // Routing weights/mask+ p.router_topk_indices = pattern::any_input();+ p.chosen_experts = pattern::any_input();+ p.scatter_elements_update = pattern::wrap_type<v3::ScatterElementsUpdate, v12::ScatterElementsUpdate>(+ {pattern::any_input(), p.router_topk_indices, p.chosen_experts, pattern::any_input()});+ p.router_transpose = pattern::wrap_type<v1::Transpose>({p.scatter_elements_update, pattern::any_input()});+ p.router_reshape = pattern::wrap_type<v1::Reshape>({p.router_transpose, pattern::any_input()});+ p.optional_unsqueeze = pattern::optional<v0::Unsqueeze>({p.router_reshape, pattern::any_input()});++ p.mul3 = pattern::wrap_type<v1::Multiply>({p.end_reshape, p.optional_unsqueeze});+ p.reduce_sum = pattern::wrap_type<v1::ReduceSum>({p.mul3, pattern::any_input()}, {{"keep_dims", false}});++ return p;+}++} // namespace++namespace ov::pass {++using ov::op::internal::GatherMatmul;++// ============================================================================+// BGM-producing passes (IR → GatherMatmul)+// ============================================================================++ConvertTiledMoeBlockTo2GatherMatmuls::ConvertTiledMoeBlockTo2GatherMatmuls() {+ MATCHER_SCOPE(ConvertTiledMoeBlockTo2GatherMatmuls);++ auto p = build_2gemm_pattern();++ matcher_pass_callback callback = [=](pattern::Matcher& m) {+ auto& pm = m.get_pattern_value_map();++ if (transformation_callback(m.get_match_root())) {+ return false;+ }++ const auto& experts_subgraph_input = pm.at(p.experts_input);+ const auto& active_indices = pm.at(p.router_topk_indices);++ const auto gate_up_mm_node = pm.at(p.gate_up_matmul).get_node_shared_ptr();+ const auto gate_up_add_node = pm.at(p.gate_up_add).get_node_shared_ptr();+ const auto gate_up_bias_node = pm.at(p.gate_up_bias).get_node_shared_ptr();++ // GatherMatmul A shape: [n_activated_experts, batch_size * seq_length, hidden_size]+ // Number of activated experts is always 1 for the first GatherMatmul+ const auto unsqueeze = introduce_n_experts_dim(experts_subgraph_input);+ const auto gate_up_gathered_mm = std::make_shared<GatherMatmul>(unsqueeze,+ gate_up_mm_node->input_value(1),+ active_indices,+ gate_up_bias_node);+ ov::replace_node_update_name(gate_up_add_node, gate_up_gathered_mm);++ validate_nodes(pm, {p.slice1, p.clamp, p.add1, p.slice2, p.minimum1, p.swish, p.multiply2});++ const auto down_proj_mm_node = pm.at(p.down_proj_matmul).get_node_shared_ptr();+ const auto down_proj_bias_node = pm.at(p.down_proj_bias).get_node_shared_ptr();++ const auto down_gathered_mm = std::make_shared<GatherMatmul>(pm.at(p.multiply2),+ down_proj_mm_node->input_value(1),+ active_indices,+ down_proj_bias_node);+ ov::copy_runtime_info(down_proj_mm_node, down_gathered_mm);+ down_gathered_mm->set_friendly_name(down_proj_mm_node->get_friendly_name());++ const auto& chosen_experts_input = pm.at(p.chosen_experts);+ const auto router_transpose_node = pm.at(p.router_transpose).get_node_shared_ptr();+ const auto new_router_transpose =+ std::make_shared<v1::Transpose>(chosen_experts_input, router_transpose_node->input_value(1));+ ov::copy_runtime_info(router_transpose_node, new_router_transpose);+ new_router_transpose->set_friendly_name(router_transpose_node->get_friendly_name());++ const auto router_unsqueeze_const = v0::Constant::create(ov::element::i32, ov::Shape{}, {-1});+ const auto router_unsqueeze = std::make_shared<v0::Unsqueeze>(new_router_transpose, router_unsqueeze_const);+ ov::copy_runtime_info(router_transpose_node, {router_unsqueeze_const, router_unsqueeze});++ const auto final_mul_node = pm.at(p.mul3).get_node_shared_ptr();+ const auto new_final_mul =+ final_mul_node->clone_with_new_inputs({down_gathered_mm->output(0), router_unsqueeze->output(0)});+ ov::copy_runtime_info(final_mul_node, new_final_mul);+ new_final_mul->set_friendly_name(final_mul_node->get_friendly_name());++ const auto reduce_sum_node = pm.at(p.reduce_sum).get_node_shared_ptr();+ const auto new_reduce_sum =+ reduce_sum_node->clone_with_new_inputs({new_final_mul->output(0), reduce_sum_node->input_value(1)});+ ov::copy_runtime_info(reduce_sum_node, new_reduce_sum);+ new_reduce_sum->set_friendly_name(reduce_sum_node->get_friendly_name());++ const auto& end_reshape_out = pm.at(p.end_reshape);+ const auto end_reshape_rank = end_reshape_out.get_partial_shape().rank();+ const auto& end_reshape_shape = pm.at(p.end_reshape_target_shape);+ // n_all_experts dimension is cut off after ReduceSum+ const auto shape_slice = std::make_shared<v8::Slice>(+ end_reshape_shape,+ v0::Constant::create(ov::element::i32, ov::Shape{1}, {1}),+ v0::Constant::create(ov::element::i32, ov::Shape{1}, {end_reshape_rank.get_length()}),+ v0::Constant::create(ov::element::i32, ov::Shape{1}, {1}),+ v0::Constant::create(ov::element::i32, ov::Shape{1}, {0}));+ ov::copy_runtime_info(end_reshape_out.get_node_shared_ptr(),+ {shape_slice,+ shape_slice->get_input_node_shared_ptr(1),+ shape_slice->get_input_node_shared_ptr(2),+ shape_slice->get_input_node_shared_ptr(3),+ shape_slice->get_input_node_shared_ptr(4)});++ const auto reshape = std::make_shared<v1::Reshape>(new_reduce_sum, shape_slice, true);+ ov::replace_output_update_name(pm.at(p.reduce_sum), reshape->output(0));+ // To avoid friendly name duplication+ reshape->set_friendly_name(reshape->get_friendly_name() + "_Reshape");+ return true;+ };++ auto matcher = std::make_shared<pattern::Matcher>(p.reduce_sum, matcher_name);+ this->register_matcher(matcher, callback);+}++ConvertTiledMoeBlockTo3GatherMatmuls::ConvertTiledMoeBlockTo3GatherMatmuls() {+ MATCHER_SCOPE(ConvertTiledMoeBlockTo3GatherMatmuls);++ auto p = build_3gemm_pattern();++ matcher_pass_callback callback = [=](pattern::Matcher& m) {+ auto& pm = m.get_pattern_value_map();++ if (transformation_callback(m.get_match_root())) {+ return false;+ }++ const auto& experts_subgraph_input = pm.at(p.experts_input);+ const auto& active_indices = pm.at(p.router_topk_indices);++ const auto gate_mm_node = pm.at(p.gate_matmul).get_node_shared_ptr();+ const auto up_mm_node = pm.at(p.up_matmul).get_node_shared_ptr();+ const auto down_mm_node = pm.at(p.down_matmul).get_node_shared_ptr();++ // GatherMatmul A shape: [n_activated_experts, batch_size * seq_length, hidden_size]+ // Number of activated experts is always 1 for the first GatherMatmul+ const auto unsqueeze = introduce_n_experts_dim(experts_subgraph_input);+ const auto gate_gathered_mm =+ std::make_shared<GatherMatmul>(unsqueeze, gate_mm_node->input_value(1), active_indices);+ const auto up_gathered_mm =+ std::make_shared<GatherMatmul>(unsqueeze, up_mm_node->input_value(1), active_indices);+ ov::replace_node_update_name(gate_mm_node, gate_gathered_mm);+ ov::replace_node_update_name(up_mm_node, up_gathered_mm);++ validate_nodes(pm, {p.swish, p.swiglu});++ const auto down_gathered_mm =+ std::make_shared<GatherMatmul>(pm.at(p.swiglu), down_mm_node->input_value(1), active_indices);+ ov::copy_runtime_info(down_mm_node, down_gathered_mm);+ down_gathered_mm->set_friendly_name(down_mm_node->get_friendly_name());++ const auto& chosen_experts_input = pm.at(p.chosen_experts);+ const auto router_transpose_node = pm.at(p.router_transpose).get_node_shared_ptr();+ const auto new_router_transpose =+ std::make_shared<v1::Transpose>(chosen_experts_input, router_transpose_node->input_value(1));+ ov::copy_runtime_info(router_transpose_node, new_router_transpose);+ new_router_transpose->set_friendly_name(router_transpose_node->get_friendly_name());++ const auto router_unsqueeze_const = v0::Constant::create(ov::element::i32, ov::Shape{}, {-1});+ const auto router_unsqueeze = std::make_shared<v0::Unsqueeze>(new_router_transpose, router_unsqueeze_const);+ ov::copy_runtime_info(router_transpose_node, {router_unsqueeze_const, router_unsqueeze});++ const auto final_mul_node = pm.at(p.mul3).get_node_shared_ptr();+ const auto new_final_mul =+ final_mul_node->clone_with_new_inputs({down_gathered_mm->output(0), router_unsqueeze->output(0)});+ ov::copy_runtime_info(final_mul_node, new_final_mul);+ new_final_mul->set_friendly_name(final_mul_node->get_friendly_name());+ const auto reduce_sum_node = pm.at(p.reduce_sum).get_node_shared_ptr();+ const auto new_reduce_sum =+ reduce_sum_node->clone_with_new_inputs({new_final_mul->output(0), reduce_sum_node->input_value(1)});+ ov::copy_runtime_info(reduce_sum_node, new_reduce_sum);+ new_reduce_sum->set_friendly_name(reduce_sum_node->get_friendly_name());++ const auto& end_reshape_out = pm.at(p.end_reshape);+ const auto end_reshape_rank = end_reshape_out.get_partial_shape().rank();+ const auto& end_reshape_shape = pm.at(p.end_reshape_target_shape);+ // n_all_experts dimension is cut off after ReduceSum+ const auto shape_slice = std::make_shared<v8::Slice>(+ end_reshape_shape,+ v0::Constant::create(ov::element::i32, ov::Shape{1}, {1}),+ v0::Constant::create(ov::element::i32, ov::Shape{1}, {end_reshape_rank.get_length()}),+ v0::Constant::create(ov::element::i32, ov::Shape{1}, {1}),+ v0::Constant::create(ov::element::i32, ov::Shape{1}, {0}));+ ov::copy_runtime_info(end_reshape_out.get_node_shared_ptr(),+ {shape_slice,+ shape_slice->get_input_node_shared_ptr(1),+ shape_slice->get_input_node_shared_ptr(2),+ shape_slice->get_input_node_shared_ptr(3),+ shape_slice->get_input_node_shared_ptr(4)});++ const auto reshape = std::make_shared<v1::Reshape>(new_reduce_sum, shape_slice, true);+ ov::replace_output_update_name(pm.at(p.reduce_sum), reshape->output(0));+ reshape->set_friendly_name(new_reduce_sum->get_friendly_name() + "_Reshape");+ return true;+ };++ auto matcher = std::make_shared<pattern::Matcher>(p.reduce_sum, matcher_name);+ this->register_matcher(matcher, callback);+}++} // namespace ov::passdiff --git a/src/common/transformations/src/transformations/common_optimizations/moe_op_fusion.cpp b/src/common/transformations/src/transformations/common_optimizations/moe_op_fusion.cppnew file mode 100644index 00000000000..27b6c0cf369--- /dev/null+++ b/src/common/transformations/src/transformations/common_optimizations/moe_op_fusion.cpp@@ -0,0 +1,375 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "transformations/common_optimizations/moe_op_fusion.hpp"++#include <limits>++#include "itt.hpp"+#include "openvino/core/graph_util.hpp"+#include "openvino/core/rt_info.hpp"+#include "openvino/core/type/element_type.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/clamp.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/minimum.hpp"+#include "openvino/op/moe.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/reduce_sum.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/op/swish.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/op/unsqueeze.hpp"+#include "openvino/pass/pattern/matcher.hpp"+#include "openvino/pass/pattern/op/or.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "ov_ops/gather_matmul.hpp"+#include "ov_ops/gather_matmul_compressed.hpp"+#include "ov_ops/moe_compressed.hpp"++namespace ov::pass {++using ov::op::internal::GatherMatmul;+using ov::op::internal::GatherMatmulCompressed;+using ov::op::internal::MOECompressed;++namespace v0 = ov::op::v0;+namespace v1 = ov::op::v1;+namespace v4 = ov::op::v4;+namespace v8 = ov::op::v8;++Convert3GatherMatmulMoeBlockToMoeOp::Convert3GatherMatmulMoeBlockToMoeOp(size_t has_batch_dim) {+ MATCHER_SCOPE(Convert3GatherMatmulMoeBlockToMoeOp);++ auto experts_reshape_m = pattern::any_input();+ auto unsqueeze_m = pattern::wrap_type<v0::Unsqueeze>({experts_reshape_m, pattern::any_input()});++ auto gate_w_m = pattern::any_input();+ auto topk_indices_m = pattern::any_input();++ // Plain BGM (4 inputs: A, B, indices, bias)+ auto bgm_gate_4_m = pattern::wrap_type<GatherMatmul>({unsqueeze_m, gate_w_m, topk_indices_m, pattern::any_input()});+ // Compressed BGM (6 inputs: A, B, indices, bias, scale, zp)+ auto gate_scale_m = pattern::any_input();+ auto gate_zp_m = pattern::any_input();+ auto bgm_gate_6_m = pattern::wrap_type<GatherMatmulCompressed>(+ {unsqueeze_m, gate_w_m, topk_indices_m, pattern::any_input(), gate_scale_m, gate_zp_m});+ // Or-pattern+ auto bgm_gate_m = std::make_shared<pattern::op::Or>(OutputVector{bgm_gate_4_m, bgm_gate_6_m});++ auto swish_m = pattern::wrap_type<v4::Swish>({bgm_gate_m});++ auto up_w_m = pattern::any_input();+ auto bgm_up_4_m = pattern::wrap_type<GatherMatmul>({unsqueeze_m, up_w_m, topk_indices_m, pattern::any_input()});+ auto up_scale_m = pattern::any_input();+ auto up_zp_m = pattern::any_input();+ auto bgm_up_6_m = pattern::wrap_type<GatherMatmulCompressed>(+ {unsqueeze_m, up_w_m, topk_indices_m, pattern::any_input(), up_scale_m, up_zp_m});+ auto bgm_up_m = std::make_shared<pattern::op::Or>(OutputVector{bgm_up_4_m, bgm_up_6_m});++ auto swiglu_m = pattern::wrap_type<v1::Multiply>({swish_m, bgm_up_m});++ auto down_w_m = pattern::any_input();+ auto bgm_down_4_m = pattern::wrap_type<GatherMatmul>({swiglu_m, down_w_m, topk_indices_m, pattern::any_input()});+ auto down_scale_m = pattern::any_input();+ auto down_zp_m = pattern::any_input();+ auto bgm_down_6_m = pattern::wrap_type<GatherMatmulCompressed>(+ {swiglu_m, down_w_m, topk_indices_m, pattern::any_input(), down_scale_m, down_zp_m});+ auto bgm_down_m = std::make_shared<pattern::op::Or>(OutputVector{bgm_down_4_m, bgm_down_6_m});++ // Compact routing: Transpose → Unsqueeze+ auto routing_transpose_m = pattern::wrap_type<v1::Transpose>({pattern::any_input(), pattern::any_input()});+ auto routing_unsqueeze_m = pattern::wrap_type<v0::Unsqueeze>({routing_transpose_m, pattern::any_input()});++ auto final_mul_m = pattern::wrap_type<v1::Multiply>({bgm_down_m, routing_unsqueeze_m}, pattern::consumers_count(1));+ auto reduce_sum_m = pattern::wrap_type<v1::ReduceSum>({final_mul_m, pattern::any_input()}, {{"keep_dims", false}});+ auto end_reshape_shape_m = pattern::any_input();+ auto end_reshape_m = pattern::wrap_type<v1::Reshape>({reduce_sum_m, end_reshape_shape_m});++ matcher_pass_callback callback = [=](pattern::Matcher& m) {+ auto& pm = m.get_pattern_value_map();++ if (transformation_callback(m.get_match_root())) {+ return false;+ }++ auto experts_reshape_node = pm.at(experts_reshape_m).get_node_shared_ptr();+ auto hidden_states = experts_reshape_node->input_value(0);++ auto routing = pm.at(routing_unsqueeze_m).get_node_shared_ptr();+ auto topk_indices = pm.at(topk_indices_m);+ auto gate_w = pm.at(gate_w_m);+ auto up_w = pm.at(up_w_m);+ auto down_w = pm.at(down_w_m);++ // Extract expert_beta from Swish+ float expert_beta = 1.0f;+ auto swish_node = pm.at(swish_m).get_node_shared_ptr();++ auto swish_op = ov::as_type_ptr<v4::Swish>(swish_node);+ OPENVINO_ASSERT(swish_op, "Unexpected node type matched for Swish: ", *swish_node);++ if (swish_op->get_input_size() > 1) {+ if (auto beta_const = ov::as_type_ptr<v0::Constant>(swish_op->get_input_node_shared_ptr(1))) {+ expert_beta = beta_const->cast_vector<float>()[0];+ }+ }++ std::shared_ptr<ov::Node> moe_node;+ const bool is_gate_compressed = pm.count(bgm_gate_6_m);+ const bool is_up_compressed = pm.count(bgm_up_6_m);+ const bool is_down_compressed = pm.count(bgm_down_6_m);++ // Bail out if BGMs are mixed (some compressed, some plain). The current+ // MOE/MOECompressed configs assume all-or-nothing compression.+ if ((is_gate_compressed != is_up_compressed) || (is_gate_compressed != is_down_compressed)) {+ return false;+ }++ const bool is_compressed = is_gate_compressed;++ if (is_compressed) {+ // Build MOECompressed with 12 inputs: hidden, routing, topk,+ // gate_w, gate_scale, gate_zp, up_w, up_scale, up_zp, down_w, down_scale, down_zp+ ov::OutputVector moe_inputs = {+ hidden_states,+ routing,+ topk_indices,+ gate_w,+ pm.at(gate_scale_m),+ pm.at(gate_zp_m),+ up_w,+ pm.at(up_scale_m),+ pm.at(up_zp_m),+ down_w,+ pm.at(down_scale_m),+ pm.at(down_zp_m),+ };++ // Populate compressed config from weight shapes+ auto wei_partial_shape = gate_w.get_partial_shape();+ OPENVINO_ASSERT(wei_partial_shape.is_static(), "MOE weight shape should be static.");+ auto weight_shape = wei_partial_shape.to_shape();+ bool group_compressed = (weight_shape.size() == 4);++ auto topk_shape = topk_indices.get_partial_shape();+ OPENVINO_ASSERT(topk_shape[1].is_static(), "K dimension in moe topk input should be static.");++ MOECompressed::Config compressed_config{+ {ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU, 0.0f, expert_beta},+ group_compressed ? weight_shape[2] * weight_shape[3] : weight_shape[2],+ weight_shape[1],+ weight_shape[0],+ 0, // num_shared_expert+ static_cast<size_t>(topk_shape[1].get_length()),+ group_compressed ? weight_shape[3] : std::numeric_limits<size_t>::max(),+ has_batch_dim,+ false,+ ov::element::f16,+ };++ auto moe_compressed = std::make_shared<MOECompressed>(moe_inputs, compressed_config);++ // Insert Convert if output type was forced and differs from original+ if (moe_compressed->get_output_element_type(0) != hidden_states.get_element_type()) {+ moe_compressed->set_friendly_name(m.get_match_root()->get_friendly_name() + "/MOECompressed");+ auto convert = std::make_shared<v0::Convert>(moe_compressed, hidden_states.get_element_type());+ convert->set_friendly_name(m.get_match_root()->get_friendly_name());+ ov::copy_runtime_info(m.get_matched_nodes(), {moe_compressed, convert});+ moe_node = convert;+ } else {+ moe_node = moe_compressed;+ }+ } else {+ ov::op::internal::MOE::Config config{ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU, 0.0f, expert_beta};+ // Plain MOE with 6 inputs+ ov::OutputVector moe_inputs = {hidden_states, routing, topk_indices, gate_w, up_w, down_w};++ moe_node = std::make_shared<ov::op::internal::MOE>(moe_inputs, config);+ }++ moe_node->set_friendly_name(m.get_match_root()->get_friendly_name());+ ov::copy_runtime_info(m.get_matched_nodes(), moe_node);+ ov::replace_node(m.get_match_root(), moe_node);++ register_new_node(moe_node);+ return true;+ };++ auto matcher = std::make_shared<pattern::Matcher>(end_reshape_m, matcher_name);+ this->register_matcher(matcher, callback);+}++Convert2GatherMatmulMoeBlockToMoeOp::Convert2GatherMatmulMoeBlockToMoeOp(size_t has_batch_dim) {+ MATCHER_SCOPE(Convert2GatherMatmulMoeBlockToMoeOp);++ auto experts_reshape_m = pattern::any_input();+ auto unsqueeze_m = pattern::wrap_type<v0::Unsqueeze>({experts_reshape_m, pattern::any_input()});++ auto gate_up_w_m = pattern::any_input();+ auto topk_indices_m = pattern::any_input();+ auto gate_up_bias_m = pattern::any_input();++ // Plain BGM (4 inputs)+ auto bgm_gate_up_4_m = pattern::wrap_type<GatherMatmul>({unsqueeze_m, gate_up_w_m, topk_indices_m, gate_up_bias_m});+ // Compressed BGM (6 inputs)+ auto gate_up_scale_m = pattern::any_input();+ auto gate_up_zp_m = pattern::any_input();+ auto bgm_gate_up_6_m = pattern::wrap_type<GatherMatmulCompressed>(+ {unsqueeze_m, gate_up_w_m, topk_indices_m, gate_up_bias_m, gate_up_scale_m, gate_up_zp_m});+ auto bgm_gate_up_m = bgm_gate_up_4_m | bgm_gate_up_6_m;++ // Activation subgraph between gate_up and down BGMs+ auto slice1_m = pattern::wrap_type<v8::Slice>(+ {bgm_gate_up_m, pattern::any_input(), pattern::any_input(), pattern::any_input(), pattern::any_input()});+ auto clamp_m = pattern::wrap_type<v0::Clamp>({slice1_m});+ auto add1_m = pattern::wrap_type<v1::Add>({clamp_m, pattern::wrap_const()});++ auto slice2_m = pattern::wrap_type<v8::Slice>(+ {bgm_gate_up_m, pattern::any_input(), pattern::any_input(), pattern::any_input(), pattern::any_input()});+ auto minimum1_m = pattern::wrap_type<v1::Minimum>({slice2_m, pattern::wrap_const()});+ auto swish_beta_m = pattern::wrap_const();+ auto swish_m = pattern::wrap_type<v4::Swish>({minimum1_m, swish_beta_m});++ auto multiply2_m = pattern::wrap_type<v1::Multiply>({add1_m, swish_m});++ auto down_w_m = pattern::any_input();+ auto down_bias_m = pattern::any_input();+ // Plain BGM (4 inputs)+ auto bgm_down_4_m = pattern::wrap_type<GatherMatmul>({multiply2_m, down_w_m, topk_indices_m, down_bias_m});+ // Compressed BGM (6 inputs)+ auto down_scale_m = pattern::any_input();+ auto down_zp_m = pattern::any_input();+ auto bgm_down_6_m = pattern::wrap_type<GatherMatmulCompressed>(+ {multiply2_m, down_w_m, topk_indices_m, down_bias_m, down_scale_m, down_zp_m});+ auto bgm_down_m = bgm_down_4_m | bgm_down_6_m;++ // Compact routing: Transpose → Unsqueeze+ auto routing_transpose_m = pattern::wrap_type<v1::Transpose>({pattern::any_input(), pattern::any_input()});+ auto routing_unsqueeze_m = pattern::wrap_type<v0::Unsqueeze>({routing_transpose_m, pattern::any_input()});++ auto final_mul_m = pattern::wrap_type<v1::Multiply>({bgm_down_m, routing_unsqueeze_m});+ auto reduce_sum_m = pattern::wrap_type<v1::ReduceSum>({final_mul_m, pattern::any_input()}, {{"keep_dims", false}});+ auto end_reshape_shape_m = pattern::any_input();+ auto end_reshape_m = pattern::wrap_type<v1::Reshape>({reduce_sum_m, end_reshape_shape_m});++ matcher_pass_callback callback = [=](pattern::Matcher& m) {+ auto& pm = m.get_pattern_value_map();++ if (transformation_callback(m.get_match_root())) {+ return false;+ }++ auto experts_reshape_node = pm.at(experts_reshape_m).get_node_shared_ptr();+ auto hidden_states = experts_reshape_node->input_value(0);++ auto routing = pm.at(routing_unsqueeze_m).get_node_shared_ptr();+ auto topk_indices = pm.at(topk_indices_m);+ auto gate_up_w = pm.at(gate_up_w_m);+ auto gate_up_bias = pm.at(gate_up_bias_m);+ auto down_w = pm.at(down_w_m);+ auto down_bias = pm.at(down_bias_m);++ // Extract expert_beta from Swish beta+ auto swish_beta_const = ov::as_type_ptr<v0::Constant>(pm.at(swish_beta_m).get_node_shared_ptr());+ float expert_beta = swish_beta_const->cast_vector<float>()[0];++ // Extract expert_alpha from Clamp max+ float expert_alpha = 0.0f;++ auto clamp_node = pm.at(clamp_m).get_node_shared_ptr();+ auto clamp_op = ov::as_type_ptr<v0::Clamp>(clamp_node);+ OPENVINO_ASSERT(clamp_op, "Unexpected node type matched for clamp: ", *clamp_node);++ std::shared_ptr<ov::Node> moe_node;++ const bool is_gate_up_compressed = pm.count(bgm_gate_up_6_m) > 0;+ const bool is_down_compressed = pm.count(bgm_down_6_m) > 0;++ // Bail out if BGMs are mixed (some compressed, some plain).+ if (is_gate_up_compressed != is_down_compressed) {+ return false;+ }++ const bool is_compressed = is_gate_up_compressed;+ if (is_compressed) {+ // Build MOECompressed inputs+ // GEMM2 compressed layout: hidden, routing, topk,+ // gate_up_w, gate_up_scale, [gate_up_zp,] gate_up_bias,+ // down_w, down_scale, [down_zp,] down_bias+ ov::OutputVector moe_inputs;+ moe_inputs.push_back(hidden_states);+ moe_inputs.push_back(routing);+ moe_inputs.push_back(topk_indices);++ // Absent zp is represented as Constant(element::dynamic, Shape{0})+ bool has_zp = pm.at(gate_up_zp_m).get_element_type() != ov::element::dynamic;++ // gate_up params+ moe_inputs.push_back(gate_up_w);+ moe_inputs.push_back(pm.at(gate_up_scale_m));+ if (has_zp) {+ moe_inputs.push_back(pm.at(gate_up_zp_m));+ }+ moe_inputs.push_back(gate_up_bias);++ // down params+ moe_inputs.push_back(down_w);+ moe_inputs.push_back(pm.at(down_scale_m));+ if (has_zp) {+ moe_inputs.push_back(pm.at(down_zp_m));+ }+ moe_inputs.push_back(down_bias);++ // Populate compressed config from weight shapes+ auto weight_shape = gate_up_w.get_shape();+ auto scale_shape = pm.at(gate_up_scale_m).get_shape();+ bool group_compressed = (weight_shape.size() == 4);+ size_t hidden = group_compressed ? weight_shape[2] * weight_shape[3] : weight_shape[2];++ auto topk_indices_shape = topk_indices.get_partial_shape();+ auto topk_rank = topk_indices_shape.rank().get_length();+ OPENVINO_ASSERT(topk_indices_shape[topk_rank - 1].is_static(),+ "K dimension in moe topk_indices input should be static.");++ MOECompressed::Config compressed_config{+ {ov::op::internal::MOE::Expert_type::GEMM2_BIAS_SWIGLU_CLAMP, expert_alpha, expert_beta},+ hidden,+ weight_shape[1],+ weight_shape[0],+ 0, // num_shared_expert+ static_cast<size_t>(topk_indices_shape[topk_rank - 1].get_length()),+ group_compressed ? weight_shape[3] : std::numeric_limits<size_t>::max(),+ has_batch_dim,+ has_zp,+ ov::element::dynamic,+ };++ moe_node = std::make_shared<MOECompressed>(moe_inputs, compressed_config);+ } else {+ const ov::op::internal::MOE::Config config{ov::op::internal::MOE::Expert_type::GEMM2_BIAS_SWIGLU_CLAMP,+ expert_alpha,+ expert_beta};+ // Plain MOE with 7 inputs+ const ov::OutputVector moe_inputs =+ {hidden_states, routing, topk_indices, gate_up_w, gate_up_bias, down_w, down_bias};++ moe_node = std::make_shared<ov::op::internal::MOE>(moe_inputs, config);+ }++ moe_node->set_friendly_name(m.get_match_root()->get_friendly_name());+ ov::copy_runtime_info(m.get_matched_nodes(), moe_node);+ ov::replace_node(m.get_match_root(), moe_node);++ register_new_node(moe_node);+ return true;+ };++ auto matcher = std::make_shared<pattern::Matcher>(end_reshape_m, matcher_name);+ this->register_matcher(matcher, callback);+}++} // namespace ov::passdiff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/convert_batch_gather_matmul_to_compressed.cpp b/src/common/transformations/src/transformations/op_conversions/convert_gather_matmul_to_compressed.cppsimilarity index 75%rename from src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/convert_batch_gather_matmul_to_compressed.cpprename to src/common/transformations/src/transformations/op_conversions/convert_gather_matmul_to_compressed.cppindex a7c2bc0e899..495ea4801a9 100644--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/convert_batch_gather_matmul_to_compressed.cpp+++ b/src/common/transformations/src/transformations/op_conversions/convert_gather_matmul_to_compressed.cpp@@ -2,7 +2,7 @@// SPDX-License-Identifier: Apache-2.0//-#include "convert_batch_gather_matmul_to_compressed.hpp"+#include "transformations/op_conversions/convert_gather_matmul_to_compressed.hpp"#include <cstddef>#include <memory>@@ -19,29 +19,30 @@#include "openvino/pass/pattern/op/pattern.hpp"#include "openvino/pass/pattern/op/wrap_type.hpp"#include "openvino/util/pp.hpp"-#include "transformations/cpu_opset/common/op/batch_gather_matmul.hpp"-#include "transformations/cpu_opset/common/op/batch_gather_matmul_compressed.hpp"+#include "ov_ops/gather_matmul.hpp"+#include "ov_ops/gather_matmul_compressed.hpp"#include "transformations/op_conversions/convert_fc_to_compressed.hpp"#include "transformations/pattern_blocks/compressed_weights_block.hpp"-ov::intel_cpu::ConvertBatchGatherMatmulToBatchGatherMatmulCompressed::- ConvertBatchGatherMatmulToBatchGatherMatmulCompressed(- const std::vector<ov::element::Type>& supported_activation_types,- const std::vector<ov::element::Type>& supported_weights_types,- const SupportsPredicate& supports_config,- bool convert_u4zp_to_u8) {+ov::pass::ConvertGatherMatmulToGatherMatmulCompressed::ConvertGatherMatmulToGatherMatmulCompressed(+ const std::vector<ov::element::Type>& supported_activation_types,+ const std::vector<ov::element::Type>& supported_weights_types,+ const SupportsPredicate& supports_config,+ bool convert_u4zp_to_u8) {using namespace ov::pass::pattern;+ using ov::op::internal::GatherMatmul;+ using ov::op::internal::GatherMatmulCompressed;auto activation = any_input(type_matches_any(supported_activation_types));auto weights_block =std::make_shared<ov::pass::pattern::op::CompressedWeightsBlock>(supported_weights_types, std::set<size_t>{3});auto indices = any_input();auto bias = any_input();- auto batch_gather_matmul = wrap_type<BatchGatherMatmul>({activation, weights_block, indices, bias});+ auto gather_matmul = wrap_type<GatherMatmul>({activation, weights_block, indices, bias});ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](Matcher& m) {const auto& pattern_map = m.get_pattern_value_map();- auto bgm = ov::as_type_ptr<BatchGatherMatmul>(pattern_map.at(batch_gather_matmul).get_node_shared_ptr());+ auto bgm = ov::as_type_ptr<GatherMatmul>(pattern_map.at(gather_matmul).get_node_shared_ptr());if (!bgm || transformation_callback(bgm)) {return false;}@@ -62,12 +63,12 @@ ov::intel_cpu::ConvertBatchGatherMatmulToBatchGatherMatmulCompressed::batched_weights,result_nodes);- auto new_bgm = std::make_shared<BatchGatherMatmulCompressed>(pattern_map.at(activation),- bgm_input_b,- pattern_map.at(indices),- pattern_map.at(bias),- bgm_input_scale,- bgm_input_zp);+ auto new_bgm = std::make_shared<GatherMatmulCompressed>(pattern_map.at(activation),+ bgm_input_b,+ pattern_map.at(indices),+ pattern_map.at(bias),+ bgm_input_scale,+ bgm_input_zp);const size_t IC = *(weights_shape.rbegin());const size_t OC = *(weights_shape.rbegin() + 1);@@ -86,6 +87,6 @@ ov::intel_cpu::ConvertBatchGatherMatmulToBatchGatherMatmulCompressed::return true;};- auto m = std::make_shared<Matcher>(batch_gather_matmul, "ConvertBatchGatherMatmulToBatchGatherMatmulCompressed");+ auto m = std::make_shared<Matcher>(gather_matmul, "ConvertGatherMatmulToGatherMatmulCompressed");this->register_matcher(m, callback);-}\ No newline at end of file+}diff --git a/src/common/transformations/tests/common_optimizations/fuse_vectorized_moe_test.cpp b/src/common/transformations/tests/common_optimizations/convert_gather_matmuls_moe_block_to_moe_op.cppsimilarity index 54%rename from src/common/transformations/tests/common_optimizations/fuse_vectorized_moe_test.cpprename to src/common/transformations/tests/common_optimizations/convert_gather_matmuls_moe_block_to_moe_op.cppindex c5db2f978c9..51232e90abd 100644--- a/src/common/transformations/tests/common_optimizations/fuse_vectorized_moe_test.cpp+++ b/src/common/transformations/tests/common_optimizations/convert_gather_matmuls_moe_block_to_moe_op.cpp@@ -8,6 +8,7 @@#include <openvino/core/model.hpp>#include <openvino/op/add.hpp>#include <openvino/op/clamp.hpp>+#include <openvino/op/concat.hpp>#include <openvino/op/constant.hpp>#include <openvino/op/matmul.hpp>#include <openvino/op/minimum.hpp>@@ -20,11 +21,11 @@#include <openvino/op/swish.hpp>#include <openvino/op/tile.hpp>#include <openvino/op/topk.hpp>+#include <openvino/pass/manager.hpp>#include <openvino/pass/serialize.hpp>#include <openvino/pass/visualize_tree.hpp>#include <vector>-#include "common_test_utils/graph_comparator.hpp"#include "common_test_utils/ov_test_utils.hpp"#include "openvino/core/node_vector.hpp"#include "openvino/op/parameter.hpp"@@ -32,10 +33,15 @@#include "openvino/op/scatter_elements_update.hpp"#include "openvino/op/transpose.hpp"#include "openvino/op/unsqueeze.hpp"-#include "openvino/runtime/core.hpp"-#include "ov_ops/type_relaxed.hpp"-#include "transformations/common_optimizations/matmul_experts_fusion.hpp"-#include "transformations/utils/gen_pattern.hpp"+#include "ov_ops/gather_matmul.hpp"+#include "transformations/common_optimizations/convert_tiled_moe_block_to_gather_matmuls.hpp"+#include "transformations/common_optimizations/moe_op_fusion.hpp"++using GatherMatmul = ov::op::internal::GatherMatmul;++// ============================================================================+// IR model builders (original MOE pattern before any transformation)+// ============================================================================inline std::shared_ptr<ov::Model> build_2gemm_moe_pattern_model() {using namespace ov;@@ -119,7 +125,7 @@ inline std::shared_ptr<ov::Model> build_2gemm_moe_pattern_model() {std::vector<int64_t>{number_of_experts, batch, -1, hidden_size}),false);- // Router subgraph used to test correctness of routing weights connection+ // Router subgraphauto reshape_2nd_consumer_router_matmul = std::make_shared<op::v0::MatMul>(experts_reshape,op::v0::Constant::create(element::f32, Shape{number_of_experts, hidden_size}, {1.0f}),@@ -159,7 +165,6 @@ inline std::shared_ptr<ov::Model> build_2gemm_moe_pattern_model() {auto mul3 = std::make_shared<op::v1::Multiply>(end_reshape, unsqueeze_routing_weights);- // ReduceSum - final node of the MOE pattern to be fusedauto reduce_sum =std::make_shared<op::v1::ReduceSum>(mul3,op::v0::Constant::create(element::i64, Shape{1}, std::vector<int64_t>{0}),@@ -168,87 +173,6 @@ inline std::shared_ptr<ov::Model> build_2gemm_moe_pattern_model() {return std::make_shared<ov::Model>(ov::OutputVector{reduce_sum}, ov::ParameterVector{input});}-inline std::shared_ptr<ov::Model> build_fused_2gemm_moe_reference_model() {- using namespace ov;-- const size_t batch = 2;- const Dimension in_dim = Dimension::dynamic();- const size_t hidden_size = 2048;- const size_t intermediate_size = 4096;- const size_t topk = 2;- const size_t number_of_experts = 3;- const size_t fusion_factor = 2;- const auto expert_alpha = 1.702f;- const auto expert_beta = 7.0f;-- auto input_shape = PartialShape{batch, in_dim, hidden_size};- auto input = std::make_shared<op::v0::Parameter>(element::f32, input_shape);-- // Begin of Router subgraph (not fused, but valuable for testing)- auto experts_reshape = std::make_shared<op::v1::Reshape>(- input,- op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{-1, hidden_size}),- false);-- auto reshape_2nd_consumer_router_matmul = std::make_shared<op::v0::MatMul>(- experts_reshape,- op::v0::Constant::create(element::f32, Shape{number_of_experts, hidden_size}, {1.0f}),- false,- true);-- auto router_bias =- std::make_shared<op::v1::Add>(reshape_2nd_consumer_router_matmul,- op::v0::Constant::create(element::f32, Shape{1, number_of_experts}, {1.0f}));-- auto router_topk_values_and_indices =- std::make_shared<op::v11::TopK>(router_bias,- op::v0::Constant::create(element::i64, Shape{}, {topk}),- -1,- op::v11::TopK::Mode::MAX,- op::v11::TopK::SortType::SORT_VALUES,- element::i64);-- auto router_topk_values = router_topk_values_and_indices->output(0);- auto router_topk_indices = router_topk_values_and_indices->output(1);-- auto scatter_elements_update = std::make_shared<op::v12::ScatterElementsUpdate>(- router_topk_values,- router_topk_indices,- op::v0::Constant::create(element::f32, Shape{batch, topk}, {0}),- op::v0::Constant::create(element::i64, Shape{1}, std::vector<int64_t>{1}));- auto router_transpose = std::make_shared<op::v1::Transpose>(- scatter_elements_update,- op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{1, 0}));- auto router_reshape = std::make_shared<op::v1::Reshape>(- router_transpose,- op::v0::Constant::create(element::i64, Shape{3}, std::vector<int64_t>{number_of_experts, batch, -1}),- true);- auto unsqueeze_routing_weights =- std::make_shared<op::v0::Unsqueeze>(router_reshape, op::v0::Constant::create(element::i64, Shape{1}, {-1}));- // End of Router subgraph-- // Expert MatMuls weights fused into MOE- auto w0_weight = op::v0::Constant::create(element::f32,- Shape{number_of_experts, intermediate_size * fusion_factor, hidden_size},- {1.0f});- auto w0_bias =- op::v0::Constant::create(element::f32, Shape{number_of_experts, 1, intermediate_size * fusion_factor}, {0.0f});- auto w1_weight =- op::v0::Constant::create(element::f32, Shape{number_of_experts, hidden_size, intermediate_size}, {1.0f});- auto w1_bias = op::v0::Constant::create(element::f32, Shape{number_of_experts, 1, hidden_size}, {1.0f});-- ov::OutputVector moe_inputs =- {input, unsqueeze_routing_weights, router_topk_indices, w0_weight, w0_bias, w1_weight, w1_bias};-- ov::op::internal::MOE::Config config;- config.expert_type = ov::op::internal::MOE::Expert_type::GEMM2_BIAS_SWIGLU_CLAMP;- config.expert_alpha = expert_alpha;- config.expert_beta = expert_beta;-- auto moe = std::make_shared<ov::op::internal::MOE>(moe_inputs, config);- return std::make_shared<ov::Model>(ov::OutputVector{moe}, ov::ParameterVector{input});-}-inline std::shared_ptr<ov::Model> build_3gemm_moe_pattern_model() {using namespace ov;@@ -306,7 +230,7 @@ inline std::shared_ptr<ov::Model> build_3gemm_moe_pattern_model() {std::vector<int64_t>{number_of_experts, batch, -1, hidden_size}),false);- // Router subgraph used to test correctness of routing weights connection+ // Router subgraphauto router_matmul = std::make_shared<op::v0::MatMul>(experts_reshape,op::v0::Constant::create(element::f32, Shape{number_of_experts, hidden_size}, {1.0f}),@@ -342,7 +266,6 @@ inline std::shared_ptr<ov::Model> build_3gemm_moe_pattern_model() {auto mul3 = std::make_shared<op::v1::Multiply>(experts_out_reshape, unsqueeze_routing_weights);- // ReduceSum - final node of the MOE pattern to be fusedauto reduce_sum =std::make_shared<op::v1::ReduceSum>(mul3,op::v0::Constant::create(element::i64, Shape{1}, std::vector<int64_t>{0}),@@ -351,7 +274,11 @@ inline std::shared_ptr<ov::Model> build_3gemm_moe_pattern_model() {return std::make_shared<ov::Model>(ov::OutputVector{reduce_sum}, ov::ParameterVector{input});}-inline std::shared_ptr<ov::Model> build_fused_3gemm_moe_reference_model() {+// ============================================================================+// Post-BGM model builders (3 BGMs + compact routing + ReduceSum + Reshape)+// ============================================================================++inline std::shared_ptr<ov::Model> build_3gemm_bgm_model() {using namespace ov;const size_t batch = 2;@@ -362,94 +289,315 @@ inline std::shared_ptr<ov::Model> build_fused_3gemm_moe_reference_model() {const size_t topk = 2;auto input = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{batch, in_dim, hidden_size});-- // Begin of Router subgraph (not fused, but valuable for testing)auto experts_reshape = std::make_shared<op::v1::Reshape>(input,- op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{-1, hidden_size}),+ op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{-1, static_cast<int64_t>(hidden_size)}),false);+ // Unsqueeze to add experts dimension: [1, batch*seq, hidden]+ auto unsqueeze =+ std::make_shared<op::v0::Unsqueeze>(experts_reshape, op::v0::Constant::create(element::i32, Shape{}, {0}));++ // Router subgraph to produce topk_indices and chosen_expertsauto router_matmul = std::make_shared<op::v0::MatMul>(experts_reshape,op::v0::Constant::create(element::f32, Shape{number_of_experts, hidden_size}, {1.0f}),false,true);-auto router_topk = std::make_shared<op::v11::TopK>(router_matmul,op::v0::Constant::create(element::i64, Shape{}, {topk}),-1,op::v11::TopK::Mode::MAX,op::v11::TopK::SortType::SORT_VALUES,element::i64);+ auto topk_indices = router_topk->output(1); // [batch*seq, topk]+ auto chosen_experts = router_topk->output(0); // [batch*seq, topk] (values used as routing weights)- auto router_topk_values = router_topk->output(0);- auto router_topk_indices = router_topk->output(1);+ // Gate weights+ auto gate_w =+ op::v0::Constant::create(element::f32, Shape{number_of_experts, intermediate_size, hidden_size}, {1.0f});+ // Up weights+ auto up_w =+ op::v0::Constant::create(element::f32, Shape{number_of_experts, intermediate_size, hidden_size}, {1.0f});+ // Down weights+ auto down_w =+ op::v0::Constant::create(element::f32, Shape{number_of_experts, hidden_size, intermediate_size}, {1.0f});- auto scatter_elements_update = std::make_shared<op::v12::ScatterElementsUpdate>(- router_topk_values,- router_topk_indices,- op::v0::Constant::create(element::f32, Shape{batch, topk}, {0}),- op::v0::Constant::create(element::i64, Shape{1}, {1}));+ // 3 BGMs+ auto bgm_gate = std::make_shared<GatherMatmul>(unsqueeze, gate_w, topk_indices);+ auto swish = std::make_shared<op::v4::Swish>(bgm_gate);+ auto bgm_up = std::make_shared<GatherMatmul>(unsqueeze, up_w, topk_indices);+ auto swiglu = std::make_shared<op::v1::Multiply>(swish, bgm_up);+ auto bgm_down = std::make_shared<GatherMatmul>(swiglu, down_w, topk_indices);- auto router_transpose =- std::make_shared<op::v1::Transpose>(scatter_elements_update,- op::v0::Constant::create(element::i64, Shape{2}, {1, 0}));- auto router_reshape = std::make_shared<op::v1::Reshape>(- router_transpose,- op::v0::Constant::create(element::i64, Shape{3}, std::vector<int64_t>{number_of_experts, batch, -1}),+ // Compact routing: chosen_experts → Transpose({1,0}) → Unsqueeze(-1)+ auto router_transpose = std::make_shared<op::v1::Transpose>(+ chosen_experts,+ op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{1, 0}));+ auto router_unsqueeze =+ std::make_shared<op::v0::Unsqueeze>(router_transpose, op::v0::Constant::create(element::i32, Shape{}, {-1}));++ // Final: Multiply → ReduceSum → Reshape+ auto final_mul = std::make_shared<op::v1::Multiply>(bgm_down, router_unsqueeze);+ auto reduce_sum =+ std::make_shared<op::v1::ReduceSum>(final_mul,+ op::v0::Constant::create(element::i64, Shape{1}, std::vector<int64_t>{0}),+ false);++ auto end_reshape = std::make_shared<op::v1::Reshape>(+ reduce_sum,+ op::v0::Constant::create(+ element::i64,+ Shape{3},+ std::vector<int64_t>{static_cast<int64_t>(batch), -1, static_cast<int64_t>(hidden_size)}),true);- auto unsqueeze_routing_weights =- std::make_shared<op::v0::Unsqueeze>(router_reshape, op::v0::Constant::create(element::i64, Shape{1}, {-1}));+ return std::make_shared<ov::Model>(ov::OutputVector{end_reshape}, ov::ParameterVector{input});+}++inline std::shared_ptr<ov::Model> build_3gemm_bgm_to_moe_reference_model() {+ using namespace ov;++ const size_t batch = 2;+ const Dimension in_dim = Dimension::dynamic();+ const size_t hidden_size = 2048;+ const size_t intermediate_size = 4096;+ const size_t number_of_experts = 3;+ const size_t topk = 2;++ auto input = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{batch, in_dim, hidden_size});- // MOE fused op- auto w0_weight =+ // Router subgraph (not fused, remains in the graph)+ auto experts_reshape = std::make_shared<op::v1::Reshape>(+ input,+ op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{-1, static_cast<int64_t>(hidden_size)}),+ false);++ auto router_matmul = std::make_shared<op::v0::MatMul>(+ experts_reshape,+ op::v0::Constant::create(element::f32, Shape{number_of_experts, hidden_size}, {1.0f}),+ false,+ true);+ auto router_topk = std::make_shared<op::v11::TopK>(router_matmul,+ op::v0::Constant::create(element::i64, Shape{}, {topk}),+ -1,+ op::v11::TopK::Mode::MAX,+ op::v11::TopK::SortType::SORT_VALUES,+ element::i64);+ auto topk_indices = router_topk->output(1);+ auto chosen_experts = router_topk->output(0);++ // Compact routing (stays as-is, becomes MOE input 1)+ auto router_transpose = std::make_shared<op::v1::Transpose>(+ chosen_experts,+ op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{1, 0}));+ auto router_unsqueeze =+ std::make_shared<op::v0::Unsqueeze>(router_transpose, op::v0::Constant::create(element::i32, Shape{}, {-1}));++ // Weights+ auto gate_w =op::v0::Constant::create(element::f32, Shape{number_of_experts, intermediate_size, hidden_size}, {1.0f});- auto w1_weight =+ auto up_w =op::v0::Constant::create(element::f32, Shape{number_of_experts, intermediate_size, hidden_size}, {1.0f});- auto w2_weight =+ auto down_w =op::v0::Constant::create(element::f32, Shape{number_of_experts, hidden_size, intermediate_size}, {1.0f});- ov::OutputVector moe_inputs =- {input, unsqueeze_routing_weights, router_topk_indices, w0_weight, w1_weight, w2_weight};-+ // MOE op with compact routing+ ov::OutputVector moe_inputs = {input, router_unsqueeze, topk_indices, gate_w, up_w, down_w};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);+return std::make_shared<ov::Model>(ov::OutputVector{moe}, ov::ParameterVector{input});}-TEST_F(TransformationTestsF, FuseVectorizedMOE2GEMM_basic) {- model = build_2gemm_moe_pattern_model();- manager.register_pass<ov::pass::FuseVectorizedMOE2GEMM>();- model_ref = build_fused_2gemm_moe_reference_model();-}+inline std::shared_ptr<ov::Model> build_2gemm_bgm_model() {+ using namespace ov;-TEST_F(TransformationTestsF, FuseVectorizedMOE2GEMM_VectorizedExpertsFusion) {- model = build_2gemm_moe_pattern_model();- manager.register_pass<ov::pass::VectorizedExpertsFusion>();- model_ref = build_fused_2gemm_moe_reference_model();-}+ const size_t batch = 2;+ const Dimension in_dim = Dimension::dynamic();+ const size_t hidden_size = 2048;+ const size_t intermediate_size = 4096;+ const size_t topk = 2;+ const size_t number_of_experts = 3;+ const size_t fusion_factor = 2;+ const auto expert_alpha = 1.702f;+ const auto expert_beta = 7.0f;++ auto input = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{batch, in_dim, hidden_size});+ auto experts_reshape = std::make_shared<op::v1::Reshape>(+ input,+ op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{-1, static_cast<int64_t>(hidden_size)}),+ false);++ auto unsqueeze =+ std::make_shared<op::v0::Unsqueeze>(experts_reshape, op::v0::Constant::create(element::i32, Shape{}, {0}));++ // Router+ auto router_matmul = std::make_shared<op::v0::MatMul>(+ experts_reshape,+ op::v0::Constant::create(element::f32, Shape{number_of_experts, hidden_size}, {1.0f}),+ false,+ true);+ auto router_bias =+ std::make_shared<op::v1::Add>(router_matmul,+ op::v0::Constant::create(element::f32, Shape{1, number_of_experts}, {1.0f}));+ auto router_topk = std::make_shared<op::v11::TopK>(router_bias,+ op::v0::Constant::create(element::i64, Shape{}, {topk}),+ -1,+ op::v11::TopK::Mode::MAX,+ op::v11::TopK::SortType::SORT_VALUES,+ element::i64);+ auto topk_indices = router_topk->output(1);+ auto chosen_experts = router_topk->output(0);++ // Gate/up weights and bias+ auto gate_up_w = op::v0::Constant::create(element::f32,+ Shape{number_of_experts, intermediate_size * fusion_factor, hidden_size},+ {1.0f});+ auto gate_up_bias =+ op::v0::Constant::create(element::f32, Shape{number_of_experts, 1, intermediate_size * fusion_factor}, {0.0f});++ // BGM gate_up (4 inputs: data, weight, indices, bias)+ auto bgm_gate_up = std::make_shared<GatherMatmul>(unsqueeze, gate_up_w, topk_indices, gate_up_bias);++ // Activation subgraph (same as in the original 2GEMM pattern)+ auto slice1 = std::make_shared<op::v8::Slice>(+ bgm_gate_up,+ op::v0::Constant::create(element::i64, Shape{3}, std::vector<int64_t>{0, 0, 0}),+ op::v0::Constant::create(element::i64,+ Shape{3},+ std::vector<int64_t>{static_cast<int64_t>(topk),+ static_cast<int64_t>(batch),+ static_cast<int64_t>(intermediate_size * 2)}),+ op::v0::Constant::create(element::i64, Shape{3}, std::vector<int64_t>{1, 1, 2}),+ op::v0::Constant::create(element::i64, Shape{3}, std::vector<int64_t>{0, 1, 2}));+ auto clamp = std::make_shared<op::v0::Clamp>(slice1, -expert_beta, expert_beta);+ auto add1 = std::make_shared<op::v1::Add>(clamp, op::v0::Constant::create(element::f32, Shape{1}, {1.0f}));++ auto slice2 = std::make_shared<op::v8::Slice>(+ bgm_gate_up,+ op::v0::Constant::create(element::i64, Shape{3}, std::vector<int64_t>{0, 1, 0}),+ op::v0::Constant::create(element::i64,+ Shape{3},+ std::vector<int64_t>{static_cast<int64_t>(topk),+ static_cast<int64_t>(batch),+ static_cast<int64_t>(intermediate_size * 2)}),+ op::v0::Constant::create(element::i64, Shape{3}, std::vector<int64_t>{1, 1, 2}),+ op::v0::Constant::create(element::i64, Shape{3}, std::vector<int64_t>{0, 1, 2}));+ auto minimum1 =+ std::make_shared<op::v1::Minimum>(slice2, op::v0::Constant::create(element::f32, Shape{1}, {10.0f}));+ auto swish_beta_const = op::v0::Constant::create(element::f32, Shape{}, std::vector<float>{expert_alpha});+ auto swish = std::make_shared<op::v4::Swish>(minimum1, swish_beta_const);+ auto multiply2 = std::make_shared<op::v1::Multiply>(add1, swish);++ // Down proj+ auto down_w =+ op::v0::Constant::create(element::f32, Shape{number_of_experts, hidden_size, intermediate_size}, {1.0f});+ auto down_bias = op::v0::Constant::create(element::f32, Shape{number_of_experts, 1, hidden_size}, {1.0f});+ auto bgm_down = std::make_shared<GatherMatmul>(multiply2, down_w, topk_indices, down_bias);++ // Compact routing+ auto router_transpose = std::make_shared<op::v1::Transpose>(+ chosen_experts,+ op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{1, 0}));+ auto router_unsqueeze =+ std::make_shared<op::v0::Unsqueeze>(router_transpose, op::v0::Constant::create(element::i32, Shape{}, {-1}));++ auto final_mul = std::make_shared<op::v1::Multiply>(bgm_down, router_unsqueeze);+ auto reduce_sum =+ std::make_shared<op::v1::ReduceSum>(final_mul,+ op::v0::Constant::create(element::i64, Shape{1}, std::vector<int64_t>{0}),+ false);+ auto end_reshape = std::make_shared<op::v1::Reshape>(+ reduce_sum,+ op::v0::Constant::create(+ element::i64,+ Shape{3},+ std::vector<int64_t>{static_cast<int64_t>(batch), -1, static_cast<int64_t>(hidden_size)}),+ true);-TEST_F(TransformationTestsF, FuseVectorizedMOE2GEMM_no_fusion) {- model = build_3gemm_moe_pattern_model();- manager.register_pass<ov::pass::FuseVectorizedMOE2GEMM>();+ return std::make_shared<ov::Model>(ov::OutputVector{end_reshape}, ov::ParameterVector{input});}-TEST_F(TransformationTestsF, FuseVectorizedMOE3GEMM_basic) {- model = build_3gemm_moe_pattern_model();- manager.register_pass<ov::pass::FuseVectorizedMOE3GEMM>();- model_ref = build_fused_3gemm_moe_reference_model();+inline std::shared_ptr<ov::Model> build_2gemm_bgm_to_moe_reference_model() {+ using namespace ov;++ const size_t batch = 2;+ const Dimension in_dim = Dimension::dynamic();+ const size_t hidden_size = 2048;+ const size_t intermediate_size = 4096;+ const size_t topk = 2;+ const size_t number_of_experts = 3;+ const size_t fusion_factor = 2;+ const auto expert_alpha = 1.702f;+ const auto expert_beta = 7.0f;++ auto input = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{batch, in_dim, hidden_size});++ auto experts_reshape = std::make_shared<op::v1::Reshape>(+ input,+ op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{-1, static_cast<int64_t>(hidden_size)}),+ false);++ // Router (stays in graph)+ auto router_matmul = std::make_shared<op::v0::MatMul>(+ experts_reshape,+ op::v0::Constant::create(element::f32, Shape{number_of_experts, hidden_size}, {1.0f}),+ false,+ true);+ auto router_bias =+ std::make_shared<op::v1::Add>(router_matmul,+ op::v0::Constant::create(element::f32, Shape{1, number_of_experts}, {1.0f}));+ auto router_topk = std::make_shared<op::v11::TopK>(router_bias,+ op::v0::Constant::create(element::i64, Shape{}, {topk}),+ -1,+ op::v11::TopK::Mode::MAX,+ op::v11::TopK::SortType::SORT_VALUES,+ element::i64);+ auto topk_indices = router_topk->output(1);+ auto chosen_experts = router_topk->output(0);++ // Compact routing (becomes MOE input 1)+ auto router_transpose = std::make_shared<op::v1::Transpose>(+ chosen_experts,+ op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{1, 0}));+ auto router_unsqueeze =+ std::make_shared<op::v0::Unsqueeze>(router_transpose, op::v0::Constant::create(element::i32, Shape{}, {-1}));++ // Weights+ auto gate_up_w = op::v0::Constant::create(element::f32,+ Shape{number_of_experts, intermediate_size * fusion_factor, hidden_size},+ {1.0f});+ auto gate_up_bias =+ op::v0::Constant::create(element::f32, Shape{number_of_experts, 1, intermediate_size * fusion_factor}, {0.0f});+ auto down_w =+ op::v0::Constant::create(element::f32, Shape{number_of_experts, hidden_size, intermediate_size}, {1.0f});+ auto down_bias = op::v0::Constant::create(element::f32, Shape{number_of_experts, 1, hidden_size}, {1.0f});++ ov::OutputVector moe_inputs = {input, router_unsqueeze, topk_indices, gate_up_w, gate_up_bias, down_w, down_bias};++ ov::op::internal::MOE::Config config;+ config.expert_type = ov::op::internal::MOE::Expert_type::GEMM2_BIAS_SWIGLU_CLAMP;+ config.expert_alpha = expert_alpha;+ config.expert_beta = expert_beta;++ auto moe = std::make_shared<ov::op::internal::MOE>(moe_inputs, config);+ return std::make_shared<ov::Model>(ov::OutputVector{moe}, ov::ParameterVector{input});}-TEST_F(TransformationTestsF, FuseVectorizedMOE3GEMM_VectorizedExpertsFusion) {- model = build_3gemm_moe_pattern_model();- manager.register_pass<ov::pass::VectorizedExpertsFusion>();- model_ref = build_fused_3gemm_moe_reference_model();+// ============================================================================+// Tests for BGM→MOE passes (Convert3GatherMatmulMoeBlockToMoeOp, Convert2GatherMatmulMoeBlockToMoeOp)+// ============================================================================++TEST_F(TransformationTestsF, Convert3GatherMatmulMoeBlockToMoeOp_basic) {+ model = build_3gemm_bgm_model();+ manager.register_pass<ov::pass::Convert3GatherMatmulMoeBlockToMoeOp>();+ model_ref = build_3gemm_bgm_to_moe_reference_model();}-TEST_F(TransformationTestsF, FuseVectorizedMOE3GEMM_no_fusion) {- model = build_2gemm_moe_pattern_model();- manager.register_pass<ov::pass::FuseVectorizedMOE3GEMM>();-}\ No newline at end of file+TEST_F(TransformationTestsF, Convert2GatherMatmulMoeBlockToMoeOp_basic) {+ model = build_2gemm_bgm_model();+ manager.register_pass<ov::pass::Convert2GatherMatmulMoeBlockToMoeOp>();+ model_ref = build_2gemm_bgm_to_moe_reference_model();+}diff --git a/src/plugins/intel_cpu/tests/unit/transformations/moe_matmuls_fusion_test.cpp b/src/common/transformations/tests/common_optimizations/convert_tiled_moe_block_to_gather_matmuls_test.cppsimilarity index 94%rename from src/plugins/intel_cpu/tests/unit/transformations/moe_matmuls_fusion_test.cpprename to src/common/transformations/tests/common_optimizations/convert_tiled_moe_block_to_gather_matmuls_test.cppindex e2a455eae0a..534910e8b30 100644--- a/src/plugins/intel_cpu/tests/unit/transformations/moe_matmuls_fusion_test.cpp+++ b/src/common/transformations/tests/common_optimizations/convert_tiled_moe_block_to_gather_matmuls_test.cpp@@ -2,7 +2,7 @@// SPDX-License-Identifier: Apache-2.0//-#include "transformations/cpu_opset/common/pass/moe_matmuls_fusion.hpp"+#include "transformations/common_optimizations/convert_tiled_moe_block_to_gather_matmuls.hpp"#include <gtest/gtest.h>@@ -12,7 +12,6 @@#include "common_test_utils/node_builders/constant.hpp"#include "common_test_utils/ov_test_utils.hpp"-#include "common_test_utils/subgraph_builders/weights_decompression_builders.hpp"#include "openvino/core/model.hpp"#include "openvino/op/add.hpp"#include "openvino/op/broadcast.hpp"@@ -20,7 +19,6 @@#include "openvino/op/concat.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/divide.hpp"-#include "openvino/op/gather.hpp"#include "openvino/op/matmul.hpp"#include "openvino/op/minimum.hpp"#include "openvino/op/multiply.hpp"@@ -38,11 +36,11 @@#include "openvino/op/transpose.hpp"#include "openvino/op/unsqueeze.hpp"#include "openvino/pass/manager.hpp"-#include "transformations/cpu_opset/common/op/batch_gather_matmul.hpp"+#include "ov_ops/gather_matmul.hpp"#include "transformations/utils/utils.hpp"using namespace testing;-using namespace ov::intel_cpu;+using namespace ov::op::internal;namespace {@@ -59,17 +57,17 @@ inline std::ostream& operator<<(std::ostream& os, const MoEType& type) {}}-using MoEMatMulsFusionParams = std::tuple<MoEType, // moe_type- bool, // use_scatter_v12- bool, // use_broadcast_v3- bool, // skip_unsqueeze- bool, // matmul_transpose_b- bool, // additional_node_consumers- bool>; // transformation_should_be_applied+using ConvertTiledMoeBlockToGatherMatmulsParams = std::tuple<MoEType, // moe_type+ bool, // use_scatter_v12+ bool, // use_broadcast_v3+ bool, // skip_unsqueeze+ bool, // matmul_transpose_b+ bool, // additional_node_consumers+ bool>; // transformation_should_be_appliedinline std::shared_ptr<ov::Node> build_matmul_weights(const ov::Shape& weights_shape,const ov::element::Type& weights_precision,- size_t seed,+ int seed,bool transpose_b) {// Note: builder takes planar weights shape, but it is transposed here// only if transpose_b=true (which is the default case for MoE matmuls)@@ -123,7 +121,7 @@ inline std::shared_ptr<ov::Model> initMoE2GeMMSubgraph(bool use_scatter_v12,false);// Note: we need to use different seed to avoid the exact weights generation for the MatMuls with the same shape- size_t seed = 1;+ int seed = 1;auto gate_up_weights =build_matmul_weights(ov::Shape{number_of_experts, hidden_size, intermediate_size * fusion_factor},weights_precision,@@ -351,7 +349,7 @@ inline std::shared_ptr<ov::Model> initMoE2GeMMSubgraphRef(bool use_scatter_v12,ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{0, 1}));// Note: we need to use different seed to avoid the exact weights generation for the MatMuls with the same shape- size_t seed = 1;+ int seed = 1;auto gate_up_weights =build_matmul_weights(ov::Shape{number_of_experts, hidden_size, intermediate_size * fusion_factor},weights_precision,@@ -363,7 +361,7 @@ inline std::shared_ptr<ov::Model> initMoE2GeMMSubgraphRef(bool use_scatter_v12,ov::Shape{number_of_experts, 1, intermediate_size * fusion_factor});auto gate_up_gathered_mm =- std::make_shared<BatchGatherMatmul>(unsqueeze_experts, gate_up_weights, router_topk_indices, gate_up_bias);+ std::make_shared<GatherMatmul>(unsqueeze_experts, gate_up_weights, router_topk_indices, gate_up_bias);auto slice1 = std::make_shared<ov::op::v8::Slice>(gate_up_gathered_mm,@@ -400,7 +398,7 @@ inline std::shared_ptr<ov::Model> initMoE2GeMMSubgraphRef(bool use_scatter_v12,auto down_proj_bias = ov::test::utils::make_constant(data_precision, ov::Shape{number_of_experts, 1, hidden_size});auto down_gathered_mm =- std::make_shared<BatchGatherMatmul>(multiply2, down_proj_weights, router_topk_indices, down_proj_bias);+ std::make_shared<GatherMatmul>(multiply2, down_proj_weights, router_topk_indices, down_proj_bias);auto router_transpose = std::make_shared<ov::op::v1::Transpose>(slice3,@@ -479,7 +477,7 @@ inline std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(bool use_scatter_v12,false);// Note: we need to use different seed to avoid the exact weights generation for the MatMuls with the same shape- size_t seed = 1;+ int seed = 1;auto gate_weights = build_matmul_weights(ov::Shape{number_of_experts, hidden_size, intermediate_size},weights_precision,seed++,@@ -680,13 +678,13 @@ inline std::shared_ptr<ov::Model> initMoE3GeMMSubgraphRef(bool use_scatter_v12,auto router_topk_indices = router_topk_values_and_indices->output(1);// Note: we need to use different seed to avoid the exact weights generation for the MatMuls with the same shape- size_t seed = 1;+ int seed = 1;auto gate_weights = build_matmul_weights(ov::Shape{number_of_experts, hidden_size, intermediate_size},weights_precision,seed++,matmul_transpose_b);- auto gate_gathered_mm = std::make_shared<BatchGatherMatmul>(unsqueeze_experts, gate_weights, router_topk_indices);+ auto gate_gathered_mm = std::make_shared<GatherMatmul>(unsqueeze_experts, gate_weights, router_topk_indices);auto swish = std::make_shared<ov::op::v4::Swish>(gate_gathered_mm);@@ -695,7 +693,7 @@ inline std::shared_ptr<ov::Model> initMoE3GeMMSubgraphRef(bool use_scatter_v12,seed++,matmul_transpose_b);- auto up_gathered_mm = std::make_shared<BatchGatherMatmul>(unsqueeze_experts, up_weights, router_topk_indices);+ auto up_gathered_mm = std::make_shared<GatherMatmul>(unsqueeze_experts, up_weights, router_topk_indices);auto swiglu = std::make_shared<ov::op::v1::Multiply>(swish, up_gathered_mm);@@ -704,7 +702,7 @@ inline std::shared_ptr<ov::Model> initMoE3GeMMSubgraphRef(bool use_scatter_v12,seed++,matmul_transpose_b);- auto down_gathered_mm = std::make_shared<BatchGatherMatmul>(swiglu, down_weights, router_topk_indices);+ auto down_gathered_mm = std::make_shared<GatherMatmul>(swiglu, down_weights, router_topk_indices);auto router_transpose = std::make_shared<ov::op::v1::Transpose>(router_topk_values_normalization,@@ -749,9 +747,10 @@ inline std::shared_ptr<ov::Model> initMoE3GeMMSubgraphRef(bool use_scatter_v12,return std::make_shared<ov::Model>(ov::OutputVector{original_final_reshape}, params);}-class MoEMatMulsFusionTest : public TransformationTestsF, public WithParamInterface<MoEMatMulsFusionParams> {+class ConvertTiledMoeBlockToGatherMatmulsTest : public TransformationTestsF,+ public WithParamInterface<ConvertTiledMoeBlockToGatherMatmulsParams> {public:- static std::string getTestCaseName(const testing::TestParamInfo<MoEMatMulsFusionParams>& obj) {+ static std::string getTestCaseName(const testing::TestParamInfo<ConvertTiledMoeBlockToGatherMatmulsParams>& obj) {const auto& [moe_type,use_scatter_v12,use_broadcast_v3,@@ -798,7 +797,7 @@ protected:OPENVINO_THROW("Unexpected MoEType value");}- manager.register_pass<MoEMatMulsFusion>();+ manager.register_pass<ov::pass::ConvertTiledMoeBlockToGatherMatmuls>();if (should_be_applied) {switch (moe_type) {@@ -817,15 +816,15 @@ protected:}};-TEST_P(MoEMatMulsFusionTest, CompareFunctions) {}+TEST_P(ConvertTiledMoeBlockToGatherMatmulsTest, CompareFunctions) {}const std::vector<MoEType> moe_types = {MoEType::MoE2GeMM, MoEType::MoE3GeMM};const std::vector<bool> scatter_versions = {false, true}; // false = v3, true = v12const std::vector<bool> broadcast_versions = {false, true}; // false = v1, true = v3const std::vector<bool> skip_unsqueeze_versions = {false, true};-INSTANTIATE_TEST_SUITE_P(MoEMatMulsFusionTest_positive_cases,- MoEMatMulsFusionTest,+INSTANTIATE_TEST_SUITE_P(ConvertTiledMoeBlockToGatherMatmulsTest_positive_cases,+ ConvertTiledMoeBlockToGatherMatmulsTest,::testing::Combine(::testing::ValuesIn(moe_types),::testing::ValuesIn(scatter_versions),::testing::ValuesIn(broadcast_versions),@@ -833,10 +832,10 @@ INSTANTIATE_TEST_SUITE_P(MoEMatMulsFusionTest_positive_cases,::testing::Values(true),::testing::Values(false),::testing::Values(true)),- MoEMatMulsFusionTest::getTestCaseName);+ ConvertTiledMoeBlockToGatherMatmulsTest::getTestCaseName);-INSTANTIATE_TEST_SUITE_P(MoEMatMulsFusionTest_negative_cases_no_transpose,- MoEMatMulsFusionTest,+INSTANTIATE_TEST_SUITE_P(ConvertTiledMoeBlockToGatherMatmulsTest_negative_cases_no_transpose,+ ConvertTiledMoeBlockToGatherMatmulsTest,::testing::Combine(::testing::ValuesIn(moe_types),::testing::ValuesIn(scatter_versions),::testing::ValuesIn(broadcast_versions),@@ -844,10 +843,10 @@ INSTANTIATE_TEST_SUITE_P(MoEMatMulsFusionTest_negative_cases_no_transpose,::testing::Values(false),::testing::Values(false),::testing::Values(false)),- MoEMatMulsFusionTest::getTestCaseName);+ ConvertTiledMoeBlockToGatherMatmulsTest::getTestCaseName);-INSTANTIATE_TEST_SUITE_P(MoEMatMulsFusionTest_negative_cases_additional_consumers,- MoEMatMulsFusionTest,+INSTANTIATE_TEST_SUITE_P(ConvertTiledMoeBlockToGatherMatmulsTest_negative_cases_additional_consumers,+ ConvertTiledMoeBlockToGatherMatmulsTest,::testing::Combine(::testing::ValuesIn(moe_types),::testing::Values(false),::testing::Values(false),@@ -855,5 +854,5 @@ INSTANTIATE_TEST_SUITE_P(MoEMatMulsFusionTest_negative_cases_additional_consumer::testing::Values(true),::testing::Values(true),::testing::Values(false)),- MoEMatMulsFusionTest::getTestCaseName);-} // namespace\ No newline at end of file+ ConvertTiledMoeBlockToGatherMatmulsTest::getTestCaseName);+} // namespacediff --git a/src/common/transformations/tests/common_optimizations/fuse_moe_test.cpp b/src/common/transformations/tests/common_optimizations/fuse_moe_test.cppindex 343ceaf79de..bd716d48ef8 100644--- a/src/common/transformations/tests/common_optimizations/fuse_moe_test.cpp+++ b/src/common/transformations/tests/common_optimizations/fuse_moe_test.cpp@@ -423,4 +423,4 @@ TEST_F(TransformationTestsF, FuseMOEExperts_to_FuseVectorizedMOE3GEMM_Integratioov::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/dev_api/openvino/op/moe.hpp b/src/core/dev_api/openvino/op/moe.hppindex bd477e33446..9d23f0e6692 100644--- a/src/core/dev_api/openvino/op/moe.hpp+++ b/src/core/dev_api/openvino/op/moe.hpp@@ -34,8 +34,9 @@ public:/// \brief Constructs a MOE operation with config only/// \param args The input tensors, in the following order:/// 0: hidden_states - input tensor with hidden representations- /// 1: routing_weights - [num_experts, ...] normalized weights for selected experts- /// (input to final multiplication)+ /// 1: routing_weights - normalized weights for selected experts.+ /// Legacy form: [num_experts, ...] (scattered via ScatterElementsUpdate).+ /// Compact form: [topk, batch*seq, 1] (post-BGM, selected experts only)./// 2: router_topk_output_indices - [..., topk] indices of selected top-k experts/// 3: w0_weight - expert weights for first projection, shape [num_experts, inter_size, hidden_size] or/// [num_experts, hidden_size, 2 * inter_size] if fuseddiff --git a/src/core/tests/type_prop/gather_matmul_compressed_test.cpp b/src/core/tests/type_prop/gather_matmul_compressed_test.cppnew file mode 100644index 00000000000..4a2e5934a61--- /dev/null+++ b/src/core/tests/type_prop/gather_matmul_compressed_test.cpp@@ -0,0 +1,117 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "ov_ops/gather_matmul_compressed.hpp"++#include <gtest/gtest.h>++#include "common_test_utils/test_assertions.hpp"+#include "common_test_utils/type_prop.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/parameter.hpp"++using ov::op::v0::Constant;+using ov::op::v0::Parameter;++namespace ov::tests {++namespace {+auto make_const(element::Type et, const Shape& shape) {+ return Constant::create(et, shape, {0.f});+}++auto make_param(element::Type et, const PartialShape& shape) {+ return std::make_shared<Parameter>(et, shape);+}++auto make_empty_bias() {+ return std::make_shared<Constant>(element::dynamic, Shape{0});+}+} // namespace++using GatherMatmulCompressedTest = TypePropOpTest<ov::op::internal::GatherMatmulCompressed>;++// ============================================================================+// Positive tests — GatherMatmulCompressed+// ============================================================================++// Basic 3D compressed weights+TEST_F(GatherMatmulCompressedTest, shape_basic_3d) {+ auto a = make_param(element::f32, {1, 64, 2048});+ auto b = make_const(element::u8, {8, 4096, 2048});+ auto idx = make_param(element::i32, {64, 2});+ auto bias = make_empty_bias();+ auto scales = make_const(element::f32, {8, 4096, 1});+ auto zp = make_const(element::u8, {8, 4096, 1});++ auto op = make_op(a, b, idx, bias, scales, zp);++ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{2, 64, 4096}));+ EXPECT_EQ(op->get_output_element_type(0), element::f32);+}++// 4D group-compressed weights with scales/zp+TEST_F(GatherMatmulCompressedTest, shape_grouped_4d) {+ auto a = make_param(element::f32, {1, 64, 2048});+ auto b = make_const(element::u8, {8, 4096, 16, 128});+ auto idx = make_param(element::i32, {64, 2});+ auto bias = make_empty_bias();+ auto scales = make_const(element::f32, {8, 4096, 16, 1});+ auto zp = make_const(element::u8, {8, 4096, 16, 1});++ auto op = make_op(a, b, idx, bias, scales, zp);++ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{2, 64, 4096}));+}++// ============================================================================+// Negative tests — GatherMatmulCompressed validation failures+// ============================================================================++TEST_F(GatherMatmulCompressedTest, fail_scales_not_constant) {+ auto a = make_param(element::f32, {1, 64, 2048});+ auto b = make_const(element::u8, {8, 4096, 2048});+ auto idx = make_param(element::i32, {64, 2});+ auto bias = make_empty_bias();+ auto scales = make_param(element::f32, {8, 4096, 1}); // Parameter, not Constant+ auto zp = make_const(element::u8, {8, 4096, 1});++ OV_EXPECT_THROW(std::ignore = make_op(a, b, idx, bias, scales, zp),+ ov::NodeValidationFailure,+ testing::HasSubstr("Input weight_scales must be a Constant"));+}++TEST_F(GatherMatmulCompressedTest, fail_zp_not_constant) {+ auto a = make_param(element::f32, {1, 64, 2048});+ auto b = make_const(element::u8, {8, 4096, 2048});+ auto idx = make_param(element::i32, {64, 2});+ auto bias = make_empty_bias();+ auto scales = make_const(element::f32, {8, 4096, 1});+ auto zp = make_param(element::u8, {8, 4096, 1}); // Parameter, not Constant++ OV_EXPECT_THROW(std::ignore = make_op(a, b, idx, bias, scales, zp),+ ov::NodeValidationFailure,+ testing::HasSubstr("Input weight_zero_points must be a Constant"));+}++// ============================================================================+// Clone tests+// ============================================================================++TEST_F(GatherMatmulCompressedTest, clone_preserves_output_shape) {+ auto a = make_param(element::f32, {1, 64, 2048});+ auto b = make_const(element::u8, {8, 4096, 2048});+ auto idx = make_param(element::i32, {64, 2});+ auto bias = make_empty_bias();+ auto scales = make_const(element::f32, {8, 4096, 1});+ auto zp = make_const(element::u8, {8, 4096, 1});++ auto op = make_op(a, b, idx, bias, scales, zp);+ auto cloned = op->clone_with_new_inputs({a, b, idx, bias, scales, zp});++ EXPECT_EQ(cloned->get_output_partial_shape(0), op->get_output_partial_shape(0));+ EXPECT_EQ(cloned->get_output_element_type(0), op->get_output_element_type(0));+}++} // namespace ov::testsdiff --git a/src/core/tests/type_prop/gather_matmul_test.cpp b/src/core/tests/type_prop/gather_matmul_test.cppnew file mode 100644index 00000000000..56ac12ebf72--- /dev/null+++ b/src/core/tests/type_prop/gather_matmul_test.cpp@@ -0,0 +1,283 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "ov_ops/gather_matmul.hpp"++#include <gtest/gtest.h>++#include "common_test_utils/test_assertions.hpp"+#include "common_test_utils/type_prop.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/parameter.hpp"++using ov::op::v0::Constant;+using ov::op::v0::Parameter;++namespace ov::tests {++namespace {+auto make_const(element::Type et, const Shape& shape) {+ return Constant::create(et, shape, {0.f});+}++auto make_param(element::Type et, const PartialShape& shape) {+ return std::make_shared<Parameter>(et, shape);+}++auto make_empty_bias() {+ return std::make_shared<Constant>(element::dynamic, Shape{0});+}+} // namespace++using GatherMatmulTest = TypePropOpTest<ov::op::internal::GatherMatmul>;++// ============================================================================+// Positive tests — GatherMatmul shape inference+// ============================================================================++// 3-arg constructor: A[0]=1 broadcasts to topk=2+TEST_F(GatherMatmulTest, shape_3arg_gate_broadcast) {+ auto a = make_param(element::f32, {1, 64, 2048});+ auto b = make_const(element::f32, {8, 4096, 2048});+ auto idx = make_param(element::i32, {64, 2});++ auto op = make_op(a, b, idx);++ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{2, 64, 4096}));+ EXPECT_EQ(op->get_output_element_type(0), element::f32);+}++// 3-arg constructor: A[0]=topk (non-broadcast)+TEST_F(GatherMatmulTest, shape_3arg_down_projection) {+ auto a = make_param(element::f32, {2, 64, 4096});+ auto b = make_const(element::f32, {8, 2048, 4096});+ auto idx = make_param(element::i32, {64, 2});++ auto op = make_op(a, b, idx);++ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{2, 64, 2048}));+}++// 4-arg constructor with 3D bias [n_experts, 1, N]+TEST_F(GatherMatmulTest, shape_4arg_bias_3d) {+ auto a = make_param(element::f32, {1, 64, 2048});+ auto b = make_const(element::f32, {8, 8192, 2048});+ auto idx = make_param(element::i32, {64, 2});+ auto bias = make_const(element::f32, {8, 1, 8192});++ auto op = make_op(a, b, idx, bias);++ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{2, 64, 8192}));+}++// 4-arg constructor with 1D bias+TEST_F(GatherMatmulTest, shape_4arg_bias_1d) {+ auto a = make_param(element::f32, {1, 64, 2048});+ auto b = make_const(element::f32, {8, 4096, 2048});+ auto idx = make_param(element::i32, {64, 2});+ auto bias = make_const(element::f32, {4096});++ auto op = make_op(a, b, idx, bias);++ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{2, 64, 4096}));+}++// 4-arg constructor with scalar bias+TEST_F(GatherMatmulTest, shape_4arg_bias_scalar) {+ auto a = make_param(element::f32, {1, 64, 2048});+ auto b = make_const(element::f32, {8, 4096, 2048});+ auto idx = make_param(element::i32, {64, 2});+ auto bias = make_const(element::f32, {});++ auto op = make_op(a, b, idx, bias);++ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{2, 64, 4096}));+}++// 4D group-compressed weights+TEST_F(GatherMatmulTest, shape_weights_4d_grouped) {+ auto a = make_param(element::f32, {1, 64, 2048});+ auto b = make_const(element::f32, {8, 4096, 16, 128});+ auto idx = make_param(element::i32, {64, 2});++ auto op = make_op(a, b, idx);++ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{2, 64, 4096}));+}++// Output element type should match input A+TEST_F(GatherMatmulTest, output_type_matches_A) {+ auto a = make_param(element::f16, {1, 64, 2048});+ auto b = make_const(element::f16, {8, 4096, 2048});+ auto idx = make_param(element::i32, {64, 2});++ auto op = make_op(a, b, idx);++ EXPECT_EQ(op->get_output_element_type(0), element::f16);+}++// Dynamic sequence length in A and indices+TEST_F(GatherMatmulTest, shape_dynamic_seq_len) {+ auto a = make_param(element::f32, {1, Dimension::dynamic(), 2048});+ auto b = make_const(element::f32, {8, 4096, 2048});+ auto idx = make_param(element::i32, {Dimension::dynamic(), 2});++ auto op = make_op(a, b, idx);++ const auto& out = op->get_output_partial_shape(0);+ EXPECT_EQ(out[0], 2);+ EXPECT_TRUE(out[1].is_dynamic());+ EXPECT_EQ(out[2], 4096);+}++// Dynamic topk dimension+TEST_F(GatherMatmulTest, shape_dynamic_topk) {+ auto a = make_param(element::f32, {Dimension::dynamic(), 64, 2048});+ auto b = make_const(element::f32, {8, 4096, 2048});+ auto idx = make_param(element::i32, {64, Dimension::dynamic()});++ auto op = make_op(a, b, idx);++ const auto& out = op->get_output_partial_shape(0);+ EXPECT_TRUE(out[0].is_dynamic());+ EXPECT_EQ(out[1], 64);+ EXPECT_EQ(out[2], 4096);+}++// Edge case: single expert, topk=1+TEST_F(GatherMatmulTest, shape_single_expert) {+ auto a = make_param(element::f32, {1, 32, 1024});+ auto b = make_const(element::f32, {1, 512, 1024});+ auto idx = make_param(element::i32, {32, 1});++ auto op = make_op(a, b, idx);++ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{1, 32, 512}));+}++// ============================================================================+// Negative tests — GatherMatmul validation failures+// ============================================================================++TEST_F(GatherMatmulTest, fail_A_rank_2d) {+ auto a = make_param(element::f32, {64, 2048});+ auto b = make_const(element::f32, {8, 4096, 2048});+ auto idx = make_param(element::i32, {64, 2});++ OV_EXPECT_THROW(std::ignore = make_op(a, b, idx),+ ov::NodeValidationFailure,+ testing::HasSubstr("Input A rank must be exactly 3D"));+}++TEST_F(GatherMatmulTest, fail_A_rank_4d) {+ auto a = make_param(element::f32, {1, 1, 64, 2048});+ auto b = make_const(element::f32, {8, 4096, 2048});+ auto idx = make_param(element::i32, {64, 2});++ OV_EXPECT_THROW(std::ignore = make_op(a, b, idx),+ ov::NodeValidationFailure,+ testing::HasSubstr("Input A rank must be exactly 3D"));+}++TEST_F(GatherMatmulTest, fail_B_rank_2d) {+ auto a = make_param(element::f32, {1, 64, 2048});+ auto b = make_const(element::f32, {4096, 2048});+ auto idx = make_param(element::i32, {64, 2});++ OV_EXPECT_THROW(std::ignore = make_op(a, b, idx),+ ov::NodeValidationFailure,+ testing::HasSubstr("Input B rank must be 3D or 4D"));+}++TEST_F(GatherMatmulTest, fail_B_rank_5d) {+ auto a = make_param(element::f32, {1, 64, 2048});+ auto b = make_const(element::f32, {8, 4096, 4, 4, 32});+ auto idx = make_param(element::i32, {64, 2});++ OV_EXPECT_THROW(std::ignore = make_op(a, b, idx),+ ov::NodeValidationFailure,+ testing::HasSubstr("Input B rank must be 3D or 4D"));+}++TEST_F(GatherMatmulTest, fail_indices_rank_1d) {+ auto a = make_param(element::f32, {1, 64, 2048});+ auto b = make_const(element::f32, {8, 4096, 2048});+ auto idx = make_param(element::i32, {64});++ OV_EXPECT_THROW(std::ignore = make_op(a, b, idx),+ ov::NodeValidationFailure,+ testing::HasSubstr("Input indices rank must be exactly 2D"));+}++TEST_F(GatherMatmulTest, fail_indices_rank_3d) {+ auto a = make_param(element::f32, {1, 64, 2048});+ auto b = make_const(element::f32, {8, 4096, 2048});+ auto idx = make_param(element::i32, {1, 64, 2});++ OV_EXPECT_THROW(std::ignore = make_op(a, b, idx),+ ov::NodeValidationFailure,+ testing::HasSubstr("Input indices rank must be exactly 2D"));+}++TEST_F(GatherMatmulTest, fail_bias_rank_2d) {+ auto a = make_param(element::f32, {1, 64, 2048});+ auto b = make_const(element::f32, {8, 4096, 2048});+ auto idx = make_param(element::i32, {64, 2});+ auto bias = make_const(element::f32, {1, 4096});++ OV_EXPECT_THROW(std::ignore = make_op(a, b, idx, bias),+ ov::NodeValidationFailure,+ testing::HasSubstr("Input bias rank must be either 1D, scalar"));+}++// A[0]=3 but topk=2 → 3 is neither 1 nor 2+TEST_F(GatherMatmulTest, fail_A0_not_broadcastable_to_topk) {+ auto a = make_param(element::f32, {3, 64, 2048});+ auto b = make_const(element::f32, {8, 4096, 2048});+ auto idx = make_param(element::i32, {64, 2});++ OV_EXPECT_THROW(std::ignore = make_op(a, b, idx),+ ov::NodeValidationFailure,+ testing::HasSubstr("first dimension of input A must be equal"));+}++// topk=8 > n_experts=4+TEST_F(GatherMatmulTest, fail_topk_exceeds_experts) {+ auto a = make_param(element::f32, {1, 64, 2048});+ auto b = make_const(element::f32, {4, 4096, 2048});+ auto idx = make_param(element::i32, {64, 8});++ OV_EXPECT_THROW(std::ignore = make_op(a, b, idx),+ ov::NodeValidationFailure,+ testing::HasSubstr("second dimension of input indices must be less"));+}++// A[1]=64 but idx[0]=32+TEST_F(GatherMatmulTest, fail_seq_length_mismatch) {+ auto a = make_param(element::f32, {1, 64, 2048});+ auto b = make_const(element::f32, {8, 4096, 2048});+ auto idx = make_param(element::i32, {32, 2});++ OV_EXPECT_THROW(std::ignore = make_op(a, b, idx),+ ov::NodeValidationFailure,+ testing::HasSubstr("first dimension of input indices must be equal"));+}++// ============================================================================+// Clone tests+// ============================================================================++TEST_F(GatherMatmulTest, clone_preserves_output_shape) {+ auto a = make_param(element::f32, {1, 64, 2048});+ auto b = make_const(element::f32, {8, 4096, 2048});+ auto idx = make_param(element::i32, {64, 2});++ auto op = make_op(a, b, idx);+ auto cloned = op->clone_with_new_inputs({a, b, idx, make_empty_bias()});++ EXPECT_EQ(cloned->get_output_partial_shape(0), op->get_output_partial_shape(0));+ EXPECT_EQ(cloned->get_output_element_type(0), op->get_output_element_type(0));+}++} // namespace ov::testsdiff --git a/src/plugins/intel_cpu/src/cpu_types.cpp b/src/plugins/intel_cpu/src/cpu_types.cppindex 26a517dc2d9..aa4a5d7eee9 100644--- a/src/plugins/intel_cpu/src/cpu_types.cpp+++ b/src/plugins/intel_cpu/src/cpu_types.cpp@@ -262,8 +262,8 @@ static const TypeToNameMap& get_type_to_name_tbl() {{"RMS", Type::RMS},{"SearchSorted", Type::SearchSorted},{"LoraSubgraph", Type::LoRA},- {"BatchGatherMatmul", Type::GatherMatmul},- {"BatchGatherMatmulCompressed", Type::GatherMatmul},+ {"GatherMatmul", Type::GatherMatmul},+ {"GatherMatmulCompressed", Type::GatherMatmul},{"GatedDeltaNet", Type::GatedDeltaNet}};return type_to_name_tbl;}diff --git a/src/plugins/intel_cpu/src/nodes/gathermatmul.cpp b/src/plugins/intel_cpu/src/nodes/gathermatmul.cppindex 68168f700fe..ed01a20109e 100644--- a/src/plugins/intel_cpu/src/nodes/gathermatmul.cpp+++ b/src/plugins/intel_cpu/src/nodes/gathermatmul.cpp@@ -41,9 +41,9 @@#include "openvino/core/type.hpp"#include "openvino/core/type/element_type.hpp"#include "openvino/op/constant.hpp"+#include "ov_ops/gather_matmul.hpp"+#include "ov_ops/gather_matmul_compressed.hpp"#include "shape_inference/custom/gathermatmul.hpp"-#include "transformations/cpu_opset/common/op/batch_gather_matmul.hpp"-#include "transformations/cpu_opset/common/op/batch_gather_matmul_compressed.hpp"#include "transformations/utils/utils.hpp"#include "utils/general_utils.h"@@ -242,12 +242,12 @@ private:bool GatherMatmul::isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept {try {- // Check if the operation is BatchGatherMatmul or BatchGatherMatmulCompressed- const bool isBatchGatherMatmul = ov::is_type<ov::intel_cpu::BatchGatherMatmul>(op);- const bool isBatchGatherMatmulCompressed = ov::is_type<ov::intel_cpu::BatchGatherMatmulCompressed>(op);+ // Check if the operation is GatherMatmul or GatherMatmulCompressed+ const bool isGatherMatmul = ov::is_type<ov::op::internal::GatherMatmul>(op);+ const bool isGatherMatmulCompressed = ov::is_type<ov::op::internal::GatherMatmulCompressed>(op);- if (!isBatchGatherMatmul && !isBatchGatherMatmulCompressed) {- errorMessage = "Only BatchGatherMatmul and BatchGatherMatmulCompressed operations are supported. Got: " ++ if (!isGatherMatmul && !isGatherMatmulCompressed) {+ errorMessage = "Only GatherMatmul and GatherMatmulCompressed operations are supported. Got: " +std::string(op->get_type_info().name);return false;}@@ -259,7 +259,7 @@ bool GatherMatmul::isSupportedOperation(const std::shared_ptr<const ov::Node>& o}// For compressed variant, check that scales and zero points are constant- if (isBatchGatherMatmulCompressed) {+ if (isGatherMatmulCompressed) {if (op->get_input_size() > WEIGHT_SCALES) {if (!ov::op::util::is_on_path<ov::op::v0::Constant>(op->input_value(WEIGHT_SCALES))) {errorMessage = "Only constant weight scales are supported for GatherMatmul operation";@@ -371,7 +371,7 @@ GatherMatmul::GatherMatmul(const std::shared_ptr<ov::Node>& op, const GraphConte}// Determine the algorithm type- if (ov::is_type<ov::intel_cpu::BatchGatherMatmulCompressed>(op)) {+ if (ov::is_type<ov::op::internal::GatherMatmulCompressed>(op)) {algorithm = Algorithm::GatherMatmulCompressed;} else {algorithm = Algorithm::GatherMatmulDefault;diff --git a/src/plugins/intel_cpu/src/shape_inference/custom/gathermatmul.hpp b/src/plugins/intel_cpu/src/shape_inference/custom/gathermatmul.hppindex f8591840324..db11f44271e 100644--- a/src/plugins/intel_cpu/src/shape_inference/custom/gathermatmul.hpp+++ b/src/plugins/intel_cpu/src/shape_inference/custom/gathermatmul.hpp@@ -41,7 +41,7 @@ public:explicit GatherMatmulShapeInferFactory(const std::shared_ptr<ov::Node>& op) : m_op(op) {}[[nodiscard]] ShapeInferPtr makeShapeInfer() const override {- // BatchGatherMatmul has fixed transpose settings: transpose_a=false, transpose_b=true+ // GatherMatmul has fixed transpose settings: transpose_a=false, transpose_b=trueOPENVINO_DEBUG_ASSERT(m_op->get_output_partial_shape(0).rank().get_length() == 3,"GatherMatmul output must be 3D, got rank: ",m_op->get_output_partial_shape(0).rank().get_length());diff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul_compressed.cpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul_compressed.cppdeleted file mode 100644index f8458d25297..00000000000--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul_compressed.cpp+++ /dev/null@@ -1,56 +0,0 @@-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#include "batch_gather_matmul_compressed.hpp"--#include <memory>--#include "batch_gather_matmul.hpp"-#include "openvino/core/attribute_visitor.hpp"-#include "openvino/core/node.hpp"-#include "openvino/core/node_vector.hpp"-#include "openvino/core/type.hpp"-#include "openvino/op/constant.hpp"-#include "transformations/itt.hpp"--namespace ov::intel_cpu {--BatchGatherMatmulCompressed::BatchGatherMatmulCompressed(const ov::Output<Node>& A,- const ov::Output<Node>& B,- const ov::Output<Node>& indices,- const ov::Output<Node>& bias,- const ov::Output<Node>& weight_scales,- const ov::Output<Node>& weight_zero_points)- : BatchGatherMatmul(A, B, indices, bias) {- set_argument(4, weight_scales);- set_argument(5, weight_zero_points);- validate_and_infer_types();-}--std::shared_ptr<ov::Node> BatchGatherMatmulCompressed::clone_with_new_inputs(const ov::OutputVector& new_args) const {- check_new_args_count(this, new_args);- return std::make_shared<BatchGatherMatmulCompressed>(new_args.at(0),- new_args.at(1),- new_args.at(2),- new_args.at(3),- new_args.at(4),- new_args.at(5));-}--void BatchGatherMatmulCompressed::validate_and_infer_types() {- const auto input_size = get_input_size();- NODE_VALIDATION_CHECK(this, input_size == 6, "Number of inputs is incorrect. Current value is: ", input_size);-- // check weight_scales and weight_zero_points are Const- auto weight_scales = get_input_node_shared_ptr(4);- NODE_VALIDATION_CHECK(this,- ov::is_type<ov::op::v0::Constant>(weight_scales),- "Input weight_scales must be a Constant node.");- auto weight_zero_points = get_input_node_shared_ptr(5);- NODE_VALIDATION_CHECK(this,- ov::is_type<ov::op::v0::Constant>(weight_zero_points),- "Input weight_zero_points must be a Constant node.");- BatchGatherMatmul::validate_and_infer_types();-}-} // namespace ov::intel_cpu\ No newline at end of filediff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul_compressed.hpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul_compressed.hppdeleted file mode 100644index d38a7e00ade..00000000000--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul_compressed.hpp+++ /dev/null@@ -1,35 +0,0 @@-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#pragma once--#include <memory>--#include "batch_gather_matmul.hpp"-#include "openvino/core/attribute_visitor.hpp"-#include "openvino/core/node.hpp"-#include "openvino/core/node_vector.hpp"-#include "openvino/op/op.hpp"--namespace ov::intel_cpu {--class BatchGatherMatmulCompressed : public BatchGatherMatmul {-public:- OPENVINO_OP("BatchGatherMatmulCompressed", "cpu_plugin_opset", BatchGatherMatmul);-- BatchGatherMatmulCompressed() = default;-- BatchGatherMatmulCompressed(const ov::Output<Node>& A,- const ov::Output<Node>& B,- const ov::Output<Node>& indices,- const ov::Output<Node>& bias,- const ov::Output<Node>& weight_scales,- const ov::Output<Node>& weight_zero_points);-- std::shared_ptr<Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;-- void validate_and_infer_types() override;-};--} // namespace ov::intel_cpu\ No newline at end of filediff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/convert_batch_gather_matmul_to_compressed.hpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/convert_batch_gather_matmul_to_compressed.hppdeleted file mode 100644index 43c8148ea50..00000000000--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/convert_batch_gather_matmul_to_compressed.hpp+++ /dev/null@@ -1,30 +0,0 @@-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#pragma once--#include <functional>-#include <memory>-#include <vector>--#include "openvino/pass/matcher_pass.hpp"-#include "transformations/cpu_opset/common/op/batch_gather_matmul_compressed.hpp"--namespace ov::intel_cpu {--class ConvertBatchGatherMatmulToBatchGatherMatmulCompressed : public ov::pass::MatcherPass {-public:- OPENVINO_MATCHER_PASS_RTTI("ConvertBatchGatherMatmulToBatchGatherMatmulCompressed");-- using SupportsPredicate =- std::function<bool(const std::shared_ptr<ov::intel_cpu::BatchGatherMatmulCompressed>&, size_t, size_t, size_t)>;-- ConvertBatchGatherMatmulToBatchGatherMatmulCompressed(- const std::vector<ov::element::Type>& supported_activation_types,- const std::vector<ov::element::Type>& supported_weights_types,- const SupportsPredicate& supports_config = nullptr,- bool convert_u4zp_to_u8 = false);-};--} // namespace ov::intel_cpu\ No newline at end of filediff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/moe_matmuls_fusion.cpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/moe_matmuls_fusion.cppdeleted file mode 100644index 2b8d7fc2c9a..00000000000--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/moe_matmuls_fusion.cpp+++ /dev/null@@ -1,357 +0,0 @@-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#include "moe_matmuls_fusion.hpp"--#include <initializer_list>-#include <memory>-#include <string>--#include "itt.hpp"-#include "openvino/cc/pass/itt.hpp"-#include "openvino/core/graph_util.hpp"-#include "openvino/core/node.hpp"-#include "openvino/core/node_output.hpp"-#include "openvino/core/rt_info.hpp"-#include "openvino/core/type/element_type.hpp"-#include "openvino/op/add.hpp"-#include "openvino/op/broadcast.hpp"-#include "openvino/op/clamp.hpp"-#include "openvino/op/constant.hpp"-#include "openvino/op/matmul.hpp"-#include "openvino/op/minimum.hpp"-#include "openvino/op/multiply.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/swish.hpp"-#include "openvino/op/tile.hpp"-#include "openvino/op/transpose.hpp"-#include "openvino/op/unsqueeze.hpp"-#include "openvino/pass/matcher_pass.hpp"-#include "openvino/pass/pattern/matcher.hpp"-#include "openvino/pass/pattern/op/label.hpp"-#include "openvino/pass/pattern/op/optional.hpp"-#include "openvino/pass/pattern/op/pattern.hpp"-#include "openvino/pass/pattern/op/wrap_type.hpp"-#include "transformations/cpu_opset/common/op/batch_gather_matmul.hpp"--using namespace ov::pass;-namespace {-// Note: intermediate nodes remain unchanged,-// but we need to explicitly call shape inference for them to keep shapes consistency-void validate_nodes(const pattern::PatternValueMap& map, const std::initializer_list<std::shared_ptr<ov::Node>> nodes) {- for (const auto& node : nodes) {- map.at(node).get_node_shared_ptr()->validate_and_infer_types();- }-};--std::shared_ptr<ov::op::v0::Unsqueeze> introduce_n_experts_dim(const ov::Output<ov::Node>& data) {- auto zero_const = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{}, 0);- auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(data, zero_const);- ov::copy_runtime_info(data.get_node_shared_ptr(), {unsqueeze, zero_const});- return unsqueeze;-}-} // namespace--ov::intel_cpu::MoE2GeMMFusion::MoE2GeMMFusion() {- MATCHER_SCOPE(MoE2GeMMFusion);-- auto data_input = pattern::any_input(pattern::rank_equals(3) && pattern::has_static_rank());- auto experts_input = pattern::wrap_type<ov::op::v1::Reshape>({data_input, pattern::any_input()});- auto tile =- pattern::wrap_type<ov::op::v0::Tile>({experts_input, pattern::any_input()}, pattern::consumers_count(1));- auto after_tile_reshape =- pattern::wrap_type<ov::op::v1::Reshape>({tile, pattern::any_input()}, pattern::consumers_count(1));- auto gate_up_matmul = pattern::wrap_type<ov::op::v0::MatMul>({after_tile_reshape, pattern::any_input()},- pattern::consumers_count(1),- {{"transpose_a", false}, {"transpose_b", true}});- auto gate_up_bias = pattern::wrap_const();- auto gate_up_add = pattern::wrap_type<ov::op::v1::Add>({gate_up_matmul, gate_up_bias}, pattern::consumers_count(2));-- // Branch 1: Slice_1 -> Clamp -> Add_1- auto slice1 = pattern::wrap_type<ov::op::v8::Slice>(- {gate_up_add, pattern::any_input(), pattern::any_input(), pattern::any_input(), pattern::any_input()},- pattern::consumers_count(1));- auto clamp = pattern::wrap_type<ov::op::v0::Clamp>({slice1}, pattern::consumers_count(1));- auto add1 = pattern::wrap_type<ov::op::v1::Add>({clamp, pattern::wrap_const()}, pattern::consumers_count(1));-- // Branch 2: Slice_2 -> Minimum_1 -> Swish- auto slice2 = pattern::wrap_type<ov::op::v8::Slice>(- {gate_up_add, pattern::any_input(), pattern::any_input(), pattern::any_input(), pattern::any_input()},- pattern::consumers_count(1));- auto minimum1 =- pattern::wrap_type<ov::op::v1::Minimum>({slice2, pattern::wrap_const()}, pattern::consumers_count(1));- auto swish_beta = pattern::wrap_const();- auto swish = pattern::wrap_type<ov::op::v4::Swish>({minimum1, swish_beta}, pattern::consumers_count(1));-- // Join: Multiply_2- auto multiply2 = pattern::wrap_type<ov::op::v1::Multiply>({add1, swish}, pattern::consumers_count(1));-- // Down projection- auto down_proj_matmul = pattern::wrap_type<ov::op::v0::MatMul>({multiply2, pattern::any_input()},- pattern::consumers_count(1),- {{"transpose_a", false}, {"transpose_b", true}});- auto down_proj_bias = pattern::wrap_const();- auto down_proj_add =- pattern::wrap_type<ov::op::v1::Add>({down_proj_matmul, down_proj_bias}, pattern::consumers_count(1));- auto end_reshape_target_shape = pattern::any_input();- auto end_reshape =- pattern::wrap_type<ov::op::v1::Reshape>({down_proj_add, end_reshape_target_shape}, pattern::consumers_count(1));-- // Routing weights/mask- auto zero_constant = pattern::wrap_type<ov::op::v0::Constant>(pattern::value_matches("0"));- auto broadcasted_const = pattern::wrap_type<ov::op::v3::Broadcast>({zero_constant, pattern::any_input()}) |- pattern::wrap_type<ov::op::v1::Broadcast, ov::op::v3::Broadcast>(- {zero_constant, pattern::any_input(), pattern::any_input()});- // Routing weights/mask- auto router_topk_indices = pattern::any_input();- auto chosen_experts = pattern::any_input();- auto slice_begin = pattern::wrap_type<ov::op::v0::Constant>(pattern::value_matches("0, 0"));- auto slice_end = pattern::wrap_type<ov::op::v3::ShapeOf>({pattern::any_input()});- auto slice_strides = pattern::wrap_type<ov::op::v0::Constant>(pattern::value_matches("1, 1"));- auto slice_axes = pattern::wrap_type<ov::op::v0::Constant>(pattern::value_matches("0, 1"));- auto slice =- pattern::optional<ov::op::v8::Slice>({chosen_experts, slice_begin, slice_end, slice_strides, slice_axes});- auto one_constant = pattern::wrap_type<ov::op::v0::Constant>(pattern::value_matches("1"));- auto scatter_elements_update = pattern::wrap_type<ov::op::v3::ScatterElementsUpdate>(- {broadcasted_const, router_topk_indices, chosen_experts, one_constant}) |- pattern::wrap_type<ov::op::v12::ScatterElementsUpdate>(- {broadcasted_const, router_topk_indices, chosen_experts, one_constant},- {{"reduction", "none"}});-- auto router_transpose = pattern::wrap_type<ov::op::v1::Transpose>({scatter_elements_update, pattern::any_input()});- auto router_reshape =- pattern::wrap_type<ov::op::v1::Reshape>({router_transpose, pattern::any_input()},- ov::pass::pattern::rank_equals(3) || ov::pass::pattern::rank_equals(4));- auto unsqueeze_axis =- pattern::wrap_type<ov::op::v0::Constant>(pattern::value_matches("3") || pattern::value_matches("-1"));- auto unsqueeze_routing_weights =- pattern::optional<ov::op::v0::Unsqueeze>({router_reshape, unsqueeze_axis}, ov::pass::pattern::rank_equals(4));-- auto mul3 =- pattern::wrap_type<ov::op::v1::Multiply>({end_reshape, unsqueeze_routing_weights}, pattern::consumers_count(1));- auto reduce_sum = pattern::wrap_type<ov::op::v1::ReduceSum>({mul3, pattern::any_input()},- pattern::consumers_count(1),- {{"keep_dims", false}});-- ov::matcher_pass_callback callback = [=](ov::pass::pattern::Matcher& m) {- const auto& pattern_map = m.get_pattern_value_map();- const auto& experts_subgraph_input = pattern_map.at(experts_input);- const auto& active_indices = pattern_map.at(router_topk_indices);-- const auto gate_up_mm_node = pattern_map.at(gate_up_matmul).get_node_shared_ptr();- const auto gate_up_add_node = pattern_map.at(gate_up_add).get_node_shared_ptr();- const auto gate_up_bias_node = pattern_map.at(gate_up_bias).get_node_shared_ptr();-- // BatchGatherMatmul A shape: [n_activated_experts, batch_size * seq_length, hidden_size]- // Number of activated experts is always 1 for the first BatchGatherMatmul- const auto unsqueeze = introduce_n_experts_dim(experts_subgraph_input);- const auto gate_up_gathered_mm = std::make_shared<BatchGatherMatmul>(unsqueeze,- gate_up_mm_node->input_value(1),- active_indices,- gate_up_bias_node);- ov::replace_node_update_name(gate_up_add_node, gate_up_gathered_mm);-- validate_nodes(pattern_map, {slice1, clamp, add1, slice2, minimum1, swish, multiply2});-- const auto down_proj_mm_node = pattern_map.at(down_proj_matmul).get_node_shared_ptr();- const auto down_proj_bias_node = pattern_map.at(down_proj_bias).get_node_shared_ptr();-- const auto down_gathered_mm = std::make_shared<BatchGatherMatmul>(pattern_map.at(multiply2),- down_proj_mm_node->input_value(1),- active_indices,- down_proj_bias_node);- ov::copy_runtime_info(down_proj_mm_node, down_gathered_mm);- down_gathered_mm->set_friendly_name(down_proj_mm_node->get_friendly_name());-- const auto& chosen_experts_input = pattern_map.at(chosen_experts);- const auto router_transpose_node = pattern_map.at(router_transpose).get_node_shared_ptr();- const auto new_router_transpose =- router_transpose_node->clone_with_new_inputs({chosen_experts_input, router_transpose_node->input_value(1)});- ov::copy_runtime_info(router_transpose_node, new_router_transpose);- new_router_transpose->set_friendly_name(router_transpose_node->get_friendly_name());-- const auto router_unsqueeze_const = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {-1});- const auto router_unsqueeze =- std::make_shared<ov::op::v0::Unsqueeze>(new_router_transpose, router_unsqueeze_const);- ov::copy_runtime_info(router_transpose_node, {router_unsqueeze_const, router_unsqueeze});-- const auto final_mul_node = pattern_map.at(mul3).get_node_shared_ptr();- const auto new_final_mul =- final_mul_node->clone_with_new_inputs({down_gathered_mm->output(0), router_unsqueeze->output(0)});- ov::copy_runtime_info(final_mul_node, new_final_mul);- new_final_mul->set_friendly_name(final_mul_node->get_friendly_name());-- const auto reduce_sum_node = pattern_map.at(reduce_sum).get_node_shared_ptr();- const auto new_reduce_sum =- reduce_sum_node->clone_with_new_inputs({new_final_mul->output(0), reduce_sum_node->input_value(1)});- ov::copy_runtime_info(reduce_sum_node, new_reduce_sum);- new_reduce_sum->set_friendly_name(reduce_sum_node->get_friendly_name());-- const auto& end_reshape_out = pattern_map.at(end_reshape);- const auto end_reshape_rank = end_reshape_out.get_partial_shape().rank();- const auto& end_reshape_shape = pattern_map.at(end_reshape_target_shape);- // n_all_experts dimension is cut off after ReduceSum- const auto slice = std::make_shared<ov::op::v8::Slice>(- end_reshape_shape,- ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1}, {1}),- ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1}, {end_reshape_rank.get_length()}),- ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1}, {1}),- ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1}, {0}));- ov::copy_runtime_info(end_reshape_out.get_node_shared_ptr(),- {slice,- slice->get_input_node_shared_ptr(1),- slice->get_input_node_shared_ptr(2),- slice->get_input_node_shared_ptr(3),- slice->get_input_node_shared_ptr(4)});-- const auto reshape = std::make_shared<ov::op::v1::Reshape>(new_reduce_sum, slice, true);- ov::replace_output_update_name(pattern_map.at(reduce_sum), reshape->output(0));- // To avoid friendly name duplication- reshape->set_friendly_name(reshape->get_friendly_name() + "_Reshape");- return true;- };-- auto m = std::make_shared<ov::pass::pattern::Matcher>(reduce_sum, matcher_name);- this->register_matcher(m, callback);-}--ov::intel_cpu::MoE3GeMMFusion::MoE3GeMMFusion() {- MATCHER_SCOPE(MoE3GeMMFusion);-- auto data_input = pattern::any_input(pattern::rank_equals(3) && pattern::has_static_rank());- auto experts_input =- pattern::wrap_type<ov::op::v1::Reshape>({data_input, pattern::any_input()}, pattern::rank_equals(2));- auto tile =- pattern::wrap_type<ov::op::v0::Tile>({experts_input, pattern::any_input()}, pattern::consumers_count(1));- auto after_tile_reshape =- pattern::wrap_type<ov::op::v1::Reshape>({tile, pattern::any_input()}, pattern::consumers_count(2));-- // First GEMM (activation gate)- auto gate_matmul = pattern::wrap_type<ov::op::v0::MatMul>({after_tile_reshape, pattern::any_input()},- pattern::consumers_count(1),- {{"transpose_a", false}, {"transpose_b", true}});- auto swish = pattern::wrap_type<ov::op::v4::Swish>({gate_matmul}, pattern::consumers_count(1));- // Second GEMM (up_projection)- auto up_matmul = pattern::wrap_type<ov::op::v0::MatMul>({after_tile_reshape, pattern::any_input()},- pattern::consumers_count(1),- {{"transpose_a", false}, {"transpose_b", true}});- // Join: Multiply (SwiGLU)- auto swiglu = pattern::wrap_type<ov::op::v1::Multiply>({swish, up_matmul}, pattern::consumers_count(1));-- // Third GEMM (down_projection)- auto down_matmul = pattern::wrap_type<ov::op::v0::MatMul>({swiglu, pattern::any_input()},- pattern::consumers_count(1),- {{"transpose_a", false}, {"transpose_b", true}});- auto end_reshape_target_shape = pattern::any_input();- auto end_reshape =- pattern::wrap_type<ov::op::v1::Reshape>({down_matmul, end_reshape_target_shape}, pattern::consumers_count(1));-- auto zero_constant = pattern::wrap_type<ov::op::v0::Constant>(pattern::value_matches("0"));- auto broadcasted_const = pattern::wrap_type<ov::op::v3::Broadcast>({zero_constant, pattern::any_input()}) |- pattern::wrap_type<ov::op::v1::Broadcast, ov::op::v3::Broadcast>(- {zero_constant, pattern::any_input(), pattern::any_input()});- // Routing weights/mask- auto router_topk_indices = pattern::any_input();- auto chosen_experts = pattern::any_input();- auto one_constant = pattern::wrap_type<ov::op::v0::Constant>(pattern::value_matches("1"));- auto scatter_elements_update = pattern::wrap_type<ov::op::v3::ScatterElementsUpdate>(- {broadcasted_const, router_topk_indices, chosen_experts, one_constant}) |- pattern::wrap_type<ov::op::v12::ScatterElementsUpdate>(- {broadcasted_const, router_topk_indices, chosen_experts, one_constant},- {{"reduction", "none"}});-- auto router_transpose = pattern::wrap_type<ov::op::v1::Transpose>({scatter_elements_update, pattern::any_input()});- auto router_reshape =- pattern::wrap_type<ov::op::v1::Reshape>({router_transpose, pattern::any_input()},- ov::pass::pattern::rank_equals(3) || ov::pass::pattern::rank_equals(4));- auto unsqueeze_axis =- pattern::wrap_type<ov::op::v0::Constant>(pattern::value_matches("3") || pattern::value_matches("-1"));- auto unsqueeze_routing_weights =- pattern::optional<ov::op::v0::Unsqueeze>({router_reshape, unsqueeze_axis}, ov::pass::pattern::rank_equals(4));-- auto mul3 =- pattern::wrap_type<ov::op::v1::Multiply>({end_reshape, unsqueeze_routing_weights}, pattern::consumers_count(1));- auto reduce_sum = pattern::wrap_type<ov::op::v1::ReduceSum>({mul3, pattern::any_input()},- pattern::consumers_count(1),- {{"keep_dims", false}});-- ov::matcher_pass_callback callback = [=](ov::pass::pattern::Matcher& m) {- const auto& pattern_map = m.get_pattern_value_map();- const auto& experts_subgraph_input = pattern_map.at(experts_input);- const auto& active_indices = pattern_map.at(router_topk_indices);-- const auto gate_mm_node = pattern_map.at(gate_matmul).get_node_shared_ptr();- const auto up_mm_node = pattern_map.at(up_matmul).get_node_shared_ptr();- const auto down_mm_node = pattern_map.at(down_matmul).get_node_shared_ptr();-- // BatchGatherMatmul A shape: [n_activated_experts, batch_size * seq_length, hidden_size]- // Number of activated experts is always 1 for the first BatchGatherMatmul- const auto unsqueeze = introduce_n_experts_dim(experts_subgraph_input);- const auto gate_gathered_mm =- std::make_shared<BatchGatherMatmul>(unsqueeze, gate_mm_node->input_value(1), active_indices);- const auto up_gathered_mm =- std::make_shared<BatchGatherMatmul>(unsqueeze, up_mm_node->input_value(1), active_indices);- ov::replace_node_update_name(gate_mm_node, gate_gathered_mm);- ov::replace_node_update_name(up_mm_node, up_gathered_mm);-- validate_nodes(pattern_map, {swish, swiglu});-- const auto down_gathered_mm =- std::make_shared<BatchGatherMatmul>(pattern_map.at(swiglu), down_mm_node->input_value(1), active_indices);- ov::copy_runtime_info(down_mm_node, down_gathered_mm);- down_gathered_mm->set_friendly_name(down_mm_node->get_friendly_name());-- const auto& chosen_experts_input = pattern_map.at(chosen_experts);- const auto router_transpose_node = pattern_map.at(router_transpose).get_node_shared_ptr();- const auto new_router_transpose =- router_transpose_node->clone_with_new_inputs({chosen_experts_input, router_transpose_node->input_value(1)});- ov::copy_runtime_info(router_transpose_node, new_router_transpose);- new_router_transpose->set_friendly_name(router_transpose_node->get_friendly_name());-- const auto router_unsqueeze_const = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {-1});- const auto router_unsqueeze =- std::make_shared<ov::op::v0::Unsqueeze>(new_router_transpose, router_unsqueeze_const);- ov::copy_runtime_info(router_transpose_node, {router_unsqueeze_const, router_unsqueeze});-- const auto final_mul_node = pattern_map.at(mul3).get_node_shared_ptr();- const auto new_final_mul =- final_mul_node->clone_with_new_inputs({down_gathered_mm->output(0), router_unsqueeze->output(0)});- ov::copy_runtime_info(final_mul_node, new_final_mul);- new_final_mul->set_friendly_name(final_mul_node->get_friendly_name());- const auto reduce_sum_node = pattern_map.at(reduce_sum).get_node_shared_ptr();- const auto new_reduce_sum =- reduce_sum_node->clone_with_new_inputs({new_final_mul->output(0), reduce_sum_node->input_value(1)});- ov::copy_runtime_info(reduce_sum_node, new_reduce_sum);- new_reduce_sum->set_friendly_name(reduce_sum_node->get_friendly_name());-- const auto& end_reshape_out = pattern_map.at(end_reshape);- const auto end_reshape_rank = end_reshape_out.get_partial_shape().rank();- const auto& end_reshape_shape = pattern_map.at(end_reshape_target_shape);- // n_all_experts dimension is cut off after ReduceSum- const auto slice = std::make_shared<ov::op::v8::Slice>(- end_reshape_shape,- ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1}, {1}),- ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1}, {end_reshape_rank.get_length()}),- ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1}, {1}),- ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1}, {0}));- ov::copy_runtime_info(end_reshape_out.get_node_shared_ptr(),- {slice,- slice->get_input_node_shared_ptr(1),- slice->get_input_node_shared_ptr(2),- slice->get_input_node_shared_ptr(3),- slice->get_input_node_shared_ptr(4)});-- const auto reshape = std::make_shared<ov::op::v1::Reshape>(new_reduce_sum, slice, true);- ov::replace_output_update_name(pattern_map.at(reduce_sum), reshape->output(0));- reshape->set_friendly_name(new_reduce_sum->get_friendly_name() + "_Reshape");- return true;- };-- auto m = std::make_shared<ov::pass::pattern::Matcher>(reduce_sum, matcher_name);- this->register_matcher(m, callback);-}diff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/moe_matmuls_fusion.hpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/moe_matmuls_fusion.hppdeleted file mode 100644index 7623af91e89..00000000000--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/moe_matmuls_fusion.hpp+++ /dev/null@@ -1,33 +0,0 @@-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#pragma once--#include "openvino/pass/graph_rewrite.hpp"-#include "openvino/pass/matcher_pass.hpp"--namespace ov::intel_cpu {--class MoE2GeMMFusion : public ov::pass::MatcherPass {-public:- OPENVINO_MATCHER_PASS_RTTI("MoE2GeMMFusion");- MoE2GeMMFusion();-};--class MoE3GeMMFusion : public ov::pass::MatcherPass {-public:- OPENVINO_MATCHER_PASS_RTTI("MoE3GeMMFusion");- MoE3GeMMFusion();-};--class MoEMatMulsFusion : public ov::pass::GraphRewrite {-public:- OPENVINO_GRAPH_REWRITE_RTTI("MoEMatMulsFusion");- MoEMatMulsFusion() {- add_matcher<ov::intel_cpu::MoE2GeMMFusion>();- add_matcher<ov::intel_cpu::MoE3GeMMFusion>();- }-};--} // namespace ov::intel_cpudiff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/convert_to_cpu_specific_opset.hpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/convert_to_cpu_specific_opset.hppindex a7bb11811fa..30240f139d3 100644--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/convert_to_cpu_specific_opset.hpp+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/convert_to_cpu_specific_opset.hpp@@ -6,14 +6,12 @@#include <memory>#include "common/pass/align_matmul_input_ranks.hpp"-#include "common/pass/convert_batch_gather_matmul_to_compressed.hpp"#include "common/pass/convert_matmul_to_fc.hpp"#include "common/pass/convert_tile_to_seq_tiles.hpp"#include "common/pass/convert_to_leaky_relu.hpp"#include "common/pass/convert_to_power_static.hpp"#include "common/pass/convert_to_swish_cpu.hpp"#include "common/pass/fc_bias_fusion.hpp"-#include "common/pass/moe_matmuls_fusion.hpp"#include "common/pass/move_fc_reshape_to_weights.hpp"#include "common/pass/move_readvalue_inputs_to_subgraph.hpp"#include "common/pass/rnn_sequences_optimization.hpp"@@ -27,12 +25,14 @@#include "openvino/pass/manager.hpp"#include "openvino/pass/validate.hpp"#include "ov_ops/fully_connected.hpp"+#include "transformations/common_optimizations/convert_tiled_moe_block_to_gather_matmuls.hpp"#include "transformations/common_optimizations/nop_elimination.hpp"#include "transformations/common_optimizations/reshape_sequence_fusion.hpp"#include "transformations/convert_precision.hpp"#include "transformations/defs.hpp"#include "transformations/op_conversions/convert_fc_to_compressed.hpp"#include "transformations/op_conversions/convert_fc_to_quantized_legacy.hpp"+#include "transformations/op_conversions/convert_gather_matmul_to_compressed.hpp"namespace ov::intel_cpu {@@ -42,14 +42,15 @@ inline void ConvertToCPUSpecificOpset(std::shared_ptr<ov::Model>& model, const Cov::pass::Manager manager("CPU:ConvertToCPUSpecificOpset");manager.set_per_pass_validation(false);- CPU_REGISTER_PASS_X64(manager, MoEMatMulsFusion);+ // TransformMoeBlockToGatherMatmuls+ CPU_REGISTER_PASS_X64(manager, ov::pass::ConvertTiledMoeBlockToGatherMatmuls);CPU_REGISTER_PASS_X64(manager, ov::pass::Validate);CPU_REGISTER_PASS_X64(manager,- ConvertBatchGatherMatmulToBatchGatherMatmulCompressed,+ ov::pass::ConvertGatherMatmulToGatherMatmulCompressed,ov::intel_cpu::node::GatherMatmul::getSupportedCompressedActivationsTypes(),ov::intel_cpu::node::GatherMatmul::getSupportedCompressedWeightsTypes(),- [&](const std::shared_ptr<ov::intel_cpu::BatchGatherMatmulCompressed>& gather_matmul,+ [&](const std::shared_ptr<ov::op::internal::GatherMatmulCompressed>& gather_matmul,size_t IC,size_t OC,size_t G) {diff --git a/src/plugins/intel_cpu/tests/unit/transformations/convert_batch_gather_matmul_to_compressed_test.cpp b/src/plugins/intel_cpu/tests/unit/transformations/convert_gather_matmul_to_compressed_test.cppsimilarity index 84%rename from src/plugins/intel_cpu/tests/unit/transformations/convert_batch_gather_matmul_to_compressed_test.cpprename to src/plugins/intel_cpu/tests/unit/transformations/convert_gather_matmul_to_compressed_test.cppindex 5b952497e37..7740dbec186 100644--- a/src/plugins/intel_cpu/tests/unit/transformations/convert_batch_gather_matmul_to_compressed_test.cpp+++ b/src/plugins/intel_cpu/tests/unit/transformations/convert_gather_matmul_to_compressed_test.cpp@@ -2,7 +2,7 @@// SPDX-License-Identifier: Apache-2.0//-#include "transformations/cpu_opset/common/pass/convert_batch_gather_matmul_to_compressed.hpp"+#include "transformations/op_conversions/convert_gather_matmul_to_compressed.hpp"#include <memory>@@ -15,12 +15,11 @@#include "openvino/op/reshape.hpp"#include "openvino/op/subtract.hpp"#include "openvino/pass/manager.hpp"-#include "transformations/cpu_opset/common/op/batch_gather_matmul.hpp"-#include "transformations/cpu_opset/common/op/batch_gather_matmul_compressed.hpp"+#include "ov_ops/gather_matmul.hpp"+#include "ov_ops/gather_matmul_compressed.hpp"using namespace testing;using namespace ov::pass;-using namespace ov::intel_cpu;namespace {struct ConvertBGMToCompressedParams {@@ -46,8 +45,8 @@ TEST_P(ConvertBGMToCompressed, ConvertBGMToCompressedTest) {const std::vector<ov::element::Type> supported_activation_types{ov::element::f32};const std::vector<ov::element::Type> supported_weights_types{compressed_type_};- manager.register_pass<ConvertBatchGatherMatmulToBatchGatherMatmulCompressed>(supported_activation_types,- supported_weights_types);+ manager.register_pass<ConvertGatherMatmulToGatherMatmulCompressed>(supported_activation_types,+ supported_weights_types);auto weight_reshaped_dims = [&]() {std::vector<int64_t> wei_reshaped;for (size_t i = 0; i < wei_shape_.size() - 2; ++i) {@@ -80,7 +79,7 @@ TEST_P(ConvertBGMToCompressed, ConvertBGMToCompressedTest) {auto index = ov::op::v0::Constant::create(ov::element::i32, index_shape_, {1});- auto bgm = std::make_shared<BatchGatherMatmul>(input, wei_scale, index);+ auto bgm = std::make_shared<ov::op::internal::GatherMatmul>(input, wei_scale, index);model = std::make_shared<ov::Model>(ov::OutputVector{bgm}, ov::ParameterVector{input});}@@ -101,8 +100,12 @@ TEST_P(ConvertBGMToCompressed, ConvertBGMToCompressedTest) {auto zp_const = ov::op::v0::Constant::create(compressed_type_, scale_zp_shape, {1});auto index = ov::op::v0::Constant::create(ov::element::i32, index_shape_, {1});auto bias = std::make_shared<ov::op::v0::Constant>(ov::element::dynamic, ov::Shape{0});- auto bgm_compressed =- std::make_shared<BatchGatherMatmulCompressed>(input, weights_const, index, bias, scale_const, zp_const);+ auto bgm_compressed = std::make_shared<ov::op::internal::GatherMatmulCompressed>(input,+ weights_const,+ index,+ bias,+ scale_const,+ zp_const);model_ref = std::make_shared<ov::Model>(ov::OutputVector{bgm_compressed}, ov::ParameterVector{input});}