Skip to content

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

[GPU] MoE 3 GeMM: separate Router Subgraph and MoE body kernels (#35691)

Vladislav Golubev423bd283b1df
diff --git a/src/common/transformations/include/ov_ops/moe_compressed.hpp b/src/common/transformations/include/ov_ops/moe_compressed.hpp
index 133a61decb2..2075ac20bcf 100644
--- a/src/common/transformations/include/ov_ops/moe_compressed.hpp
+++ b/src/common/transformations/include/ov_ops/moe_compressed.hpp
@@ -19,8 +19,6 @@ public:
MOECompressed() = default;
- enum class RoutingType { SOFTMAX, SIGMOID_BIAS };
-
struct Config : public MOE::Config {
size_t hidden_size = 0;
size_t inter_size = 0;
@@ -35,20 +33,13 @@ public:
bool has_batch_dim = false;
bool has_zp = false;
ov::element::Type out_type = ov::element::dynamic;
- RoutingType routing_type = RoutingType::SOFTMAX;
std::optional<float> scale_factor;
};
/// \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.).
+ /// 1: routing_weights - [..., topk] normalized routing weights for selected experts.
/// 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]
@@ -86,20 +77,4 @@ 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 ov
diff --git a/src/common/transformations/src/ov_ops/moe_compressed.cpp b/src/common/transformations/src/ov_ops/moe_compressed.cpp
index e32a14316b3..c59a4bfc58b 100644
--- a/src/common/transformations/src/ov_ops/moe_compressed.cpp
+++ b/src/common/transformations/src/ov_ops/moe_compressed.cpp
@@ -21,6 +21,22 @@ void MOECompressed::validate_and_infer_types() {
set_output_type(0, output_type, get_input_partial_shape(0));
+ if (m_config.expert_type == Expert_type::GEMM2_BIAS_SWIGLU_CLAMP) {
+ NODE_VALIDATION_CHECK(this,
+ m_config.activation_type == Activation_type::SWIGLU,
+ "GEMM2_BIAS_SWIGLU_CLAMP expert type only supports SWIGLU activation");
+ }
+
+ // Check that routing_weights and router_topk_output_indices have the same shape
+ const auto& routing_weights_shape = get_input_partial_shape(1);
+ const auto& topk_indices_shape = get_input_partial_shape(2);
+ NODE_VALIDATION_CHECK(this,
+ routing_weights_shape == topk_indices_shape,
+ "routing_weights shape ",
+ routing_weights_shape,
+ " must be compatible with router_topk_output_indices shape ",
+ topk_indices_shape);
+
// Config carries a single group_size; gate/up/down must share it.
auto check_scale = [&](size_t scale_idx, size_t K, const char* name) {
if (scale_idx >= get_input_size())
@@ -164,28 +180,9 @@ bool MOECompressed::visit_attributes(ov::AttributeVisitor& visitor) {
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);
if (m_config.scale_factor.has_value())
visitor.on_attribute("scale_factor", m_config.scale_factor.value());
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 ov
diff --git a/src/common/transformations/src/transformations/common_optimizations/moe_op_fusion.cpp b/src/common/transformations/src/transformations/common_optimizations/moe_op_fusion.cpp
index 6a7cdf92324..badb4bee920 100644
--- a/src/common/transformations/src/transformations/common_optimizations/moe_op_fusion.cpp
+++ b/src/common/transformations/src/transformations/common_optimizations/moe_op_fusion.cpp
@@ -91,8 +91,10 @@ Convert3GatherMatmulMoeBlockToMoeOp::Convert3GatherMatmulMoeBlockToMoeOp(bool ha
{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_m = pattern::any_input();
+ auto routing_slice_m = pattern::optional<v8::Slice>(
+ {routing_m, pattern::any_input(), pattern::any_input(), pattern::any_input(), pattern::any_input()});
+ auto routing_transpose_m = pattern::wrap_type<v1::Transpose>({routing_slice_m, 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));
@@ -109,7 +111,7 @@ Convert3GatherMatmulMoeBlockToMoeOp::Convert3GatherMatmulMoeBlockToMoeOp(bool ha
auto hidden_states = pm.at(hidden_states_m);
- auto routing = pm.at(routing_unsqueeze_m).get_node_shared_ptr();
+ auto routing = pm.at(routing_m);
auto topk_indices = pm.at(topk_indices_m);
auto gate_w = pm.at(gate_w_m);
auto up_w = pm.at(up_w_m);
diff --git a/src/common/transformations/tests/common_optimizations/convert_gather_matmuls_moe_block_to_moe_op.cpp b/src/common/transformations/tests/common_optimizations/convert_gather_matmuls_moe_block_to_moe_op.cpp
index 7d63eb796cc..f2a47fc9727 100644
--- a/src/common/transformations/tests/common_optimizations/convert_gather_matmuls_moe_block_to_moe_op.cpp
+++ b/src/common/transformations/tests/common_optimizations/convert_gather_matmuls_moe_block_to_moe_op.cpp
@@ -395,14 +395,7 @@ inline std::shared_ptr<ov::Model> build_3gemm_bgm_to_moe_reference_model(
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}));
+ auto routing = router_topk->output(0);
// Weights
auto gate_w =
@@ -413,7 +406,7 @@ inline std::shared_ptr<ov::Model> build_3gemm_bgm_to_moe_reference_model(
op::v0::Constant::create(element::f32, Shape{number_of_experts, hidden_size, intermediate_size}, {1.0f});
// MOE op with compact routing
- ov::OutputVector moe_inputs = {input, router_unsqueeze, topk_indices, gate_w, up_w, down_w};
+ ov::OutputVector moe_inputs = {input, routing, 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;
config.activation_type = activation_type;
@@ -723,14 +716,7 @@ inline std::shared_ptr<ov::Model> build_3gemm_bgm_to_moe_reference_model_multipl
op::v11::TopK::SortType::SORT_VALUES,
element::i64);
auto topk_indices = router_topk->output(1);
- auto chosen_experts = router_topk->output(0);
-
- // 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 routing = router_topk->output(0);
// Weights
auto gate_w =
@@ -741,7 +727,7 @@ inline std::shared_ptr<ov::Model> build_3gemm_bgm_to_moe_reference_model_multipl
op::v0::Constant::create(element::f32, Shape{number_of_experts, hidden_size, intermediate_size}, {1.0f});
// MOE op — hidden_states input is the layernorm Multiply output (NOT the Parameter)
- ov::OutputVector moe_inputs = {layernorm_mul, router_unsqueeze, topk_indices, gate_w, up_w, down_w};
+ ov::OutputVector moe_inputs = {layernorm_mul, routing, 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;
config.activation_type = activation_type;
diff --git a/src/core/dev_api/openvino/op/moe.hpp b/src/core/dev_api/openvino/op/moe.hpp
index 6cec74b2e8a..2efde56433b 100644
--- a/src/core/dev_api/openvino/op/moe.hpp
+++ b/src/core/dev_api/openvino/op/moe.hpp
@@ -41,9 +41,7 @@ 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 - normalized weights for selected experts.
- /// Legacy form: [num_experts, ...] (scattered via ScatterElementsUpdate).
- /// Compact form: [topk, batch*seq, 1] (post-BGM, selected experts only).
+ /// 1: routing_weights - [..., topk] normalized weights for selected experts.
/// 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 fused
diff --git a/src/core/src/op/moe.cpp b/src/core/src/op/moe.cpp
index e50c457127b..47e5ccafc3c 100644
--- a/src/core/src/op/moe.cpp
+++ b/src/core/src/op/moe.cpp
@@ -32,10 +32,35 @@ std::shared_ptr<ov::Node> MOE::clone_with_new_inputs(const ov::OutputVector& new
void MOE::validate_and_infer_types() {
OV_OP_SCOPE(internal_MOE_validate_and_infer_types);
if (m_config.expert_type == Expert_type::GEMM2_BIAS_SWIGLU_CLAMP) {
- OPENVINO_ASSERT(m_config.activation_type == Activation_type::SWIGLU,
- "GEMM2_BIAS_SWIGLU_CLAMP expert type only supports SWIGLU activation");
+ NODE_VALIDATION_CHECK(this,
+ m_config.activation_type == Activation_type::SWIGLU,
+ "GEMM2_BIAS_SWIGLU_CLAMP expert type only supports SWIGLU activation");
+ }
+
+ // Check that routing_weights and router_topk_output_indices have the same shape
+ const auto& routing_weights_shape = get_input_partial_shape(1);
+ const auto& topk_indices_shape = get_input_partial_shape(2);
+ NODE_VALIDATION_CHECK(this,
+ routing_weights_shape == topk_indices_shape,
+ "routing_weights shape ",
+ routing_weights_shape,
+ " must be compatible with router_topk_output_indices shape ",
+ topk_indices_shape);
+
+ // Check that all expert weight inputs (index >= 3) have the same first dimension (num_experts).
+ const size_t base_inputs_count = (m_config.expert_type == Expert_type::GEMM3_SWIGLU) ? 6 : 7;
+ NODE_VALIDATION_CHECK(this, get_input_partial_shape(3).is_static(), "Weights must have static shape.");
+ const auto& num_experts = get_input_shape(3)[0];
+ for (size_t i = 4; i < base_inputs_count; i++) {
+ const auto& ps = get_input_partial_shape(i);
+ NODE_VALIDATION_CHECK(this, ps.is_static(), "Weights must have static shape.");
+ // Note: dynamic element type means empty zero point input
+ if (get_input_element_type(i) != ov::element::dynamic) {
+ NODE_VALIDATION_CHECK(this,
+ num_experts == get_input_shape(i)[0],
+ "All weight inputs must have the same first dimension (num_experts).");
+ }
}
- // TODO: Add inputs validation
set_output_type(0, get_input_element_type(0), get_input_partial_shape(0));
}
diff --git a/src/plugins/intel_gpu/include/intel_gpu/op/moe_3gemm_fused_compressed.hpp b/src/plugins/intel_gpu/include/intel_gpu/op/moe_3gemm_fused_compressed.hpp
deleted file mode 100644
index 089ddee095d..00000000000
--- a/src/plugins/intel_gpu/include/intel_gpu/op/moe_3gemm_fused_compressed.hpp
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright (C) 2018-2026 Intel Corporation
-// SPDX-License-Identifier: Apache-2.0
-//
-
-#pragma once
-
-#include "ov_ops/moe_compressed.hpp"
-
-namespace ov::intel_gpu::op {
-
-/// \brief MOE3GemmFusedCompressed that support compressed and fused MOE for GEMM3_SWIGLU.
-class MOE3GemmFusedCompressed : public ov::op::internal::MOECompressed {
-public:
- OPENVINO_OP("MOE3GemmFusedCompressed", "gpu_opset", ov::op::internal::MOECompressed);
-
- MOE3GemmFusedCompressed() = default;
-
- /// \brief Constructs a MOE3GemmFusedCompressed 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_seq, num_experts] routing weights for all experts
- /// 2: w0_weight - expert weights for first projection,
- /// shape [num_experts, inter_size, group_num, group_size]
- /// 3: w0_scale - expert scale for first projection for compressed experts,
- /// shape [num_experts, inter_size, group_num, 1]
- /// 4: w0_zp - expert zp for first projection for compressed experts,
- /// shape [num_experts, inter_size, group_num, 1]
- /// 5: w1_weight - expert weights for second projection,
- /// shape [num_experts, inter_size, group_num, group_size]
- /// 6: w1_scale - expert scale for second projection for compressed experts,
- /// shape [num_experts, inter_size, group_num, 1]
- /// 7: w1_zp - expert zp for second projection for compressed experts,
- /// shape [num_experts, inter_size, group_num, 1]
- /// 8: w2_weight - expert weights for final projection,
- /// shape [num_experts, hidden_size, group_num, group_size]
- /// 9: w2_scale - expert scale for final projection for compressed experts,
- /// shape [num_experts, hidden_size, group_num, 1]
- /// 10: w2_zp - expert zp for final projection for compressed experts,
- /// shape [num_experts, hidden_size, group_num, 1]
- /// 11: routing_bias (optional, SIGMOID_BIAS only) - [1, num_experts] routing bias for sigmoid routing
- /// 12: routing_eps (optional, SIGMOID_BIAS only) - scalar epsilon for normalization (read at kernel compile time)
- /// \param config Configuration for the MOE 3GEMM SWIGLU fused operation
- MOE3GemmFusedCompressed(const OutputVector& args, const MOECompressed::Config config);
-
- void validate_and_infer_types() override;
-
- std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& new_args) const override;
-};
-
-} // namespace ov::intel_gpu::op
diff --git a/src/plugins/intel_gpu/include/intel_gpu/op/moe_router_fused.hpp b/src/plugins/intel_gpu/include/intel_gpu/op/moe_router_fused.hpp
new file mode 100644
index 00000000000..bfcea3fb3b6
--- /dev/null
+++ b/src/plugins/intel_gpu/include/intel_gpu/op/moe_router_fused.hpp
@@ -0,0 +1,68 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+#include "openvino/op/op.hpp"
+#include "ov_ops/moe_compressed.hpp"
+
+namespace ov::intel_gpu::op {
+
+/// \brief MoERouterFused — GPU-internal op that computes expert selection and
+/// routing-weight normalization for Mixture-of-Experts blocks.
+///
+/// Performs softmax/sigmoid + top-k + normalization on raw router logits,
+/// producing the normalized routing weights and selected expert indices
+/// consumed by MOECompressed.
+///
+/// Inputs:
+/// 0: router_logits [num_tokens, num_experts] — output of the router MatMul
+/// 1: routing_bias (optional, SIGMOID_BIAS only) [1, num_experts]
+/// 2: routing_eps (optional, SIGMOID_BIAS only) scalar constant
+///
+/// Outputs:
+/// 0: topk_weights [num_tokens, top_k] — normalized routing weights (f16/f32)
+/// 1: topk_indices [num_tokens, top_k] — selected expert indices (i32)
+///
+class MoERouterFused : public ov::op::Op {
+public:
+ OPENVINO_OP("MoERouterFused", "gpu_opset");
+
+ enum class RoutingType { SOFTMAX, SIGMOID_BIAS };
+
+ struct Config {
+ size_t num_expert = 0;
+ size_t top_k = 0;
+ RoutingType routing_type = RoutingType::SOFTMAX;
+ };
+
+ MoERouterFused() = default;
+ MoERouterFused(const ov::OutputVector& args, const Config& config);
+
+ void validate_and_infer_types() override;
+ std::shared_ptr<ov::Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;
+ bool visit_attributes(ov::AttributeVisitor& visitor) override;
+
+ const Config& get_config() const { return m_config; }
+
+private:
+ Config m_config;
+};
+
+std::ostream& operator<<(std::ostream& s, const MoERouterFused::RoutingType& type);
+
+} // namespace ov::intel_gpu::op
+
+namespace ov {
+template <>
+class AttributeAdapter<ov::intel_gpu::op::MoERouterFused::RoutingType>
+ : public EnumAttributeAdapterBase<ov::intel_gpu::op::MoERouterFused::RoutingType> {
+public:
+ AttributeAdapter(ov::intel_gpu::op::MoERouterFused::RoutingType& value)
+ : EnumAttributeAdapterBase<ov::intel_gpu::op::MoERouterFused::RoutingType>(value) {}
+
+ OPENVINO_RTTI("AttributeAdapter<ov::intel_gpu::op::MoERouterFused::RoutingType>");
+ ~AttributeAdapter() override = default;
+};
+
+} // namespace ov
diff --git a/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp b/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp
index 208e4c7af7d..d7585f3af31 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp
@@ -319,8 +319,8 @@ REGISTER_FACTORY(internal, PagedGatedDeltaNet);
REGISTER_FACTORY(internal, LoraSubgraph);
REGISTER_FACTORY(internal, LoraSubgraphFused);
REGISTER_FACTORY(internal, VLSDPA);
-REGISTER_FACTORY(internal, MOE3GemmFusedCompressed);
REGISTER_FACTORY(internal, MOECompressed);
+REGISTER_FACTORY(internal, MoERouterFused);
REGISTER_FACTORY(internal, GatedDeltaNet);
REGISTER_FACTORY(internal, PagedCausalConv1D);
REGISTER_FACTORY(internal, GatherMatmulCompressed);
diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_3gemm_fused_compressed.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_3gemm_fused_compressed.hpp
index b1c430d1850..5caedd8c255 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_3gemm_fused_compressed.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_3gemm_fused_compressed.hpp
@@ -5,12 +5,12 @@
#pragma once
#include <vector>
-#include "intel_gpu/op/moe_3gemm_fused_compressed.hpp"
+#include "ov_ops/moe_compressed.hpp"
#include "intel_gpu/runtime/engine.hpp"
#include "primitive.hpp"
namespace cldnn {
-using MOE3GemmFusedCompressed = ov::intel_gpu::op::MOE3GemmFusedCompressed;
+using MOECompressed = ov::op::internal::MOECompressed;
/// @brief moe compressed primitive
/// @details Performs moe compressed
@@ -24,57 +24,54 @@ struct moe_3gemm_fused_compressed : public primitive_base<moe_3gemm_fused_compre
// @param id An identifier of new primitive.
// @param inputs A list of Input primitive ids (inputs).
// 0: hidden_states - input tensor with hidden representations
- // 1: routing_weights - [num_seq, num_experts] routing weights for all experts
- // 2: w0_weight - expert weights for first projection,
+ // 1: topk_weights - [num_tokens, top_k] normalized routing weights from MoERouterFused
+ // 2: topk_indices - [num_tokens, top_k] expert indices from MoERouterFused
+ // 3: w0_weight - expert weights for first projection,
// shape [num_experts, inter_size, group_num, group_size]
- // 3: w0_scale - expert scale for first projection for compressed experts,
+ // 4: w0_scale - expert scale for first projection for compressed experts,
// shape [num_experts, inter_size, group_num, 1]
- // 4: w0_zp - expert zp for first projection for compressed experts,
+ // 5: w0_zp - expert zp for first projection for compressed experts,
// shape [num_experts, inter_size, group_num, 1]
- // 5: w1_weight - expert weights for second projection,
+ // 6: w1_weight - expert weights for second projection,
// shape [num_experts, inter_size, group_num, group_size]
- // 6: w1_scale - expert scale for second projection for compressed experts,
+ // 7: w1_scale - expert scale for second projection for compressed experts,
// shape [num_experts, inter_size, group_num, 1]
- // 7: w1_zp - expert zp for second projection for compressed experts,
+ // 8: w1_zp - expert zp for second projection for compressed experts,
// shape [num_experts, inter_size, group_num, 1]
- // 8: w2_weight - expert weights for final projection,
+ // 9: w2_weight - expert weights for final projection,
// shape [num_experts, hidden_size, group_num, group_size]
- // 9: w2_scale - expert scale for final projection for compressed experts,
+ // 10: w2_scale - expert scale for final projection for compressed experts,
// shape [num_experts, hidden_size, group_num, 1]
- // 10: w2_zp - expert zp for final projection for compressed experts,
+ // 11: w2_zp - expert zp for final projection for compressed experts,
// shape [num_experts, hidden_size, group_num, 1]
- // 11: routing_bias (optional, SIGMOID_BIAS only; dummy placeholder for SOFTMAX+shared) -
- // [1, num_experts] routing bias for sigmoid routing
- // 12: routing_eps (optional, SIGMOID_BIAS only; dummy placeholder for SOFTMAX+shared) -
- // scalar epsilon for normalization (read at kernel compile time)
//
- // Options for shared experts (if config.num_shared_expert > 0, always starting at index 13):
- // 13: shared_gate_weight - shared expert weights for first projection,
+ // Options for shared experts (if config.num_shared_expert > 0, always starting at index 12):
+ // 12: shared_gate_weight - shared expert weights for first projection,
// shape [1, inter_size, group_num, group_size]
- // 14: shared_gate_scale - shared expert scale for first projection,
+ // 13: shared_gate_scale - shared expert scale for first projection,
// shape [1, inter_size, group_num, 1]
- // 15: shared_gate_zp - shared expert zp for first projection,
+ // 14: shared_gate_zp - shared expert zp for first projection,
// shape [1, inter_size, group_num, 1]
- // 16: shared_up_weight - shared expert weights for second projection,
+ // 15: shared_up_weight - shared expert weights for second projection,
// shape [1, inter_size, group_num, group_size]
- // 17: shared_up_scale - shared expert scale for second projection,
+ // 16: shared_up_scale - shared expert scale for second projection,
// shape [1, inter_size, group_num, 1]
- // 18: shared_up_zp - shared expert zp for second projection,
+ // 17: shared_up_zp - shared expert zp for second projection,
// shape [1, inter_size, group_num, 1]
- // 19: shared_down_weight - shared expert weights for final projection,
+ // 18: shared_down_weight - shared expert weights for final projection,
// shape [1, hidden_size, group_num, group_size]
- // 20: shared_down_scale - shared expert scale for final projection,
+ // 19: shared_down_scale - shared expert scale for final projection,
// shape [1, hidden_size, group_num, 1]
- // 21: shared_down_zp - shared expert zp for final projection,
+ // 20: shared_down_zp - shared expert zp for final projection,
// shape [1, hidden_size, group_num, 1]
- // 22: shared_gate_gate_weight - shared expert gate weight for gating,
+ // 21: shared_gate_gate_weight - shared expert gate weight for gating,
// shape [hidden_size]
//
- moe_3gemm_fused_compressed(const primitive_id& id, const std::vector<input_info>& inputs, const MOE3GemmFusedCompressed::Config& config)
+ moe_3gemm_fused_compressed(const primitive_id& id, const std::vector<input_info>& inputs, const MOECompressed::Config& config)
: primitive_base(id, inputs, 1, {optional_data_type()}),
_config(config) {}
- MOE3GemmFusedCompressed::Config _config;
+ MOECompressed::Config _config;
bool operator==(const primitive& rhs) const override {
if (!compare_common_params(rhs))
diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_router_fused.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_router_fused.hpp
new file mode 100644
index 00000000000..5159bdc71b3
--- /dev/null
+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_router_fused.hpp
@@ -0,0 +1,60 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+#include <vector>
+
+#include "intel_gpu/op/moe_router_fused.hpp"
+#include "primitive.hpp"
+
+namespace cldnn {
+using MoERouterFused = ov::intel_gpu::op::MoERouterFused;
+
+/// @brief moe_router_fused primitive
+/// @details Performs expert routing (softmax/sigmoid + top-k + normalization).
+///
+/// Inputs:
+/// 0: router_logits [num_tokens, num_experts]
+/// 1: routing_bias (optional, SIGMOID_BIAS only) [1, num_experts]
+/// 2: routing_eps (optional, SIGMOID_BIAS only) scalar
+///
+/// Outputs:
+/// 0: topk_weights [num_tokens, top_k] (f16/f32)
+/// 1: topk_indices [num_tokens, top_k] (u32)
+struct moe_router_fused : public primitive_base<moe_router_fused> {
+ CLDNN_DECLARE_PRIMITIVE(moe_router_fused)
+
+ moe_router_fused() : primitive_base("", {}) {}
+
+ moe_router_fused(const primitive_id& id,
+ const std::vector<input_info>& inputs,
+ const MoERouterFused::Config& config)
+ : primitive_base(id, inputs, 2, {optional_data_type(), optional_data_type()}),
+ _config(config) {}
+
+ MoERouterFused::Config _config;
+
+ bool operator==(const primitive& rhs) const override {
+ if (!compare_common_params(rhs))
+ return false;
+
+ auto rhs_casted = downcast<const moe_router_fused>(rhs);
+
+ return _config.num_expert == rhs_casted._config.num_expert &&
+ _config.top_k == rhs_casted._config.top_k &&
+ _config.routing_type == rhs_casted._config.routing_type;
+ }
+
+ void save(BinaryOutputBuffer& ob) const override {
+ primitive_base<moe_router_fused>::save(ob);
+ ob << make_data(&_config, sizeof(_config));
+ }
+
+ void load(BinaryInputBuffer& ib) override {
+ primitive_base<moe_router_fused>::load(ib);
+ ib >> make_data(&_config, sizeof(_config));
+ }
+};
+
+} // namespace cldnn
diff --git a/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_quantization.cpp b/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_quantization.cpp
index 9872fc63ffc..3ba74a1d6d8 100644
--- a/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_quantization.cpp
+++ b/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_quantization.cpp
@@ -6,6 +6,7 @@
#include "gather_matmul_inst.h"
#include "moe_3gemm_fused_inst.h"
#include "moe_gemm_inst.h"
+#include "impls/ocl_v2/moe/moe_3gemm_base.hpp"
#include "pooling_inst.h"
#include "quantize_inst.h"
#include "reorder_inst.h"
@@ -634,17 +635,26 @@ static void optimize_moe_gemm_decompression_parameters(moe_gemm_node& node, prog
}
static void optimize_moe_3gemm_fused_decompression_parameters(moe_node& node, program& p) {
+ using ov::intel_gpu::ocl::MOE3GemmInputIndex;
auto prim = node.get_primitive();
const auto& cfg = prim->_config;
- // Routed-expert scales at 3/6/9 (gate/up/down); zp at +1 when has_zp.
- constexpr std::array<size_t, 3> routed_scale_indices{3u, 6u, 9u};
+ // Routed-expert scales (gate/up/down); zp at +1 when has_zp.
+ constexpr std::array<size_t, 3> routed_scale_indices{
+ static_cast<size_t>(MOE3GemmInputIndex::SCALE_0),
+ static_cast<size_t>(MOE3GemmInputIndex::SCALE_1),
+ static_cast<size_t>(MOE3GemmInputIndex::SCALE_2),
+ };
for (size_t idx : routed_scale_indices) {
reorder_decompression_param_to_byfx(node, idx, p);
if (cfg.has_zp)
reorder_decompression_param_to_byfx(node, idx + 1, p);
}
if (cfg.num_shared_expert > 0) {
- constexpr std::array<size_t, 3> shared_scale_indices{14u, 17u, 20u};
+ constexpr std::array<size_t, 3> shared_scale_indices{
+ static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_SCALE),
+ static_cast<size_t>(MOE3GemmInputIndex::SHARED_UP_SCALE),
+ static_cast<size_t>(MOE3GemmInputIndex::SHARED_DOWN_SCALE),
+ };
for (size_t idx : shared_scale_indices) {
reorder_decompression_param_to_byfx(node, idx, p);
if (cfg.has_zp)
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_base.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_base.hpp
index 3cb9ab694f8..efcfd9c572d 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_base.hpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_base.hpp
@@ -11,21 +11,19 @@
namespace ov::intel_gpu::ocl {
-#define MOE_INTERNAL_BUFFER_TOPK_IDX 0 // topk_idx
-#define MOE_INTERNAL_BUFFER_TOPK_WEIGHTS 1 // topk_weights
-#define MOE_INTERNAL_BUFFER_UP_OUTPUT 2 // up output
-#define MOE_INTERNAL_BUFFER_DOWN_OUTPUT 3 // down output
-#define MOE_INTERNAL_BUFFER_GATE_UP_INPUT 4 // gather input tensor
-#define MOE_INTERNAL_BUFFER_ROUTING_WEIGHTS 5 // routing_weights
-#define MOE_INTERNAL_BUFFER_GATE_OUTPUT 6 // gate output
-#define MOE_INTERNAL_BUFFER_EXPERT_MASK_BATCH 7 // expert_mask_batch
-#define MOE_INTERNAL_BUFFER_EXPERT_MASK_TOPK 8 // expert_mask_topk
-#define MOE_INTERNAL_BUFFER_ACTIVATED_EXPERT_IDS 9 // experts_ids for each activated expert
-#define MOE_INTERNAL_BUFFER_TOKEN_START_OFFSET_PER_EXPERT 10 // token start offset idx (input gather tokens) for each activated expert
-#define MOE_INTERNAL_BUFFER_TOKEN_LEN_PER_ACTIVATED_EXPERT 11 // token len (input gather tokens) for each activated expert
-#define MOE_INTERNAL_BUFFER_TOKEN_IDX_PER_EXPERT 12 // token idx per expert
-#define MOE_INTERNAL_BUFFER_ACTUAL_USED_EXPERT_NUM 13 // num_actual_used_experts
-#define MOE_INTERNAL_BUFFER_GROUPED_OFFSETS 14 // int32_t cumulative end-offsets per expert for OneDNN grouped GEMM
+#define MOE_INTERNAL_BUFFER_UP_OUTPUT 0 // up output
+#define MOE_INTERNAL_BUFFER_DOWN_OUTPUT 1 // down output
+#define MOE_INTERNAL_BUFFER_GATE_UP_INPUT 2 // gather input tensor
+#define MOE_INTERNAL_BUFFER_ROUTING_WEIGHTS 3 // routing_weights
+#define MOE_INTERNAL_BUFFER_GATE_OUTPUT 4 // gate output
+#define MOE_INTERNAL_BUFFER_EXPERT_MASK_BATCH 5 // expert_mask_batch
+#define MOE_INTERNAL_BUFFER_EXPERT_MASK_TOPK 6 // expert_mask_topk
+#define MOE_INTERNAL_BUFFER_ACTIVATED_EXPERT_IDS 7 // experts_ids for each activated expert
+#define MOE_INTERNAL_BUFFER_TOKEN_START_OFFSET_PER_EXPERT 8 // token start offset idx (input gather tokens) for each activated expert
+#define MOE_INTERNAL_BUFFER_TOKEN_LEN_PER_ACTIVATED_EXPERT 9 // token len (input gather tokens) for each activated expert
+#define MOE_INTERNAL_BUFFER_TOKEN_IDX_PER_EXPERT 10 // token idx per expert
+#define MOE_INTERNAL_BUFFER_ACTUAL_USED_EXPERT_NUM 11 // num_actual_used_experts
+#define MOE_INTERNAL_BUFFER_GROUPED_OFFSETS 12 // int32_t cumulative end-offsets per expert for OneDNN grouped GEMM
#define ENABLE_MOE_MICRO_GEMM_POST_PROC_SILU_MUL 1
@@ -33,33 +31,29 @@ enum class MoE3GemmMicroKernelType : uint8_t { MLP_GATE = 0, MLP_UP = 1, MLP_DOW
enum class MOE3GemmInputIndex : uint8_t {
HIDDEN_STATES = 0,
- ROUTING_WEIGHTS = 1,
- WEIGHT_0 = 2,
- SCALE_0 = 3,
- ZP_0 = 4,
- WEIGHT_1 = 5,
- SCALE_1 = 6,
- ZP_1 = 7,
- WEIGHT_2 = 8,
- SCALE_2 = 9,
- ZP_2 = 10,
- // Sigmoid routing (optional, always at index 11-12)
- // For SOFTMAX routing without shared expert these are absent.
- // For SOFTMAX routing with shared expert, dummy placeholders fill these slots.
- ROUTING_BIAS = 11,
- ROUTING_EPS = 12,
+ TOPK_WEIGHTS = 1,
+ TOPK_INDICES = 2,
+ WEIGHT_0 = 3,
+ SCALE_0 = 4,
+ ZP_0 = 5,
+ WEIGHT_1 = 6,
+ SCALE_1 = 7,
+ ZP_1 = 8,
+ WEIGHT_2 = 9,
+ SCALE_2 = 10,
+ ZP_2 = 11,
// Shared expert inputs (optional, when num_shared_expert > 0)
- // Always start at index 13 regardless of routing type.
- SHARED_GATE_WEIGHT = 13,
- SHARED_GATE_SCALE = 14,
- SHARED_GATE_ZP = 15,
- SHARED_UP_WEIGHT = 16,
- SHARED_UP_SCALE = 17,
- SHARED_UP_ZP = 18,
- SHARED_DOWN_WEIGHT = 19,
- SHARED_DOWN_SCALE = 20,
- SHARED_DOWN_ZP = 21,
- SHARED_GATE_GATE_WEIGHT = 22
+ // Always start at index 12 regardless of routing type.
+ SHARED_GATE_WEIGHT = 12,
+ SHARED_GATE_SCALE = 13,
+ SHARED_GATE_ZP = 14,
+ SHARED_UP_WEIGHT = 15,
+ SHARED_UP_SCALE = 16,
+ SHARED_UP_ZP = 17,
+ SHARED_DOWN_WEIGHT = 18,
+ SHARED_DOWN_SCALE = 19,
+ SHARED_DOWN_ZP = 20,
+ SHARED_GATE_GATE_WEIGHT = 21
};
struct moe_3gemm_config {
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.cpp
index 86ddaf15628..86a3298c1a4 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.cpp
@@ -75,62 +75,6 @@ inline dnnl::algorithm moe_activation_to_dnnl_algo(ov::op::internal::MOE::Activa
}
}
-class MoE3GemmSwigluSoftMaxTopK : public KernelGenerator {
-public:
- MoE3GemmSwigluSoftMaxTopK() : KernelGenerator("moe_3gemm_swiglu_fuse", "softmax_topk") {}
-
-protected:
- [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {
- auto jit = KernelGenerator::get_jit_constants(params);
- auto desc = params.typed_desc<moe_3gemm_fused_compressed>();
- jit.make("SOFTMAX_TOPK_ENABLE", 1);
- jit.make("TOP_K", desc->_config.top_k);
- jit.make("VALUE_NUM", desc->_config.num_expert);
- jit.make("SHARED_EXPERT_ENABLE", desc->_config.num_shared_expert > 0 ? 1 : 0);
- jit.make("MOE_DTYPE", params.get_input_layout(0).data_type == ov::element::f16 ? "half" : "float");
- jit.make("MOE_DTYPE_SIZE", params.get_input_layout(0).data_type == ov::element::f16 ? 2 : 4);
- return jit;
- }
-
- [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& params) const override {
- Arguments args;
-
- return args;
- }
-
- [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {
- return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {}};
- }
-};
-
-class MoE3GemmSwigluSigmoidBiasTopK : public KernelGenerator {
-public:
- MoE3GemmSwigluSigmoidBiasTopK() : KernelGenerator("moe_3gemm_swiglu_fuse", "sigmoid_bias_topk") {}
-
-protected:
- [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {
- auto jit = KernelGenerator::get_jit_constants(params);
- auto desc = params.typed_desc<moe_3gemm_fused_compressed>();
- jit.make("SIGMOID_BIAS_TOPK_ENABLE", 1);
- jit.make("TOP_K", desc->_config.top_k);
- jit.make("VALUE_NUM", desc->_config.num_expert);
- jit.make("SHARED_EXPERT_ENABLE", desc->_config.num_shared_expert > 0 ? 1 : 0);
- jit.make("MOE_DTYPE", params.get_input_layout(0).data_type == ov::element::f16 ? "half" : "float");
- jit.make("MOE_DTYPE_SIZE", params.get_input_layout(0).data_type == ov::element::f16 ? 2 : 4);
- return jit;
- }
-
- [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& params) const override {
- Arguments args;
-
- return args;
- }
-
- [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {
- return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {}};
- }
-};
-
class MoE3GemmSwigluGather : public KernelGenerator {
public:
MoE3GemmSwigluGather() : KernelGenerator("moe_3gemm_swiglu_fuse", "gather") {}
@@ -599,8 +543,6 @@ dnnl::memory convert2dnnl(const memory::ptr& ptr, const std::vector<int64_t>& di
class moe_3gemm_swiglu_opt_impl : public PrimitiveImplOCL {
public:
DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::ocl::MoE3GemmSwigluImpl)
- Stage::Ptr softmax_topk = make_stage<MoE3GemmSwigluSoftMaxTopK>();
- Stage::Ptr sigmoid_bias_topk = make_stage<MoE3GemmSwigluSigmoidBiasTopK>();
Stage::Ptr gather = make_stage<MoE3GemmSwigluGather>();
Stage::Ptr scatter = make_stage<MoE3GemmSwigluScatter>();
Stage::Ptr mlp_gate_up = make_stage<MoE3GemmSwigluMLPGateUp>();
@@ -767,14 +709,6 @@ public:
}
// Don't change the order of stages
- auto routing_type = node.as<moe_3gemm_fused_compressed>().get_primitive()->_config.routing_type;
- if (routing_type == ov::op::internal::MOECompressed::RoutingType::SOFTMAX) {
- add_stage(softmax_topk, params);
- } else if (routing_type == ov::op::internal::MOECompressed::RoutingType::SIGMOID_BIAS) {
- add_stage(sigmoid_bias_topk, params);
- } else {
- OPENVINO_THROW("Unsupported routing type for moe_3gemm_swiglu_opt_impl: ", static_cast<int>(routing_type));
- }
add_stage(gather, params);
add_stage(scatter, params);
add_stage(mlp_gate_up, params);
@@ -1076,59 +1010,53 @@ public:
bool has_shared_expert = params.input_layouts.size() > static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_WEIGHT);
std::vector<BufferDescriptor> internal_buffers;
- // softmax+topk
- layout layout_topk_id(ov::Shape{token_num, max_topk}, data_types::u32, cldnn::format::bfyx);
- layout layout_topk_weights(ov::Shape{token_num, max_topk + (has_shared_expert ? 1 : 0)}, data_type, cldnn::format::bfyx);
- internal_buffers.emplace_back(layout_topk_id, true); // 0: topk_id
- internal_buffers.emplace_back(layout_topk_weights, true); // 1: topk_weights
-
// To support micro_gemm, prefill need to allocate max_topk * token_num for input data of micro_gemm
auto max_batch = has_shared_expert ? (max_topk + 1) * token_num : max_topk * token_num;
layout layout_gateup_out(ov::Shape{max_batch, static_cast<size_t>(config.inter_size)}, data_type, cldnn::format::bfyx);
layout layout_down_out(ov::Shape{max_batch, static_cast<size_t>(config.hidden_size)}, data_type, cldnn::format::bfyx);
- internal_buffers.emplace_back(layout_gateup_out, false); // 2: up output (GPU-only)
- internal_buffers.emplace_back(layout_down_out, false); // 3: down output (GPU-only)
+ internal_buffers.emplace_back(layout_gateup_out, false); // 0: up output (GPU-only)
+ internal_buffers.emplace_back(layout_down_out, false); // 1: down output (GPU-only)
// onednn: scratch.x, scratch.routing_weights = gather(x, ...)
// scratch.up = up(scratch.x)
// scratch.gate = gate(scratch.x) * scratch.up
// scratch.y = down(scratch.gate) * routing_weights
- internal_buffers.emplace_back(layout_down_out, false); // 4: up/gate input, scratch.x has same layout with down output (GPU-only)
+ internal_buffers.emplace_back(layout_down_out, false); // 2: up/gate input, scratch.x has same layout with down output (GPU-only)
layout routing_layout(ov::Shape{max_batch}, data_type, cldnn::format::bfyx);
- internal_buffers.emplace_back(routing_layout, true); // 5: routing_weights
- internal_buffers.emplace_back(layout_gateup_out, false); // 6: gate output, scratch.gate has same layout with up (GPU-only)
+ internal_buffers.emplace_back(routing_layout, true); // 3: routing_weights
+ internal_buffers.emplace_back(layout_gateup_out, false); // 4: gate output, scratch.gate has same layout with up (GPU-only)
// expert masks for gpu
layout index_layout(ov::Shape{expert_num, token_num}, ov::element::i32, cldnn::format::bfyx);
- internal_buffers.emplace_back(index_layout, true); // 7: expert_mask_batch
- internal_buffers.emplace_back(index_layout, true); // 8: expert_mask_topk
+ internal_buffers.emplace_back(index_layout, true); // 5: expert_mask_batch
+ internal_buffers.emplace_back(index_layout, true); // 6: expert_mask_topk
GPU_DEBUG_TRACE_DETAIL << "[DEBUG] get_internal_buffer_descs(): use_micro_gemm_prefill=" << use_micro_gemm_prefill
<< ", use_grouped_gemm_prefill=" << use_grouped_gemm_prefill << std::endl;
// for micro_gemm
if (use_micro_gemm_prefill && token_num > 1) {
layout layout_micro_gemm(ov::Shape{expert_num, token_num}, ov::element::i32, cldnn::format::bfyx);
- internal_buffers.emplace_back(layout_micro_gemm, true); // 9: experts_ids for each activated expert
- internal_buffers.emplace_back(layout_micro_gemm, true); // 10: token start offset idx (input gather tokens) for each activated expert
- internal_buffers.emplace_back(layout_micro_gemm, true); // 11: token len (input gather tokens) for each activated expert
+ internal_buffers.emplace_back(layout_micro_gemm, true); // 7: experts_ids for each activated expert
+ internal_buffers.emplace_back(layout_micro_gemm, true); // 8: token start offset idx (input gather tokens) for each activated expert
+ internal_buffers.emplace_back(layout_micro_gemm, true); // 9: token len (input gather tokens) for each activated expert
layout layout_token_idx(ov::Shape{token_num * max_topk}, ov::element::i32, cldnn::format::bfyx);
- internal_buffers.emplace_back(layout_token_idx, true); // 12: token idx per expert
+ internal_buffers.emplace_back(layout_token_idx, true); // 10: token idx per expert
layout layout_actual_used_expert_num(ov::Shape{1}, ov::element::i32, cldnn::format::bfyx);
- internal_buffers.emplace_back(layout_actual_used_expert_num, false); // 13: actual_used_expert_num
+ internal_buffers.emplace_back(layout_actual_used_expert_num, false); // 11: actual_used_expert_num
}
- // for grouped_gemm: shared metadata buffers (9-13) + int64_t expert-row-offsets (14)
+ // for grouped_gemm: shared metadata buffers (7-11) + int32_t expert-row-offsets (12)
if (use_grouped_gemm_prefill && token_num > 1) {
layout layout_meta(ov::Shape{expert_num, token_num}, ov::element::i32, cldnn::format::bfyx);
- internal_buffers.emplace_back(layout_meta, true); // 9: activated expert ids
- internal_buffers.emplace_back(layout_meta, true); // 10: token start offset per activated expert
- internal_buffers.emplace_back(layout_meta, true); // 11: token len per activated expert
+ internal_buffers.emplace_back(layout_meta, true); // 7: activated expert ids
+ internal_buffers.emplace_back(layout_meta, true); // 8: token start offset per activated expert
+ internal_buffers.emplace_back(layout_meta, true); // 9: token len per activated expert
layout layout_token_idx(ov::Shape{token_num * max_topk}, ov::element::i32, cldnn::format::bfyx);
- internal_buffers.emplace_back(layout_token_idx, true); // 12: flat token idx per expert (for gather)
+ internal_buffers.emplace_back(layout_token_idx, true); // 10: flat token idx per expert (for gather)
layout layout_actual_used_expert_num(ov::Shape{1}, ov::element::i32, cldnn::format::bfyx);
- internal_buffers.emplace_back(layout_actual_used_expert_num, false); // 13: actual_used_expert_num
+ internal_buffers.emplace_back(layout_actual_used_expert_num, false); // 11: actual_used_expert_num
// int32_t end-offsets per expert for OneDNN grouped memory descriptor
// offsets[e] = sum(n_0..n_e), the exclusive end index of expert e in the flat buffer
layout layout_grouped_offsets(ov::Shape{expert_num}, ov::element::i32, cldnn::format::bfyx);
- internal_buffers.emplace_back(layout_grouped_offsets, true); // 14: grouped end-offsets
+ internal_buffers.emplace_back(layout_grouped_offsets, true); // 12: grouped end-offsets
}
return internal_buffers;
}
@@ -1136,13 +1064,15 @@ public:
void prepare_internal_buffers(typed_primitive_inst<moe_3gemm_fused_compressed>& instance, scratch_buffers& scratch, size_t token_num) {
const auto& intermediates_memories = instance.get_intermediates_memories();
auto& engine = instance.get_network().get_engine();
- scratch.topk_id = intermediates_memories[MOE_INTERNAL_BUFFER_TOPK_IDX];
- scratch.topk_weights = intermediates_memories[MOE_INTERNAL_BUFFER_TOPK_WEIGHTS];
+ // topk_id / topk_weights are read from inputs (computed by MoERouterFused).
+ scratch.topk_weights = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::TOPK_WEIGHTS));
+ scratch.topk_id = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::TOPK_INDICES));
scratch.up = intermediates_memories[MOE_INTERNAL_BUFFER_UP_OUTPUT];
scratch.y = intermediates_memories[MOE_INTERNAL_BUFFER_DOWN_OUTPUT];
+ // Routing weights scratch buffer (used in prefill paths and reused as shared_gate_vals in batched GEMV)
+ scratch.routing_weights = intermediates_memories[MOE_INTERNAL_BUFFER_ROUTING_WEIGHTS];
if (token_num > 1) {
scratch.x = intermediates_memories[MOE_INTERNAL_BUFFER_GATE_UP_INPUT];
- scratch.routing_weights = intermediates_memories[MOE_INTERNAL_BUFFER_ROUTING_WEIGHTS];
scratch.gate = intermediates_memories[MOE_INTERNAL_BUFFER_GATE_OUTPUT];
const auto& config = instance.get_typed_desc<moe_3gemm_fused_compressed>()->_config;
int expert_num = static_cast<int>(config.num_expert);
@@ -1210,7 +1140,7 @@ public:
}
}
- void get_expert_mask_from_gpu(const MOE3GemmFusedCompressed::Config& config, memory::ptr mem, stream& stream, expert_mask_cpu& expert_mask) {
+ void get_expert_mask_from_gpu(const MOECompressed::Config& config, memory::ptr mem, stream& stream, expert_mask_cpu& expert_mask) {
// shape: [token_num, topk]
auto layout = mem->get_layout();
const auto& shape = layout.get_shape();
@@ -1394,7 +1324,7 @@ public:
scratch.moe_fusion_wei_addr.shared_scale[1],
scratch.moe_fusion_wei_addr.shared_zp[1],
scratch.moe_fusion_wei_addr.shared_weight[3],
- routing_mem_ptr};
+ scratch.routing_weights}; // reused as shared_gate_out [token_num]
extra_args_down = {scratch.moe_fusion_wei_addr.shared_weight[2],
scratch.moe_fusion_wei_addr.shared_scale[2],
@@ -1425,7 +1355,9 @@ public:
if (_has_shared_expert)
args_down.insert(args_down.end(), extra_args_down.begin(), extra_args_down.end());
args_down.push_back(scratch.up);
- args_down.push_back(routing_mem_ptr);
+ args_down.push_back(routing_mem_ptr); // compact topk_weights [token_num * MAX_TOPK]
+ if (_has_shared_expert)
+ args_down.push_back(scratch.routing_weights); // shared_gate_in [token_num]
ret_event = execute_stage({ret_event},
instance,
*stage_down,
@@ -2299,37 +2231,10 @@ public:
prepare_internal_buffers(instance, scratch, token_num);
kernel_dump_info.clear_entries();
- // routing: softmax+topk or sigmoid+bias+topk
- auto lws_size = config.num_expert;
- cldnn::event::ptr topk_event;
- if (config.routing_type == ov::op::internal::MOECompressed::RoutingType::SOFTMAX) {
- topk_event = execute_stage(events,
- instance,
- *softmax_topk,
- {instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::ROUTING_WEIGHTS))},
- {scratch.topk_id, scratch.topk_weights},
- {token_num, lws_size},
- {1, lws_size},
- instance.needs_completion_event());
- } else if (config.routing_type == ov::op::internal::MOECompressed::RoutingType::SIGMOID_BIAS) {
- topk_event = execute_stage(events,
- instance,
- *sigmoid_bias_topk,
- {instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::ROUTING_WEIGHTS)),
- instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::ROUTING_BIAS)),
- instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::ROUTING_EPS))},
- {scratch.topk_id, scratch.topk_weights},
- {token_num, lws_size},
- {1, lws_size},
- instance.needs_completion_event());
- } else {
- OPENVINO_THROW("Unsupported routing type ", static_cast<int>(config.routing_type));
- }
-
// Batched GEMV: for small token counts (including single token, MTP/speculative decoding),
// use optimized GEMV kernels with batch dimension. Avoids gather/scatter overhead.
if (token_num <= batched_gemv_threshold) {
- return exec_batched_gemv({topk_event}, instance, scratch, token_num);
+ return exec_batched_gemv(events, instance, scratch, token_num);
}
auto final_hidden_states_mem_ptr = instance.output_memory_ptr(0);
@@ -2343,8 +2248,12 @@ public:
// always use CPU mask gen and therefore always need topk to be ready first.
const bool use_gpu_mask_gen = use_micro_gemm_prefill && use_gpu_mask_gen_prefill;
if (!use_gpu_mask_gen) {
- // Wait for topk is ready
- topk_event->wait();
+ // Wait for input events (topk produced upstream by MoERouterFused)
+ for (auto& ev : events) {
+ if (ev) {
+ ev->wait();
+ }
+ }
}
GPU_DEBUG_TRACE_DETAIL << "\nMoE3GemmFusedCompressed exec(): token_num=" << token_num << ", max_topk=" << static_cast<int>(config.top_k)
@@ -2352,11 +2261,11 @@ public:
<< std::endl;
update_rt_params(instance);
if (use_micro_gemm_prefill) {
- ret_env = exec_prefill_micro_gemm({topk_event}, instance, scratch, use_gpu_mask_gen);
+ ret_env = exec_prefill_micro_gemm(events, instance, scratch, use_gpu_mask_gen);
} else if (use_grouped_gemm_prefill) {
- ret_env = exec_prefill_grouped_gemm({topk_event}, stream, instance, scratch);
+ ret_env = exec_prefill_grouped_gemm(events, stream, instance, scratch);
} else {
- ret_env = exec_prefill_onednn({topk_event}, stream, instance, scratch);
+ ret_env = exec_prefill_onednn(events, stream, instance, scratch);
}
if (_has_shared_expert) {
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_router_fused_opt.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_router_fused_opt.cpp
new file mode 100644
index 00000000000..8af09306b32
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_router_fused_opt.cpp
@@ -0,0 +1,153 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "moe_router_fused_opt.hpp"
+
+#include "../common_utils/dispatch_utils.hpp"
+#include "../common_utils/jitter.hpp"
+#include "../primitive_ocl_base.hpp"
+#include "../utils/kernel_generator.hpp"
+#include "intel_gpu/primitives/moe_router_fused.hpp"
+
+namespace ov::intel_gpu::ocl {
+namespace {
+
+class MoeRouterSoftMaxTopK : public KernelGenerator {
+public:
+ MoeRouterSoftMaxTopK() : KernelGenerator("moe_3gemm_swiglu_fuse", "softmax_topk") {}
+
+protected:
+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {
+ auto jit = KernelGenerator::get_jit_constants(params);
+ auto desc = params.typed_desc<moe_router_fused>();
+ jit.make("SOFTMAX_TOPK_ENABLE", 1);
+ jit.make("TOP_K", desc->_config.top_k);
+ jit.make("VALUE_NUM", desc->_config.num_expert);
+ jit.make("MOE_DTYPE", params.get_input_layout(0).data_type == ov::element::f16 ? "half" : "float");
+ jit.make("MOE_DTYPE_SIZE", params.get_input_layout(0).data_type == ov::element::f16 ? 2 : 4);
+ return jit;
+ }
+
+ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& params) const override {
+ Arguments args;
+ return args;
+ }
+
+ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {
+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {}};
+ }
+};
+
+class MoeRouterSigmoidBiasTopK : public KernelGenerator {
+public:
+ MoeRouterSigmoidBiasTopK() : KernelGenerator("moe_3gemm_swiglu_fuse", "sigmoid_bias_topk") {}
+
+protected:
+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {
+ auto jit = KernelGenerator::get_jit_constants(params);
+ auto desc = params.typed_desc<moe_router_fused>();
+ jit.make("SIGMOID_BIAS_TOPK_ENABLE", 1);
+ jit.make("TOP_K", desc->_config.top_k);
+ jit.make("VALUE_NUM", desc->_config.num_expert);
+ jit.make("MOE_DTYPE", params.get_input_layout(0).data_type == ov::element::f16 ? "half" : "float");
+ jit.make("MOE_DTYPE_SIZE", params.get_input_layout(0).data_type == ov::element::f16 ? 2 : 4);
+ return jit;
+ }
+
+ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& params) const override {
+ Arguments args;
+ return args;
+ }
+
+ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {
+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {}};
+ }
+};
+
+class MoeRouterFusedImpl : public PrimitiveImplOCL {
+public:
+ DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::ocl::MoeRouterFusedImpl)
+
+ Stage::Ptr softmax_topk = make_stage<MoeRouterSoftMaxTopK>();
+ Stage::Ptr sigmoid_bias_topk = make_stage<MoeRouterSigmoidBiasTopK>();
+
+ MoeRouterFusedImpl() : PrimitiveImplOCL(MoeRouterFusedOpt::get_type_info_static()) {}
+ MoeRouterFusedImpl(const program_node& node, const RuntimeParams& params) : MoeRouterFusedImpl() {
+ auto desc = params.typed_desc<moe_router_fused>();
+ if (desc->_config.routing_type == MoERouterFused::RoutingType::SOFTMAX) {
+ add_stage(softmax_topk, params);
+ } else {
+ OPENVINO_ASSERT(desc->_config.routing_type == MoERouterFused::RoutingType::SIGMOID_BIAS, "Unsupported routing type");
+ add_stage(sigmoid_bias_topk, params);
+ }
+ }
+
+ [[nodiscard]] std::unique_ptr<primitive_impl> clone() const override {
+ return make_deep_copy<MoeRouterFusedImpl>(this);
+ }
+
+ cldnn::event::ptr execute(const std::vector<cldnn::event::ptr>& events, cldnn::primitive_inst& instance) override {
+ kernel_dump_info.clear_entries();
+
+ cldnn::stream& stream = instance.get_network().get_stream();
+ auto desc = instance.get_typed_desc<moe_router_fused>();
+ const auto& config = desc->_config;
+
+ // Determine token count from input layout
+ auto input_mem = instance.input_memory_ptr(0);
+ auto input_layout = instance.dependencies()[0].first->get_impl_params()->get_output_layout(instance.dependencies()[0].second);
+ auto input_shape = input_layout.get_shape();
+ size_t token_num = input_shape[0];
+ if (input_shape.size() >= 3)
+ token_num = input_shape[0] * input_shape[1];
+ size_t lws_size = config.num_expert;
+
+ // Select routing stage and build inputs
+ Stage* routing_stage = nullptr;
+ std::vector<memory::ptr> inputs;
+ if (config.routing_type == MoERouterFused::RoutingType::SOFTMAX) {
+ routing_stage = softmax_topk.get();
+ inputs = {input_mem};
+ } else {
+ routing_stage = sigmoid_bias_topk.get();
+ inputs = {input_mem, instance.input_memory_ptr(1), instance.input_memory_ptr(2)};
+ }
+
+ // Kernel signature: (input, output_index, output_weights)
+ // MoERouterFused outputs: 0 = topk_weights, 1 = topk_indices
+ auto topk_weights_mem = instance.output_memory_ptr(0);
+ auto topk_indices_mem = instance.output_memory_ptr(1);
+
+ // Build kernel arguments manually (same as execute_stage in moe_3gemm)
+ cldnn::kernel_arguments_data args;
+ cldnn::kernel_arguments_desc kargs_desc;
+
+ for (uint32_t i = 0; i < inputs.size(); i++) {
+ kargs_desc.arguments.push_back({ArgumentDescriptor::Types::INPUT, i});
+ args.inputs.push_back(inputs[i]);
+ }
+ // Kernel outputs: first = indices (u32), second = weights (f16/f32)
+ kargs_desc.arguments.push_back({ArgumentDescriptor::Types::OUTPUT, 0});
+ args.outputs.push_back(topk_indices_mem);
+ kargs_desc.arguments.push_back({ArgumentDescriptor::Types::OUTPUT, 1});
+ args.outputs.push_back(topk_weights_mem);
+
+ stream.set_arguments(*routing_stage->kernel, kargs_desc, args);
+ kargs_desc.workGroups.global = {token_num, lws_size};
+ kargs_desc.workGroups.local = {1, lws_size};
+
+ kernel_dump_info.add_entry_point(routing_stage->kernel->get_id());
+
+ return stream.enqueue_kernel(*routing_stage->kernel, kargs_desc, {}, events, instance.needs_completion_event());
+ }
+};
+
+} // namespace
+
+std::unique_ptr<primitive_impl> MoeRouterFusedOpt::create_impl(const program_node& node, const RuntimeParams& params) const {
+ assert(node.is_type<moe_router_fused>());
+ return std::make_unique<MoeRouterFusedImpl>(node, params);
+}
+
+} // namespace ov::intel_gpu::ocl
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_router_fused_opt.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_router_fused_opt.hpp
new file mode 100644
index 00000000000..fc529765d6e
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_router_fused_opt.hpp
@@ -0,0 +1,34 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <memory>
+#include <utility>
+
+#include "intel_gpu/primitives/moe_router_fused.hpp"
+#include "program_node.h"
+#include "registry/implementation_manager.hpp"
+
+using namespace cldnn; // TODO: Remove once namespaces are aligned
+namespace ov::intel_gpu::ocl {
+
+struct MoeRouterFusedOpt : public ImplementationManager {
+ OV_GPU_PRIMITIVE_IMPL("ocl::moe::moe_router_fused_opt")
+ explicit MoeRouterFusedOpt(shape_types shape_type, ValidateFunc vf = nullptr) : ImplementationManager(impl_types::ocl, shape_type, std::move(vf)) {}
+ [[nodiscard]] std::unique_ptr<primitive_impl> create_impl(const program_node& node, const RuntimeParams& params) const override;
+ [[nodiscard]] bool validate_impl(const program_node& node) const override {
+ static constexpr std::array supported_types = {
+ ov::element::f16,
+ };
+
+ const auto& in_layout = node.get_input_layout(0);
+ if (!one_of(in_layout.data_type, supported_types))
+ return false;
+
+ return true;
+ }
+};
+
+} // namespace ov::intel_gpu::ocl
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_3gemm_swiglu_fuse.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_3gemm_swiglu_fuse.cl
index 58ad0fd52da..e533f4b3c14 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_3gemm_swiglu_fuse.cl
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_3gemm_swiglu_fuse.cl
@@ -62,9 +62,7 @@ KERNEL(softmax_topk)(
softmax_total += local_output[i];
}
output_index += batch * TOP_K;
- // Use EXPERTS_PER_TOKEN stride so batched GEMV reads multi-token weights correctly.
- // For shared expert: EXPERTS_PER_TOKEN=TOP_K+1. For non-shared: TOP_K (no change).
- output += batch * (TOP_K + SHARED_EXPERT_ENABLE);
+ output += batch * TOP_K;
for(uint i = 0; i < TOP_K; i++) {
output[i] = local_output[i]/softmax_total;
@@ -148,7 +146,7 @@ KERNEL(sigmoid_bias_topk)(
sum_weights += (float)eps_ptr[0]; // epsilon to avoid division by zero
output_index += batch * TOP_K;
- output += batch * (TOP_K + SHARED_EXPERT_ENABLE);
+ output += batch * TOP_K;
for(uint i = 0; i < actual_topk; i++) {
output[i] = (MOE_DTYPE)((float)local_output[i] / sum_weights);
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_3gemm_swiglu_mlp.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_3gemm_swiglu_mlp.cl
index b7d526eb891..e65d26b2fae 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_3gemm_swiglu_mlp.cl
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_3gemm_swiglu_mlp.cl
@@ -5,8 +5,6 @@
#include "include/batch_headers/sub_group_block_read.cl"
-#define unroll_for __attribute__((opencl_unroll_hint)) for
-
// Fake group size for compatibility and computation performance balance.
// Each gk-iteration of the inner GEMV loop processes FAKE_GROUP_SIZE K-elements
// using a single (scale, zp) entry, so FAKE_GROUP_SIZE must divide both
@@ -454,7 +452,7 @@ __attribute__((intel_reqd_sub_group_size(SUBGROUP_SIZE))) KERNEL(mlp_gate_up)(
const __global MOE_SCALE_DT* shared_up_scale,
const __global MOE_ZP_DT* shared_up_zp,
const __global half* shared_gate_gate_weight, // [HIDDEN_SIZE] (assuming no scale/zp for now, or pre-dequantized)
- __global MOE_DTYPE* routing_weights, // Input routing weights, will append shared gate result at end
+ __global MOE_DTYPE* shared_gate_out, // [token_num] — output: sigmoid(dot(x, gate_weight)) for shared expert
# endif
__global MOE_DTYPE* x, // [token_num, HIDDEN_SIZE]
__global MOE_DTYPE* y) { // [token_num * EXPERTS_PER_TOKEN, INTERMEDIATE_SIZE]
@@ -593,7 +591,7 @@ __attribute__((intel_reqd_sub_group_size(SUBGROUP_SIZE))) KERNEL(mlp_gate_up)(
# if SHARED_EXPERT_ENABLE
// Compute scalar gate for shared expert using all threads in the workgroup.
- // Only the N-block-0 workgroup writes routing_weights[MAX_TOPK]; other N-block workgroups
+ // Only the N-block-0 workgroup writes shared_gate_out[token_idx]; other N-block workgroups
// skip this entirely to avoid redundant work and races.
if (is_shared && get_group_id(2) == 0) {
// Step 1: every thread accumulates a partial dot product over its slice of HIDDEN_SIZE.
@@ -620,11 +618,11 @@ __attribute__((intel_reqd_sub_group_size(SUBGROUP_SIZE))) KERNEL(mlp_gate_up)(
float final_val = (id_local < num_sg) ? shared_gate_partial[id_local] : 0.0f;
final_val = sub_group_reduce_add(final_val);
if (id_local == 0) {
- routing_weights[token_idx * EXPERTS_PER_TOKEN + MAX_TOPK] = (MOE_DTYPE)(1.0f / (1.0f + exp(-final_val)));
+ shared_gate_out[token_idx] = (MOE_DTYPE)(1.0f / (1.0f + exp(-final_val)));
}
}
}
- // routing_weights[MAX_TOPK] is consumed by the next kernel (mlp_down) — no barrier needed here.
+ // shared_gate_out[token_idx] is consumed by the next kernel (mlp_down) — no barrier needed here.
# endif
# if WEIGHT_COMPRESSEION_DT == 0
@@ -644,14 +642,13 @@ __attribute__((intel_reqd_sub_group_size(SUBGROUP_SIZE))) KERNEL(mlp_gate_up)(
inline void down_gemv_n2x_u4(const __global uchar* weight,
__global half* scales,
__global uchar* zps,
- __global MOE_DTYPE* routing_weights,
+ MOE_DTYPE routing_weight_val,
__global half* y,
int N,
int K,
half* x2,
float* xg_sum) {
int id_local = get_sub_group_local_id();
- int expert_no = get_global_id(0);
int n_start = get_global_id(2) * N_BLOCK;
int n_end = n_start + N_BLOCK;
@@ -758,8 +755,8 @@ inline void down_gemv_n2x_u4(const __global uchar* weight,
sum_all0 = sub_group_reduce_add(sum_all0);
sum_all1 = sub_group_reduce_add(sum_all1);
if (id_local == 0) {
- y[n] = sum_all0 * routing_weights[expert_no];
- y[n + 1] = sum_all1 * routing_weights[expert_no];
+ y[n] = sum_all0 * routing_weight_val;
+ y[n + 1] = sum_all1 * routing_weight_val;
}
}
}
@@ -767,14 +764,13 @@ inline void down_gemv_n2x_u4(const __global uchar* weight,
inline void down_gemv_n2x_u8(const __global uchar* weight,
__global half* scales,
__global uchar* zps,
- __global MOE_DTYPE* routing_weights,
+ MOE_DTYPE routing_weight_val,
__global half* y,
int N,
int K,
half* x2,
float* xg_sum) {
int id_local = get_sub_group_local_id();
- int expert_no = get_global_id(0);
int n_start = get_global_id(2) * N_BLOCK;
int n_end = n_start + N_BLOCK;
@@ -880,15 +876,14 @@ inline void down_gemv_n2x_u8(const __global uchar* weight,
sum_all0 = sub_group_reduce_add(sum_all0);
sum_all1 = sub_group_reduce_add(sum_all1);
if (id_local == 0) {
- y[n] = sum_all0 * routing_weights[expert_no];
- y[n + 1] = sum_all1 * routing_weights[expert_no];
+ y[n] = sum_all0 * routing_weight_val;
+ y[n + 1] = sum_all1 * routing_weight_val;
}
}
}
-inline void down_gemv_n2x_f16(const __global half* weight, __global MOE_DTYPE* routing_weights, __global half* y, int N, int K, half* x2) {
+inline void down_gemv_n2x_f16(const __global half* weight, MOE_DTYPE routing_weight_val, __global half* y, int N, int K, half* x2) {
int id_local = get_sub_group_local_id();
- int expert_no = get_global_id(0);
int n_start = get_global_id(2) * N_BLOCK;
int n_end = n_start + N_BLOCK;
@@ -967,8 +962,8 @@ inline void down_gemv_n2x_f16(const __global half* weight, __global MOE_DTYPE* r
sum_all0 = sub_group_reduce_add(sum_all0);
sum_all1 = sub_group_reduce_add(sum_all1);
if (id_local == 0) {
- y[n] = sum_all0 * routing_weights[expert_no];
- y[n + 1] = sum_all1 * routing_weights[expert_no];
+ y[n] = sum_all0 * routing_weight_val;
+ y[n + 1] = sum_all1 * routing_weight_val;
}
}
}
@@ -983,7 +978,10 @@ __attribute__((intel_reqd_sub_group_size(SUBGROUP_SIZE))) KERNEL(mlp_down)(const
const __global MOE_ZP_DT* shared_down_zp,
# endif
const __global MOE_DTYPE* x, // [token_num * EXPERTS_PER_TOKEN, INTERMEDIATE_SIZE]
- __global MOE_DTYPE* routing_weights, // [token_num * EXPERTS_PER_TOKEN]
+ const __global MOE_DTYPE* routing_weights, // [token_num * MAX_TOPK] compact buffer from MoERouterFused
+# if SHARED_EXPERT_ENABLE
+ const __global MOE_DTYPE* shared_gate_in, // [token_num] separate shared expert gate values
+# endif
__global MOE_DTYPE* y) { // [token_num * EXPERTS_PER_TOKEN, HIDDEN_SIZE]
// global: [token_num*EXPERTS_PER_TOKEN, SUBGROUP_SIZE, N//N_BLOCK],[1, SUBGROUP_SIZE, SUBGROUP_NUM]
int flat_id = get_global_id(0);
@@ -1102,12 +1100,20 @@ __attribute__((intel_reqd_sub_group_size(SUBGROUP_SIZE))) KERNEL(mlp_down)(const
barrier(CLK_LOCAL_MEM_FENCE);
+ // Compute the routing weight for this (token, expert) work item.
+ // routing_weights is compact [token_num * MAX_TOPK]; shared expert gate is separate.
+# if SHARED_EXPERT_ENABLE
+ MOE_DTYPE routing_weight_val = is_shared ? shared_gate_in[token_idx] : routing_weights[token_idx * MAX_TOPK + expert_slot];
+# else
+ MOE_DTYPE routing_weight_val = routing_weights[token_idx * MAX_TOPK + expert_slot];
+# endif
+
# if WEIGHT_COMPRESSEION_DT == 0
- down_gemv_n2x_u4(weight, scales, zps, routing_weights, y, N, K, x2, xg_sum);
+ down_gemv_n2x_u4(weight, scales, zps, routing_weight_val, y, N, K, x2, xg_sum);
# elif WEIGHT_COMPRESSEION_DT == 1
- down_gemv_n2x_u8(weight, scales, zps, routing_weights, y, N, K, x2, xg_sum);
+ down_gemv_n2x_u8(weight, scales, zps, routing_weight_val, y, N, K, x2, xg_sum);
# elif WEIGHT_COMPRESSEION_DT == 2
- down_gemv_n2x_f16(weight, routing_weights, y, N, K, x2);
+ down_gemv_n2x_f16(weight, routing_weight_val, y, N, K, x2);
# endif
}
diff --git a/src/plugins/intel_gpu/src/graph/include/moe_router_fused_inst.h b/src/plugins/intel_gpu/src/graph/include/moe_router_fused_inst.h
new file mode 100644
index 00000000000..d363bfd37d3
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/include/moe_router_fused_inst.h
@@ -0,0 +1,51 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "intel_gpu/primitives/moe_router_fused.hpp"
+#include "primitive_inst.h"
+
+namespace cldnn {
+
+template <>
+struct typed_program_node<moe_router_fused> : public typed_program_node_base<moe_router_fused> {
+private:
+ using parent = typed_program_node_base<moe_router_fused>;
+
+public:
+ using parent::parent;
+
+ typed_program_node(std::shared_ptr<moe_router_fused> prim, program& prog) : parent(prim, prog) {}
+
+ using parent::get_kernel_impl_params;
+ std::unique_ptr<kernel_impl_params> get_kernel_impl_params(const std::vector<layout>& in_layouts, const std::vector<layout>& out_layouts) const override {
+ auto params = parent::get_kernel_impl_params(in_layouts, out_layouts);
+ return params;
+ }
+ std::vector<size_t> get_shape_infer_dependencies() const override { return {}; }
+};
+
+using moe_router_fused_node = typed_program_node<moe_router_fused>;
+
+template <>
+class typed_primitive_inst<moe_router_fused> : public typed_primitive_inst_base<moe_router_fused> {
+ using parent = typed_primitive_inst_base<moe_router_fused>;
+ using parent::parent;
+
+public:
+ template <typename ShapeType>
+ static std::vector<layout> calc_output_layouts(const moe_router_fused_node& /*node*/, const kernel_impl_params& impl_param);
+ static layout calc_output_layout(const moe_router_fused_node& /* node */, const kernel_impl_params& impl_param);
+ static std::string to_string(const moe_router_fused_node& node);
+ typed_primitive_inst(network& network, const moe_router_fused_node& node);
+};
+
+using moe_router_fused_inst = typed_primitive_inst<moe_router_fused>;
+
+} // namespace cldnn
diff --git a/src/plugins/intel_gpu/src/graph/moe_router_fused.cpp b/src/plugins/intel_gpu/src/graph/moe_router_fused.cpp
new file mode 100644
index 00000000000..6f0a8ab20e2
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/moe_router_fused.cpp
@@ -0,0 +1,70 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <string>
+
+#include "intel_gpu/runtime/error_handler.hpp"
+#include "json_object.h"
+#include "moe_router_fused_inst.h"
+#include "openvino/core/except.hpp"
+#include "primitive_type_base.h"
+#include "program_node.h"
+
+namespace cldnn {
+GPU_DEFINE_PRIMITIVE_TYPE_ID(moe_router_fused)
+
+layout moe_router_fused_inst::calc_output_layout(const moe_router_fused_node& /* node */, const kernel_impl_params& impl_param) {
+ auto desc = impl_param.typed_desc<moe_router_fused>();
+ auto input_layout = impl_param.get_input_layout(0);
+ auto shape = input_layout.get_shape();
+ size_t num_tokens = shape[0];
+ if (shape.size() == 3)
+ num_tokens = shape[0] * shape[1];
+ size_t top_k = desc->_config.top_k;
+ return layout(ov::Shape{num_tokens, top_k}, input_layout.data_type, format::bfyx);
+}
+
+template <typename ShapeType>
+std::vector<layout> moe_router_fused_inst::calc_output_layouts(const moe_router_fused_node& /* node */, const kernel_impl_params& impl_param) {
+ auto desc = impl_param.typed_desc<moe_router_fused>();
+ auto input_layout = impl_param.get_input_layout(0);
+ auto input_pshape = input_layout.get_partial_shape();
+ size_t top_k = desc->_config.top_k;
+
+ OPENVINO_ASSERT(input_pshape.rank().is_static(), "Input rank must be static");
+ ov::PartialShape out_shape;
+ auto num_tokens = input_pshape[0];
+ if (input_pshape.rank().get_length() == 3) {
+ // 3D input [batch, seq_len, num_experts] -> num_tokens = batch * seq_len
+ num_tokens = input_pshape[0] * input_pshape[1];
+ }
+ out_shape = ov::PartialShape{num_tokens, static_cast<int64_t>(top_k)};
+
+ // Output 0: topk_weights [num_tokens, top_k] — same element type as input
+ layout weights_layout(out_shape, input_layout.data_type, format::bfyx);
+ // Output 1: topk_indices [num_tokens, top_k] — i32
+ layout indices_layout(out_shape, ov::element::i32, format::bfyx);
+
+ return {weights_layout, indices_layout};
+}
+
+template std::vector<layout> moe_router_fused_inst::calc_output_layouts<ov::PartialShape>(const moe_router_fused_node& node, const kernel_impl_params& impl_param);
+
+std::string moe_router_fused_inst::to_string(const moe_router_fused_node& node) {
+ auto desc = node.get_primitive();
+ auto node_info = node.desc_to_json();
+ json_composite info;
+ info.add("num_expert", desc->_config.num_expert);
+ info.add("top_k", desc->_config.top_k);
+ info.add("routing_type", static_cast<int>(desc->_config.routing_type));
+ node_info->add("moe_router_fused info", info);
+
+ std::stringstream primitive_description;
+ node_info->dump(primitive_description);
+ return primitive_description.str();
+}
+
+moe_router_fused_inst::typed_primitive_inst(network& network, const moe_router_fused_node& node) : parent(network, node) {}
+
+} // namespace cldnn
diff --git a/src/plugins/intel_gpu/src/graph/registry/moe_router_fused_impls.cpp b/src/plugins/intel_gpu/src/graph/registry/moe_router_fused_impls.cpp
new file mode 100644
index 00000000000..84d4352998f
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/registry/moe_router_fused_impls.cpp
@@ -0,0 +1,23 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "intel_gpu/primitives/moe_router_fused.hpp"
+#include "primitive_inst.h"
+#include "registry.hpp"
+
+#if OV_GPU_WITH_OCL
+# include "impls/ocl_v2/moe/moe_router_fused_opt.hpp"
+#endif
+
+namespace ov::intel_gpu {
+
+using namespace cldnn;
+
+const std::vector<std::shared_ptr<cldnn::ImplementationManager>>& Registry<moe_router_fused>::get_implementations() {
+ static const std::vector<std::shared_ptr<ImplementationManager>> impls = {OV_GPU_CREATE_INSTANCE_OCL(ocl::MoeRouterFusedOpt, shape_types::any)};
+
+ return impls;
+}
+
+} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/graph/registry/registry.hpp b/src/plugins/intel_gpu/src/graph/registry/registry.hpp
index 9d9e4e85403..6cd5dc1c344 100644
--- a/src/plugins/intel_gpu/src/graph/registry/registry.hpp
+++ b/src/plugins/intel_gpu/src/graph/registry/registry.hpp
@@ -181,6 +181,7 @@ REGISTER_IMPLS(tile);
REGISTER_IMPLS(col2im);
REGISTER_IMPLS(vl_sdpa);
REGISTER_IMPLS(moe_3gemm_fused_compressed);
+REGISTER_IMPLS(moe_router_fused);
REGISTER_IMPLS(moe_mask_gen);
REGISTER_IMPLS(moe_mask_gen_reshape);
REGISTER_IMPLS(moe_gemm);
diff --git a/src/plugins/intel_gpu/src/plugin/ops/moe.cpp b/src/plugins/intel_gpu/src/plugin/ops/moe.cpp
index b7b4dcd1d2d..68598643f30 100644
--- a/src/plugins/intel_gpu/src/plugin/ops/moe.cpp
+++ b/src/plugins/intel_gpu/src/plugin/ops/moe.cpp
@@ -11,9 +11,10 @@
#include "ov_ops/moe_compressed.hpp"
#include "intel_gpu/plugin/program_builder.hpp"
-#include "intel_gpu/op/moe_3gemm_fused_compressed.hpp"
+#include "intel_gpu/op/moe_router_fused.hpp"
#include "intel_gpu/plugin/common_utils.hpp"
#include "intel_gpu/primitives/moe_3gemm_fused_compressed.hpp"
+#include "intel_gpu/primitives/moe_router_fused.hpp"
#include "intel_gpu/primitives/moe_gemm.hpp"
#include "intel_gpu/primitives/moe_mask_gen.hpp"
#include "openvino/op/constant.hpp"
@@ -21,7 +22,7 @@
namespace ov {
namespace op {
namespace internal {
-using MOE3GemmFusedCompressed = ov::intel_gpu::op::MOE3GemmFusedCompressed;
+using MoERouterFused = ov::intel_gpu::op::MoERouterFused;
} // namespace internal
} // namespace op
} // namespace ov
@@ -29,66 +30,6 @@ using MOE3GemmFusedCompressed = ov::intel_gpu::op::MOE3GemmFusedCompressed;
namespace ov::intel_gpu {
using namespace cldnn;
-static void CreateMOE3GemmFusedCompressedOp(ProgramBuilder& p, const std::shared_ptr<ov::intel_gpu::op::MOE3GemmFusedCompressed>& op) {
- auto inputs = p.GetInputInfo(op);
- const auto& config = op->get_config();
- /// 0: hidden_states - input tensor with hidden representations
- /// 1: routing_weights - [num_seq, num_experts] routing weights for all experts
- /// 2: w0_weight - expert weights for first projection,
- /// shape [num_experts, inter_size, group_num, group_size]
- /// 3: w0_scale - expert scale for first projection for compressed experts,
- /// shape [num_experts, inter_size, group_num, 1]
- /// 4: w0_zp - expert zp for first projection for compressed experts,
- /// shape [num_experts, inter_size, group_num, 1]
- /// 5: w1_weight - expert weights for second projection,
- /// shape [num_experts, inter_size, group_num, group_size]
- /// 6: w1_scale - expert scale for second projection for compressed experts,
- /// shape [num_experts, inter_size, group_num, 1]
- /// 7: w1_zp - expert zp for second projection for compressed experts,
- /// shape [num_experts, inter_size, group_num, 1]
- /// 8: w2_weight - expert weights for final projection,
- /// shape [num_experts, hidden_size, group_num, group_size]
- /// 9: w2_scale - expert scale for final projection for compressed experts,
- /// shape [num_experts, hidden_size, group_num, 1]
- /// 10: w2_zp - expert zp for final projection for compressed experts,
- /// shape [num_experts, hidden_size, group_num, 1]
- /// 11: routing_bias (optional, SIGMOID_BIAS only; dummy placeholder for SOFTMAX+shared) -
- /// [1, num_experts] routing bias for sigmoid routing
- /// 12: routing_eps (optional, SIGMOID_BIAS only; dummy placeholder for SOFTMAX+shared) -
- /// scalar epsilon for normalization
- ///
- /// Options for shared experts (if config.num_shared_expert > 0, always starting at index 13):
- /// 13: shared_gate_weight - shared expert weights for first projection,
- /// shape [1, inter_size, group_num, group_size]
- /// 14: shared_gate_scale - shared expert scale for first projection,
- /// shape [1, inter_size, group_num, 1]
- /// 15: shared_gate_zp - shared expert zp for first projection,
- /// shape [1, inter_size, group_num, 1]
- /// 16: shared_up_weight - shared expert weights for second projection,
- /// shape [1, inter_size, group_num, group_size]
- /// 17: shared_up_scale - shared expert scale for second projection,
- /// shape [1, inter_size, group_num, 1]
- /// 18: shared_up_zp - shared expert zp for second projection,
- /// shape [1, inter_size, group_num, 1]
- /// 19: shared_down_weight - shared expert weights for final projection,
- /// shape [1, hidden_size, group_num, group_size]
- /// 20: shared_down_scale - shared expert scale for final projection,
- /// shape [1, hidden_size, group_num, 1]
- /// 21: shared_down_zp - shared expert zp for final projection,
- /// shape [1, hidden_size, group_num, 1]
- /// 22: shared_gate_gate_weight - shared expert gate weight for gating,
- /// shape [hidden_size]
- const size_t expected_inputs = config.num_shared_expert > 0 ? 23
- : config.routing_type == ov::op::internal::MOECompressed::RoutingType::SIGMOID_BIAS ? 13
- : 11;
- validate_inputs_count(op, {expected_inputs});
-
- const std::string layerName = layer_type_name_ID(op);
- const cldnn::moe_3gemm_fused_compressed moe(layerName, inputs, config);
-
- p.add_primitive(*op, moe);
-}
-
static void CreateMOECompressedOp(ProgramBuilder& p, const std::shared_ptr<ov::op::internal::MOECompressed>& op) {
auto inputs = p.GetInputInfo(op);
auto& config = op->get_config();
@@ -97,39 +38,14 @@ static void CreateMOECompressedOp(ProgramBuilder& p, const std::shared_ptr<ov::o
input_infos.push_back(cldnn::input_info(input));
}
if (config.expert_type == ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU) {
- // Create GEMM3_SWIGLU specific primitives
- // 0: hidden_states - input tensor with hidden representations
- // 1: routing_weights - [num_experts, ...] normalized weights for selected experts
- // (input to final multiplication)
- // 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]
- // Use moe_3gemm_fused_compressed to replace it.
+ const size_t base_inputs = 12;
+ const size_t shared_inputs = config.num_shared_expert > 0 ? 10 : 0;
+ const size_t expected_inputs = base_inputs + shared_inputs;
+ validate_inputs_count(op, {expected_inputs});
- // Reaching here means MOECompressed (GEMM3_SWIGLU) survived all transformation passes.
- // It must be replaced by moe_3gemm_fused_compressed via FuseMOE3GemmCompressed; if the
- // routing subgraph did not match the expected pattern, the model would otherwise fail later
- // with the cryptic "Input ... hasn't been found in primitive_ids map" from the program builder.
- // Surface the real cause explicitly here.
- OPENVINO_THROW("[GPU] MOECompressed (GEMM3_SWIGLU) reached the GPU backend without being fused: "
- "FuseMOE3GemmCompressed transformation did not match the routing subgraph for op '",
- op->get_friendly_name(), "'. Please check the routing pattern.");
+ const std::string layerName = layer_type_name_ID(op);
+ const cldnn::moe_3gemm_fused_compressed moe(layerName, input_infos, config);
+ p.add_primitive(*op, moe);
} else {
// Create GEMM2_BIAS_SWIGLU_CLAMP specific primitives
// input0 : input {#tokens, hidden_size}
@@ -245,7 +161,17 @@ static void CreateMOECompressedOp(ProgramBuilder& p, const std::shared_ptr<ov::o
p.add_primitive(*op, moe_scatter_reduce_prim);
}
}
-REGISTER_FACTORY_IMPL(internal, MOE3GemmFusedCompressed);
+
+static void CreateMoERouterFusedOp(ProgramBuilder& p, const std::shared_ptr<ov::intel_gpu::op::MoERouterFused>& op) {
+ auto inputs = p.GetInputInfo(op);
+ const auto& config = op->get_config();
+ const size_t expected_inputs = (config.routing_type == ov::intel_gpu::op::MoERouterFused::RoutingType::SIGMOID_BIAS) ? 3 : 1;
+ validate_inputs_count(op, {expected_inputs});
+ const std::string layerName = layer_type_name_ID(op);
+ p.add_primitive(*op, cldnn::moe_router_fused(layerName, inputs, config));
+}
+
REGISTER_FACTORY_IMPL(internal, MOECompressed);
+REGISTER_FACTORY_IMPL(internal, MoERouterFused);
} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_3gemm_compressed.cpp b/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_3gemm_compressed.cpp
deleted file mode 100644
index a9c464e8b5c..00000000000
--- a/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_3gemm_compressed.cpp
+++ /dev/null
@@ -1,271 +0,0 @@
-// Copyright (C) 2018-2026 Intel Corporation
-// SPDX-License-Identifier: Apache-2.0
-//
-
-#include "fuse_moe_3gemm_compressed.hpp"
-
-#include <memory>
-
-#include "intel_gpu/op/moe_3gemm_fused_compressed.hpp"
-#include "openvino/core/graph_util.hpp"
-#include "openvino/core/node.hpp"
-#include "openvino/core/rt_info.hpp"
-#include "openvino/core/validation_util.hpp"
-#include "openvino/op/add.hpp"
-#include "openvino/op/constant.hpp"
-#include "openvino/op/convert.hpp"
-#include "openvino/op/divide.hpp"
-#include "openvino/op/gather.hpp"
-#include "openvino/op/gather_elements.hpp"
-#include "openvino/op/matmul.hpp"
-#include "openvino/op/multiply.hpp"
-#include "openvino/op/reduce_sum.hpp"
-#include "openvino/op/reshape.hpp"
-#include "openvino/op/shape_of.hpp"
-#include "openvino/op/sigmoid.hpp"
-#include "openvino/op/slice.hpp"
-#include "openvino/op/softmax.hpp"
-#include "openvino/op/topk.hpp"
-#include "openvino/op/transpose.hpp"
-#include "openvino/op/unsqueeze.hpp"
-#include "openvino/pass/pattern/matcher.hpp"
-#include "openvino/pass/pattern/op/label.hpp"
-#include "openvino/pass/pattern/op/op.hpp"
-#include "openvino/pass/pattern/op/optional.hpp"
-#include "openvino/pass/pattern/op/pattern.hpp"
-#include "openvino/pass/pattern/op/wrap_type.hpp"
-#include "openvino/util/pp.hpp"
-#include "ov_ops/moe_compressed.hpp"
-
-namespace ov::intel_gpu {
-FuseMOE3GemmCompressed::FuseMOE3GemmCompressed() {
- using namespace ov::pass::pattern;
- using namespace ov::pass;
-#define ANY any_input()
-
- auto hidden_state_m = ANY;
- // If Reshape on routing subgraph is detected,
- // the FusedMOE3GemmCompressed consumes it as new input instead of hidden_state_m
- auto hidden_state_reshape = optional<ov::op::v1::Reshape>({hidden_state_m, ANY});
- auto routing_matmul = wrap_type<ov::op::v0::MatMul>({hidden_state_reshape | ANY, ANY}, consumers_count(1));
-
- // ── Softmax routing branch ──────────────────────────────────────────
- auto sm_softmax = wrap_type<ov::op::v8::Softmax>({routing_matmul}, consumers_count(1));
- auto sm_topk = wrap_type<ov::op::v11::TopK>({sm_softmax, ANY});
- sm_topk->set_output_size(2);
-
- auto sm_reduce = wrap_type<ov::op::v1::ReduceSum>({sm_topk->output(0), ANY}, consumers_count(1));
- auto sm_norm = wrap_type<ov::op::v1::Divide>({sm_topk->output(0), sm_reduce}, consumers_count(1));
- auto sm_convert_topk = optional<ov::op::v0::Convert>({sm_topk->output(1)});
-
- // Some models apply an additional `routed_scaling_factor` (Per-expert scale)
- auto sm_per_expert_scale_const = wrap_const();
- auto sm_per_expert_gather = wrap_type<ov::op::v8::Gather>(
- {sm_per_expert_scale_const, sm_convert_topk, ANY}, consumers_count(1));
- auto sm_norm_scaled = optional<ov::op::v1::Multiply>(
- {sm_norm, sm_per_expert_gather}, consumers_count(1));
- auto sm_slice = optional<ov::op::v8::Slice>({sm_norm_scaled, ANY, ANY, ANY, ANY});
- auto sm_transpose = wrap_type<ov::op::v1::Transpose>({sm_slice, ANY}, consumers_count(1));
- auto sm_unsqueeze = wrap_type<ov::op::v0::Unsqueeze>({sm_transpose, ANY}, consumers_count(1));
-
- // ── Sigmoid+bias routing branch ─────────────────────────────────────
- auto sig_sigmoid = wrap_type<ov::op::v0::Sigmoid>({routing_matmul});
- auto sig_routing_bias = ANY;
- auto sig_add = wrap_type<ov::op::v1::Add>({sig_sigmoid, sig_routing_bias}, consumers_count(1));
- auto sig_topk = wrap_type<ov::op::v11::TopK>({sig_add, ANY});
- sig_topk->set_output_size(2);
-
- auto sig_convert_topk = optional<ov::op::v0::Convert>({sig_topk->output(1)});
- auto sig_gather_el = wrap_type<ov::op::v6::GatherElements>({sig_sigmoid, sig_convert_topk});
- auto sig_reduce = wrap_type<ov::op::v1::ReduceSum>({sig_gather_el, ANY}, consumers_count(1));
-
- // Note: only scalar eps is supported for now
- auto sig_eps_value = wrap_type<ov::op::v0::Constant>([](const ov::Output<ov::Node>& output) {
- return ov::shape_size(output.get_shape()) == 1;
- });
- auto sig_add_eps = wrap_type<ov::op::v1::Add>({sig_reduce, sig_eps_value}, consumers_count(1));
- auto sig_norm = wrap_type<ov::op::v1::Divide>({sig_gather_el, sig_add_eps}, consumers_count(1));
- // Some models (e.g. trinity-mini afmoe) apply an additional `routed_scaling_factor`
- // multiplication on the normalized routing weights before the final Slice.
- // The named `sig_norm_scale` lets the callback fetch the scale directly from pattern_map
- // without manually inspecting Multiply inputs.
- auto sig_norm_scale = ANY;
- auto sig_norm_scaled = optional<ov::op::v1::Multiply>({sig_norm, sig_norm_scale}, consumers_count(1));
- auto sig_slice = optional<ov::op::v8::Slice>({sig_norm_scaled, ANY, ANY, ANY, ANY});
- auto sig_transpose = wrap_type<ov::op::v1::Transpose>({sig_slice, ANY}, consumers_count(1));
- auto sig_unsqueeze = wrap_type<ov::op::v0::Unsqueeze>({sig_transpose, ANY}, consumers_count(1));
-
- // ── Or-pattern: combine both branches ───────────────────────────────
- auto topk_idces = sm_convert_topk | sig_convert_topk;
- auto unsqueeze_moe = sm_unsqueeze | sig_unsqueeze;
-
- // ── Common: hidden state + compressed weights + MOECompressed ───────
- auto gate_wei_m = wrap_const();
- auto gate_scale_m = ANY;
- auto gate_zp_m = ANY;
- auto up_wei_m = wrap_const();
- auto up_scale_m = ANY;
- auto up_zp_m = ANY;
- auto down_wei_m = wrap_const();
- auto down_scale_m = ANY;
- auto down_zp_m = ANY;
-
- ov::OutputVector moe_inputs = {hidden_state_reshape | hidden_state_m,
- unsqueeze_moe,
- topk_idces,
- gate_wei_m,
- gate_scale_m,
- gate_zp_m,
- up_wei_m,
- up_scale_m,
- up_zp_m,
- down_wei_m,
- down_scale_m,
- down_zp_m};
- auto moe_compressed_no_shared_m = wrap_type<ov::op::internal::MOECompressed>(moe_inputs);
-
- // ── Shared expert weights ───────────────────────────────────────────
- auto shared_gate_wei_m = wrap_const();
- auto shared_gate_scale_m = ANY;
- auto shared_gate_zp_m = ANY;
- auto shared_up_wei_m = wrap_const();
- auto shared_up_scale_m = ANY;
- auto shared_up_zp_m = ANY;
- auto shared_down_wei_m = wrap_const();
- auto shared_down_scale_m = ANY;
- auto shared_down_zp_m = ANY;
-
- ov::OutputVector moe_inputs_shared = moe_inputs;
- moe_inputs_shared.push_back(shared_gate_wei_m);
- moe_inputs_shared.push_back(shared_gate_scale_m);
- moe_inputs_shared.push_back(shared_gate_zp_m);
- moe_inputs_shared.push_back(shared_up_wei_m);
- moe_inputs_shared.push_back(shared_up_scale_m);
- moe_inputs_shared.push_back(shared_up_zp_m);
- moe_inputs_shared.push_back(shared_down_wei_m);
- moe_inputs_shared.push_back(shared_down_scale_m);
- moe_inputs_shared.push_back(shared_down_zp_m);
- auto shared_gate_gate_wei_m = ANY;
- moe_inputs_shared.push_back(shared_gate_gate_wei_m);
- auto moe_compressed_shared_m = wrap_type<ov::op::internal::MOECompressed>(moe_inputs_shared);
-
- auto moe_compressed_m = std::make_shared<ov::pass::pattern::op::Or>(OutputVector{moe_compressed_no_shared_m, moe_compressed_shared_m});
-#undef ANY
- ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](ov::pass::pattern::Matcher& m) {
- const auto& pattern_map = m.get_pattern_value_map();
-
- auto moe_compressed = ov::as_type_ptr<ov::op::internal::MOECompressed>(pattern_map.at(moe_compressed_m).get_node_shared_ptr());
- if (!moe_compressed || transformation_callback(moe_compressed)) {
- return false;
- }
-
- auto config = moe_compressed->get_config();
- bool has_shared_expert = pattern_map.count(shared_gate_wei_m) > 0;
- if (!has_shared_expert) {
- config.num_shared_expert = 0;
- }
- auto hs_reshaped = pattern_map.count(hidden_state_reshape) ? pattern_map.at(hidden_state_reshape) : pattern_map.at(hidden_state_m);
- OutputVector args{
- hs_reshaped,
- pattern_map.at(routing_matmul),
- pattern_map.at(gate_wei_m),
- pattern_map.at(gate_scale_m),
- pattern_map.at(gate_zp_m),
- pattern_map.at(up_wei_m),
- pattern_map.at(up_scale_m),
- pattern_map.at(up_zp_m),
- pattern_map.at(down_wei_m),
- pattern_map.at(down_scale_m),
- pattern_map.at(down_zp_m),
- };
- if (pattern_map.count(sig_routing_bias)) {
- args.push_back(pattern_map.at(sig_routing_bias));
- args.push_back(pattern_map.at(sig_eps_value));
- config.routing_type = ov::op::internal::MOECompressed::RoutingType::SIGMOID_BIAS;
- } else if (has_shared_expert) {
- // SOFTMAX + shared expert: insert dummy placeholders at indices 11-12
- // so that shared expert inputs always start at index 13.
- auto dummy_bias = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{1}, {0.0f});
- auto dummy_eps = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{1}, {0.0f});
- args.push_back(dummy_bias);
- args.push_back(dummy_eps);
- }
- if (has_shared_expert) {
- args.push_back(pattern_map.at(shared_gate_wei_m));
- args.push_back(pattern_map.at(shared_gate_scale_m));
- args.push_back(pattern_map.at(shared_gate_zp_m));
- args.push_back(pattern_map.at(shared_up_wei_m));
- args.push_back(pattern_map.at(shared_up_scale_m));
- args.push_back(pattern_map.at(shared_up_zp_m));
- args.push_back(pattern_map.at(shared_down_wei_m));
- args.push_back(pattern_map.at(shared_down_scale_m));
- args.push_back(pattern_map.at(shared_down_zp_m));
- args.push_back(pattern_map.at(shared_gate_gate_wei_m));
- }
-
- // WA: per_expert_scale[N] scale on routing subgraph is folded into w2_scale[N,...]
- if (pattern_map.count(sm_per_expert_scale_const)) {
- const auto per_expert_const = ov::as_type_ptr<ov::op::v0::Constant>(
- pattern_map.at(sm_per_expert_scale_const).get_node_shared_ptr());
- const auto w2_scale_const = ov::as_type_ptr<ov::op::v0::Constant>(args[9].get_node_shared_ptr());
- OPENVINO_ASSERT(per_expert_const && w2_scale_const,
- "FuseMOE3GemmCompressed: per_expert_scale and w2_scale must be Constant nodes");
- const size_t ndim = w2_scale_const->get_shape().size();
- std::vector<int64_t> axes(ndim - 1);
- for (size_t i = 0; i < ndim - 1; ++i)
- axes[i] = static_cast<int64_t>(i + 1);
- auto axes_const = ov::op::v0::Constant::create(ov::element::i64, {axes.size()}, axes);
- ov::Output<ov::Node> per_expert_for_mul = per_expert_const;
- if (per_expert_const->get_element_type() != w2_scale_const->get_element_type()) {
- per_expert_for_mul = std::make_shared<ov::op::v0::Convert>(
- per_expert_const, w2_scale_const->get_element_type());
- }
- auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(per_expert_for_mul, axes_const);
- auto scaled_w2 = std::make_shared<ov::op::v1::Multiply>(w2_scale_const, unsqueeze);
- auto folded = ov::util::get_constant_from_source(scaled_w2->output(0));
- ov::copy_runtime_info(args[9].get_node_shared_ptr(), folded);
- OPENVINO_ASSERT(folded, "FuseMOE3GemmCompressed: failed to constant-fold per-expert scale into w2_scale");
- args[9] = folded;
- }
-
- std::shared_ptr<ov::Node> moe_router_fused = std::make_shared<ov::intel_gpu::op::MOE3GemmFusedCompressed>(args, config);
- ov::copy_runtime_info(moe_compressed, moe_router_fused);
-
- // If MOECompressed's first input was the original (un-reshaped) hidden state
- // but the fused op works on the flattened 2D input, reshape the output back.
- if (moe_compressed->input_value(0) != hs_reshaped) {
- auto hidden_state_shape = std::make_shared<ov::op::v3::ShapeOf>(pattern_map.at(hidden_state_m));
- moe_router_fused = std::make_shared<ov::op::v1::Reshape>(moe_router_fused, hidden_state_shape, false);
- ov::copy_runtime_info(moe_compressed, {hidden_state_shape, moe_router_fused});
- }
-
- // If the routing branch contained an additional `routed_scaling_factor` Multiply
- // (e.g. trinity-mini afmoe), it was consumed by the pattern but is NOT applied
- // inside the fused op. Re-apply it on the output: since the routing weights
- // are used as Σ w·y_e, scaling each w by `s` is equivalent to scaling the final
- // sum by `s` (Σ (w·s)·y_e = s · Σ w·y_e). Insert a post-multiplication so the
- // kernel does not need to know about this scale.
- if (pattern_map.count(sig_norm_scaled)) {
- auto scale = pattern_map.at(sig_norm_scale);
- // Match the dtype of the fused-op output (typically f16) to avoid
- // an element-type mismatch in Multiply.
- if (scale.get_element_type() != moe_router_fused->get_output_element_type(0)) {
- scale = std::make_shared<ov::op::v0::Convert>(scale, moe_router_fused->get_output_element_type(0));
- ov::copy_runtime_info(moe_compressed, scale.get_node_shared_ptr());
- }
- auto post_mul = std::make_shared<ov::op::v1::Multiply>(moe_router_fused, scale);
- ov::copy_runtime_info(moe_compressed, post_mul);
- moe_router_fused = post_mul;
- }
-
- moe_router_fused->set_friendly_name(moe_compressed->get_friendly_name());
- ov::replace_node(moe_compressed, moe_router_fused);
-
- return true;
- };
-
- auto m = std::make_shared<Matcher>(moe_compressed_m, "FuseMOE3GemmCompressed");
- this->register_matcher(m, callback);
-}
-
-} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_3gemm_compressed.hpp b/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_3gemm_compressed.hpp
deleted file mode 100644
index d47793619c0..00000000000
--- a/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_3gemm_compressed.hpp
+++ /dev/null
@@ -1,19 +0,0 @@
-// Copyright (C) 2018-2026 Intel Corporation
-// SPDX-License-Identifier: Apache-2.0
-//
-
-#pragma once
-
-#include "openvino/pass/matcher_pass.hpp"
-
-namespace ov::intel_gpu {
-
-// Fuse routing subgraph + MOECompressed into MOE3GemmFusedCompressed.
-// Handles both Softmax and Sigmoid+bias routing patterns via pattern::op::Or.
-class FuseMOE3GemmCompressed : public ov::pass::MatcherPass {
-public:
- OPENVINO_MATCHER_PASS_RTTI("FuseMOE3GemmCompressed");
- FuseMOE3GemmCompressed();
-};
-
-} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_router.cpp b/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_router.cpp
new file mode 100644
index 00000000000..1dbe7119a26
--- /dev/null
+++ b/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_router.cpp
@@ -0,0 +1,153 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "fuse_moe_router.hpp"
+
+#include <memory>
+
+#include "intel_gpu/op/moe_router_fused.hpp"
+#include "openvino/core/graph_util.hpp"
+#include "openvino/core/node.hpp"
+#include "openvino/core/rt_info.hpp"
+#include "openvino/op/add.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/divide.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/gather_elements.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/reduce_sum.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/sigmoid.hpp"
+#include "openvino/op/softmax.hpp"
+#include "openvino/op/topk.hpp"
+#include "openvino/op/transpose.hpp"
+#include "openvino/op/unsqueeze.hpp"
+#include "openvino/pass/pattern/matcher.hpp"
+#include "openvino/pass/pattern/op/label.hpp"
+#include "openvino/pass/pattern/op/op.hpp"
+#include "openvino/pass/pattern/op/optional.hpp"
+#include "openvino/pass/pattern/op/pattern.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "openvino/util/pp.hpp"
+
+namespace ov::intel_gpu {
+using namespace ov::pass::pattern;
+using namespace ov::pass;
+
+FuseMoESoftmaxRouter::FuseMoESoftmaxRouter() {
+ auto routing_matmul = wrap_type<ov::op::v0::MatMul>();
+
+ auto softmax_m = wrap_type<ov::op::v8::Softmax>({routing_matmul}, consumers_count(1));
+ auto topk_k_m = wrap_const();
+ auto topk_m = wrap_type<ov::op::v11::TopK>({softmax_m, topk_k_m});
+ topk_m->set_output_size(2);
+
+ auto reduce_m = wrap_type<ov::op::v1::ReduceSum>({topk_m->output(0), any_input()}, consumers_count(1));
+ auto norm_m = wrap_type<ov::op::v1::Divide>({topk_m->output(0), reduce_m});
+
+ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](ov::pass::pattern::Matcher& m) {
+ if (transformation_callback(m.get_match_root())) {
+ return false;
+ }
+ const auto& pattern_map = m.get_pattern_value_map();
+ const auto& topk_in_shape = pattern_map.at(softmax_m).get_partial_shape();
+ const auto& topk_out_shape = pattern_map.at(topk_m).get_partial_shape();
+ for (const auto& shape : {topk_in_shape, topk_out_shape}) {
+ if (shape.rank().is_dynamic() || shape.size() == 0 || shape.rbegin()->is_dynamic()) {
+ return false;
+ }
+ }
+
+ const OutputVector router_args{pattern_map.at(routing_matmul)};
+
+ const size_t num_expert = topk_in_shape.rbegin()->get_length();
+ const size_t top_k = topk_out_shape.rbegin()->get_length();
+ const ov::intel_gpu::op::MoERouterFused::Config router_config{num_expert, top_k, ov::intel_gpu::op::MoERouterFused::RoutingType::SOFTMAX};
+
+ auto router_node = std::make_shared<ov::intel_gpu::op::MoERouterFused>(router_args, router_config);
+ ov::copy_runtime_info(m.get_match_root(), router_node);
+
+ OPENVINO_ASSERT(ov::replace_output_update_name(pattern_map.at(norm_m), router_node->output(0)), "MoERouter fusion failed");
+
+ // TopK indices output may be followed by an optional Convert (i64 -> i32).
+ // Since the matcher doesn't support several roots, the Convert is detected in the callback.
+ auto actual_topk = pattern_map.at(topk_m).get_node_shared_ptr();
+ auto indices_output = actual_topk->output(1);
+ for (const auto& consumer_in : actual_topk->output(1).get_target_inputs()) {
+ if (ov::is_type<ov::op::v0::Convert>(consumer_in.get_node())) {
+ indices_output = consumer_in.get_node()->output(0);
+ break;
+ }
+ }
+ OPENVINO_ASSERT(ov::replace_output_update_name(indices_output, router_node->output(1)), "MoERouter fusion failed");
+ return true;
+ };
+
+ auto matcher = std::make_shared<ov::pass::pattern::Matcher>(norm_m, "FuseMoESoftmaxRouter");
+ this->register_matcher(matcher, callback);
+}
+
+FuseMoESigmoidRouter::FuseMoESigmoidRouter() {
+ auto routing_matmul = wrap_type<ov::op::v0::MatMul>();
+
+ auto sigmoid_m = wrap_type<ov::op::v0::Sigmoid>({routing_matmul});
+ auto routing_bias_m = any_input();
+ auto add_m = wrap_type<ov::op::v1::Add>({sigmoid_m, routing_bias_m}, consumers_count(1));
+ auto topk_k_m = wrap_const();
+ auto topk_m = wrap_type<ov::op::v11::TopK>({add_m, topk_k_m});
+ topk_m->set_output_size(2);
+
+ auto convert_topk_m = wrap_type<ov::op::v0::Convert>({topk_m->output(1)});
+ auto indices_m = convert_topk_m | topk_m->output(1);
+ auto gather_el_m = wrap_type<ov::op::v6::GatherElements>({sigmoid_m, indices_m});
+ auto reduce_m = wrap_type<ov::op::v1::ReduceSum>({gather_el_m, any_input()}, consumers_count(1));
+
+ // Note: only scalar eps is supported for now
+ auto eps_value_m = wrap_type<ov::op::v0::Constant>([](const ov::Output<ov::Node>& output) {
+ return ov::shape_size(output.get_shape()) == 1;
+ });
+ auto add_eps_m = wrap_type<ov::op::v1::Add>({reduce_m, eps_value_m}, consumers_count(1));
+ auto norm_m = wrap_type<ov::op::v1::Divide>({gather_el_m, add_eps_m});
+
+ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](ov::pass::pattern::Matcher& m) {
+ if (transformation_callback(m.get_match_root())) {
+ return false;
+ }
+ const auto& pattern_map = m.get_pattern_value_map();
+ const auto& topk_in_shape = pattern_map.at(add_m).get_partial_shape();
+ const auto& topk_out_shape = pattern_map.at(topk_m).get_partial_shape();
+ for (const auto& shape : {topk_in_shape, topk_out_shape}) {
+ if (shape.rank().is_dynamic() || shape.size() == 0 || shape.rbegin()->is_dynamic()) {
+ return false;
+ }
+ }
+
+ const size_t top_k = topk_out_shape.rbegin()->get_length();
+ const size_t num_expert = topk_in_shape.rbegin()->get_length();
+ const ov::intel_gpu::op::MoERouterFused::Config router_config{num_expert, top_k, ov::intel_gpu::op::MoERouterFused::RoutingType::SIGMOID_BIAS};
+
+ OutputVector router_args{pattern_map.at(routing_matmul)};
+ router_args.push_back(pattern_map.at(routing_bias_m));
+ router_args.push_back(pattern_map.at(eps_value_m));
+
+ auto router_node = std::make_shared<ov::intel_gpu::op::MoERouterFused>(router_args, router_config);
+ ov::copy_runtime_info(m.get_match_root(), router_node);
+
+ OPENVINO_ASSERT(ov::replace_output_update_name(pattern_map.at(norm_m), router_node->output(0)), "MoERouter fusion failed");
+ OPENVINO_ASSERT(ov::replace_output_update_name(pattern_map.at(indices_m), router_node->output(1)), "MoERouter fusion failed");
+ return true;
+ };
+
+ auto matcher = std::make_shared<ov::pass::pattern::Matcher>(norm_m, "FuseMoESigmoidRouter");
+ this->register_matcher(matcher, callback);
+}
+
+FuseMoERouter::FuseMoERouter() {
+ add_matcher<FuseMoESoftmaxRouter>();
+ add_matcher<FuseMoESigmoidRouter>();
+}
+
+} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_router.hpp b/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_router.hpp
new file mode 100644
index 00000000000..744052c89a0
--- /dev/null
+++ b/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_router.hpp
@@ -0,0 +1,30 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/pass/graph_rewrite.hpp"
+
+namespace ov::intel_gpu {
+
+class FuseMoESoftmaxRouter : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("FuseMoESoftmaxRouter");
+ FuseMoESoftmaxRouter();
+};
+
+class FuseMoESigmoidRouter : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("FuseMoESigmoidRouter");
+ FuseMoESigmoidRouter();
+};
+
+/// GraphRewrite that applies Mixture of Experts routing subgraph fusion
+class FuseMoERouter : public ov::pass::GraphRewrite {
+public:
+ OPENVINO_GRAPH_REWRITE_RTTI("FuseMoERouter");
+ FuseMoERouter();
+};
+
+} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_router_scale.cpp b/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_router_scale.cpp
new file mode 100644
index 00000000000..4395fa36517
--- /dev/null
+++ b/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_router_scale.cpp
@@ -0,0 +1,116 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "fuse_moe_router_scale.hpp"
+
+#include <memory>
+
+#include "openvino/core/graph_util.hpp"
+#include "openvino/core/rt_info.hpp"
+#include "openvino/core/validation_util.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/unsqueeze.hpp"
+#include "openvino/pass/pattern/op/label.hpp"
+#include "openvino/pass/pattern/op/optional.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "openvino/util/pp.hpp"
+#include "ov_ops/moe_compressed.hpp"
+
+namespace ov::intel_gpu {
+
+FuseMoERouterScale::FuseMoERouterScale() {
+ using namespace ov::pass;
+ using namespace ov::pass::pattern;
+
+ auto routing_m = any_input();
+
+ auto per_expert_const_m = wrap_type<ov::op::v0::Constant>(rank_equals(1));
+ auto topk_idx_m = any_input();
+ auto axis_m = wrap_const();
+ auto gather_m = wrap_type<ov::op::v8::Gather>({per_expert_const_m, topk_idx_m, axis_m});
+
+ auto scalar_scale_const_m = wrap_const();
+ auto multiply_m = wrap_type<ov::op::v1::Multiply>({routing_m, gather_m | scalar_scale_const_m});
+
+ auto w2_scale_m = wrap_const();
+ auto moe_compressed_m = wrap_type<ov::op::internal::MOECompressed>({any_input(),
+ multiply_m,
+ any_input(),
+ any_input(),
+ any_input(),
+ any_input(),
+ any_input(),
+ any_input(),
+ any_input(),
+ any_input(),
+ w2_scale_m,
+ any_input()});
+
+ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](ov::pass::pattern::Matcher& m) {
+ if (transformation_callback(m.get_match_root())) {
+ return false;
+ }
+
+ const auto& pm = m.get_pattern_value_map();
+ const auto& w2_scale = pm.at(w2_scale_m);
+ auto apply_scale = [&](ov::Output<ov::Node> scale, bool need_unsqueeze) {
+ if (scale.get_element_type() != w2_scale.get_element_type()) {
+ scale = std::make_shared<ov::op::v0::Convert>(scale, w2_scale.get_element_type());
+ }
+ if (need_unsqueeze) {
+ const auto w2_scale_shape = w2_scale.get_shape();
+ const size_t ndim = w2_scale_shape.size();
+ std::vector<int32_t> axes(ndim - 1);
+ for (size_t i = 0; i < ndim - 1; ++i) {
+ axes[i] = static_cast<int32_t>(i + 1);
+ }
+ auto axes_const = ov::op::v0::Constant::create(ov::element::i32, {axes.size()}, axes);
+ scale = std::make_shared<ov::op::v0::Unsqueeze>(scale, axes_const);
+ }
+ return std::make_shared<ov::op::v1::Multiply>(w2_scale, scale);
+ };
+
+ ov::Output<ov::Node> new_w2_scale;
+ if (pm.count(scalar_scale_const_m)) {
+ const auto& constant = pm.at(scalar_scale_const_m);
+ if (ov::shape_size(constant.get_shape()) != 1) {
+ return false;
+ }
+ new_w2_scale = apply_scale(constant, false);
+ } else if (pm.count(per_expert_const_m)) {
+ const auto w2_scale_shape = w2_scale.get_shape();
+ const auto per_expert_const_shape = pm.at(per_expert_const_m).get_shape();
+ if (w2_scale_shape.empty() || per_expert_const_shape.size() != 1 || per_expert_const_shape[0] != w2_scale_shape[0]) {
+ return false;
+ }
+ new_w2_scale = apply_scale(pm.at(per_expert_const_m), true);
+ } else {
+ return false;
+ }
+ auto folded = ov::util::get_constant_from_source(new_w2_scale);
+ if (!folded) {
+ return false;
+ }
+ ov::copy_runtime_info(w2_scale.get_node_shared_ptr(), folded);
+
+ auto moe_compressed = pm.at(moe_compressed_m).get_node_shared_ptr();
+ auto new_inputs = moe_compressed->input_values();
+ new_inputs[1] = pm.at(routing_m);
+ new_inputs[10] = folded;
+
+ auto new_moe = moe_compressed->clone_with_new_inputs(new_inputs);
+ new_moe->set_friendly_name(moe_compressed->get_friendly_name());
+ ov::copy_runtime_info(moe_compressed, new_moe);
+ ov::replace_node(moe_compressed, new_moe);
+ return true;
+ };
+
+ auto matcher = std::make_shared<ov::pass::pattern::Matcher>(moe_compressed_m, "FuseMoERouterScale");
+ this->register_matcher(matcher, callback);
+}
+
+} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_router_scale.hpp b/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_router_scale.hpp
new file mode 100644
index 00000000000..5e0e24a9aac
--- /dev/null
+++ b/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_router_scale.hpp
@@ -0,0 +1,19 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/pass/graph_rewrite.hpp"
+
+namespace ov::intel_gpu {
+
+/// Fuse a scale on routing weights path to MOECompressed operation
+/// by folding the per-expert scale into w2_scale. Scalar and per-expert scales are supported
+class FuseMoERouterScale : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("FuseMoERouterScale");
+ FuseMoERouterScale();
+};
+
+} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/keep_moe_3gemm_const_precision.cpp b/src/plugins/intel_gpu/src/plugin/transformations/keep_moe_3gemm_const_precision.cpp
index 6648ffa0547..1ae62e4e698 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations/keep_moe_3gemm_const_precision.cpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations/keep_moe_3gemm_const_precision.cpp
@@ -6,7 +6,7 @@
#include <memory>
-#include "intel_gpu/op/moe_3gemm_fused_compressed.hpp"
+#include "ov_ops/moe_compressed.hpp"
#include "openvino/pass/pattern/op/or.hpp"
#include "openvino/pass/pattern/op/pattern.hpp"
#include "openvino/pass/pattern/op/wrap_type.hpp"
@@ -24,14 +24,6 @@ KeepMOE3GemmConstPrecision::KeepMOE3GemmConstPrecision() {
auto zp_1_m = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::u4));
auto zp_2_m = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::u4));
- // Softmax routing: 11 inputs (no routing_bias)
- auto moe_softmax_m = wrap_type<ov::intel_gpu::op::MOE3GemmFusedCompressed>(
- {any_input(), any_input(), wei_0_m, any_input(), zp_0_m, wei_1_m, any_input(), zp_1_m, wei_2_m, any_input(), zp_2_m});
-
- // SigmoidBias routing: 13 inputs (routing_bias at index 11, routing_eps at index 12)
- auto moe_sigmoid_m = wrap_type<ov::intel_gpu::op::MOE3GemmFusedCompressed>(
- {any_input(), any_input(), wei_0_m, any_input(), zp_0_m, wei_1_m, any_input(), zp_1_m, wei_2_m, any_input(), zp_2_m, any_input(), any_input()});
-
// Shared expert weights
auto sh_gate_wei_m = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::u4));
auto sh_gate_zp_m = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::u4));
@@ -40,23 +32,26 @@ KeepMOE3GemmConstPrecision::KeepMOE3GemmConstPrecision() {
auto sh_down_wei_m = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::u4));
auto sh_down_zp_m = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::u4));
- // Softmax + shared expert: 23 inputs (indices 11-12 are dummy placeholders)
- auto moe_softmax_shared_m = wrap_type<ov::intel_gpu::op::MOE3GemmFusedCompressed>(
- {any_input(), any_input(), wei_0_m, any_input(), zp_0_m, wei_1_m, any_input(), zp_1_m, wei_2_m, any_input(),
- zp_2_m, any_input(), any_input(), sh_gate_wei_m, any_input(), sh_gate_zp_m, sh_up_wei_m, any_input(), sh_up_zp_m, sh_down_wei_m, any_input(), sh_down_zp_m, any_input()});
+ // Without shared expert: 12 inputs [hs, routing, topk, w0, s0, zp0, w1, s1, zp1, w2, s2, zp2]
+ auto moe_no_shared_m = wrap_type<ov::op::internal::MOECompressed>(
+ {any_input(), any_input(), any_input(), wei_0_m, any_input(), zp_0_m, wei_1_m, any_input(), zp_1_m, wei_2_m, any_input(), zp_2_m});
- // SigmoidBias + shared expert: 23 inputs (indices 11-12 are routing_bias/eps)
- auto moe_sigmoid_shared_m = wrap_type<ov::intel_gpu::op::MOE3GemmFusedCompressed>(
- {any_input(), any_input(), wei_0_m, any_input(), zp_0_m, wei_1_m, any_input(), zp_1_m, wei_2_m, any_input(),
- zp_2_m, any_input(), any_input(), sh_gate_wei_m, any_input(), sh_gate_zp_m, sh_up_wei_m, any_input(), sh_up_zp_m, sh_down_wei_m, any_input(), sh_down_zp_m, any_input()});
+ // With shared expert: 22 inputs
+ auto moe_shared_m = wrap_type<ov::op::internal::MOECompressed>(
+ {any_input(), any_input(), any_input(), wei_0_m, any_input(), zp_0_m, wei_1_m, any_input(), zp_1_m, wei_2_m, any_input(),
+ zp_2_m, sh_gate_wei_m, any_input(), sh_gate_zp_m, sh_up_wei_m, any_input(), sh_up_zp_m, sh_down_wei_m, any_input(), sh_down_zp_m, any_input()});
- auto moe_3gemm_fused_compressed_m = std::make_shared<ov::pass::pattern::op::Or>(
- OutputVector{moe_softmax_m, moe_sigmoid_m, moe_softmax_shared_m, moe_sigmoid_shared_m});
+ auto moe_compressed_m = std::make_shared<ov::pass::pattern::op::Or>(
+ OutputVector{moe_no_shared_m, moe_shared_m});
ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](ov::pass::pattern::Matcher& m) {
const auto& pattern_map = m.get_pattern_value_map();
- auto moe_3gemm_fused_compressed = ov::as_type_ptr<ov::intel_gpu::op::MOE3GemmFusedCompressed>(m.get_match_root());
- if (!moe_3gemm_fused_compressed || transformation_callback(moe_3gemm_fused_compressed)) {
+ auto moe_compressed = ov::as_type_ptr<ov::op::internal::MOECompressed>(m.get_match_root());
+ if (!moe_compressed || transformation_callback(moe_compressed)) {
+ return false;
+ }
+ // Only apply to GEMM3_SWIGLU (the 3-GEMM fused path)
+ if (moe_compressed->get_config().expert_type != ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU) {
return false;
}
@@ -82,7 +77,7 @@ KeepMOE3GemmConstPrecision::KeepMOE3GemmConstPrecision() {
return true;
};
- auto m = std::make_shared<ov::pass::pattern::Matcher>(moe_3gemm_fused_compressed_m, "KeepMOE3GemmConstPrecision");
+ auto m = std::make_shared<ov::pass::pattern::Matcher>(moe_compressed_m, "KeepMOE3GemmConstPrecision");
this->register_matcher(m, callback);
}
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/op/moe_3gemm_fused_compressed.cpp b/src/plugins/intel_gpu/src/plugin/transformations/op/moe_3gemm_fused_compressed.cpp
deleted file mode 100644
index b1e78f993de..00000000000
--- a/src/plugins/intel_gpu/src/plugin/transformations/op/moe_3gemm_fused_compressed.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright (C) 2018-2026 Intel Corporation
-// SPDX-License-Identifier: Apache-2.0
-//
-
-#include "ov_ops/moe_compressed.hpp"
-#include "intel_gpu/op/moe_3gemm_fused_compressed.hpp"
-#include "ov_ops/moe_compressed.hpp"
-
-namespace ov::intel_gpu::op {
-
-MOE3GemmFusedCompressed::MOE3GemmFusedCompressed(const OutputVector& args, const ov::op::internal::MOECompressed::Config config) : ov::op::internal::MOECompressed(args, config) {
- constructor_validate_and_infer_types();
-}
-
-void MOE3GemmFusedCompressed::validate_and_infer_types() {
- const size_t expected_inputs = m_config.num_shared_expert > 0 ? 23
- : m_config.routing_type == MOECompressed::RoutingType::SIGMOID_BIAS ? 13
- : 11;
- OPENVINO_ASSERT(get_input_size() == expected_inputs,
- "MOECompressed: expected ",
- expected_inputs,
- " inputs for routing type ",
- m_config.routing_type,
- ", got ",
- get_input_size());
-
- if (m_config.routing_type == MOECompressed::RoutingType::SIGMOID_BIAS) {
- // Input 12 is routing_eps — must be a scalar
- OPENVINO_ASSERT(ov::shape_size(get_input_partial_shape(12).to_shape()) == 1,
- "MOE3GemmFusedCompressed: routing_eps (input 12) must be scalar, got shape ",
- get_input_partial_shape(12));
- }
-
- MOECompressed::validate_and_infer_types();
-}
-
-std::shared_ptr<ov::Node> MOE3GemmFusedCompressed::clone_with_new_inputs(const ov::OutputVector& new_args) const {
- check_new_args_count(this, new_args);
-
- return std::make_shared<MOE3GemmFusedCompressed>(new_args, get_config());
-}
-
-} // namespace ov::intel_gpu::op
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/op/moe_router_fused.cpp b/src/plugins/intel_gpu/src/plugin/transformations/op/moe_router_fused.cpp
new file mode 100644
index 00000000000..9cb2e182e64
--- /dev/null
+++ b/src/plugins/intel_gpu/src/plugin/transformations/op/moe_router_fused.cpp
@@ -0,0 +1,68 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "intel_gpu/op/moe_router_fused.hpp"
+
+namespace ov::intel_gpu::op {
+
+MoERouterFused::MoERouterFused(const ov::OutputVector& args, const Config& config)
+ : ov::op::Op(args), m_config(config) {
+ constructor_validate_and_infer_types();
+}
+
+void MoERouterFused::validate_and_infer_types() {
+ const size_t expected_inputs = (m_config.routing_type == RoutingType::SIGMOID_BIAS) ? 3 : 1;
+ NODE_VALIDATION_CHECK(this, get_input_size() == expected_inputs,
+ "MoERouterFused: expected ", expected_inputs,
+ " inputs, got ", get_input_size());
+
+ const auto& input_type = get_input_element_type(0);
+ const auto& input_pshape = get_input_partial_shape(0);
+ NODE_VALIDATION_CHECK(this,
+ input_pshape.rank().is_static() && (input_pshape.rank().get_length() == 2 || input_pshape.rank().get_length() == 3),
+ "MoERouterFused expects input of rank 2 or 3, got rank ",
+ input_pshape.rank());
+
+ ov::PartialShape out_shape = input_pshape;
+ if (input_pshape.rank().is_static()) {
+ *out_shape.rbegin() = static_cast<int64_t>(m_config.top_k);
+ }
+
+ // Output 0: topk_weights [num_tokens, top_k] — same type as input
+ set_output_type(0, input_type, out_shape);
+ // Output 1: topk_indices [num_tokens, top_k] — i32
+ set_output_type(1, ov::element::i32, out_shape);
+}
+
+std::shared_ptr<ov::Node> MoERouterFused::clone_with_new_inputs(const ov::OutputVector& new_args) const {
+ check_new_args_count(this, new_args);
+ return std::make_shared<MoERouterFused>(new_args, m_config);
+}
+
+bool MoERouterFused::visit_attributes(ov::AttributeVisitor& visitor) {
+ visitor.on_attribute("num_expert", m_config.num_expert);
+ visitor.on_attribute("top_k", m_config.top_k);
+ visitor.on_attribute("routing_type", m_config.routing_type);
+ return true;
+}
+
+std::ostream& operator<<(std::ostream& s, const MoERouterFused::RoutingType& type) {
+ return s << as_string(type);
+}
+
+} // namespace ov::intel_gpu::op
+
+namespace ov {
+using RoutingType = ov::intel_gpu::op::MoERouterFused::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 ov
diff --git a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
index 382fe0178d8..e7adc7160ec 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
@@ -93,8 +93,9 @@
#include "plugin/transformations/fc_horizontal_fusion.hpp"
#include "plugin/transformations/fold_activation_transpose.hpp"
#include "plugin/transformations/fuse_gated_mlp.hpp"
-#include "plugin/transformations/fuse_moe_3gemm_compressed.hpp"
#include "plugin/transformations/fuse_atan2_decomposed.hpp"
+#include "plugin/transformations/fuse_moe_router.hpp"
+#include "plugin/transformations/fuse_moe_router_scale.hpp"
#include "plugin/transformations/increase_position_ids_precision.hpp"
#include "plugin/transformations/indirect_kv_cache.hpp"
#include "plugin/transformations/keep_moe_3gemm_const_precision.hpp"
@@ -580,17 +581,18 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {
std::vector<ov::element::Type>{ov::element::f32, ov::element::f16},
std::vector<ov::element::Type>{ov::element::u4, ov::element::i4,
ov::element::i8, ov::element::u8});
+ manager.register_pass<ov::intel_gpu::FuseMoERouter>();
if (!disable_moe_opt) {
// PA models flatten batch into seq.
const bool has_batch_dim = !is_pa;
- manager.register_pass<ov::pass::MoeOpFusion>(has_batch_dim);
- manager.register_pass<ov::intel_gpu::FuseMOESharedExpert>();
- // MOE3GemmFusedCompressed kernel dispatches expert GEMMs through
+ // MOE3GemmCompressed kernel dispatches expert GEMMs through
// oneDNN, which requires an in-order OCL queue. If oneDNN is
// disabled (e.g. via OV_GPU_USE_ONEDNN=0 on an IMMAD GPU), the
// queue stays out-of-order and the oneDNN stream creation may assert.
- manager.register_pass<ov::intel_gpu::FuseMOE3GemmCompressed>();
+ manager.register_pass<ov::pass::MoeOpFusion>(has_batch_dim);
+ manager.register_pass<ov::intel_gpu::FuseMoERouterScale>();
+ manager.register_pass<ov::intel_gpu::FuseMOESharedExpert>();
}
}
manager.register_pass<ov::pass::GatedDeltaNetFusion>();
diff --git a/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/moe.cpp b/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/moe.cpp
index 9f5be16e4e5..0c87ec8178e 100644
--- a/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/moe.cpp
+++ b/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/moe.cpp
@@ -155,6 +155,8 @@ protected:
ov::test::SubgraphBaseTest::validate();
const auto pattern_type = std::get<1>(GetParam());
const auto force_gather_matmul = std::get<11>(GetParam());
+ const auto use_per_expert_scale = std::get<13>(GetParam());
+ const auto layer_norm_mul = std::get<14>(GetParam());
if (force_gather_matmul) {
// GEMM3: gate, up, down → 3 GatherMatmul ops; GEMM2: fused gate_up + down → 2.
ov::test::CheckNumberOfNodesWithType(compiledModel, "gather_matmul", pattern_type == MoePatternType::GEMM3 ? 3 : 2);
@@ -164,6 +166,23 @@ protected:
pattern_type == MoePatternType::GEMM3 ? "moe_3gemm_fused_compressed" : "moe_gemm",
pattern_type == MoePatternType::GEMM3 ? 1 : 2);
}
+ if (pattern_type == MoePatternType::GEMM3) {
+ ov::test::CheckNumberOfNodesWithType(compiledModel, "moe_router_fused", 1);
+ // Additional check to make sure that there are no extra scales on the routing path
+ // Even if the original model has this scale, FuseMoERouterScale pass must fuse it into the MOECompressed op
+ if (!force_gather_matmul) {
+ size_t expected_eltwise_count = 0;
+ // Note: use_per_expert_scale adds 2 scales: before routing matmul and after router output,
+ // the second one is fused into MoE by FuseMoERouterScale
+ if (use_per_expert_scale) {
+ expected_eltwise_count += 1;
+ }
+ if (layer_norm_mul) {
+ expected_eltwise_count += 1;
+ }
+ ov::test::CheckNumberOfNodesWithType(compiledModel, "Eltwise", expected_eltwise_count);
+ }
+ }
}
void TearDown() override {
@@ -221,7 +240,7 @@ const std::vector<MoeTestShapeParams> moe_params_smoke = {
},
};
-// Compressed weights — full GatherMatmul → MOECompressed → FuseMOE3GemmCompressed pipeline.
+// Compressed weights — full GatherMatmul → MOECompressed → FuseMoERouter pipeline.
const std::vector<ov::element::Type> weights_precisions = {
ov::element::u8,
ov::element::u4,
@@ -239,7 +258,8 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoE3GemmCompressedFusion,
::testing::Values(ov::element::f16), // decompression_precision
::testing::Values(ov::element::f16), // scale_precision
::testing::Values(ov::test::utils::DecompressionType::full),
- ::testing::Values(ov::test::utils::DecompressionType::full),
+ ::testing::Values(ov::test::utils::DecompressionType::full,
+ ov::test::utils::DecompressionType::empty),
::testing::Values(true), // reshape_on_decompression
::testing::Values(128),
::testing::Values(size_t{0}), // gate_idx unused for GEMM3
@@ -270,11 +290,8 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoE2GemmCompressedFusion,
::testing::Values(false)), // use_layernorm_multiply
MoECompressedFusionTest::getTestCaseName);
-// MoEGatherMatmulTest: alias for MoECompressedFusionTest with force_gather_matmul=true.
-using MoEGatherMatmulTest = MoECompressedFusionTest;
-
INSTANTIATE_TEST_SUITE_P(smoke_MoEGatherMatmul,
- MoEGatherMatmulTest,
+ MoECompressedFusionTest,
::testing::Combine(::testing::ValuesIn(moe_params_smoke),
::testing::Values(MoePatternType::GEMM3),
::testing::ValuesIn(routing_types),
@@ -290,11 +307,11 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoEGatherMatmul,
::testing::Values(MoEActivationType::SWISH),
::testing::Values(false), // use_per_expert_scale
::testing::Values(false)), // use_layernorm_multiply
- MoEGatherMatmulTest::getTestCaseName);
+ MoECompressedFusionTest::getTestCaseName);
// 2-GEMM unfused: covers GatherMatmul OCL clamp/bias/swiglu compile path.
INSTANTIATE_TEST_SUITE_P(smoke_MoE2GemmGatherMatmul,
- MoEGatherMatmulTest,
+ MoECompressedFusionTest,
::testing::Combine(::testing::ValuesIn(moe_params_smoke),
::testing::Values(MoePatternType::GEMM2),
::testing::Values(MoERoutingType::SOFTMAX),
@@ -310,7 +327,7 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoE2GemmGatherMatmul,
::testing::Values(MoEActivationType::SWISH),
::testing::Values(false), // use_per_expert_scale
::testing::Values(false)), // use_layernorm_multiply
- MoEGatherMatmulTest::getTestCaseName);
+ MoECompressedFusionTest::getTestCaseName);
// Gemma-4 style: Gelu activation + SOFTMAX routing with a per-expert scale table (Const[N] → Gather(topk_idx) → Multiply).
INSTANTIATE_TEST_SUITE_P(smoke_MoE3GemmGeluCompressed,
diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cpp
index c7063eeec79..d6167d4a0b6 100644
--- a/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cpp
@@ -7,6 +7,7 @@
#include <intel_gpu/primitives/data.hpp>
#include <intel_gpu/primitives/fully_connected.hpp>
#include <intel_gpu/primitives/moe_3gemm_fused_compressed.hpp>
+#include <intel_gpu/primitives/moe_router_fused.hpp>
#include <intel_gpu/primitives/reorder.hpp>
#include <intel_gpu/runtime/engine.hpp>
#include <intel_gpu/runtime/layout.hpp>
@@ -392,7 +393,7 @@ struct Moe3GemmTestParams {
bool is_signed = false;
};
-class moe_3gemm_compressed_gpu_random : public ::testing::TestWithParam<std::tuple<cldnn::MOE3GemmFusedCompressed::RoutingType, Moe3GemmTestParams>> {};
+class moe_3gemm_compressed_gpu_random : public ::testing::TestWithParam<std::tuple<cldnn::MoERouterFused::RoutingType, Moe3GemmTestParams>> {};
TEST_P(moe_3gemm_compressed_gpu_random, moe_accuracy_test_random) {
const auto& [routing_type, param] = GetParam();
@@ -515,18 +516,36 @@ TEST_P(moe_3gemm_compressed_gpu_random, moe_accuracy_test_random) {
topology.add(data("w2_scale", w2_scale_mem));
topology.add(data("w2_zp", w2_zp_mem));
- cldnn::MOE3GemmFusedCompressed::Config moe_config;
+ // Create MoERouterFused primitive
+ MoERouterFused::Config router_config;
+ router_config.num_expert = config.num_experts;
+ router_config.top_k = config.top_k;
+ std::vector<input_info> router_inputs{input_info("routing_weights")};
+ if (routing_type == cldnn::MoERouterFused::RoutingType::SIGMOID_BIAS) {
+ router_config.routing_type = MoERouterFused::RoutingType::SIGMOID_BIAS;
+ topology.add(data("routing_bias", routing_bias_mem));
+ auto routing_eps_mem = engine.allocate_memory({data_types::f16, format::bfyx, {1, 1, 1, 1}});
+ set_values(routing_eps_mem, {routing_eps_val});
+ get_test_stream().finish();
+ topology.add(data("routing_eps", routing_eps_mem));
+ router_inputs.push_back(input_info("routing_bias"));
+ router_inputs.push_back(input_info("routing_eps"));
+ }
+ topology.add(moe_router_fused("router", router_inputs, router_config));
+
+ // Create MOE3GemmFusedCompressed primitive
+ cldnn::MOECompressed::Config moe_config;
moe_config.hidden_size = config.hidden_size;
moe_config.inter_size = config.inter_size;
moe_config.num_expert = config.num_experts;
moe_config.top_k = config.top_k;
moe_config.group_size = config.group_size;
moe_config.out_type = data_types::f16;
- moe_config.routing_type = routing_type;
moe_config.has_zp = true;
std::vector<input_info> moe_inputs{input_info("hidden_states"),
- input_info("routing_weights"),
+ input_info("router", 0), // topk_weights
+ input_info("router", 1), // topk_indices
input_info("w0_weight"),
input_info("w0_scale"),
input_info("w0_zp"),
@@ -536,21 +555,12 @@ TEST_P(moe_3gemm_compressed_gpu_random, moe_accuracy_test_random) {
input_info("w2_weight"),
input_info("w2_scale"),
input_info("w2_zp")};
- if (routing_type == cldnn::MOE3GemmFusedCompressed::RoutingType::SIGMOID_BIAS) {
- topology.add(data("routing_bias", routing_bias_mem));
- moe_inputs.push_back(input_info("routing_bias"));
- auto routing_eps_mem = engine.allocate_memory({data_types::f16, format::bfyx, {1, 1, 1, 1}});
- set_values(routing_eps_mem, {routing_eps_val});
- get_test_stream().finish();
- topology.add(data("routing_eps", routing_eps_mem));
- moe_inputs.push_back(input_info("routing_eps"));
- }
-
- auto moe_prim = moe_3gemm_fused_compressed("moe_3gemm_fused_compressed", moe_inputs, moe_config);
- topology.add(moe_prim);
+ topology.add(moe_3gemm_fused_compressed("moe_3gemm_fused_compressed", moe_inputs, moe_config));
- network network(engine, topology, get_test_default_config(engine));
+ auto net_config = get_test_default_config(engine);
+ net_config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ network network(engine, topology, net_config);
network.set_input_data("hidden_states", hidden_states_mem);
network.set_input_data("routing_weights", routing_weights_mem);
@@ -559,12 +569,12 @@ TEST_P(moe_3gemm_compressed_gpu_random, moe_accuracy_test_random) {
get_test_stream().flush();
cldnn::mem_lock<ov::float16, mem_lock_type::read> output_ptr(output_prim, get_test_stream());
- auto ref_output = routing_type == cldnn::MOE3GemmFusedCompressed::RoutingType::SIGMOID_BIAS
+ auto ref_output = routing_type == cldnn::MoERouterFused::RoutingType::SIGMOID_BIAS
? ref.run_reference_sigmoid(hidden_states, routing_weights, routing_bias_data, routing_eps_val, w0_data, w1_data, w2_data)
: ref.run_reference_softmax(hidden_states, routing_weights, w0_data, w1_data, w2_data);
// SigmoidBias routing performs all routing math (sigmoid, bias, normalization) in f16 on the kernel side,
// while the reference uses f32, leading to slightly larger numerical divergence than Softmax.
- const float base_tolerance = routing_type == cldnn::MOE3GemmFusedCompressed::RoutingType::SIGMOID_BIAS ? 0.2f : 0.1f;
+ const float base_tolerance = routing_type == cldnn::MoERouterFused::RoutingType::SIGMOID_BIAS ? 0.2f : 0.1f;
const float tolerance = base_tolerance * (config.hidden_size / 128);
for (size_t i = 0; i < ref_output.size(); ++i) {
ASSERT_NEAR(static_cast<float>(output_ptr[i]), static_cast<float>(ref_output[i]), tolerance);
@@ -573,8 +583,8 @@ TEST_P(moe_3gemm_compressed_gpu_random, moe_accuracy_test_random) {
INSTANTIATE_TEST_SUITE_P(smoke,
moe_3gemm_compressed_gpu_random,
- ::testing::Combine(::testing::Values(cldnn::MOE3GemmFusedCompressed::RoutingType::SOFTMAX,
- cldnn::MOE3GemmFusedCompressed::RoutingType::SIGMOID_BIAS),
+ ::testing::Combine(::testing::Values(cldnn::MoERouterFused::RoutingType::SOFTMAX,
+ cldnn::MoERouterFused::RoutingType::SIGMOID_BIAS),
::testing::Values(Moe3GemmTestParams{1, true, 128, 256, 4, 2, 128},
Moe3GemmTestParams{16, true, 128, 256, 4, 2, 128},
Moe3GemmTestParams{1, false, 128, 256, 4, 2, 128},
@@ -589,7 +599,7 @@ INSTANTIATE_TEST_SUITE_P(smoke,
// to avoid known accuracy noise of the SOFTMAX path on some platforms.
INSTANTIATE_TEST_SUITE_P(smoke_sub128_group_size,
moe_3gemm_compressed_gpu_random,
- ::testing::Combine(::testing::Values(cldnn::MOE3GemmFusedCompressed::RoutingType::SIGMOID_BIAS),
+ ::testing::Combine(::testing::Values(cldnn::MoERouterFused::RoutingType::SIGMOID_BIAS),
::testing::Values(Moe3GemmTestParams{1, true, 128, 256, 4, 2, 64},
Moe3GemmTestParams{16, true, 128, 256, 4, 2, 64},
Moe3GemmTestParams{1, false, 128, 256, 4, 2, 64},
@@ -601,8 +611,8 @@ INSTANTIATE_TEST_SUITE_P(smoke_sub128_group_size,
// which avoids gather/scatter/CPU-sync overhead of the prefill GEMM path.
INSTANTIATE_TEST_SUITE_P(smoke_batched_gemv_mtp,
moe_3gemm_compressed_gpu_random,
- ::testing::Combine(::testing::Values(cldnn::MOE3GemmFusedCompressed::RoutingType::SOFTMAX,
- cldnn::MOE3GemmFusedCompressed::RoutingType::SIGMOID_BIAS),
+ ::testing::Combine(::testing::Values(cldnn::MoERouterFused::RoutingType::SOFTMAX,
+ cldnn::MoERouterFused::RoutingType::SIGMOID_BIAS),
::testing::Values(Moe3GemmTestParams{2, true, 128, 256, 4, 2, 128},
Moe3GemmTestParams{4, true, 128, 256, 4, 2, 128},
Moe3GemmTestParams{8, true, 128, 256, 4, 2, 128},
@@ -617,7 +627,7 @@ INSTANTIATE_TEST_SUITE_P(smoke_batched_gemv_mtp,
Moe3GemmTestParams{2, true, 128, 256, 4, 2, 64},
Moe3GemmTestParams{2, false, 128, 256, 4, 2, 64})));
-class moe_3gemm_compressed_gpu_u4 : public ::testing::TestWithParam<cldnn::MOE3GemmFusedCompressed::RoutingType> {};
+class moe_3gemm_compressed_gpu_u4 : public ::testing::TestWithParam<cldnn::MoERouterFused::RoutingType> {};
class moe_3gemm_compressed_gpu_shared_random : public ::testing::TestWithParam<Moe3GemmTestParams> {};
@@ -789,16 +799,6 @@ TEST_P(moe_3gemm_compressed_gpu_shared_random, moe_accuracy_test_shared_expert_r
topology.add(data("w2_zp", w2_zp_mem));
// Add shared inputs
- // Insert dummy routing_bias/eps placeholders at indices 11-12 (SOFTMAX + shared expert)
- auto dummy_bias_mem = engine.allocate_memory({data_types::f16, format::bfyx, {1, 1, 1, 1}});
- set_values(dummy_bias_mem, {ov::float16(0.0f)});
- get_test_stream().finish();
- auto dummy_eps_mem = engine.allocate_memory({data_types::f16, format::bfyx, {1, 1, 1, 1}});
- set_values(dummy_eps_mem, {ov::float16(0.0f)});
- get_test_stream().finish();
- topology.add(data("dummy_routing_bias", dummy_bias_mem));
- topology.add(data("dummy_routing_eps", dummy_eps_mem));
-
topology.add(data("s_gate_weight", s_gate_weight_mem));
topology.add(data("s_gate_scale", s_gate_scale_mem));
topology.add(data("s_gate_zp", s_gate_zp_mem));
@@ -810,7 +810,14 @@ TEST_P(moe_3gemm_compressed_gpu_shared_random, moe_accuracy_test_shared_expert_r
topology.add(data("s_down_zp", s_down_zp_mem));
topology.add(data("s_gate_scalar", s_gate_scalar_mem));
- cldnn::MOE3GemmFusedCompressed::Config moe_config;
+ // Create MoERouterFused primitive (softmax for shared expert tests)
+ MoERouterFused::Config router_config;
+ router_config.num_expert = config.num_experts;
+ router_config.top_k = config.top_k;
+ router_config.routing_type = MoERouterFused::RoutingType::SOFTMAX;
+ topology.add(moe_router_fused("router", {input_info("routing_weights")}, router_config));
+
+ cldnn::MOECompressed::Config moe_config;
moe_config.hidden_size = config.hidden_size;
moe_config.inter_size = config.inter_size;
moe_config.num_expert = config.num_experts;
@@ -819,40 +826,37 @@ TEST_P(moe_3gemm_compressed_gpu_shared_random, moe_accuracy_test_shared_expert_r
moe_config.out_type = data_types::f16;
moe_config.num_shared_expert = 1;
moe_config.has_zp = true;
- // has_batch_dim default is 0.
-
- // Create Primitive with extended inputs
- auto moe_prim = moe_3gemm_fused_compressed("moe_3gemm_fused_compressed",
- {input_info("hidden_states"),
- input_info("routing_weights"),
- input_info("w0_weight"),
- input_info("w0_scale"),
- input_info("w0_zp"),
- input_info("w1_weight"),
- input_info("w1_scale"),
- input_info("w1_zp"),
- input_info("w2_weight"),
- input_info("w2_scale"),
- input_info("w2_zp"),
- // Dummy placeholders for routing_bias/eps (indices 11-12)
- input_info("dummy_routing_bias"),
- input_info("dummy_routing_eps"),
- // Shared Expert Inputs (indices 13-22)
- input_info("s_gate_weight"),
- input_info("s_gate_scale"),
- input_info("s_gate_zp"),
- input_info("s_up_weight"),
- input_info("s_up_scale"),
- input_info("s_up_zp"),
- input_info("s_down_weight"),
- input_info("s_down_scale"),
- input_info("s_down_zp"),
- input_info("s_gate_scalar")},
- moe_config);
-
- topology.add(moe_prim);
-
- network network(engine, topology, get_test_default_config(engine));
+
+ // Create Primitive with new input layout
+ topology.add(moe_3gemm_fused_compressed("moe_3gemm_fused_compressed",
+ {input_info("hidden_states"),
+ input_info("router", 0), // topk_weights
+ input_info("router", 1), // topk_indices
+ input_info("w0_weight"),
+ input_info("w0_scale"),
+ input_info("w0_zp"),
+ input_info("w1_weight"),
+ input_info("w1_scale"),
+ input_info("w1_zp"),
+ input_info("w2_weight"),
+ input_info("w2_scale"),
+ input_info("w2_zp"),
+ // Shared Expert Inputs (indices 12-21)
+ input_info("s_gate_weight"),
+ input_info("s_gate_scale"),
+ input_info("s_gate_zp"),
+ input_info("s_up_weight"),
+ input_info("s_up_scale"),
+ input_info("s_up_zp"),
+ input_info("s_down_weight"),
+ input_info("s_down_scale"),
+ input_info("s_down_zp"),
+ input_info("s_gate_scalar")},
+ moe_config));
+
+ auto net_config = get_test_default_config(engine);
+ net_config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ network network(engine, topology, net_config);
network.set_input_data("hidden_states", hidden_states_mem);
network.set_input_data("routing_weights", routing_weights_mem);
@@ -992,18 +996,35 @@ TEST_P(moe_3gemm_compressed_gpu_u4, moe_accuracy_test_u4) {
topology.add(data("w2_zp", w2_zp));
// Create MOE3GemmFusedCompressed config
- cldnn::MOE3GemmFusedCompressed::Config config;
+ cldnn::MOECompressed::Config config;
config.hidden_size = hidden_size;
config.inter_size = inter_size;
config.num_expert = num_experts;
config.top_k = top_k;
config.group_size = group_size;
config.out_type = data_types::f16;
- config.routing_type = routing_type;
config.has_zp = true;
+ // Create MoERouterFused primitive
+ MoERouterFused::Config router_config;
+ router_config.num_expert = num_experts;
+ router_config.top_k = top_k;
+ std::vector<input_info> router_inputs{input_info("routing_weights")};
+ if (routing_type == cldnn::MoERouterFused::RoutingType::SIGMOID_BIAS) {
+ router_config.routing_type = MoERouterFused::RoutingType::SIGMOID_BIAS;
+ topology.add(data("routing_bias", routing_bias));
+ auto routing_eps_mem = engine.allocate_memory({data_types::f16, format::bfyx, {1, 1, 1, 1}});
+ set_values(routing_eps_mem, {ov::float16(1e-6f)});
+ get_test_stream().finish();
+ topology.add(data("routing_eps", routing_eps_mem));
+ router_inputs.push_back(input_info("routing_bias"));
+ router_inputs.push_back(input_info("routing_eps"));
+ }
+ topology.add(moe_router_fused("router", router_inputs, router_config));
+
std::vector<input_info> moe_inputs{input_info("hidden_states"),
- input_info("routing_weights"),
+ input_info("router", 0), // topk_weights
+ input_info("router", 1), // topk_indices
input_info("w0_weight"),
input_info("w0_scale"),
input_info("w0_zp"),
@@ -1013,21 +1034,14 @@ TEST_P(moe_3gemm_compressed_gpu_u4, moe_accuracy_test_u4) {
input_info("w2_weight"),
input_info("w2_scale"),
input_info("w2_zp")};
- if (routing_type == cldnn::MOE3GemmFusedCompressed::RoutingType::SIGMOID_BIAS) {
- topology.add(data("routing_bias", routing_bias));
- moe_inputs.push_back(input_info("routing_bias"));
- auto routing_eps_mem = engine.allocate_memory({data_types::f16, format::bfyx, {1, 1, 1, 1}});
- set_values(routing_eps_mem, {ov::float16(1e-6f)});
- get_test_stream().finish();
- topology.add(data("routing_eps", routing_eps_mem));
- moe_inputs.push_back(input_info("routing_eps"));
- }
// Create MOECompressed primitive
topology.add(moe_3gemm_fused_compressed("moe_3gemm_fused_compressed", moe_inputs, config));
// Create and execute network
- network network(engine, topology, get_test_default_config(engine));
+ auto net_config = get_test_default_config(engine);
+ net_config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ network network(engine, topology, net_config);
network.set_input_data("hidden_states", hidden_states);
network.set_input_data("routing_weights", routing_weights);
@@ -1044,7 +1058,7 @@ TEST_P(moe_3gemm_compressed_gpu_u4, moe_accuracy_test_u4) {
EXPECT_EQ(output_layout.batch(), batch_size);
EXPECT_EQ(output_layout.feature(), seq_len);
- const auto& output_reference = routing_type == cldnn::MOE3GemmFusedCompressed::RoutingType::SIGMOID_BIAS ? output_ref_sigmoid_bias : output_ref_softmax;
+ const auto& output_reference = routing_type == cldnn::MoERouterFused::RoutingType::SIGMOID_BIAS ? output_ref_sigmoid_bias : output_ref_softmax;
for (size_t i = 0; i < batch_size * seq_len * hidden_size; ++i) {
EXPECT_NEAR(static_cast<float>(output_ptr[i]), static_cast<float>(output_reference[i]), 1e-3f);
}
@@ -1052,10 +1066,10 @@ TEST_P(moe_3gemm_compressed_gpu_u4, moe_accuracy_test_u4) {
INSTANTIATE_TEST_SUITE_P(smoke,
moe_3gemm_compressed_gpu_u4,
- ::testing::Values(cldnn::MOE3GemmFusedCompressed::RoutingType::SOFTMAX, cldnn::MOE3GemmFusedCompressed::RoutingType::SIGMOID_BIAS));
+ ::testing::Values(cldnn::MoERouterFused::RoutingType::SOFTMAX, cldnn::MoERouterFused::RoutingType::SIGMOID_BIAS));
// Symmetric quantization tests (i4/i8 weights, no zero points)
-class moe_3gemm_compressed_gpu_symmetric_random : public ::testing::TestWithParam<std::tuple<cldnn::MOE3GemmFusedCompressed::RoutingType, Moe3GemmTestParams>> {
+class moe_3gemm_compressed_gpu_symmetric_random : public ::testing::TestWithParam<std::tuple<cldnn::MoERouterFused::RoutingType, Moe3GemmTestParams>> {
};
TEST_P(moe_3gemm_compressed_gpu_symmetric_random, moe_accuracy_test_symmetric) {
@@ -1175,18 +1189,35 @@ TEST_P(moe_3gemm_compressed_gpu_symmetric_random, moe_accuracy_test_symmetric) {
topology.add(data("w2_scale", w2_scale_mem));
topology.add(data("w2_zp", w2_zp_mem));
- cldnn::MOE3GemmFusedCompressed::Config moe_config;
+ // Create MoERouterFused primitive
+ MoERouterFused::Config router_config;
+ router_config.num_expert = config.num_experts;
+ router_config.top_k = config.top_k;
+ std::vector<input_info> router_inputs{input_info("routing_weights")};
+ if (routing_type == cldnn::MoERouterFused::RoutingType::SIGMOID_BIAS) {
+ router_config.routing_type = MoERouterFused::RoutingType::SIGMOID_BIAS;
+ topology.add(data("routing_bias", routing_bias_mem));
+ auto routing_eps_mem = engine.allocate_memory({data_types::f16, format::bfyx, {1, 1, 1, 1}});
+ set_values(routing_eps_mem, {routing_eps_val});
+ get_test_stream().finish();
+ topology.add(data("routing_eps", routing_eps_mem));
+ router_inputs.push_back(input_info("routing_bias"));
+ router_inputs.push_back(input_info("routing_eps"));
+ }
+ topology.add(moe_router_fused("router", router_inputs, router_config));
+
+ cldnn::MOECompressed::Config moe_config;
moe_config.hidden_size = config.hidden_size;
moe_config.inter_size = config.inter_size;
moe_config.num_expert = config.num_experts;
moe_config.top_k = config.top_k;
moe_config.group_size = config.group_size;
moe_config.out_type = data_types::f16;
- moe_config.routing_type = routing_type;
moe_config.has_zp = false;
std::vector<input_info> moe_inputs{input_info("hidden_states"),
- input_info("routing_weights"),
+ input_info("router", 0), // topk_weights
+ input_info("router", 1), // topk_indices
input_info("w0_weight"),
input_info("w0_scale"),
input_info("w0_zp"),
@@ -1196,20 +1227,12 @@ TEST_P(moe_3gemm_compressed_gpu_symmetric_random, moe_accuracy_test_symmetric) {
input_info("w2_weight"),
input_info("w2_scale"),
input_info("w2_zp")};
- if (routing_type == cldnn::MOE3GemmFusedCompressed::RoutingType::SIGMOID_BIAS) {
- topology.add(data("routing_bias", routing_bias_mem));
- moe_inputs.push_back(input_info("routing_bias"));
- auto routing_eps_mem = engine.allocate_memory({data_types::f16, format::bfyx, {1, 1, 1, 1}});
- set_values(routing_eps_mem, {routing_eps_val});
- get_test_stream().finish();
- topology.add(data("routing_eps", routing_eps_mem));
- moe_inputs.push_back(input_info("routing_eps"));
- }
- auto moe_prim = moe_3gemm_fused_compressed("moe_3gemm_fused_compressed", moe_inputs, moe_config);
- topology.add(moe_prim);
+ topology.add(moe_3gemm_fused_compressed("moe_3gemm_fused_compressed", moe_inputs, moe_config));
- network network(engine, topology, get_test_default_config(engine));
+ auto net_config = get_test_default_config(engine);
+ net_config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ network network(engine, topology, net_config);
network.set_input_data("hidden_states", hidden_states_mem);
network.set_input_data("routing_weights", routing_weights_mem);
@@ -1218,11 +1241,11 @@ TEST_P(moe_3gemm_compressed_gpu_symmetric_random, moe_accuracy_test_symmetric) {
get_test_stream().flush();
cldnn::mem_lock<ov::float16, mem_lock_type::read> output_ptr(output_prim, get_test_stream());
- auto ref_output = routing_type == cldnn::MOE3GemmFusedCompressed::RoutingType::SIGMOID_BIAS
+ auto ref_output = routing_type == cldnn::MoERouterFused::RoutingType::SIGMOID_BIAS
? ref.run_reference_sigmoid(hidden_states, routing_weights, routing_bias_data, routing_eps_val, w0_data, w1_data, w2_data)
: ref.run_reference_softmax(hidden_states, routing_weights, w0_data, w1_data, w2_data);
- const float base_tolerance = routing_type == cldnn::MOE3GemmFusedCompressed::RoutingType::SIGMOID_BIAS ? 0.25f : 0.15f;
+ const float base_tolerance = routing_type == cldnn::MoERouterFused::RoutingType::SIGMOID_BIAS ? 0.25f : 0.15f;
const float tolerance = base_tolerance * std::max(1, static_cast<int>(config.hidden_size / 128));
for (size_t i = 0; i < ref_output.size(); ++i) {
ASSERT_NEAR(static_cast<float>(output_ptr[i]), static_cast<float>(ref_output[i]), tolerance);
@@ -1231,8 +1254,8 @@ TEST_P(moe_3gemm_compressed_gpu_symmetric_random, moe_accuracy_test_symmetric) {
INSTANTIATE_TEST_SUITE_P(smoke,
moe_3gemm_compressed_gpu_symmetric_random,
- ::testing::Combine(::testing::Values(cldnn::MOE3GemmFusedCompressed::RoutingType::SOFTMAX,
- cldnn::MOE3GemmFusedCompressed::RoutingType::SIGMOID_BIAS),
+ ::testing::Combine(::testing::Values(cldnn::MoERouterFused::RoutingType::SOFTMAX,
+ cldnn::MoERouterFused::RoutingType::SIGMOID_BIAS),
::testing::Values(Moe3GemmTestParams{1, true, 128, 256, 4, 2, 128, true},
Moe3GemmTestParams{16, true, 128, 256, 4, 2, 128, true},
Moe3GemmTestParams{1, false, 128, 256, 4, 2, 128, true},
@@ -1401,15 +1424,6 @@ TEST_P(moe_3gemm_compressed_gpu_shared_symmetric_random, moe_accuracy_test_share
topology.add(data("w2_scale", w2_scale_mem));
topology.add(data("w2_zp", w2_zp_mem));
- auto dummy_bias_mem = engine.allocate_memory({data_types::f16, format::bfyx, {1, 1, 1, 1}});
- set_values(dummy_bias_mem, {ov::float16(0.0f)});
- get_test_stream().finish();
- auto dummy_eps_mem = engine.allocate_memory({data_types::f16, format::bfyx, {1, 1, 1, 1}});
- set_values(dummy_eps_mem, {ov::float16(0.0f)});
- get_test_stream().finish();
- topology.add(data("dummy_routing_bias", dummy_bias_mem));
- topology.add(data("dummy_routing_eps", dummy_eps_mem));
-
topology.add(data("s_gate_weight", s_gate_weight_mem));
topology.add(data("s_gate_scale", s_gate_scale_mem));
topology.add(data("s_gate_zp", s_gate_zp_mem));
@@ -1421,7 +1435,14 @@ TEST_P(moe_3gemm_compressed_gpu_shared_symmetric_random, moe_accuracy_test_share
topology.add(data("s_down_zp", s_down_zp_mem));
topology.add(data("s_gate_scalar", s_gate_scalar_mem));
- cldnn::MOE3GemmFusedCompressed::Config moe_config;
+ // Create MoERouterFused primitive (softmax for shared expert tests)
+ MoERouterFused::Config router_config;
+ router_config.num_expert = config.num_experts;
+ router_config.top_k = config.top_k;
+ router_config.routing_type = MoERouterFused::RoutingType::SOFTMAX;
+ topology.add(moe_router_fused("router", {input_info("routing_weights")}, router_config));
+
+ cldnn::MOECompressed::Config moe_config;
moe_config.hidden_size = config.hidden_size;
moe_config.inter_size = config.inter_size;
moe_config.num_expert = config.num_experts;
@@ -1431,20 +1452,35 @@ TEST_P(moe_3gemm_compressed_gpu_shared_symmetric_random, moe_accuracy_test_share
moe_config.num_shared_expert = 1;
moe_config.has_zp = false;
- auto moe_prim = moe_3gemm_fused_compressed("moe_3gemm_fused_compressed",
- {input_info("hidden_states"), input_info("routing_weights"), input_info("w0_weight"),
- input_info("w0_scale"), input_info("w0_zp"), input_info("w1_weight"),
- input_info("w1_scale"), input_info("w1_zp"), input_info("w2_weight"),
- input_info("w2_scale"), input_info("w2_zp"), input_info("dummy_routing_bias"),
- input_info("dummy_routing_eps"), input_info("s_gate_weight"), input_info("s_gate_scale"),
- input_info("s_gate_zp"), input_info("s_up_weight"), input_info("s_up_scale"),
- input_info("s_up_zp"), input_info("s_down_weight"), input_info("s_down_scale"),
- input_info("s_down_zp"), input_info("s_gate_scalar")},
- moe_config);
-
- topology.add(moe_prim);
-
- network network(engine, topology, get_test_default_config(engine));
+ topology.add(moe_3gemm_fused_compressed("moe_3gemm_fused_compressed",
+ {input_info("hidden_states"),
+ input_info("router", 0), // topk_weights
+ input_info("router", 1), // topk_indices
+ input_info("w0_weight"),
+ input_info("w0_scale"),
+ input_info("w0_zp"),
+ input_info("w1_weight"),
+ input_info("w1_scale"),
+ input_info("w1_zp"),
+ input_info("w2_weight"),
+ input_info("w2_scale"),
+ input_info("w2_zp"),
+ // Shared Expert Inputs (indices 12-21)
+ input_info("s_gate_weight"),
+ input_info("s_gate_scale"),
+ input_info("s_gate_zp"),
+ input_info("s_up_weight"),
+ input_info("s_up_scale"),
+ input_info("s_up_zp"),
+ input_info("s_down_weight"),
+ input_info("s_down_scale"),
+ input_info("s_down_zp"),
+ input_info("s_gate_scalar")},
+ moe_config));
+
+ auto net_config = get_test_default_config(engine);
+ net_config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ network network(engine, topology, net_config);
network.set_input_data("hidden_states", hidden_states_mem);
network.set_input_data("routing_weights", routing_weights_mem);
diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/moe_router_fused_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/moe_router_fused_gpu_test.cpp
new file mode 100644
index 00000000000..0fd334c036f
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/unit/test_cases/moe_router_fused_gpu_test.cpp
@@ -0,0 +1,248 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <algorithm>
+#include <cmath>
+#include <intel_gpu/primitives/data.hpp>
+#include <intel_gpu/primitives/moe_router_fused.hpp>
+#include <intel_gpu/primitives/reorder.hpp>
+#include <intel_gpu/runtime/engine.hpp>
+#include <intel_gpu/runtime/layout.hpp>
+#include <intel_gpu/runtime/memory.hpp>
+#include <numeric>
+#include <vector>
+
+#include "../../common/random_generator.hpp"
+#include "../test_utils/test_utils.h"
+
+using namespace cldnn;
+using namespace ::tests;
+
+struct MoeRouterTestParams {
+ size_t num_tokens;
+ size_t num_experts;
+ size_t top_k;
+};
+
+class moe_router_fused_softmax_gpu : public ::testing::TestWithParam<MoeRouterTestParams> {};
+
+TEST_P(moe_router_fused_softmax_gpu, router_accuracy_test) {
+ auto param = GetParam();
+ auto& engine = get_test_engine();
+ if (!engine.get_device_info().supports_immad) {
+ GTEST_SKIP() << "No immad support";
+ }
+
+ tests::random_generator rg(GET_SUITE_NAME);
+ const size_t num_tokens = param.num_tokens;
+ const size_t num_experts = param.num_experts;
+ const size_t top_k = param.top_k;
+
+ // Generate random logits
+ auto logits_data = rg.generate_random_1d<ov::float16>(num_tokens * num_experts, -2.0f, 2.0f, 1000);
+
+ // Create input memory
+ auto logits_mem = engine.allocate_memory(layout{ov::PartialShape{static_cast<int64_t>(num_tokens), static_cast<int64_t>(num_experts)},
+ data_types::f16, format::bfyx});
+ set_values(logits_mem, logits_data);
+ get_test_stream().finish();
+
+ // Build topology
+ topology topology;
+ topology.add(input_layout("logits", logits_mem->get_layout()));
+
+ MoERouterFused::Config config;
+ config.num_expert = num_experts;
+ config.top_k = top_k;
+ config.routing_type = MoERouterFused::RoutingType::SOFTMAX;
+
+ topology.add(moe_router_fused("router", {input_info("logits")}, config));
+ topology.add(reorder("topk_weights", input_info("router", 0), format::bfyx, data_types::f16));
+ topology.add(reorder("topk_indices", input_info("router", 1), format::bfyx, data_types::i32));
+
+ auto net_config = get_test_default_config(engine);
+ net_config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ network network(engine, topology, net_config);
+ network.set_input_data("logits", logits_mem);
+
+ auto outputs = network.execute();
+ get_test_stream().flush();
+
+ auto weights_mem = outputs.at("topk_weights").get_memory();
+ auto indices_mem = outputs.at("topk_indices").get_memory();
+
+ cldnn::mem_lock<ov::float16, mem_lock_type::read> weights_ptr(weights_mem, get_test_stream());
+ cldnn::mem_lock<int32_t, mem_lock_type::read> indices_ptr(indices_mem, get_test_stream());
+
+ // Compute reference: softmax + top-k + normalize
+ for (size_t t = 0; t < num_tokens; ++t) {
+ // Softmax
+ std::vector<float> logits(num_experts);
+ float max_val = std::numeric_limits<float>::lowest();
+ for (size_t e = 0; e < num_experts; ++e) {
+ logits[e] = static_cast<float>(logits_data[t * num_experts + e]);
+ if (logits[e] > max_val) max_val = logits[e];
+ }
+ float sum_exp = 0.0f;
+ for (size_t e = 0; e < num_experts; ++e) {
+ logits[e] = std::exp(logits[e] - max_val);
+ sum_exp += logits[e];
+ }
+ for (size_t e = 0; e < num_experts; ++e) {
+ logits[e] /= sum_exp;
+ }
+
+ // Top-k by sorting
+ std::vector<std::pair<float, size_t>> expert_weights;
+ for (size_t e = 0; e < num_experts; ++e) {
+ expert_weights.push_back({logits[e], e});
+ }
+ std::partial_sort(expert_weights.begin(),
+ expert_weights.begin() + top_k,
+ expert_weights.end(),
+ [](const std::pair<float, size_t>& a, const std::pair<float, size_t>& b) {
+ return a.first > b.first;
+ });
+
+ // Normalize top-k weights
+ float sum_weights = 0.0f;
+ for (size_t k = 0; k < top_k; ++k)
+ sum_weights += expert_weights[k].first;
+
+ // Compare
+ for (size_t k = 0; k < top_k; ++k) {
+ float ref_weight = expert_weights[k].first / sum_weights;
+ int32_t ref_index = static_cast<int32_t>(expert_weights[k].second);
+
+ float actual_weight = static_cast<float>(weights_ptr[t * top_k + k]);
+ int32_t actual_index = indices_ptr[t * top_k + k];
+
+ ASSERT_NEAR(actual_weight, ref_weight, 0.01f)
+ << "Token " << t << ", k=" << k << " weight mismatch";
+ ASSERT_EQ(actual_index, ref_index)
+ << "Token " << t << ", k=" << k << " index mismatch";
+ }
+ }
+}
+
+class moe_router_fused_sigmoid_bias_gpu : public ::testing::TestWithParam<MoeRouterTestParams> {};
+
+TEST_P(moe_router_fused_sigmoid_bias_gpu, router_accuracy_test) {
+ auto param = GetParam();
+ auto& engine = get_test_engine();
+ if (!engine.get_device_info().supports_immad) {
+ GTEST_SKIP() << "No immad support";
+ }
+
+ tests::random_generator rg(GET_SUITE_NAME);
+ const size_t num_tokens = param.num_tokens;
+ const size_t num_experts = param.num_experts;
+ const size_t top_k = param.top_k;
+
+ // Generate random data
+ auto logits_data = rg.generate_random_1d<ov::float16>(num_tokens * num_experts, -2.0f, 2.0f, 1000);
+ auto bias_data = rg.generate_random_1d<ov::float16>(num_experts, -0.5f, 0.5f, 1000);
+ ov::float16 eps_val = ov::float16(1e-6f);
+
+ // Create memories
+ auto logits_mem = engine.allocate_memory(layout{ov::PartialShape{static_cast<int64_t>(num_tokens), static_cast<int64_t>(num_experts)},
+ data_types::f16, format::bfyx});
+ set_values(logits_mem, logits_data);
+ get_test_stream().finish();
+
+ auto bias_mem = engine.allocate_memory(layout{ov::PartialShape{1, static_cast<int64_t>(num_experts)},
+ data_types::f16, format::bfyx});
+ set_values(bias_mem, bias_data);
+ get_test_stream().finish();
+
+ auto eps_mem = engine.allocate_memory({data_types::f16, format::bfyx, {1, 1, 1, 1}});
+ set_values(eps_mem, {eps_val});
+ get_test_stream().finish();
+
+ // Build topology
+ topology topology;
+ topology.add(input_layout("logits", logits_mem->get_layout()));
+ topology.add(data("bias", bias_mem));
+ topology.add(data("eps", eps_mem));
+
+ MoERouterFused::Config config;
+ config.num_expert = num_experts;
+ config.top_k = top_k;
+ config.routing_type = MoERouterFused::RoutingType::SIGMOID_BIAS;
+
+ topology.add(moe_router_fused("router", {input_info("logits"), input_info("bias"), input_info("eps")}, config));
+ topology.add(reorder("topk_weights", input_info("router", 0), format::bfyx, data_types::f16));
+ topology.add(reorder("topk_indices", input_info("router", 1), format::bfyx, data_types::i32));
+
+ auto net_config = get_test_default_config(engine);
+ net_config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ network network(engine, topology, net_config);
+ network.set_input_data("logits", logits_mem);
+
+ auto outputs = network.execute();
+ get_test_stream().flush();
+
+ auto weights_mem = outputs.at("topk_weights").get_memory();
+ auto indices_mem = outputs.at("topk_indices").get_memory();
+
+ cldnn::mem_lock<ov::float16, mem_lock_type::read> weights_ptr(weights_mem, get_test_stream());
+ cldnn::mem_lock<int32_t, mem_lock_type::read> indices_ptr(indices_mem, get_test_stream());
+
+ // Compute reference: sigmoid + bias topk + normalize
+ for (size_t t = 0; t < num_tokens; ++t) {
+ // Sigmoid
+ std::vector<float> sigmoid_scores(num_experts);
+ for (size_t e = 0; e < num_experts; ++e) {
+ float logit = static_cast<float>(logits_data[t * num_experts + e]);
+ sigmoid_scores[e] = 1.0f / (1.0f + std::exp(-logit));
+ }
+
+ // Selection = sigmoid + bias
+ std::vector<std::pair<float, size_t>> expert_weights;
+ for (size_t e = 0; e < num_experts; ++e) {
+ float score = sigmoid_scores[e] + static_cast<float>(bias_data[e]);
+ expert_weights.push_back({score, e});
+ }
+ std::partial_sort(expert_weights.begin(),
+ expert_weights.begin() + top_k,
+ expert_weights.end(),
+ [](const std::pair<float, size_t>& a, const std::pair<float, size_t>& b) {
+ return a.first > b.first;
+ });
+
+ // Normalize using raw sigmoid values at top-k indices + eps
+ float sum_weights = 0.0f;
+ for (size_t k = 0; k < top_k; ++k)
+ sum_weights += sigmoid_scores[expert_weights[k].second];
+ sum_weights += static_cast<float>(eps_val);
+
+ // Compare
+ for (size_t k = 0; k < top_k; ++k) {
+ float ref_weight = sigmoid_scores[expert_weights[k].second] / sum_weights;
+ int32_t ref_index = static_cast<int32_t>(expert_weights[k].second);
+
+ float actual_weight = static_cast<float>(weights_ptr[t * top_k + k]);
+ int32_t actual_index = indices_ptr[t * top_k + k];
+
+ ASSERT_NEAR(actual_weight, ref_weight, 0.02f)
+ << "Token " << t << ", k=" << k << " weight mismatch";
+ ASSERT_EQ(actual_index, ref_index)
+ << "Token " << t << ", k=" << k << " index mismatch";
+ }
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(smoke,
+ moe_router_fused_softmax_gpu,
+ ::testing::Values(MoeRouterTestParams{1, 4, 2},
+ MoeRouterTestParams{4, 4, 2},
+ MoeRouterTestParams{16, 8, 2},
+ MoeRouterTestParams{1, 8, 4}));
+
+INSTANTIATE_TEST_SUITE_P(smoke,
+ moe_router_fused_sigmoid_bias_gpu,
+ ::testing::Values(MoeRouterTestParams{1, 4, 2},
+ MoeRouterTestParams{4, 4, 2},
+ MoeRouterTestParams{16, 8, 2},
+ MoeRouterTestParams{1, 8, 4}));
diff --git a/src/plugins/intel_gpu/tests/unit/transformations/fuse_moe_3gemm_compressed_test.cpp b/src/plugins/intel_gpu/tests/unit/transformations/fuse_moe_3gemm_compressed_test.cpp
deleted file mode 100644
index 419650fd47e..00000000000
--- a/src/plugins/intel_gpu/tests/unit/transformations/fuse_moe_3gemm_compressed_test.cpp
+++ /dev/null
@@ -1,770 +0,0 @@
-// Copyright (C) 2018-2026 Intel Corporation
-// SPDX-License-Identifier: Apache-2.0
-//
-
-#include "plugin/transformations/fuse_moe_3gemm_compressed.hpp"
-
-#include <gtest/gtest.h>
-
-#include "common_test_utils/node_builders/moe_builders.hpp"
-#include "common_test_utils/ov_test_utils.hpp"
-#include "intel_gpu/op/moe_3gemm_fused_compressed.hpp"
-#include "openvino/op/add.hpp"
-#include "openvino/op/broadcast.hpp"
-#include "openvino/op/concat.hpp"
-#include "openvino/op/constant.hpp"
-#include "openvino/op/convert.hpp"
-#include "openvino/op/divide.hpp"
-#include "openvino/op/gather.hpp"
-#include "openvino/op/gather_elements.hpp"
-#include "openvino/op/matmul.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/sigmoid.hpp"
-#include "openvino/op/slice.hpp"
-#include "openvino/op/softmax.hpp"
-#include "openvino/op/topk.hpp"
-#include "openvino/op/transpose.hpp"
-#include "openvino/op/unsqueeze.hpp"
-#include "ov_ops/moe_compressed.hpp"
-
-using namespace testing;
-using namespace ov::intel_gpu;
-
-namespace ov {
-namespace test {
-namespace intel_gpu {
-
-using namespace ov::test;
-using AT = ov::op::internal::MOE::Activation_type;
-
-using FuseMOE3GemmCompressedTestParams = std::tuple<MoERoutingType,
- bool, // reshape_on_moe_input
- bool, // with_routed_scale
- ov::op::internal::MOE::Activation_type>;
-
-class FuseMOE3GemmCompressedTest : public TransformationTestsF, public ::testing::WithParamInterface<FuseMOE3GemmCompressedTestParams> {
-public:
- static std::string get_test_case_name(const ::testing::TestParamInfo<FuseMOE3GemmCompressedTestParams>& info) {
- std::string name;
- switch (std::get<0>(info.param)) {
- case MoERoutingType::SOFTMAX:
- name = "Softmax";
- break;
- case MoERoutingType::SIGMOID_BIAS:
- name = "SigmoidBias";
- break;
- default:
- OPENVINO_THROW("Unsupported routing type");
- }
- if (std::get<1>(info.param))
- name += "_ReshapeOnMoeInput";
- if (std::get<2>(info.param))
- name += "_RoutedScalingFactor";
- switch (std::get<3>(info.param)) {
- case AT::SWIGLU:
- break;
- case AT::GEGLU_TANH:
- name += "_GeluTanh";
- break;
- case AT::GEGLU_ERF:
- name += "_GeluErf";
- break;
- }
- return name;
- }
-};
-
-// Softmax routing: MatMul → Softmax → TopK → ReduceSum → Divide
-// [→ Convert(i32) → Gather(per_expert_scale, topk_idx) → Multiply(norm, gathered) when per_expert_scale is set]
-// → Transpose → Unsqueeze.
-static std::pair<ov::Output<ov::Node>, ov::Output<ov::Node>> build_softmax_routing_for_fuse_test(const ov::Output<ov::Node>& routing_weights,
- size_t topk,
- size_t number_of_experts = 0,
- std::optional<float> per_expert_scale = std::nullopt) {
- auto softmax = std::make_shared<ov::op::v8::Softmax>(routing_weights, 1);
- auto k = op::v0::Constant::create(element::i32, Shape{}, {static_cast<int32_t>(topk)});
- auto topk_node = std::make_shared<ov::op::v11::TopK>(softmax, k, 1, ov::op::v11::TopK::Mode::MAX, ov::op::v11::TopK::SortType::SORT_VALUES);
-
- auto reduce_axis = op::v0::Constant::create(element::i64, Shape{1}, {1});
- auto reduce_sum = std::make_shared<ov::op::v1::ReduceSum>(topk_node->output(0), reduce_axis, true);
- ov::Output<ov::Node> norm = std::make_shared<ov::op::v1::Divide>(topk_node->output(0), reduce_sum);
-
- ov::Output<ov::Node> topk_indices = topk_node->output(1);
- if (per_expert_scale.has_value()) {
- auto convert_topk = std::make_shared<ov::op::v0::Convert>(topk_node->output(1), element::i32);
- auto scale_const = op::v0::Constant::create(routing_weights.get_element_type(), Shape{number_of_experts}, {*per_expert_scale});
- auto gather_axis = op::v0::Constant::create(element::i32, Shape{}, {0});
- auto gathered = std::make_shared<ov::op::v8::Gather>(scale_const, convert_topk, gather_axis, 0);
- norm = std::make_shared<ov::op::v1::Multiply>(norm, gathered);
- topk_indices = convert_topk;
- }
-
- auto transpose_order = op::v0::Constant::create(element::i64, Shape{2}, {1, 0});
- auto transpose = std::make_shared<ov::op::v1::Transpose>(norm, transpose_order);
- auto unsqueeze_const = op::v0::Constant::create(element::i64, Shape{1}, {-1});
- auto unsqueeze_moe = std::make_shared<ov::op::v0::Unsqueeze>(transpose, unsqueeze_const);
-
- return {unsqueeze_moe, topk_indices};
-}
-
-// Sigmoid+bias routing: Sigmoid → Add → TopK → Convert → GatherElements → ReduceSum → Add(eps) → Divide
-// [→ Multiply(routed_scaling_factor) when scale_value is set]
-// → Transpose → Unsqueeze.
-static std::pair<ov::Output<ov::Node>, ov::Output<ov::Node>> build_sigmoid_routing_for_fuse_test(const ov::Output<ov::Node>& routing_weights,
- ov::element::Type data_precision,
- size_t number_of_experts,
- size_t topk,
- std::optional<float> scale_value = std::nullopt) {
- auto sigmoid = std::make_shared<ov::op::v0::Sigmoid>(routing_weights);
- auto bias = op::v0::Constant::create(data_precision, Shape{1, number_of_experts}, {0.1f});
- auto sig_add = std::make_shared<ov::op::v1::Add>(sigmoid, bias);
-
- auto k = op::v0::Constant::create(element::i64, Shape{}, {static_cast<int64_t>(topk)});
- auto topk_node =
- std::make_shared<ov::op::v11::TopK>(sig_add, k, -1, ov::op::v11::TopK::Mode::MAX, ov::op::v11::TopK::SortType::SORT_VALUES, ov::element::i64);
-
- auto convert_topk = std::make_shared<ov::op::v0::Convert>(topk_node->output(1), ov::element::i32);
- auto gather_el = std::make_shared<ov::op::v6::GatherElements>(sigmoid, convert_topk, 1);
- auto reduce_axis = op::v0::Constant::create(element::i64, Shape{1}, {1});
- auto reduce_sum = std::make_shared<ov::op::v1::ReduceSum>(gather_el, reduce_axis, true);
- auto eps = op::v0::Constant::create(data_precision, Shape{1, 1}, {1e-6f});
- auto add_eps = std::make_shared<ov::op::v1::Add>(reduce_sum, eps);
- std::shared_ptr<ov::Node> norm = std::make_shared<ov::op::v1::Divide>(gather_el, add_eps);
-
- // Mirror trinity-mini afmoe `routed_scaling_factor`: an extra Multiply between
- // the normalized routing weights and the final Transpose. The matcher's optional<Multiply>
- // absorbs it; the callback re-applies it as a post-op Multiply on the fused MOE output.
- if (scale_value.has_value()) {
- auto scale_const = op::v0::Constant::create(data_precision, Shape{1, 1}, {*scale_value});
- norm = std::make_shared<ov::op::v1::Multiply>(norm, scale_const);
- }
-
- auto transpose_order = op::v0::Constant::create(element::i64, Shape{2}, {1, 0});
- auto transpose = std::make_shared<ov::op::v1::Transpose>(norm, transpose_order);
- auto unsqueeze_const = op::v0::Constant::create(element::i64, Shape{1}, {-1});
- auto unsqueeze_moe = std::make_shared<ov::op::v0::Unsqueeze>(transpose, unsqueeze_const);
-
- return {unsqueeze_moe, convert_topk};
-}
-
-TEST_P(FuseMOE3GemmCompressedTest, CompareFunctions) {
- const auto& [routing_type, reshape_on_moe_input, with_routed_scale, activation_type] = GetParam();
- constexpr float routed_scale_value = 2.5f;
- // SOFTMAX uses per-expert scale (Gather+Multiply, folded into scale_down in the reference).
- // SIGMOID_BIAS uses a global routed_scaling_factor Multiply (re-emitted as a post-op in the reference).
- constexpr auto data_precision = element::f32;
-
- // ── MoE shape parameters (shared between input model and reference model) ──
- constexpr size_t batch = 4;
- constexpr size_t seq_len = 8;
- constexpr size_t tokens = batch * seq_len;
- constexpr size_t hidden_size = 2048;
- constexpr size_t inter_size = 768;
- constexpr size_t num_experts = 128;
- constexpr size_t top_k = 8;
- constexpr size_t group_size = 128;
- constexpr size_t gate_up_groups = hidden_size / group_size; // gate/up weights grouped along K=hidden_size
- constexpr size_t down_groups = inter_size / group_size; // down weight grouped along K=inter_size
-
- {
- auto hidden_states = std::make_shared<ov::op::v0::Parameter>(data_precision, Shape{batch, seq_len, hidden_size});
- auto flatten_shape = op::v0::Constant::create(element::i32, Shape{2}, {static_cast<int32_t>(tokens), static_cast<int32_t>(hidden_size)});
- auto hidden_states_reshape = std::make_shared<ov::op::v1::Reshape>(hidden_states, flatten_shape, false);
- auto routers = op::v0::Constant::create(data_precision, Shape{hidden_size, num_experts}, {0.2});
-
- // Gemma-4 style: the router MatMul uses a separately-normed hidden state while
- // MOECompressed input[0] uses the plain reshape. Only applies to SOFTMAX+per-expert scale.
- ov::Output<ov::Node> router_input = hidden_states_reshape;
- if (routing_type == MoERoutingType::SOFTMAX && with_routed_scale) {
- auto norm_scale = op::v0::Constant::create(data_precision, Shape{1, 1, hidden_size}, {1.0f});
- auto hidden_normed = std::make_shared<ov::op::v1::Multiply>(hidden_states, norm_scale);
- router_input = std::make_shared<ov::op::v1::Reshape>(hidden_normed, flatten_shape, false);
- }
- auto routing_weights = std::make_shared<ov::op::v0::MatMul>(router_input, routers);
- const std::optional<float> softmax_per_expert_scale =
- (routing_type == MoERoutingType::SOFTMAX && with_routed_scale) ? std::optional<float>{routed_scale_value} : std::nullopt;
- const std::optional<float> sigmoid_scale =
- (routing_type == MoERoutingType::SIGMOID_BIAS && with_routed_scale) ? std::optional<float>{routed_scale_value} : std::nullopt;
- auto [unsqueeze_moe, topk_indices] = routing_type == MoERoutingType::SOFTMAX
- ? build_softmax_routing_for_fuse_test(routing_weights, top_k, num_experts, softmax_per_expert_scale)
- : build_sigmoid_routing_for_fuse_test(routing_weights, data_precision, num_experts, top_k, sigmoid_scale);
-
- // Compressed weights: 4-D weight = {experts, N, num_groups, group_size};
- // 3-D scale/zp = {experts, N, num_groups}. K = num_groups * group_size.
- auto wei_gate = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups, group_size}, {1});
- auto scale_gate = op::v0::Constant::create(element::f16, Shape{num_experts, inter_size, gate_up_groups}, {0.01f});
- auto zp_gate = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups}, {0});
- auto wei_up = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups, group_size}, {1});
- auto scale_up = op::v0::Constant::create(element::f16, Shape{num_experts, inter_size, gate_up_groups}, {0.01f});
- auto zp_up = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups}, {0});
- auto wei_down = op::v0::Constant::create(element::u4, Shape{num_experts, hidden_size, down_groups, group_size}, {1});
- auto scale_down = op::v0::Constant::create(element::f16, Shape{num_experts, hidden_size, down_groups}, {0.01f});
- auto zp_down = op::v0::Constant::create(element::u4, Shape{num_experts, hidden_size, down_groups}, {0});
-
- ov::op::internal::MOECompressed::Config config;
- config.expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU;
- config.activation_type = activation_type;
- config.has_zp = true;
- config.hidden_size = hidden_size;
- config.inter_size = inter_size;
- config.num_expert = num_experts;
- config.group_size = group_size;
- config.top_k = top_k;
- config.out_type = ov::element::f16;
-
- // When reshape_on_moe_input is true, MOECompressed gets the flattened 2D hidden_states_reshape;
- // otherwise it gets the original 3D hidden_states.
- auto moe_input_0 = reshape_on_moe_input ? ov::Output<ov::Node>(hidden_states_reshape) : ov::Output<ov::Node>(hidden_states);
- auto moe_compressed = std::make_shared<ov::op::internal::MOECompressed>(
- ov::OutputVector{moe_input_0, unsqueeze_moe, topk_indices, wei_gate, scale_gate, zp_gate, wei_up, scale_up, zp_up, wei_down, scale_down, zp_down},
- config);
- model = std::make_shared<ov::Model>(moe_compressed, ov::ParameterVector{hidden_states});
- }
- manager.register_pass<FuseMOE3GemmCompressed>();
- {
- auto hidden_states = std::make_shared<ov::op::v0::Parameter>(data_precision, Shape{batch, seq_len, hidden_size});
- auto flatten_shape = op::v0::Constant::create(element::i32, Shape{2}, {static_cast<int32_t>(tokens), static_cast<int32_t>(hidden_size)});
- auto hidden_states_reshape = std::make_shared<ov::op::v1::Reshape>(hidden_states, flatten_shape, false);
- auto routers = op::v0::Constant::create(data_precision, Shape{hidden_size, num_experts}, {0.2});
-
- // Mirror the normed router input from the input model.
- ov::Output<ov::Node> router_input = hidden_states_reshape;
- if (routing_type == MoERoutingType::SOFTMAX && with_routed_scale) {
- auto norm_scale = op::v0::Constant::create(data_precision, Shape{1, 1, hidden_size}, {1.0f});
- auto hidden_normed = std::make_shared<ov::op::v1::Multiply>(hidden_states, norm_scale);
- router_input = std::make_shared<ov::op::v1::Reshape>(hidden_normed, flatten_shape, false);
- }
- auto routing_weights = std::make_shared<ov::op::v0::MatMul>(router_input, routers);
-
- auto wei_gate = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups, group_size}, {1});
- auto scale_gate = op::v0::Constant::create(element::f16, Shape{num_experts, inter_size, gate_up_groups}, {0.01f});
- auto zp_gate = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups}, {0});
- auto wei_up = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups, group_size}, {1});
- auto scale_up = op::v0::Constant::create(element::f16, Shape{num_experts, inter_size, gate_up_groups}, {0.01f});
- auto zp_up = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups}, {0});
- auto wei_down = op::v0::Constant::create(element::u4, Shape{num_experts, hidden_size, down_groups, group_size}, {1});
- // SOFTMAX + with_routed_scale: per-expert scale is folded into scale_down by the transformation.
- const float scale_down_val = (routing_type == MoERoutingType::SOFTMAX && with_routed_scale) ? 0.01f * routed_scale_value : 0.01f;
- auto scale_down = op::v0::Constant::create(element::f16, Shape{num_experts, hidden_size, down_groups}, {scale_down_val});
- auto zp_down = op::v0::Constant::create(element::u4, Shape{num_experts, hidden_size, down_groups}, {0});
-
- ov::op::internal::MOECompressed::Config config;
- config.expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU;
- config.activation_type = activation_type;
- config.has_zp = true;
- config.hidden_size = hidden_size;
- config.inter_size = inter_size;
- config.num_expert = num_experts;
- config.group_size = group_size;
- config.top_k = top_k;
- config.out_type = ov::element::f16;
- if (routing_type == MoERoutingType::SOFTMAX) {
- config.routing_type = ov::op::internal::MOECompressed::RoutingType::SOFTMAX;
- } else if (routing_type == MoERoutingType::SIGMOID_BIAS) {
- config.routing_type = ov::op::internal::MOECompressed::RoutingType::SIGMOID_BIAS;
- } else {
- OPENVINO_THROW("Unsupported routing type");
- }
-
- // When SOFTMAX+with_routed_scale and no reshape on MOE input, the transformation binds
- // hidden_state_reshape (optional) to hidden_states (3D, a Parameter) because the normed
- // router uses its own separate Reshape. So hs_reshaped = hidden_states, and
- // moe_compressed->input_value(0) == hs_reshaped => no reshape-back is emitted.
- const bool normed_router_no_reshape = (routing_type == MoERoutingType::SOFTMAX && with_routed_scale && !reshape_on_moe_input);
- ov::Output<ov::Node> fused_hs_input = normed_router_no_reshape ? ov::Output<ov::Node>(hidden_states) : ov::Output<ov::Node>(hidden_states_reshape);
- ov::OutputVector args{fused_hs_input, routing_weights, wei_gate, scale_gate, zp_gate, wei_up, scale_up, zp_up, wei_down, scale_down, zp_down};
- if (routing_type == MoERoutingType::SIGMOID_BIAS) {
- auto routing_bias = op::v0::Constant::create(data_precision, Shape{1, num_experts}, {0.1f});
- args.push_back(routing_bias);
- auto routing_eps = op::v0::Constant::create(data_precision, Shape{1, 1}, {1e-6f});
- args.push_back(routing_eps);
- }
-
- std::shared_ptr<ov::Node> result = std::make_shared<ov::intel_gpu::op::MOE3GemmFusedCompressed>(args, config);
-
- // When reshape_on_moe_input is false AND the router uses hidden_states_reshape (not a separate
- // normed reshape), hs_reshaped = hidden_states_reshape != moe_compressed->input_value(0), so the
- // transformation inserts a reshape-back. For the normed router path (SOFTMAX+with_routed_scale),
- // hs_reshaped = hidden_states (3D) == moe_compressed->input_value(0), so no reshape-back.
- if (!reshape_on_moe_input && !normed_router_no_reshape) {
- auto hidden_state_shape = std::make_shared<ov::op::v3::ShapeOf>(hidden_states);
- result = std::make_shared<ov::op::v1::Reshape>(result, hidden_state_shape, false);
- }
-
- // SIGMOID_BIAS: the transformation re-applies the absorbed routed_scaling_factor as a post-op Multiply.
- // When the scale dtype (data_precision=f32) != MOE output dtype (f16), the transformation
- // inserts a Convert so the Multiply inputs have matching types. Mirror that here.
- // SOFTMAX: the per-expert scale is folded into scale_down above; no post-op Multiply.
- if (with_routed_scale && routing_type == MoERoutingType::SIGMOID_BIAS) {
- auto post_scale = op::v0::Constant::create(data_precision, Shape{1, 1}, {routed_scale_value});
- auto post_scale_converted = std::make_shared<ov::op::v0::Convert>(post_scale, element::f16);
- result = std::make_shared<ov::op::v1::Multiply>(result, post_scale_converted);
- }
-
- model_ref = std::make_shared<ov::Model>(result, ov::ParameterVector{hidden_states});
- }
-}
-
-INSTANTIATE_TEST_SUITE_P(smoke,
- FuseMOE3GemmCompressedTest,
- ::testing::Combine(::testing::Values(MoERoutingType::SOFTMAX, MoERoutingType::SIGMOID_BIAS),
- ::testing::Bool(), // reshape_on_moe_input
- ::testing::Bool(), // with_routed_scale (per-expert for SOFTMAX, global Multiply for SIGMOID_BIAS)
- ::testing::Values(AT::SWIGLU, AT::GEGLU_TANH, AT::GEGLU_ERF)),
- FuseMOE3GemmCompressedTest::get_test_case_name);
-
-TEST_F(TransformationTestsF, FuseMOE3GemmSharedExpertCompressedTest) {
- // ── MoE shape parameters (shared between input model and reference model) ──
- constexpr size_t tokens = 32;
- constexpr size_t hidden_size = 2048;
- constexpr size_t inter_size = 768;
- constexpr size_t num_experts = 128;
- constexpr size_t num_shared = 1;
- constexpr size_t top_k = 8;
- constexpr size_t group_size = 128;
- constexpr size_t gate_up_groups = hidden_size / group_size; // gate/up grouped along K=hidden_size
- constexpr size_t down_groups = inter_size / group_size; // down grouped along K=inter_size
-
- {
- auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{tokens, hidden_size});
- auto routers = op::v0::Constant::create(element::f16, Shape{hidden_size, num_experts}, {0.2});
- auto routing_weights = std::make_shared<ov::op::v0::MatMul>(hidden_states, routers);
-
- auto [unsqueeze_moe, topk_indices] = build_softmax_routing_for_fuse_test(routing_weights, top_k);
-
- auto wei_gate = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups, group_size}, {1});
- auto scale_gate = op::v0::Constant::create(element::f16, Shape{num_experts, inter_size, gate_up_groups}, {0.01f});
- auto zp_gate = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups}, {0});
- auto wei_up = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups, group_size}, {1});
- auto scale_up = op::v0::Constant::create(element::f16, Shape{num_experts, inter_size, gate_up_groups}, {0.01f});
- auto zp_up = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups}, {0});
- auto wei_down = op::v0::Constant::create(element::u4, Shape{num_experts, hidden_size, down_groups, group_size}, {1});
- auto scale_down = op::v0::Constant::create(element::f16, Shape{num_experts, hidden_size, down_groups}, {0.01f});
- auto zp_down = op::v0::Constant::create(element::u4, Shape{num_experts, hidden_size, down_groups}, {0});
-
- // Shared expert weights: same N/K layout, leading dim = num_shared.
- auto sh_wei_gate = op::v0::Constant::create(element::u4, Shape{num_shared, inter_size, gate_up_groups, group_size}, {2});
- auto sh_scale_gate = op::v0::Constant::create(element::f16, Shape{num_shared, inter_size, gate_up_groups}, {0.02f});
- auto sh_zp_gate = op::v0::Constant::create(element::u4, Shape{num_shared, inter_size, gate_up_groups}, {0});
- auto sh_wei_up = op::v0::Constant::create(element::u4, Shape{num_shared, inter_size, gate_up_groups, group_size}, {2});
- auto sh_scale_up = op::v0::Constant::create(element::f16, Shape{num_shared, inter_size, gate_up_groups}, {0.02f});
- auto sh_zp_up = op::v0::Constant::create(element::u4, Shape{num_shared, inter_size, gate_up_groups}, {0});
- auto sh_wei_down = op::v0::Constant::create(element::u4, Shape{num_shared, hidden_size, down_groups, group_size}, {2});
- auto sh_scale_down = op::v0::Constant::create(element::f16, Shape{num_shared, hidden_size, down_groups}, {0.02f});
- auto sh_zp_down = op::v0::Constant::create(element::u4, Shape{num_shared, hidden_size, down_groups}, {0});
- auto sh_gate_gate_wei = op::v0::Constant::create(element::f16, Shape{hidden_size, num_shared}, {0.5f});
-
- ov::op::internal::MOECompressed::Config config;
- config.expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU;
- config.has_zp = true;
- config.hidden_size = hidden_size;
- config.inter_size = inter_size;
- config.num_expert = num_experts;
- config.num_shared_expert = num_shared;
- config.group_size = group_size;
- config.top_k = top_k;
- config.out_type = ov::element::f16;
- auto moe_compressed = std::make_shared<ov::op::internal::MOECompressed>(
- ov::OutputVector{hidden_states, unsqueeze_moe, topk_indices, wei_gate, scale_gate, zp_gate, wei_up, scale_up,
- zp_up, wei_down, scale_down, zp_down, sh_wei_gate, sh_scale_gate, sh_zp_gate, sh_wei_up,
- sh_scale_up, sh_zp_up, sh_wei_down, sh_scale_down, sh_zp_down, sh_gate_gate_wei},
- config);
- model = std::make_shared<ov::Model>(moe_compressed, ov::ParameterVector{hidden_states});
- manager.register_pass<FuseMOE3GemmCompressed>();
- }
- {
- auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{tokens, hidden_size});
- auto routers = op::v0::Constant::create(element::f16, Shape{hidden_size, num_experts}, {0.2});
- auto routing_weights = std::make_shared<ov::op::v0::MatMul>(hidden_states, routers);
-
- // MOE expert weights
- auto wei_gate = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups, group_size}, {1});
- auto scale_gate = op::v0::Constant::create(element::f16, Shape{num_experts, inter_size, gate_up_groups}, {0.01f});
- auto zp_gate = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups}, {0});
- auto wei_up = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups, group_size}, {1});
- auto scale_up = op::v0::Constant::create(element::f16, Shape{num_experts, inter_size, gate_up_groups}, {0.01f});
- auto zp_up = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups}, {0});
- auto wei_down = op::v0::Constant::create(element::u4, Shape{num_experts, hidden_size, down_groups, group_size}, {1});
- auto scale_down = op::v0::Constant::create(element::f16, Shape{num_experts, hidden_size, down_groups}, {0.01f});
- auto zp_down = op::v0::Constant::create(element::u4, Shape{num_experts, hidden_size, down_groups}, {0});
-
- // Shared expert weights: same N/K layout, leading dim = num_shared.
- auto sh_wei_gate = op::v0::Constant::create(element::u4, Shape{num_shared, inter_size, gate_up_groups, group_size}, {2});
- auto sh_scale_gate = op::v0::Constant::create(element::f16, Shape{num_shared, inter_size, gate_up_groups}, {0.02f});
- auto sh_zp_gate = op::v0::Constant::create(element::u4, Shape{num_shared, inter_size, gate_up_groups}, {0});
- auto sh_wei_up = op::v0::Constant::create(element::u4, Shape{num_shared, inter_size, gate_up_groups, group_size}, {2});
- auto sh_scale_up = op::v0::Constant::create(element::f16, Shape{num_shared, inter_size, gate_up_groups}, {0.02f});
- auto sh_zp_up = op::v0::Constant::create(element::u4, Shape{num_shared, inter_size, gate_up_groups}, {0});
- auto sh_wei_down = op::v0::Constant::create(element::u4, Shape{num_shared, hidden_size, down_groups, group_size}, {2});
- auto sh_scale_down = op::v0::Constant::create(element::f16, Shape{num_shared, hidden_size, down_groups}, {0.02f});
- auto sh_zp_down = op::v0::Constant::create(element::u4, Shape{num_shared, hidden_size, down_groups}, {0});
- auto sh_gate_gate_wei = op::v0::Constant::create(element::f16, Shape{hidden_size, num_shared}, {0.5f});
-
- // Dummy placeholders for SOFTMAX + shared expert (indices 11-12)
- auto dummy_bias = op::v0::Constant::create(element::f16, Shape{1}, {0.0f});
- auto dummy_eps = op::v0::Constant::create(element::f16, Shape{1}, {0.0f});
-
- ov::op::internal::MOECompressed::Config config;
- config.expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU;
- config.has_zp = true;
- config.hidden_size = hidden_size;
- config.inter_size = inter_size;
- config.num_expert = num_experts;
- config.num_shared_expert = num_shared;
- config.group_size = group_size;
- config.top_k = top_k;
- config.out_type = ov::element::f16;
- auto moe_3gemm_fused_compressed = std::make_shared<ov::intel_gpu::op::MOE3GemmFusedCompressed>(
- ov::OutputVector{hidden_states, routing_weights, wei_gate, scale_gate, zp_gate, wei_up, scale_up, zp_up,
- wei_down, scale_down, zp_down, dummy_bias, dummy_eps, sh_wei_gate, sh_scale_gate, sh_zp_gate,
- sh_wei_up, sh_scale_up, sh_zp_up, sh_wei_down, sh_scale_down, sh_zp_down, sh_gate_gate_wei},
- config);
-
- model_ref = std::make_shared<ov::Model>(moe_3gemm_fused_compressed, ov::ParameterVector{hidden_states});
- }
-}
-
-TEST_F(TransformationTestsF, FuseMOE3GemmSharedExpertCompressedSigmoidTest) {
- // ── MoE shape parameters (shared between input model and reference model) ──
- constexpr size_t tokens = 32;
- constexpr size_t hidden_size = 2048;
- constexpr size_t inter_size = 768;
- constexpr size_t num_experts = 128;
- constexpr size_t num_shared = 1;
- constexpr size_t top_k = 8;
- constexpr size_t group_size = 128;
- constexpr size_t gate_up_groups = hidden_size / group_size; // gate/up grouped along K=hidden_size
- constexpr size_t down_groups = inter_size / group_size; // down grouped along K=inter_size
-
- {
- auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{tokens, hidden_size});
- auto routers = op::v0::Constant::create(element::f16, Shape{hidden_size, num_experts}, {0.2});
- auto routing_weights = std::make_shared<ov::op::v0::MatMul>(hidden_states, routers);
-
- auto [unsqueeze_moe, topk_indices] = build_sigmoid_routing_for_fuse_test(routing_weights, element::f16, num_experts, top_k);
-
- auto wei_gate = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups, group_size}, {1});
- auto scale_gate = op::v0::Constant::create(element::f16, Shape{num_experts, inter_size, gate_up_groups}, {0.01f});
- auto zp_gate = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups}, {0});
- auto wei_up = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups, group_size}, {1});
- auto scale_up = op::v0::Constant::create(element::f16, Shape{num_experts, inter_size, gate_up_groups}, {0.01f});
- auto zp_up = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups}, {0});
- auto wei_down = op::v0::Constant::create(element::u4, Shape{num_experts, hidden_size, down_groups, group_size}, {1});
- auto scale_down = op::v0::Constant::create(element::f16, Shape{num_experts, hidden_size, down_groups}, {0.01f});
- auto zp_down = op::v0::Constant::create(element::u4, Shape{num_experts, hidden_size, down_groups}, {0});
-
- // Shared expert weights: same N/K layout, leading dim = num_shared.
- auto sh_wei_gate = op::v0::Constant::create(element::u4, Shape{num_shared, inter_size, gate_up_groups, group_size}, {2});
- auto sh_scale_gate = op::v0::Constant::create(element::f16, Shape{num_shared, inter_size, gate_up_groups}, {0.02f});
- auto sh_zp_gate = op::v0::Constant::create(element::u4, Shape{num_shared, inter_size, gate_up_groups}, {0});
- auto sh_wei_up = op::v0::Constant::create(element::u4, Shape{num_shared, inter_size, gate_up_groups, group_size}, {2});
- auto sh_scale_up = op::v0::Constant::create(element::f16, Shape{num_shared, inter_size, gate_up_groups}, {0.02f});
- auto sh_zp_up = op::v0::Constant::create(element::u4, Shape{num_shared, inter_size, gate_up_groups}, {0});
- auto sh_wei_down = op::v0::Constant::create(element::u4, Shape{num_shared, hidden_size, down_groups, group_size}, {2});
- auto sh_scale_down = op::v0::Constant::create(element::f16, Shape{num_shared, hidden_size, down_groups}, {0.02f});
- auto sh_zp_down = op::v0::Constant::create(element::u4, Shape{num_shared, hidden_size, down_groups}, {0});
- auto sh_gate_gate_wei = op::v0::Constant::create(element::f16, Shape{hidden_size, num_shared}, {0.5f});
-
- ov::op::internal::MOECompressed::Config config;
- config.expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU;
- config.has_zp = true;
- config.hidden_size = hidden_size;
- config.inter_size = inter_size;
- config.num_expert = num_experts;
- config.num_shared_expert = num_shared;
- config.group_size = group_size;
- config.top_k = top_k;
- config.out_type = ov::element::f16;
- auto moe_compressed = std::make_shared<ov::op::internal::MOECompressed>(
- ov::OutputVector{hidden_states, unsqueeze_moe, topk_indices, wei_gate, scale_gate, zp_gate, wei_up, scale_up,
- zp_up, wei_down, scale_down, zp_down, sh_wei_gate, sh_scale_gate, sh_zp_gate, sh_wei_up,
- sh_scale_up, sh_zp_up, sh_wei_down, sh_scale_down, sh_zp_down, sh_gate_gate_wei},
- config);
- model = std::make_shared<ov::Model>(moe_compressed, ov::ParameterVector{hidden_states});
- manager.register_pass<FuseMOE3GemmCompressed>();
- }
- {
- auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{tokens, hidden_size});
- auto routers = op::v0::Constant::create(element::f16, Shape{hidden_size, num_experts}, {0.2});
- auto routing_weights = std::make_shared<ov::op::v0::MatMul>(hidden_states, routers);
-
- // MOE expert weights
- auto wei_gate = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups, group_size}, {1});
- auto scale_gate = op::v0::Constant::create(element::f16, Shape{num_experts, inter_size, gate_up_groups}, {0.01f});
- auto zp_gate = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups}, {0});
- auto wei_up = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups, group_size}, {1});
- auto scale_up = op::v0::Constant::create(element::f16, Shape{num_experts, inter_size, gate_up_groups}, {0.01f});
- auto zp_up = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups}, {0});
- auto wei_down = op::v0::Constant::create(element::u4, Shape{num_experts, hidden_size, down_groups, group_size}, {1});
- auto scale_down = op::v0::Constant::create(element::f16, Shape{num_experts, hidden_size, down_groups}, {0.01f});
- auto zp_down = op::v0::Constant::create(element::u4, Shape{num_experts, hidden_size, down_groups}, {0});
-
- // Shared expert weights: same N/K layout, leading dim = num_shared.
- auto sh_wei_gate = op::v0::Constant::create(element::u4, Shape{num_shared, inter_size, gate_up_groups, group_size}, {2});
- auto sh_scale_gate = op::v0::Constant::create(element::f16, Shape{num_shared, inter_size, gate_up_groups}, {0.02f});
- auto sh_zp_gate = op::v0::Constant::create(element::u4, Shape{num_shared, inter_size, gate_up_groups}, {0});
- auto sh_wei_up = op::v0::Constant::create(element::u4, Shape{num_shared, inter_size, gate_up_groups, group_size}, {2});
- auto sh_scale_up = op::v0::Constant::create(element::f16, Shape{num_shared, inter_size, gate_up_groups}, {0.02f});
- auto sh_zp_up = op::v0::Constant::create(element::u4, Shape{num_shared, inter_size, gate_up_groups}, {0});
- auto sh_wei_down = op::v0::Constant::create(element::u4, Shape{num_shared, hidden_size, down_groups, group_size}, {2});
- auto sh_scale_down = op::v0::Constant::create(element::f16, Shape{num_shared, hidden_size, down_groups}, {0.02f});
- auto sh_zp_down = op::v0::Constant::create(element::u4, Shape{num_shared, hidden_size, down_groups}, {0});
- auto sh_gate_gate_wei = op::v0::Constant::create(element::f16, Shape{hidden_size, num_shared}, {0.5f});
-
- auto routing_bias = op::v0::Constant::create(element::f16, Shape{1, num_experts}, {0.1f});
- auto routing_eps = op::v0::Constant::create(element::f16, Shape{1, 1}, {1e-6f});
-
- ov::op::internal::MOECompressed::Config config;
- config.expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU;
- config.has_zp = true;
- config.hidden_size = hidden_size;
- config.inter_size = inter_size;
- config.num_expert = num_experts;
- config.num_shared_expert = num_shared;
- config.group_size = group_size;
- config.top_k = top_k;
- config.out_type = ov::element::f16;
- config.routing_type = ov::op::internal::MOECompressed::RoutingType::SIGMOID_BIAS;
- auto moe_3gemm_fused_compressed = std::make_shared<ov::intel_gpu::op::MOE3GemmFusedCompressed>(
- ov::OutputVector{hidden_states, routing_weights, wei_gate, scale_gate, zp_gate, wei_up, scale_up, zp_up,
- wei_down, scale_down, zp_down, routing_bias, routing_eps, sh_wei_gate, sh_scale_gate, sh_zp_gate,
- sh_wei_up, sh_scale_up, sh_zp_up, sh_wei_down, sh_scale_down, sh_zp_down, sh_gate_gate_wei},
- config);
-
- model_ref = std::make_shared<ov::Model>(moe_3gemm_fused_compressed, ov::ParameterVector{hidden_states});
- }
-}
-
-TEST_F(TransformationTestsF, FuseMOE3GemmCompressedTest1) {
- // ── MoE shape parameters (larger experts, smaller inter_size, larger top_k) ──
- constexpr size_t batch = 4;
- constexpr size_t seq_len = 8;
- constexpr size_t tokens = batch * seq_len;
- constexpr size_t hidden_size = 2048;
- constexpr size_t inter_size = 512;
- constexpr size_t num_experts = 512;
- constexpr size_t top_k = 10;
- constexpr size_t group_size = 128;
- constexpr size_t gate_up_groups = hidden_size / group_size; // gate/up grouped along K=hidden_size
- constexpr size_t down_groups = inter_size / group_size; // down grouped along K=inter_size
-
- {
- auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{batch, seq_len, hidden_size});
- auto flatten_shape = op::v0::Constant::create(element::i32, Shape{2}, {static_cast<int32_t>(tokens), static_cast<int32_t>(hidden_size)});
- auto hidden_states_reshape = std::make_shared<ov::op::v1::Reshape>(hidden_states, flatten_shape, false);
- auto routers = op::v0::Constant::create(element::f16, Shape{hidden_size, num_experts}, {0.2});
- // [tokens, num_experts]
- auto routing_weights = std::make_shared<ov::op::v0::MatMul>(hidden_states_reshape, routers);
-
- // Build post-GatherMatmul softmax routing (no ScatterElementsUpdate)
- auto [unsqueeze_moe, topk_indices] = build_softmax_routing_for_fuse_test(routing_weights, top_k);
-
- auto wei_gate = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups, group_size}, {1});
- auto scale_gate = op::v0::Constant::create(element::f16, Shape{num_experts, inter_size, gate_up_groups}, {0.01f});
- auto zp_gate = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups}, {0});
- auto wei_up = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups, group_size}, {1});
- auto scale_up = op::v0::Constant::create(element::f16, Shape{num_experts, inter_size, gate_up_groups}, {0.01f});
- auto zp_up = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups}, {0});
- auto wei_down = op::v0::Constant::create(element::u4, Shape{num_experts, hidden_size, down_groups, group_size}, {1});
- auto scale_down = op::v0::Constant::create(element::f16, Shape{num_experts, hidden_size, down_groups}, {0.01f});
- auto zp_down = op::v0::Constant::create(element::u4, Shape{num_experts, hidden_size, down_groups}, {0});
-
- ov::op::internal::MOECompressed::Config config;
- config.expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU;
- config.has_zp = true;
- config.hidden_size = hidden_size;
- config.inter_size = inter_size;
- config.num_expert = num_experts;
- config.group_size = group_size;
- config.top_k = top_k;
- config.out_type = ov::element::f16;
- auto moe_compressed = std::make_shared<ov::op::internal::MOECompressed>(ov::OutputVector{hidden_states_reshape,
- unsqueeze_moe,
- topk_indices,
- wei_gate,
- scale_gate,
- zp_gate,
- wei_up,
- scale_up,
- zp_up,
- wei_down,
- scale_down,
- zp_down},
- config);
- model = std::make_shared<ov::Model>(moe_compressed, ov::ParameterVector{hidden_states});
- manager.register_pass<FuseMOE3GemmCompressed>();
- }
- {
- auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{batch, seq_len, hidden_size});
- auto flatten_shape = op::v0::Constant::create(element::i32, Shape{2}, {static_cast<int32_t>(tokens), static_cast<int32_t>(hidden_size)});
- auto hidden_states_reshape = std::make_shared<ov::op::v1::Reshape>(hidden_states, flatten_shape, false);
- auto routers = op::v0::Constant::create(element::f16, Shape{hidden_size, num_experts}, {0.2});
- auto routing_weights = std::make_shared<ov::op::v0::MatMul>(hidden_states_reshape, routers);
-
- auto wei_gate = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups, group_size}, {1});
- auto scale_gate = op::v0::Constant::create(element::f16, Shape{num_experts, inter_size, gate_up_groups}, {0.01f});
- auto zp_gate = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups}, {0});
- auto wei_up = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups, group_size}, {1});
- auto scale_up = op::v0::Constant::create(element::f16, Shape{num_experts, inter_size, gate_up_groups}, {0.01f});
- auto zp_up = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups}, {0});
- auto wei_down = op::v0::Constant::create(element::u4, Shape{num_experts, hidden_size, down_groups, group_size}, {1});
- auto scale_down = op::v0::Constant::create(element::f16, Shape{num_experts, hidden_size, down_groups}, {0.01f});
- auto zp_down = op::v0::Constant::create(element::u4, Shape{num_experts, hidden_size, down_groups}, {0});
-
- ov::op::internal::MOECompressed::Config config;
- config.expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU;
- config.has_zp = true;
- config.hidden_size = hidden_size;
- config.inter_size = inter_size;
- config.num_expert = num_experts;
- config.group_size = group_size;
- config.top_k = top_k;
- config.out_type = ov::element::f16;
- auto moe_3gemm_fused_compressed = std::make_shared<ov::intel_gpu::op::MOE3GemmFusedCompressed>(
- ov::OutputVector{hidden_states_reshape, routing_weights, wei_gate, scale_gate, zp_gate, wei_up, scale_up, zp_up, wei_down, scale_down, zp_down},
- config);
-
- model_ref = std::make_shared<ov::Model>(moe_3gemm_fused_compressed, ov::ParameterVector{hidden_states});
- }
-}
-
-// Qwen3.5-35B-A3B pattern
-TEST_F(TransformationTestsF, FuseMOE3GemmCompressed_SoftmaxRouting_SliceAfterDivide) {
- // ── MoE shape parameters (shared between input model and reference model) ──
- constexpr size_t batch = 4;
- constexpr size_t seq_len = 8;
- constexpr size_t tokens = batch * seq_len;
- constexpr size_t hidden_size = 2048;
- constexpr size_t inter_size = 768;
- constexpr size_t num_experts = 128;
- constexpr size_t top_k = 8;
- constexpr size_t group_size = 128;
- constexpr size_t gate_up_groups = hidden_size / group_size; // weight is grouped along K=hidden_size
- constexpr size_t down_groups = inter_size / group_size; // weight is grouped along K=inter_size
- constexpr int64_t routing_axis = 1; // top-k axis on routing weights
-
- {
- // Hidden states: original 3D layout, flattened to 2D before the routing matmul.
- auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{batch, seq_len, hidden_size});
- auto flatten_shape = op::v0::Constant::create(element::i32, Shape{2}, {static_cast<int32_t>(tokens), static_cast<int32_t>(hidden_size)});
- auto hidden_states_reshape = std::make_shared<ov::op::v1::Reshape>(hidden_states, flatten_shape, false);
- auto routers = op::v0::Constant::create(element::f16, Shape{hidden_size, num_experts}, {0.2});
- auto routing_weights = std::make_shared<ov::op::v0::MatMul>(hidden_states_reshape, routers);
-
- // Softmax routing with an extra Slice inserted between Divide and Transpose
- // (mirrors the Qwen3.5 graph: Softmax → TopK → ReduceSum → Divide → Slice → Transpose → Unsqueeze).
- auto softmax = std::make_shared<ov::op::v8::Softmax>(routing_weights, routing_axis);
- auto k = op::v0::Constant::create(element::i32, Shape{}, {static_cast<int32_t>(top_k)});
- auto topk_node = std::make_shared<ov::op::v11::TopK>(softmax, k, routing_axis, ov::op::v11::TopK::Mode::MAX, ov::op::v11::TopK::SortType::SORT_VALUES);
- auto reduce_axis = op::v0::Constant::create(element::i64, Shape{1}, {routing_axis});
- auto reduce_sum = std::make_shared<ov::op::v1::ReduceSum>(topk_node->output(0), reduce_axis, true);
- auto norm = std::make_shared<ov::op::v1::Divide>(topk_node->output(0), reduce_sum);
-
- auto slice_start = op::v0::Constant::create(element::i64, Shape{1}, {0});
- auto topk_idx_convert = std::make_shared<ov::op::v0::Convert>(topk_node->output(1), element::i32);
- auto topk_idx_shape = std::make_shared<ov::op::v3::ShapeOf>(topk_idx_convert);
- auto gather_idx = op::v0::Constant::create(element::i64, Shape{1}, {routing_axis});
- auto gather_axis = op::v0::Constant::create(element::i64, Shape{}, {0});
- auto slice_stop = std::make_shared<ov::op::v8::Gather>(topk_idx_shape, gather_idx, gather_axis);
- auto slice_step = op::v0::Constant::create(element::i64, Shape{1}, {1});
- auto slice_axis = op::v0::Constant::create(element::i64, Shape{1}, {routing_axis});
- auto slice = std::make_shared<ov::op::v8::Slice>(norm, slice_start, slice_stop, slice_step, slice_axis);
-
- auto transpose_order = op::v0::Constant::create(element::i64, Shape{2}, {1, 0});
- auto transpose = std::make_shared<ov::op::v1::Transpose>(slice, transpose_order);
- auto unsqueeze_const = op::v0::Constant::create(element::i64, Shape{1}, {-1});
- auto unsqueeze_moe = std::make_shared<ov::op::v0::Unsqueeze>(transpose, unsqueeze_const);
-
- // Compressed weights: 4-D weight = {experts, N, num_groups, group_size};
- // 3-D scale/zp = {experts, N, num_groups}. The K axis is split into groups of
- // `group_size`, so num_groups * group_size = K (gate/up: K=hidden_size, down: K=inter_size).
- auto wei_gate = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups, group_size}, {1});
- auto scale_gate = op::v0::Constant::create(element::f16, Shape{num_experts, inter_size, gate_up_groups}, {0.01f});
- auto zp_gate = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups}, {0});
- auto wei_up = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups, group_size}, {1});
- auto scale_up = op::v0::Constant::create(element::f16, Shape{num_experts, inter_size, gate_up_groups}, {0.01f});
- auto zp_up = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups}, {0});
- auto wei_down = op::v0::Constant::create(element::u4, Shape{num_experts, hidden_size, down_groups, group_size}, {1});
- auto scale_down = op::v0::Constant::create(element::f16, Shape{num_experts, hidden_size, down_groups}, {0.01f});
- auto zp_down = op::v0::Constant::create(element::u4, Shape{num_experts, hidden_size, down_groups}, {0});
-
- ov::op::internal::MOECompressed::Config config;
- config.expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU;
- config.has_zp = true;
- config.hidden_size = hidden_size;
- config.inter_size = inter_size;
- config.num_expert = num_experts;
- config.group_size = group_size;
- config.top_k = top_k;
- config.out_type = ov::element::f16;
-
- // Reuse `topk_idx_convert` as MOECompressed's indices input — that mirrors the real
- // graph's `MOECompressed(..., Convert, ...)` and keeps the Convert with two consumers
- // (ShapeOf and MOECompressed), neither pattern-constrained on consumers count.
- auto moe_compressed = std::make_shared<ov::op::internal::MOECompressed>(ov::OutputVector{hidden_states_reshape,
- unsqueeze_moe,
- topk_idx_convert,
- wei_gate,
- scale_gate,
- zp_gate,
- wei_up,
- scale_up,
- zp_up,
- wei_down,
- scale_down,
- zp_down},
- config);
- model = std::make_shared<ov::Model>(moe_compressed, ov::ParameterVector{hidden_states});
- }
- manager.register_pass<FuseMOE3GemmCompressed>();
- {
- auto hidden_states_ref = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{batch, seq_len, hidden_size});
- auto flatten_shape_ref = op::v0::Constant::create(element::i32, Shape{2}, {static_cast<int32_t>(tokens), static_cast<int32_t>(hidden_size)});
- auto hidden_states_reshape_ref = std::make_shared<ov::op::v1::Reshape>(hidden_states_ref, flatten_shape_ref, false);
- auto routers_ref = op::v0::Constant::create(element::f16, Shape{hidden_size, num_experts}, {0.2});
- auto routing_weights_ref = std::make_shared<ov::op::v0::MatMul>(hidden_states_reshape_ref, routers_ref);
-
- auto wei_gate_ref = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups, group_size}, {1});
- auto scale_gate_ref = op::v0::Constant::create(element::f16, Shape{num_experts, inter_size, gate_up_groups}, {0.01f});
- auto zp_gate_ref = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups}, {0});
- auto wei_up_ref = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups, group_size}, {1});
- auto scale_up_ref = op::v0::Constant::create(element::f16, Shape{num_experts, inter_size, gate_up_groups}, {0.01f});
- auto zp_up_ref = op::v0::Constant::create(element::u4, Shape{num_experts, inter_size, gate_up_groups}, {0});
- auto wei_down_ref = op::v0::Constant::create(element::u4, Shape{num_experts, hidden_size, down_groups, group_size}, {1});
- auto scale_down_ref = op::v0::Constant::create(element::f16, Shape{num_experts, hidden_size, down_groups}, {0.01f});
- auto zp_down_ref = op::v0::Constant::create(element::u4, Shape{num_experts, hidden_size, down_groups}, {0});
-
- ov::op::internal::MOECompressed::Config config_ref;
- config_ref.expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU;
- config_ref.has_zp = true;
- config_ref.hidden_size = hidden_size;
- config_ref.inter_size = inter_size;
- config_ref.num_expert = num_experts;
- config_ref.group_size = group_size;
- config_ref.top_k = top_k;
- config_ref.out_type = ov::element::f16;
- config_ref.routing_type = ov::op::internal::MOECompressed::RoutingType::SOFTMAX;
-
- ov::OutputVector args{hidden_states_reshape_ref,
- routing_weights_ref,
- wei_gate_ref,
- scale_gate_ref,
- zp_gate_ref,
- wei_up_ref,
- scale_up_ref,
- zp_up_ref,
- wei_down_ref,
- scale_down_ref,
- zp_down_ref};
- auto fused = std::make_shared<ov::intel_gpu::op::MOE3GemmFusedCompressed>(args, config_ref);
- model_ref = std::make_shared<ov::Model>(fused, ov::ParameterVector{hidden_states_ref});
- }
-}
-
-} // namespace intel_gpu
-} // namespace test
-} // namespace ov
diff --git a/src/plugins/intel_gpu/tests/unit/transformations/fuse_moe_router_scale_test.cpp b/src/plugins/intel_gpu/tests/unit/transformations/fuse_moe_router_scale_test.cpp
new file mode 100644
index 00000000000..c7b90998543
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/unit/transformations/fuse_moe_router_scale_test.cpp
@@ -0,0 +1,147 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "plugin/transformations/fuse_moe_router_scale.hpp"
+
+#include <gtest/gtest.h>
+
+#include <limits>
+
+#include "common_test_utils/ov_test_utils.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/parameter.hpp"
+#include "ov_ops/moe_compressed.hpp"
+
+using namespace testing;
+using namespace ov::intel_gpu;
+
+namespace ov::test::intel_gpu {
+
+namespace {
+
+using MOECompressed = ov::op::internal::MOECompressed;
+
+// Returns {gate_w, gate_scale, gate_zp, up_w, up_scale, up_zp, down_w, down_scale, down_zp}
+ov::OutputVector gemm3_weights(size_t num_experts, size_t hidden_size, size_t inter_size, float down_scale_val = 1.0f) {
+ using C = ov::op::v0::Constant;
+ const size_t gate_w = num_experts * inter_size * hidden_size;
+ const size_t gate_s = num_experts * inter_size;
+ const size_t down_w = num_experts * hidden_size * inter_size;
+ const size_t down_s = num_experts * hidden_size;
+ return {
+ C::create(ov::element::u8, {num_experts, inter_size, hidden_size}, std::vector<uint8_t>(gate_w, 1)),
+ C::create(ov::element::f16, {num_experts, inter_size, 1}, std::vector<float>(gate_s, 1.0f)),
+ C::create(ov::element::u8, {num_experts, inter_size, 1}, std::vector<uint8_t>(gate_s, 0)),
+ C::create(ov::element::u8, {num_experts, inter_size, hidden_size}, std::vector<uint8_t>(gate_w, 1)),
+ C::create(ov::element::f16, {num_experts, inter_size, 1}, std::vector<float>(gate_s, 1.0f)),
+ C::create(ov::element::u8, {num_experts, inter_size, 1}, std::vector<uint8_t>(gate_s, 0)),
+ C::create(ov::element::u8, {num_experts, hidden_size, inter_size}, std::vector<uint8_t>(down_w, 1)),
+ C::create(ov::element::f16, {num_experts, hidden_size, 1}, std::vector<float>(down_s, down_scale_val)),
+ C::create(ov::element::u8, {num_experts, hidden_size, 1}, std::vector<uint8_t>(down_s, 0)),
+ };
+}
+
+MOECompressed::Config gemm3_config(size_t num_experts, size_t hidden_size, size_t inter_size, size_t top_k) {
+ MOECompressed::Config c;
+ c.expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU;
+ c.activation_type = ov::op::internal::MOE::Activation_type::SWIGLU;
+ c.hidden_size = hidden_size;
+ c.inter_size = inter_size;
+ c.num_expert = num_experts;
+ c.num_shared_expert = 0;
+ c.top_k = top_k;
+ c.group_size = std::numeric_limits<size_t>::max();
+ c.has_zp = true;
+ c.out_type = ov::element::f16;
+ return c;
+}
+
+} // namespace
+
+TEST_F(TransformationTestsF, FuseMoEPerExpertScale) {
+ const size_t num_experts = 4, hidden_size = 8, inter_size = 4, top_k = 2;
+ const std::vector<float> per_expert_scales = {1.0f, 2.0f, 1.0f, 0.5f};
+
+ {
+ auto hidden = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, hidden_size});
+ auto routing = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, top_k});
+ auto topk_idx = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1, top_k});
+
+ auto pes_const = ov::op::v0::Constant::create(ov::element::f16, {num_experts}, per_expert_scales);
+ auto axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});
+ auto gathered = std::make_shared<ov::op::v8::Gather>(pes_const, topk_idx, axis);
+ auto scaled = std::make_shared<ov::op::v1::Multiply>(routing, gathered);
+
+ auto ws = gemm3_weights(num_experts, hidden_size, inter_size);
+ auto moe = std::make_shared<MOECompressed>(
+ ov::OutputVector{hidden, scaled, topk_idx, ws[0], ws[1], ws[2], ws[3], ws[4], ws[5], ws[6], ws[7], ws[8]},
+ gemm3_config(num_experts, hidden_size, inter_size, top_k));
+
+ model = std::make_shared<ov::Model>(ov::OutputVector{moe}, ov::ParameterVector{hidden, routing, topk_idx});
+ manager.register_pass<FuseMoERouterScale>();
+ comparator.enable(FunctionsComparator::CmpValues::CONST_VALUES);
+ }
+
+ {
+ auto hidden = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, hidden_size});
+ auto routing = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, top_k});
+ auto topk_idx = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1, top_k});
+
+ std::vector<float> folded_down_scale(num_experts * hidden_size);
+ for (size_t n = 0; n < num_experts; ++n)
+ for (size_t h = 0; h < hidden_size; ++h)
+ folded_down_scale[n * hidden_size + h] = per_expert_scales[n];
+
+ auto ws = gemm3_weights(num_experts, hidden_size, inter_size);
+ auto down_scale = ov::op::v0::Constant::create(ov::element::f16, {num_experts, hidden_size, 1}, folded_down_scale);
+ auto moe = std::make_shared<MOECompressed>(
+ ov::OutputVector{hidden, routing, topk_idx, ws[0], ws[1], ws[2], ws[3], ws[4], ws[5], ws[6], down_scale, ws[8]},
+ gemm3_config(num_experts, hidden_size, inter_size, top_k));
+
+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{moe}, ov::ParameterVector{hidden, routing, topk_idx});
+ }
+}
+
+TEST_F(TransformationTestsF, FuseMoEScalarScale) {
+ const size_t num_experts = 4, hidden_size = 8, inter_size = 4, top_k = 2;
+ const float scale_val = 2.0f;
+
+ {
+ auto hidden = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, hidden_size});
+ auto routing = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, top_k});
+ auto topk_idx = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1, top_k});
+
+ auto scalar = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{1}, {scale_val});
+ auto scaled = std::make_shared<ov::op::v1::Multiply>(routing, scalar);
+
+ auto ws = gemm3_weights(num_experts, hidden_size, inter_size);
+ auto moe = std::make_shared<MOECompressed>(
+ ov::OutputVector{hidden, scaled, topk_idx, ws[0], ws[1], ws[2], ws[3], ws[4], ws[5], ws[6], ws[7], ws[8]},
+ gemm3_config(num_experts, hidden_size, inter_size, top_k));
+
+ model = std::make_shared<ov::Model>(ov::OutputVector{moe}, ov::ParameterVector{hidden, routing, topk_idx});
+ manager.register_pass<FuseMoERouterScale>();
+ comparator.enable(FunctionsComparator::CmpValues::CONST_VALUES);
+ }
+
+ {
+ auto hidden = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, hidden_size});
+ auto routing = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, top_k});
+ auto topk_idx = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1, top_k});
+
+ auto ws = gemm3_weights(num_experts, hidden_size, inter_size);
+ auto down_scale = ov::op::v0::Constant::create(ov::element::f16,
+ {num_experts, hidden_size, 1},
+ std::vector<float>(num_experts * hidden_size, scale_val));
+ auto moe = std::make_shared<MOECompressed>(
+ ov::OutputVector{hidden, routing, topk_idx, ws[0], ws[1], ws[2], ws[3], ws[4], ws[5], ws[6], down_scale, ws[8]},
+ gemm3_config(num_experts, hidden_size, inter_size, top_k));
+
+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{moe}, ov::ParameterVector{hidden, routing, topk_idx});
+ }
+}
+
+} // namespace ov::test::intel_gpu
diff --git a/src/plugins/intel_gpu/tests/unit/transformations/fuse_moe_router_test.cpp b/src/plugins/intel_gpu/tests/unit/transformations/fuse_moe_router_test.cpp
new file mode 100644
index 00000000000..492f7aa03c8
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/unit/transformations/fuse_moe_router_test.cpp
@@ -0,0 +1,153 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "plugin/transformations/fuse_moe_router.hpp"
+
+#include <gtest/gtest.h>
+
+#include "common_test_utils/node_builders/moe_builders.hpp"
+#include "common_test_utils/ov_test_utils.hpp"
+#include "intel_gpu/op/moe_router_fused.hpp"
+#include "openvino/op/add.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/divide.hpp"
+#include "openvino/op/gather_elements.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/reduce_sum.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/sigmoid.hpp"
+#include "openvino/op/softmax.hpp"
+#include "openvino/op/topk.hpp"
+#include "openvino/op/unsqueeze.hpp"
+
+using namespace testing;
+using namespace ov::intel_gpu;
+
+namespace ov {
+namespace test {
+namespace intel_gpu {
+
+using namespace ov::test;
+
+using TestParams = std::tuple<MoERoutingType, bool, size_t, size_t>; // routing_type, with_convert_on_indices, num_expert, top_k
+
+class FuseMoERouterTest : public TransformationTestsF, public ::testing::WithParamInterface<TestParams> {
+public:
+ static std::string get_test_case_name(const ::testing::TestParamInfo<TestParams>& info) {
+ const auto routing_type = std::get<0>(info.param);
+ const bool with_convert = std::get<1>(info.param);
+ const size_t num_expert = std::get<2>(info.param);
+ const size_t top_k = std::get<3>(info.param);
+ std::string name;
+ switch (routing_type) {
+ case MoERoutingType::SOFTMAX:
+ name = "Softmax";
+ break;
+ case MoERoutingType::SIGMOID_BIAS:
+ name = "SigmoidBias";
+ break;
+ default:
+ OPENVINO_THROW("Unsupported routing type");
+ }
+ name += with_convert ? "_WithConvert" : "_NoConvert";
+ name += "_E" + std::to_string(num_expert) + "_K" + std::to_string(top_k);
+ return name;
+ }
+};
+
+static std::pair<ov::Output<ov::Node>, ov::Output<ov::Node>> build_softmax_routing_for_fuse_test(const ov::Output<ov::Node>& routing_weights,
+ size_t topk,
+ bool with_convert_on_indices) {
+ auto softmax = std::make_shared<ov::op::v8::Softmax>(routing_weights, 1);
+ const auto index_type = with_convert_on_indices ? ov::element::i64 : ov::element::i32;
+ auto k = op::v0::Constant::create(element::i32, Shape{}, {static_cast<int32_t>(topk)});
+ auto topk_node = std::make_shared<ov::op::v11::TopK>(softmax, k, 1, ov::op::v11::TopK::Mode::MAX, ov::op::v11::TopK::SortType::SORT_VALUES, index_type);
+ auto reduce_axis = op::v0::Constant::create(element::i64, Shape{1}, {1});
+ auto reduce_sum = std::make_shared<ov::op::v1::ReduceSum>(topk_node->output(0), reduce_axis, true);
+ ov::Output<ov::Node> norm = std::make_shared<ov::op::v1::Divide>(topk_node->output(0), reduce_sum);
+ ov::Output<ov::Node> indices = topk_node->output(1);
+ if (with_convert_on_indices)
+ indices = std::make_shared<ov::op::v0::Convert>(indices, ov::element::i32);
+ return {norm, indices};
+}
+
+static std::pair<ov::Output<ov::Node>, ov::Output<ov::Node>> build_sigmoid_routing_for_fuse_test(const ov::Output<ov::Node>& routing_weights,
+ ov::element::Type data_precision,
+ size_t number_of_experts,
+ size_t topk,
+ bool with_convert_on_indices) {
+ auto sigmoid = std::make_shared<ov::op::v0::Sigmoid>(routing_weights);
+ auto bias = op::v0::Constant::create(data_precision, Shape{1, number_of_experts}, {0.1f});
+ auto sig_add = std::make_shared<ov::op::v1::Add>(sigmoid, bias);
+ const auto index_type = with_convert_on_indices ? ov::element::i64 : ov::element::i32;
+ auto k = op::v0::Constant::create(element::i64, Shape{}, {static_cast<int64_t>(topk)});
+ auto topk_node = std::make_shared<ov::op::v11::TopK>(sig_add, k, -1, ov::op::v11::TopK::Mode::MAX, ov::op::v11::TopK::SortType::SORT_VALUES, index_type);
+ ov::Output<ov::Node> indices = topk_node->output(1);
+ if (with_convert_on_indices)
+ indices = std::make_shared<ov::op::v0::Convert>(indices, ov::element::i32);
+ auto gather_el = std::make_shared<ov::op::v6::GatherElements>(sigmoid, indices, 1);
+ auto reduce_axis = op::v0::Constant::create(element::i64, Shape{1}, {1});
+ auto reduce_sum = std::make_shared<ov::op::v1::ReduceSum>(gather_el, reduce_axis, true);
+ auto eps = op::v0::Constant::create(data_precision, Shape{1, 1}, {1e-6f});
+ auto add_eps = std::make_shared<ov::op::v1::Add>(reduce_sum, eps);
+ ov::Output<ov::Node> norm = std::make_shared<ov::op::v1::Divide>(gather_el, add_eps);
+ return {norm, indices};
+}
+
+TEST_P(FuseMoERouterTest, CompareFunctions) {
+ const auto [routing_type, with_convert_on_indices, num_expert, top_k] = GetParam();
+ {
+ auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{4, 8, 2048});
+ auto flatten_shape = op::v0::Constant::create(element::i32, Shape{2}, {32, 2048});
+ auto hidden_states_reshape = std::make_shared<ov::op::v1::Reshape>(hidden_states, flatten_shape, false);
+ auto routers = op::v0::Constant::create(element::f16, Shape{2048, num_expert}, {0.2});
+ auto routing_weights = std::make_shared<ov::op::v0::MatMul>(hidden_states_reshape, routers);
+
+ const auto [routing_out, topk_indices] =
+ routing_type == MoERoutingType::SOFTMAX
+ ? build_softmax_routing_for_fuse_test(routing_weights, top_k, with_convert_on_indices)
+ : build_sigmoid_routing_for_fuse_test(routing_weights, element::f16, num_expert, top_k, with_convert_on_indices);
+
+ // Wrap outputs to avoid feeding Result nodes directly (required by replace_output_update_name)
+ auto weights_out = std::make_shared<ov::op::v0::Unsqueeze>(routing_out, ov::op::v0::Constant::create(element::i32, Shape{1}, {0}));
+ auto indices_out = std::make_shared<ov::op::v0::Unsqueeze>(topk_indices, ov::op::v0::Constant::create(element::i32, Shape{1}, {0}));
+ model = std::make_shared<ov::Model>(ov::OutputVector{weights_out, indices_out}, ov::ParameterVector{hidden_states});
+ }
+ manager.register_pass<FuseMoERouter>();
+ {
+ auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{4, 8, 2048});
+ auto flatten_shape = op::v0::Constant::create(element::i32, Shape{2}, {32, 2048});
+ auto hidden_states_reshape = std::make_shared<ov::op::v1::Reshape>(hidden_states, flatten_shape, false);
+ auto routers = op::v0::Constant::create(element::f16, Shape{2048, num_expert}, {0.2});
+ auto routing_weights = std::make_shared<ov::op::v0::MatMul>(hidden_states_reshape, routers);
+
+ ov::intel_gpu::op::MoERouterFused::Config router_config;
+ router_config.num_expert = num_expert;
+ router_config.top_k = top_k;
+ ov::OutputVector router_args{routing_weights};
+ if (routing_type == MoERoutingType::SIGMOID_BIAS) {
+ router_config.routing_type = ov::intel_gpu::op::MoERouterFused::RoutingType::SIGMOID_BIAS;
+ router_args.push_back(op::v0::Constant::create(element::f16, Shape{1, num_expert}, {0.1f}));
+ router_args.push_back(op::v0::Constant::create(element::f16, Shape{1, 1}, {1e-6f}));
+ }
+ auto router_node = std::make_shared<ov::intel_gpu::op::MoERouterFused>(router_args, router_config);
+
+ auto weights_out = std::make_shared<ov::op::v0::Unsqueeze>(router_node->output(0), ov::op::v0::Constant::create(element::i32, Shape{1}, {0}));
+ auto indices_out = std::make_shared<ov::op::v0::Unsqueeze>(router_node->output(1), ov::op::v0::Constant::create(element::i32, Shape{1}, {0}));
+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{weights_out, indices_out}, ov::ParameterVector{hidden_states});
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(smoke,
+ FuseMoERouterTest,
+ ::testing::Combine(::testing::Values(MoERoutingType::SOFTMAX, MoERoutingType::SIGMOID_BIAS),
+ ::testing::Values(true, false),
+ ::testing::Values(128, 512),
+ ::testing::Values(8, 10)),
+ FuseMoERouterTest::get_test_case_name);
+
+} // namespace intel_gpu
+} // namespace test
+} // namespace ov
diff --git a/src/plugins/intel_gpu/tests/unit/transformations/fuse_moe_shared_expert_test.cpp b/src/plugins/intel_gpu/tests/unit/transformations/fuse_moe_shared_expert_test.cpp
index 40a7a3c5735..c6b3676771a 100644
--- a/src/plugins/intel_gpu/tests/unit/transformations/fuse_moe_shared_expert_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/transformations/fuse_moe_shared_expert_test.cpp
@@ -73,7 +73,7 @@ TEST_F(TransformationTestsF, FuseMOESharedExpertWithSigmoidGating) {
{
// tokens:32, hidden_size:2048, inter_size:768, experts:128, topk:8
auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{32, 2048});
- auto routing_weights = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{128, 1, 32, 1});
+ auto routing_weights = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{32, 8});
auto routing_idx = std::make_shared<ov::op::v0::Parameter>(element::i32, Shape{32, 8});
// MOE expert decompression chains
@@ -126,7 +126,7 @@ TEST_F(TransformationTestsF, FuseMOESharedExpertWithSigmoidGating) {
{
// Expected: MOE with 10 inputs (shared expert weights absorbed)
auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{32, 2048});
- auto routing_weights = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{128, 1, 32, 1});
+ auto routing_weights = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{32, 8});
auto routing_idx = std::make_shared<ov::op::v0::Parameter>(element::i32, Shape{32, 8});
auto hidden_states_f32 = std::make_shared<ov::op::v0::Convert>(hidden_states, element::f32);
@@ -165,7 +165,7 @@ TEST_F(TransformationTestsF, FuseMOESharedExpertWithoutGating) {
{
// Same as above but without sigmoid gating (shared_down output goes through Add directly)
auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{32, 2048});
- auto routing_weights = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{128, 1, 32, 1});
+ auto routing_weights = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{32, 8});
auto routing_idx = std::make_shared<ov::op::v0::Parameter>(element::i32, Shape{32, 8});
auto gate_decompressed = create_decompression_chain(
@@ -206,7 +206,7 @@ TEST_F(TransformationTestsF, FuseMOESharedExpertWithoutGating) {
}
{
auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{32, 2048});
- auto routing_weights = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{128, 1, 32, 1});
+ auto routing_weights = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{32, 8});
auto routing_idx = std::make_shared<ov::op::v0::Parameter>(element::i32, Shape{32, 8});
auto hidden_states_f32 = std::make_shared<ov::op::v0::Convert>(hidden_states, element::f32);
@@ -245,7 +245,7 @@ TEST_F(TransformationTestsF, FuseMOESharedExpertSymmetricWithGating) {
disable_rt_info_check();
{
auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{32, 2048});
- auto routing_weights = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{128, 1, 32, 1});
+ auto routing_weights = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{32, 8});
auto routing_idx = std::make_shared<ov::op::v0::Parameter>(element::i32, Shape{32, 8});
// MOE expert sym-quant decompression chains (no Subtract)
@@ -295,7 +295,7 @@ TEST_F(TransformationTestsF, FuseMOESharedExpertSymmetricWithGating) {
}
{
auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{32, 2048});
- auto routing_weights = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{128, 1, 32, 1});
+ auto routing_weights = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{32, 8});
auto routing_idx = std::make_shared<ov::op::v0::Parameter>(element::i32, Shape{32, 8});
auto hidden_states_f32 = std::make_shared<ov::op::v0::Convert>(hidden_states, element::f32);
@@ -334,7 +334,7 @@ TEST_F(TransformationTestsF, FuseMOECompressedSharedExpertWithSigmoidGating) {
{
// tokens:32, hidden_size:2048, inter_size:768, experts:128, topk:8
auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{32, 2048});
- auto routing_weights = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{128, 1, 32, 1});
+ auto routing_weights = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{32, 8});
auto routing_idx = std::make_shared<ov::op::v0::Parameter>(element::i32, Shape{32, 8});
// MOE compressed weights (no decompression chains)
@@ -396,7 +396,7 @@ TEST_F(TransformationTestsF, FuseMOECompressedSharedExpertWithSigmoidGating) {
{
// Expected: MOECompressed with shared expert weights absorbed
auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{32, 2048});
- auto routing_weights = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{128, 1, 32, 1});
+ auto routing_weights = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{32, 8});
auto routing_idx = std::make_shared<ov::op::v0::Parameter>(element::i32, Shape{32, 8});
auto wei_gate = op::v0::Constant::create(element::u4, Shape{128, 768, 16, 128}, {1});