Skip to content

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

[GPU] Support MoE pattern from gemma4 in GPU composite operation (#35744)

Vladislav Golubev9f012f8984e3
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 f0fd136f2c5..6a7cdf92324 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
@@ -14,6 +14,7 @@
#include "openvino/op/clamp.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/convert.hpp"
+#include "openvino/op/gelu.hpp"
#include "openvino/op/minimum.hpp"
#include "openvino/op/moe.hpp"
#include "openvino/op/multiply.hpp"
@@ -40,6 +41,7 @@ using ov::op::internal::MOECompressed;
namespace v0 = ov::op::v0;
namespace v1 = ov::op::v1;
namespace v4 = ov::op::v4;
+namespace v7 = ov::op::v7;
namespace v8 = ov::op::v8;
// Logical K from a weight shape: rank-3 [E, ofm, K] or rank-4 [E, ofm, G, GS].
@@ -51,8 +53,9 @@ static size_t weight_logical_K(const ov::Shape& shape) {
Convert3GatherMatmulMoeBlockToMoeOp::Convert3GatherMatmulMoeBlockToMoeOp(bool has_batch_dim) {
MATCHER_SCOPE(Convert3GatherMatmulMoeBlockToMoeOp);
- auto experts_reshape_m = pattern::any_input();
- auto unsqueeze_m = pattern::wrap_type<v0::Unsqueeze>({experts_reshape_m, pattern::any_input()});
+ auto hidden_states_m = pattern::any_input();
+ auto hidden_state_reshape = pattern::optional<v1::Reshape>({hidden_states_m, pattern::any_input()});
+ auto unsqueeze_m = pattern::wrap_type<v0::Unsqueeze>({hidden_state_reshape, pattern::any_input()});
auto gate_w_m = pattern::any_input();
auto topk_indices_m = pattern::any_input();
@@ -67,7 +70,8 @@ Convert3GatherMatmulMoeBlockToMoeOp::Convert3GatherMatmulMoeBlockToMoeOp(bool ha
// Or-pattern
auto bgm_gate_m = std::make_shared<pattern::op::Or>(OutputVector{bgm_gate_4_m, bgm_gate_6_m});
- auto swish_m = pattern::wrap_type<v4::Swish>({bgm_gate_m});
+ // Gate activation: Swish (SwiGLU) or Gelu (GeGLU) with TANH or ERF approximation.
+ auto swish_m = pattern::wrap_type<v4::Swish, v7::Gelu>({bgm_gate_m});
auto up_w_m = pattern::any_input();
auto bgm_up_4_m = pattern::wrap_type<GatherMatmul>({unsqueeze_m, up_w_m, topk_indices_m, pattern::any_input()});
@@ -103,8 +107,7 @@ Convert3GatherMatmulMoeBlockToMoeOp::Convert3GatherMatmulMoeBlockToMoeOp(bool ha
return false;
}
- auto experts_reshape_node = pm.at(experts_reshape_m).get_node_shared_ptr();
- auto hidden_states = experts_reshape_node->input_value(0);
+ auto hidden_states = pm.at(hidden_states_m);
auto routing = pm.at(routing_unsqueeze_m).get_node_shared_ptr();
auto topk_indices = pm.at(topk_indices_m);
@@ -112,17 +115,27 @@ Convert3GatherMatmulMoeBlockToMoeOp::Convert3GatherMatmulMoeBlockToMoeOp(bool ha
auto up_w = pm.at(up_w_m);
auto down_w = pm.at(down_w_m);
- // Extract expert_beta from Swish
+ // Extract expert_beta and detect activation type from the matched gate activation node.
float expert_beta = 1.0f;
- auto swish_node = pm.at(swish_m).get_node_shared_ptr();
-
- auto swish_op = ov::as_type_ptr<v4::Swish>(swish_node);
- OPENVINO_ASSERT(swish_op, "Unexpected node type matched for Swish: ", *swish_node);
-
- if (swish_op->get_input_size() > 1) {
- if (auto beta_const = ov::as_type_ptr<v0::Constant>(swish_op->get_input_node_shared_ptr(1))) {
- expert_beta = beta_const->cast_vector<float>()[0];
+ ov::op::internal::MOE::Activation_type activation_type = ov::op::internal::MOE::Activation_type::SWIGLU;
+ auto activation_node = pm.at(swish_m).get_node_shared_ptr();
+
+ if (auto swish_op = ov::as_type_ptr<v4::Swish>(activation_node)) {
+ if (swish_op->get_input_size() > 1) {
+ if (auto beta_const = ov::as_type_ptr<v0::Constant>(swish_op->get_input_node_shared_ptr(1))) {
+ expert_beta = beta_const->cast_vector<float>()[0];
+ }
}
+ } else if (auto gelu_op = ov::as_type_ptr<v7::Gelu>(activation_node)) {
+ if (gelu_op->get_approximation_mode() == ov::op::GeluApproximationMode::TANH) {
+ activation_type = ov::op::internal::MOE::Activation_type::GEGLU_TANH;
+ } else if (gelu_op->get_approximation_mode() == ov::op::GeluApproximationMode::ERF) {
+ activation_type = ov::op::internal::MOE::Activation_type::GEGLU_ERF;
+ } else {
+ return false;
+ }
+ } else {
+ OPENVINO_THROW("Unexpected node type matched for gate activation: ", activation_node);
}
std::shared_ptr<ov::Node> moe_node;
@@ -175,7 +188,7 @@ Convert3GatherMatmulMoeBlockToMoeOp::Convert3GatherMatmulMoeBlockToMoeOp(bool ha
const bool has_zp = pm.at(gate_zp_m).get_element_type() != ov::element::dynamic;
MOECompressed::Config compressed_config{
- {ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU, 0.0f, expert_beta},
+ {ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU, 0.0f, expert_beta, 0, activation_type},
gate_K,
weight_shape[1],
weight_shape[0],
@@ -200,7 +213,11 @@ Convert3GatherMatmulMoeBlockToMoeOp::Convert3GatherMatmulMoeBlockToMoeOp(bool ha
moe_node = moe_compressed;
}
} else {
- ov::op::internal::MOE::Config config{ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU, 0.0f, expert_beta};
+ ov::op::internal::MOE::Config config{ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU,
+ 0.0f,
+ expert_beta,
+ 0,
+ activation_type};
// Plain MOE with 6 inputs
ov::OutputVector moe_inputs = {hidden_states, routing, topk_indices, gate_w, up_w, down_w};
@@ -222,8 +239,9 @@ Convert3GatherMatmulMoeBlockToMoeOp::Convert3GatherMatmulMoeBlockToMoeOp(bool ha
Convert2GatherMatmulMoeBlockToMoeOp::Convert2GatherMatmulMoeBlockToMoeOp(bool has_batch_dim) {
MATCHER_SCOPE(Convert2GatherMatmulMoeBlockToMoeOp);
- auto experts_reshape_m = pattern::any_input();
- auto unsqueeze_m = pattern::wrap_type<v0::Unsqueeze>({experts_reshape_m, pattern::any_input()});
+ auto hidden_states_m = pattern::any_input();
+ auto hidden_state_reshape = pattern::optional<v1::Reshape>({hidden_states_m, pattern::any_input()});
+ auto unsqueeze_m = pattern::wrap_type<v0::Unsqueeze>({hidden_state_reshape, pattern::any_input()});
auto gate_up_w_m = pattern::any_input();
auto topk_indices_m = pattern::any_input();
@@ -282,8 +300,7 @@ Convert2GatherMatmulMoeBlockToMoeOp::Convert2GatherMatmulMoeBlockToMoeOp(bool ha
return false;
}
- auto experts_reshape_node = pm.at(experts_reshape_m).get_node_shared_ptr();
- auto hidden_states = experts_reshape_node->input_value(0);
+ auto hidden_states = pm.at(hidden_states_m);
// Bypass the [1,0] Transpose: moe_scatter_reduction expects tokens-major routing.
// Order is enforced by the pattern (value_matches("1, 0")).
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 430c9041fb1..7d63eb796cc 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
@@ -10,6 +10,7 @@
#include <openvino/op/clamp.hpp>
#include <openvino/op/concat.hpp>
#include <openvino/op/constant.hpp>
+#include <openvino/op/gelu.hpp>
#include <openvino/op/matmul.hpp>
#include <openvino/op/minimum.hpp>
#include <openvino/op/moe.hpp>
@@ -278,7 +279,8 @@ inline std::shared_ptr<ov::Model> build_3gemm_moe_pattern_model() {
// Post-BGM model builders (3 BGMs + compact routing + ReduceSum + Reshape)
// ============================================================================
-inline std::shared_ptr<ov::Model> build_3gemm_bgm_model() {
+inline std::shared_ptr<ov::Model> build_3gemm_bgm_model(
+ ov::op::internal::MOE::Activation_type activation_type = ov::op::internal::MOE::Activation_type::SWIGLU) {
using namespace ov;
const size_t batch = 2;
@@ -325,9 +327,16 @@ inline std::shared_ptr<ov::Model> build_3gemm_bgm_model() {
// 3 BGMs
auto bgm_gate = std::make_shared<GatherMatmul>(unsqueeze, gate_w, topk_indices);
- auto swish = std::make_shared<op::v4::Swish>(bgm_gate);
+ std::shared_ptr<ov::Node> gate_act;
+ if (activation_type == ov::op::internal::MOE::Activation_type::GEGLU_TANH) {
+ gate_act = std::make_shared<op::v7::Gelu>(bgm_gate, ov::op::GeluApproximationMode::TANH);
+ } else if (activation_type == ov::op::internal::MOE::Activation_type::GEGLU_ERF) {
+ gate_act = std::make_shared<op::v7::Gelu>(bgm_gate, ov::op::GeluApproximationMode::ERF);
+ } else {
+ gate_act = std::make_shared<op::v4::Swish>(bgm_gate);
+ }
auto bgm_up = std::make_shared<GatherMatmul>(unsqueeze, up_w, topk_indices);
- auto swiglu = std::make_shared<op::v1::Multiply>(swish, bgm_up);
+ auto swiglu = std::make_shared<op::v1::Multiply>(gate_act, bgm_up);
auto bgm_down = std::make_shared<GatherMatmul>(swiglu, down_w, topk_indices);
// Compact routing: chosen_experts → Transpose({1,0}) → Unsqueeze(-1)
@@ -355,7 +364,8 @@ inline std::shared_ptr<ov::Model> build_3gemm_bgm_model() {
return std::make_shared<ov::Model>(ov::OutputVector{end_reshape}, ov::ParameterVector{input});
}
-inline std::shared_ptr<ov::Model> build_3gemm_bgm_to_moe_reference_model() {
+inline std::shared_ptr<ov::Model> build_3gemm_bgm_to_moe_reference_model(
+ ov::op::internal::MOE::Activation_type activation_type = ov::op::internal::MOE::Activation_type::SWIGLU) {
using namespace ov;
const size_t batch = 2;
@@ -406,6 +416,7 @@ inline std::shared_ptr<ov::Model> build_3gemm_bgm_to_moe_reference_model() {
ov::OutputVector moe_inputs = {input, router_unsqueeze, topk_indices, gate_w, up_w, down_w};
ov::op::internal::MOE::Config config;
config.expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU;
+ config.activation_type = activation_type;
auto moe = std::make_shared<ov::op::internal::MOE>(moe_inputs, config);
return std::make_shared<ov::Model>(ov::OutputVector{moe}, ov::ParameterVector{input});
@@ -582,6 +593,163 @@ inline std::shared_ptr<ov::Model> build_2gemm_bgm_to_moe_reference_model() {
return std::make_shared<ov::Model>(ov::OutputVector{moe}, ov::ParameterVector{input});
}
+// ============================================================================
+// Post-BGM model builders (3 BGMs + compact routing) — Multiply instead of Reshape
+// before Unsqueeze (gemma4 pattern: layernorm Multiply feeds expert path directly)
+// ============================================================================
+
+inline std::shared_ptr<ov::Model> build_3gemm_bgm_model_multiply_input(
+ ov::op::internal::MOE::Activation_type activation_type = ov::op::internal::MOE::Activation_type::SWIGLU) {
+ using namespace ov;
+
+ const size_t batch = 2;
+ const Dimension in_dim = Dimension::dynamic();
+ const size_t hidden_size = 2048;
+ const size_t intermediate_size = 4096;
+ const size_t number_of_experts = 3;
+ const size_t topk = 2;
+
+ auto input = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{batch, in_dim, hidden_size});
+
+ // Simulate layernorm output: Multiply(input, scale) — no Reshape
+ auto norm_scale = op::v0::Constant::create(element::f32, Shape{1, 1, hidden_size}, {1.0f});
+ auto layernorm_mul = std::make_shared<op::v1::Multiply>(input, norm_scale);
+
+ // Reshape to [batch*seq, hidden] for router path
+ auto experts_reshape = std::make_shared<op::v1::Reshape>(
+ layernorm_mul,
+ op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{-1, static_cast<int64_t>(hidden_size)}),
+ false);
+
+ // Unsqueeze feeds from Multiply (via Reshape) — but the pattern's optional<Reshape>
+ // means hidden_states_m captures the Multiply output (layernorm_mul).
+ auto unsqueeze =
+ std::make_shared<op::v0::Unsqueeze>(experts_reshape, op::v0::Constant::create(element::i32, Shape{}, {0}));
+
+ // Router subgraph
+ auto router_matmul = std::make_shared<op::v0::MatMul>(
+ experts_reshape,
+ op::v0::Constant::create(element::f32, Shape{number_of_experts, hidden_size}, {1.0f}),
+ false,
+ true);
+ auto router_topk = std::make_shared<op::v11::TopK>(router_matmul,
+ op::v0::Constant::create(element::i64, Shape{}, {topk}),
+ -1,
+ op::v11::TopK::Mode::MAX,
+ op::v11::TopK::SortType::SORT_VALUES,
+ element::i64);
+ auto topk_indices = router_topk->output(1);
+ auto chosen_experts = router_topk->output(0);
+
+ // Weights
+ auto gate_w =
+ op::v0::Constant::create(element::f32, Shape{number_of_experts, intermediate_size, hidden_size}, {1.0f});
+ auto up_w =
+ op::v0::Constant::create(element::f32, Shape{number_of_experts, intermediate_size, hidden_size}, {1.0f});
+ auto down_w =
+ op::v0::Constant::create(element::f32, Shape{number_of_experts, hidden_size, intermediate_size}, {1.0f});
+
+ // 3 BGMs
+ auto bgm_gate = std::make_shared<GatherMatmul>(unsqueeze, gate_w, topk_indices);
+ std::shared_ptr<ov::Node> gate_act;
+ if (activation_type == ov::op::internal::MOE::Activation_type::GEGLU_TANH) {
+ gate_act = std::make_shared<op::v7::Gelu>(bgm_gate, ov::op::GeluApproximationMode::TANH);
+ } else if (activation_type == ov::op::internal::MOE::Activation_type::GEGLU_ERF) {
+ gate_act = std::make_shared<op::v7::Gelu>(bgm_gate, ov::op::GeluApproximationMode::ERF);
+ } else {
+ gate_act = std::make_shared<op::v4::Swish>(bgm_gate);
+ }
+ auto bgm_up = std::make_shared<GatherMatmul>(unsqueeze, up_w, topk_indices);
+ auto swiglu = std::make_shared<op::v1::Multiply>(gate_act, bgm_up);
+ auto bgm_down = std::make_shared<GatherMatmul>(swiglu, down_w, topk_indices);
+
+ // 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}));
+
+ // Final: Multiply → ReduceSum → Reshape
+ auto final_mul = std::make_shared<op::v1::Multiply>(bgm_down, router_unsqueeze);
+ auto reduce_sum =
+ std::make_shared<op::v1::ReduceSum>(final_mul,
+ op::v0::Constant::create(element::i64, Shape{1}, std::vector<int64_t>{0}),
+ false);
+
+ auto end_reshape = std::make_shared<op::v1::Reshape>(
+ reduce_sum,
+ op::v0::Constant::create(
+ element::i64,
+ Shape{3},
+ std::vector<int64_t>{static_cast<int64_t>(batch), -1, static_cast<int64_t>(hidden_size)}),
+ true);
+
+ return std::make_shared<ov::Model>(ov::OutputVector{end_reshape}, ov::ParameterVector{input});
+}
+
+inline std::shared_ptr<ov::Model> build_3gemm_bgm_to_moe_reference_model_multiply_input(
+ ov::op::internal::MOE::Activation_type activation_type = ov::op::internal::MOE::Activation_type::SWIGLU) {
+ using namespace ov;
+
+ const size_t batch = 2;
+ const Dimension in_dim = Dimension::dynamic();
+ const size_t hidden_size = 2048;
+ const size_t intermediate_size = 4096;
+ const size_t number_of_experts = 3;
+ const size_t topk = 2;
+
+ auto input = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{batch, in_dim, hidden_size});
+
+ // Layernorm Multiply — its OUTPUT is the correct hidden_states for the MOE op
+ auto norm_scale = op::v0::Constant::create(element::f32, Shape{1, 1, hidden_size}, {1.0f});
+ auto layernorm_mul = std::make_shared<op::v1::Multiply>(input, norm_scale);
+
+ // Router subgraph (not fused, remains in the graph)
+ auto experts_reshape = std::make_shared<op::v1::Reshape>(
+ layernorm_mul,
+ op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{-1, static_cast<int64_t>(hidden_size)}),
+ false);
+
+ auto router_matmul = std::make_shared<op::v0::MatMul>(
+ experts_reshape,
+ op::v0::Constant::create(element::f32, Shape{number_of_experts, hidden_size}, {1.0f}),
+ false,
+ true);
+ auto router_topk = std::make_shared<op::v11::TopK>(router_matmul,
+ op::v0::Constant::create(element::i64, Shape{}, {topk}),
+ -1,
+ op::v11::TopK::Mode::MAX,
+ op::v11::TopK::SortType::SORT_VALUES,
+ element::i64);
+ auto topk_indices = router_topk->output(1);
+ auto chosen_experts = router_topk->output(0);
+
+ // Compact routing
+ auto router_transpose = std::make_shared<op::v1::Transpose>(
+ chosen_experts,
+ op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{1, 0}));
+ auto router_unsqueeze =
+ std::make_shared<op::v0::Unsqueeze>(router_transpose, op::v0::Constant::create(element::i32, Shape{}, {-1}));
+
+ // Weights
+ auto gate_w =
+ op::v0::Constant::create(element::f32, Shape{number_of_experts, intermediate_size, hidden_size}, {1.0f});
+ auto up_w =
+ op::v0::Constant::create(element::f32, Shape{number_of_experts, intermediate_size, hidden_size}, {1.0f});
+ auto down_w =
+ 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::op::internal::MOE::Config config;
+ config.expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU;
+ config.activation_type = activation_type;
+ auto moe = std::make_shared<ov::op::internal::MOE>(moe_inputs, config);
+
+ return std::make_shared<ov::Model>(ov::OutputVector{moe}, ov::ParameterVector{input});
+}
+
// ============================================================================
// Tests for BGM→MOE passes (Convert3GatherMatmulMoeBlockToMoeOp, Convert2GatherMatmulMoeBlockToMoeOp)
// ============================================================================
@@ -592,6 +760,33 @@ TEST_F(TransformationTestsF, Convert3GatherMatmulMoeBlockToMoeOp_basic) {
model_ref = build_3gemm_bgm_to_moe_reference_model();
}
+TEST_F(TransformationTestsF, Convert3GatherMatmulMoeBlockToMoeOp_gelu_tanh) {
+ using AT = ov::op::internal::MOE::Activation_type;
+ model = build_3gemm_bgm_model(AT::GEGLU_TANH);
+ manager.register_pass<ov::pass::Convert3GatherMatmulMoeBlockToMoeOp>();
+ model_ref = build_3gemm_bgm_to_moe_reference_model(AT::GEGLU_TANH);
+}
+
+TEST_F(TransformationTestsF, Convert3GatherMatmulMoeBlockToMoeOp_gelu_erf) {
+ using AT = ov::op::internal::MOE::Activation_type;
+ model = build_3gemm_bgm_model(AT::GEGLU_ERF);
+ manager.register_pass<ov::pass::Convert3GatherMatmulMoeBlockToMoeOp>();
+ model_ref = build_3gemm_bgm_to_moe_reference_model(AT::GEGLU_ERF);
+}
+
+TEST_F(TransformationTestsF, Convert3GatherMatmulMoeBlockToMoeOp_multiply_input) {
+ model = build_3gemm_bgm_model_multiply_input();
+ manager.register_pass<ov::pass::Convert3GatherMatmulMoeBlockToMoeOp>();
+ model_ref = build_3gemm_bgm_to_moe_reference_model_multiply_input();
+}
+
+TEST_F(TransformationTestsF, Convert3GatherMatmulMoeBlockToMoeOp_multiply_input_gelu_tanh) {
+ using AT = ov::op::internal::MOE::Activation_type;
+ model = build_3gemm_bgm_model_multiply_input(AT::GEGLU_TANH);
+ manager.register_pass<ov::pass::Convert3GatherMatmulMoeBlockToMoeOp>();
+ model_ref = build_3gemm_bgm_to_moe_reference_model_multiply_input(AT::GEGLU_TANH);
+}
+
TEST_F(TransformationTestsF, Convert2GatherMatmulMoeBlockToMoeOp_basic) {
model = build_2gemm_bgm_model();
manager.register_pass<ov::pass::Convert2GatherMatmulMoeBlockToMoeOp>();
diff --git a/src/core/dev_api/openvino/op/moe.hpp b/src/core/dev_api/openvino/op/moe.hpp
index 253ea62d256..6cec74b2e8a 100644
--- a/src/core/dev_api/openvino/op/moe.hpp
+++ b/src/core/dev_api/openvino/op/moe.hpp
@@ -24,12 +24,18 @@ public:
MOE(const OutputVector& args) : Op(args) {}
enum class Expert_type { GEMM2_BIAS_SWIGLU_CLAMP, GEMM3_SWIGLU };
+ enum class Activation_type {
+ SWIGLU, // Swish gate activation (default; matches existing behavior)
+ GEGLU_TANH, // Gelu gate with Tanh approximation
+ GEGLU_ERF, // Gelu gate with ERF (exact) activation
+ };
struct Config {
Expert_type expert_type{Expert_type::GEMM2_BIAS_SWIGLU_CLAMP};
float expert_alpha{0.0f}; // Expert attribute for clamp bounds
float expert_beta{1.0f}; // Expert attribute for swish beta
size_t gate_idx{0}; // gate (swish) lane in interleaved gate/up; GEMM2 only
+ Activation_type activation_type{Activation_type::SWIGLU}; // Gate activation; GEMM3 only
};
/// \brief Constructs a MOE operation with config only
@@ -68,6 +74,7 @@ private:
namespace ov {
std::ostream& operator<<(std::ostream& s, const ov::op::internal::MOE::Expert_type& type);
+std::ostream& operator<<(std::ostream& s, const ov::op::internal::MOE::Activation_type& type);
template <>
class AttributeAdapter<ov::op::internal::MOE::Expert_type>
@@ -79,4 +86,15 @@ public:
OPENVINO_RTTI("AttributeAdapter<ov::op::internal::MOE::Expert_type>");
~AttributeAdapter() override = default;
};
+
+template <>
+class AttributeAdapter<ov::op::internal::MOE::Activation_type>
+ : public EnumAttributeAdapterBase<ov::op::internal::MOE::Activation_type> {
+public:
+ AttributeAdapter(ov::op::internal::MOE::Activation_type& value)
+ : EnumAttributeAdapterBase<ov::op::internal::MOE::Activation_type>(value) {}
+
+ OPENVINO_RTTI("AttributeAdapter<ov::op::internal::MOE::Activation_type>");
+ ~AttributeAdapter() override = default;
+};
} // namespace ov
diff --git a/src/core/src/op/moe.cpp b/src/core/src/op/moe.cpp
index 2f5b46c50bb..e50c457127b 100644
--- a/src/core/src/op/moe.cpp
+++ b/src/core/src/op/moe.cpp
@@ -31,8 +31,11 @@ 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");
+ }
// TODO: Add inputs validation
-
set_output_type(0, get_input_element_type(0), get_input_partial_shape(0));
}
@@ -42,6 +45,7 @@ bool MOE::visit_attributes(ov::AttributeVisitor& visitor) {
visitor.on_attribute("expert_alpha", m_config.expert_alpha);
visitor.on_attribute("expert_beta", m_config.expert_beta);
visitor.on_attribute("gate_idx", m_config.gate_idx);
+ visitor.on_attribute("activation_type", m_config.activation_type);
return true;
}
@@ -53,6 +57,10 @@ std::ostream& operator<<(std::ostream& s, const ov::op::internal::MOE::Expert_ty
return s << as_string(type);
}
+std::ostream& operator<<(std::ostream& s, const ov::op::internal::MOE::Activation_type& type) {
+ return s << as_string(type);
+}
+
template <>
OPENVINO_API EnumNames<ov::op::internal::MOE::Expert_type>& EnumNames<ov::op::internal::MOE::Expert_type>::get() {
static auto enum_names = EnumNames<ov::op::internal::MOE::Expert_type>(
@@ -63,4 +71,17 @@ OPENVINO_API EnumNames<ov::op::internal::MOE::Expert_type>& EnumNames<ov::op::in
});
return enum_names;
}
+
+template <>
+OPENVINO_API EnumNames<ov::op::internal::MOE::Activation_type>&
+EnumNames<ov::op::internal::MOE::Activation_type>::get() {
+ static auto enum_names = EnumNames<ov::op::internal::MOE::Activation_type>(
+ "ov::op::internal::MOE::Activation_type",
+ {
+ {"swiglu", ov::op::internal::MOE::Activation_type::SWIGLU},
+ {"geglu_tanh", ov::op::internal::MOE::Activation_type::GEGLU_TANH},
+ {"geglu_erf", ov::op::internal::MOE::Activation_type::GEGLU_ERF},
+ });
+ return enum_names;
+}
} // namespace ov
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/expert_gemm_compute.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/expert_gemm_compute.cl
index 2f46867d87e..8d8212ed623 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/expert_gemm_compute.cl
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/expert_gemm_compute.cl
@@ -159,7 +159,16 @@ inline bool expert_gemm_compute(
float gate = tiles[1].x[ri][rj];
float value = tiles[0].x[ri][rj];
#endif
+#ifdef GATE_ACT_GELU_ERF
+ float z_g = fabs(gate) * 0.7071067811865475f;
+ float t_g = 1.0f / (1.0f + 0.3275911f * z_g);
+ float erf_g = 1.0f - (((((1.061405429f * t_g + (-1.453152027f)) * t_g + 1.421413741f) * t_g + (-0.284496736f)) * t_g + 0.254829592f)) * t_g * native_exp(-(z_g * z_g));
+ float swish = 0.5f * gate * (1.0f + ((gate >= 0.0f) ? erf_g : -erf_g));
+#elif defined(GATE_ACT_GELU_TANH)
+ float swish = 0.5f * gate * (1.0f + (tanh(0.79788458347320556640625f * gate * (1.0f + 0.044715f * gate * gate))));
+#else
float swish = gate / (1.0f + native_exp(-SWISH_BETA * gate));
+#endif
c_tile_half.x[ri][rj] = (half)(value * swish);
}
}
@@ -212,7 +221,17 @@ inline bool expert_gemm_compute(
int reg_idx_i = (i0 / br) + nbr * (j / bc);
int reg_idx_j = (i0 % br) / sg + (j % bc) * (br / sg);
float val = c_tile_half.x[reg_idx_i][reg_idx_j];
- float res = post_val * (val / (1.0f + native_exp(-val)));
+#ifdef GATE_ACT_GELU_ERF
+ float z_v = fabs(val) * 0.7071067811865475f;
+ float t_v = 1.0f / (1.0f + 0.3275911f * z_v);
+ float erf_v = 1.0f - (((((1.061405429f * t_v + (-1.453152027f)) * t_v + 1.421413741f) * t_v + (-0.284496736f)) * t_v + 0.254829592f)) * t_v * native_exp(-(z_v * z_v));
+ float act = 0.5f * val * (1.0f + ((val >= 0.0f) ? erf_v : -erf_v));
+#elif defined(GATE_ACT_GELU_TANH)
+ float act = 0.5f * val * (1.0f + (tanh(0.79788458347320556640625f * val * (1.0f + 0.044715f * val * val))));
+#else
+ float act = val / (1.0f + native_exp(-val));
+#endif
+ float res = post_val * act;
c_tile_half.x[reg_idx_i][reg_idx_j] = res;
}
}
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_gen_micro.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_gen_micro.cpp
index e75effe40a0..4cd35dba9d4 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_gen_micro.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_gen_micro.cpp
@@ -143,8 +143,14 @@ JitConstants MoE3GemmMicroGenerator::get_jit_constants(const kernel_impl_params&
jit.make("USE_SLM", 1);
const bool enable_silu_mul = ENABLE_MOE_MICRO_GEMM_POST_PROC_SILU_MUL;
- if (enable_silu_mul && m_type == MoE3GemmMicroKernelType::MLP_GATE)
+ if (enable_silu_mul && m_type == MoE3GemmMicroKernelType::MLP_GATE) {
jit.make("POST_PROC_SILU_MUL", 1);
+ if (desc->_config.activation_type == ov::op::internal::MOE::Activation_type::GEGLU_TANH) {
+ jit.make("GATE_ACT_GELU_TANH", 1);
+ } else if (desc->_config.activation_type == ov::op::internal::MOE::Activation_type::GEGLU_ERF) {
+ jit.make("GATE_ACT_GELU_ERF", 1);
+ }
+ }
return jit;
}
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 01b0f9b97b5..67260f4eb54 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
@@ -56,6 +56,18 @@ dnnl::memory::data_type convert_data_type(cldnn::data_types dt) {
}
}
+inline dnnl::algorithm moe_activation_to_dnnl_algo(ov::op::internal::MOE::Activation_type act) {
+ switch (act) {
+ case ov::op::internal::MOE::Activation_type::GEGLU_TANH:
+ return dnnl::algorithm::eltwise_gelu_tanh;
+ case ov::op::internal::MOE::Activation_type::GEGLU_ERF:
+ return dnnl::algorithm::eltwise_gelu_erf;
+ case ov::op::internal::MOE::Activation_type::SWIGLU:
+ default:
+ return dnnl::algorithm::eltwise_swish;
+ }
+}
+
struct onednn_matmul {
dnnl::matmul m_prim;
dnnl::memory::desc m_wei_md;
@@ -124,10 +136,10 @@ struct onednn_matmul {
attr.set_fpmath_mode(dnnl::fpmath_mode::f16, true);
return *this;
}
- onednn_matmul& post_op_silu() {
+ onednn_matmul& post_op_gate_activation(dnnl::algorithm algo) {
float alpha = 1.0f;
float beta = 0.0f;
- postops.append_eltwise(dnnl::algorithm::eltwise_swish, alpha, beta);
+ postops.append_eltwise(algo, alpha, beta);
return *this;
}
onednn_matmul& post_op_bin_mul(bool per_oc = true) {
@@ -172,8 +184,8 @@ struct onednn_matmul {
with_bin_mul,
with_bin_mul_per_row,
with_bin_mul_per_row_sum,
- with_silu,
- with_silu_bin_mul,
+ with_gate_act,
+ with_gate_act_bin_mul,
with_sigmoid,
with_bin_mul_sum,
};
@@ -187,7 +199,8 @@ struct onednn_matmul {
int oc,
int ic_group_size,
type t,
- bool has_zp = true)
+ bool has_zp = true,
+ dnnl::algorithm activation_algo = dnnl::algorithm::eltwise_swish)
: onednn_matmul(act_dtype, weight_dtype, batch, ic, oc, ic_group_size, has_zp) {
if (t == type::with_bin_mul) {
bin_post_id = 0;
@@ -212,11 +225,11 @@ struct onednn_matmul {
post_op_bin_mul(false);
post_op_sum();
}
- if (t == type::with_silu)
- post_op_silu();
- if (t == type::with_silu_bin_mul) {
+ if (t == type::with_gate_act)
+ post_op_gate_activation(activation_algo);
+ if (t == type::with_gate_act_bin_mul) {
bin_post_id = 1;
- post_op_silu();
+ post_op_gate_activation(activation_algo);
post_op_bin_mul(true);
}
@@ -304,10 +317,11 @@ struct onednn_linear {
onednn_matmul::type t,
dnnl::memory weight, // external weight
dnnl::memory scale,
- dnnl::memory zp) {
+ dnnl::memory zp,
+ dnnl::algorithm activation_algo = dnnl::algorithm::eltwise_swish) {
OV_ITT_SCOPED_TASK(ov::intel_gpu::itt::domains::intel_gpu_plugin, openvino::itt::handle("onednn_linear::create()"));
bool has_zp = static_cast<bool>(zp);
- auto mm = make_cacheable<onednn_matmul>(eng, act_dtype, weight_dtype, batch, ic, oc, ic_group_size, t, has_zp);
+ auto mm = make_cacheable<onednn_matmul>(eng, act_dtype, weight_dtype, batch, ic, oc, ic_group_size, t, has_zp, activation_algo);
onednn_linear linear;
linear.mm = mm;
linear.bin_post_id = mm->bin_post_id;
@@ -597,6 +611,11 @@ protected:
jit.make("SUBGROUP_SIZE", info.arch >= gpu_arch::xe2 ? 32 : 16);
jit.make("INTERMEDIA_SIZE", desc->_config.inter_size);
jit.make("MOE_DTYPE", "half");
+ if (desc->_config.activation_type == ov::op::internal::MOE::Activation_type::GEGLU_TANH) {
+ jit.make("GATE_ACT_GELU_TANH", 1);
+ } else if (desc->_config.activation_type == ov::op::internal::MOE::Activation_type::GEGLU_ERF) {
+ jit.make("GATE_ACT_GELU_ERF", 1);
+ }
if (m_use_grouped_gemm)
jit.make("ONEDNN_GROUPED_GEMM_USED", 1);
return jit;
@@ -754,6 +773,11 @@ protected:
auto desc = params.typed_desc<moe_3gemm_fused_compressed>();
add_common_consts(params, jit);
jit.make("GATE_UP_ENABLE", 1);
+ if (desc->_config.activation_type == ov::op::internal::MOE::Activation_type::GEGLU_TANH) {
+ jit.make("GATE_ACT_GELU_TANH", 1);
+ } else if (desc->_config.activation_type == ov::op::internal::MOE::Activation_type::GEGLU_ERF) {
+ jit.make("GATE_ACT_GELU_ERF", 1);
+ }
if (!_disable_shared_experts && desc->_config.num_shared_expert > 0 &&
params.input_layouts.size() > static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_WEIGHT)) {
jit.make("SHARED_EXPERT_ENABLE", 1);
@@ -937,6 +961,7 @@ public:
int _shared_intermediate_size;
int _gate_up_group_size;
int _down_group_size;
+ ov::op::internal::MOE::Activation_type _activation_type = ov::op::internal::MOE::Activation_type::SWIGLU;
bool _has_shared_expert = false;
// Shared expert primitives
@@ -1043,6 +1068,7 @@ public:
_intermediate_size = static_cast<int>(cur_moe->_config.inter_size);
_gate_up_group_size = static_cast<int>(cur_moe->_config.group_size);
_down_group_size = static_cast<int>(cur_moe->_config.group_size);
+ _activation_type = cur_moe->_config.activation_type;
if (cur_moe->_config.group_size == std::numeric_limits<size_t>::max()) {
_gate_up_group_size = static_cast<int>(cur_moe->_config.hidden_size);
@@ -1199,10 +1225,11 @@ public:
_hidden_size,
_shared_intermediate_size,
_gate_up_group_size,
- t::with_silu_bin_mul,
+ t::with_gate_act_bin_mul,
gate_w,
gate_s,
- gate_z));
+ gate_z,
+ moe_activation_to_dnnl_algo(_activation_type)));
// 3. Scalar Gate (Sigmoid)
// It is very small weight with shape of [Hidden, 1], and not need to keep compressed, so KeepMOE3GemmConstPrecision will not keep its precision and
@@ -1284,6 +1311,7 @@ public:
cur_moe->_intermediate_size = _intermediate_size;
cur_moe->_gate_up_group_size = _gate_up_group_size;
cur_moe->_down_group_size = _down_group_size;
+ cur_moe->_activation_type = _activation_type;
return cur_moe;
}
@@ -1969,6 +1997,9 @@ public:
auto hidden_states_layout_dt =
convert_data_type(instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::HIDDEN_STATES))->get_layout().data_type);
+ auto cur_moe = instance.get_typed_desc<moe_3gemm_fused_compressed>();
+ const auto gate_activation_algo = moe_activation_to_dnnl_algo(cur_moe->_config.activation_type);
+
auto& dnnl_weights = _dnnl_weights[expert_no];
auto kernel = std::make_shared<onednn_kernel>();
@@ -1981,10 +2012,11 @@ public:
dnnl_weights[0].ic,
dnnl_weights[0].oc,
dnnl_weights[0].ic_group_size,
- onednn_matmul::type::with_silu_bin_mul,
+ onednn_matmul::type::with_gate_act_bin_mul,
dnnl_weights[0].weight,
dnnl_weights[0].scale,
- dnnl_weights[0].zp);
+ dnnl_weights[0].zp,
+ gate_activation_algo);
// up
auto up_weight_layout_dt = convert_data_type(instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::WEIGHT_1))->get_layout().data_type);
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 980dc17c77d..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
@@ -229,6 +229,39 @@ KERNEL (index_add_)(const __global MOE_DTYPE* src_tok,
#define SWISH_BETA 1.0f
#define ACC_DTYPE float
+
+// Tanh-approximation Gelu: 0.5 * x * (1 + tanh(sqrt(2/pi) * (x + 0.044715 * x^3)))
+#define GELU_TANH_SQRT_2_OVER_PI 0.7978845608028654f
+#define GELU_TANH_C 0.044715f
+
+// ERF Gelu: 0.5 * x * (1 + erf(x / sqrt(2))); 1/sqrt(2) = 0.7071067811865475
+// Fast erf approximation (A&S 7.1.26) — same coefficients as swiglu_gpu_opt.cl
+inline float moe_fast_erf(float x) {
+ if (x > 4.0f) return 1.0f;
+ if (x < -4.0f) return -1.0f;
+ const float p = 0.3275911f;
+ const float a1 = 0.254829592f;
+ const float a2 = -0.284496736f;
+ const float a3 = 1.421413741f;
+ const float a4 = -1.453152027f;
+ const float a5 = 1.061405429f;
+ float z = fabs(x);
+ float t = 1.0f / (1.0f + p * z);
+ float y = 1.0f - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * native_exp(-(z * z));
+ return (x >= 0.0f) ? y : -y;
+}
+
+inline ACC_DTYPE moe_gate_activation(ACC_DTYPE x) {
+#if GATE_ACT_GELU_ERF
+ return 0.5f * x * (1.0f + moe_fast_erf(x * 0.7071067811865475f));
+#elif GATE_ACT_GELU_TANH
+ return 0.5f * x * (1.0f + (tanh(0.79788458347320556640625f * x * (1.0f + 0.044715f * x * x))));
+#else
+ // Swish (SwiGLU): x * sigmoid(beta * x)
+ return x / (1.0f + native_exp(-SWISH_BETA * x));
+#endif
+}
+
__attribute__((intel_reqd_sub_group_size(SUBGROUP_SIZE)))
KERNEL(swiglu_ref) (
const __global MOE_DTYPE* up, // [token_len * expert_topK, inter_size]
@@ -245,14 +278,14 @@ KERNEL(swiglu_ref) (
const uint offset = token_idx * INTERMEDIA_SIZE + n_offset - sg_id;
ACC_DTYPE up_value = as_half(intel_sub_group_block_read_us((const __global ushort *)(up + offset)));
ACC_DTYPE gate_value = as_half(intel_sub_group_block_read_us((const __global ushort *)(gate + offset)));
- ACC_DTYPE value = gate_value / (1.0f + native_exp(-SWISH_BETA * gate_value));
+ ACC_DTYPE value = moe_gate_activation(gate_value);
half result = value * up_value;
intel_sub_group_block_write_us((__global ushort *)(output + offset), as_ushort(result));
#else
const uint offset = token_idx * INTERMEDIA_SIZE + n_offset;
ACC_DTYPE gate_value = gate[offset];
ACC_DTYPE up_value = up[offset];
- ACC_DTYPE value = gate_value / (1.0f + native_exp(-SWISH_BETA * gate_value));
+ ACC_DTYPE value = moe_gate_activation(gate_value);
ACC_DTYPE result = value * up_value;
output[offset] = result;
#endif
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 17bb3cfb503..c5c9fec04d1 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
@@ -33,6 +33,29 @@
// 4 (e.g. SG=32 + FAKE=128 or SG=16 + FAKE=64), and 8 (SG=16 + FAKE=128).
#define ELEMS_PER_LANE (FAKE_GROUP_SIZE / SUBGROUP_SIZE)
+// Gate activation: SwiGLU (Swish, default), GeGLU-Tanh, or GeGLU-ERF.
+// GATE_ACT_GELU_ERF takes precedence over GATE_ACT_GELU_TANH when both are set.
+#ifdef GATE_ACT_GELU_ERF
+// ERF Gelu: 0.5 * x * (1 + erf(x / sqrt(2))); A&S 7.1.26 fast erf approximation
+inline float moe_mlp_fast_erf(float x) {
+ const float p = 0.3275911f;
+ const float a1 = 0.254829592f;
+ const float a2 = -0.284496736f;
+ const float a3 = 1.421413741f;
+ const float a4 = -1.453152027f;
+ const float a5 = 1.061405429f;
+ float z = fabs(x);
+ float t = 1.0f / (1.0f + p * z);
+ float y = 1.0f - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * exp(-(z * z));
+ return (x >= 0.0f) ? y : -y;
+}
+# define MOE_GATE_ACT(x) (0.5f * (x) * (1.0f + moe_mlp_fast_erf((x) * 0.7071067811865475f)))
+#elif defined(GATE_ACT_GELU_TANH)
+# define MOE_GATE_ACT(x) (0.5f * (x) * (1.0f + (tanh(0.79788458347320556640625f * (x) * (1.0f + 0.044715f * (x) * (x))))))
+#else
+# define MOE_GATE_ACT(x) ((x) / (1.0f + exp(-(x))))
+#endif
+
// HAS_ZP: 1 = asymmetric quantization (subtract zero point), 0 = symmetric (no zero point)
#if HAS_ZP
# define ZP_ADJUST_2(sum0, sum1, xg_sum_gk, z0, z1) ((sum0) - (xg_sum_gk) * (z0)), ((sum1) - (xg_sum_gk) * (z1))
@@ -175,8 +198,8 @@ inline void gate_up_gemv_n2x_u4(const __global uchar* weight,
sum_all1 = sub_group_reduce_add(sum_all1);
if (id_local == 0) {
if (silu) {
- y[n] *= sum_all0 / (1 + exp(-sum_all0));
- y[n + 1] *= sum_all1 / (1 + exp(-sum_all1));
+ y[n] *= MOE_GATE_ACT(sum_all0);
+ y[n + 1] *= MOE_GATE_ACT(sum_all1);
} else {
y[n] = sum_all0;
y[n + 1] = sum_all1;
@@ -303,8 +326,8 @@ inline void gate_up_gemv_n2x_u8(const __global uchar* weight,
sum_all1 = sub_group_reduce_add(sum_all1);
if (id_local == 0) {
if (silu) {
- y[n] *= sum_all0 / (1 + exp(-sum_all0));
- y[n + 1] *= sum_all1 / (1 + exp(-sum_all1));
+ y[n] *= MOE_GATE_ACT(sum_all0);
+ y[n + 1] *= MOE_GATE_ACT(sum_all1);
} else {
y[n] = sum_all0;
y[n + 1] = sum_all1;
@@ -395,8 +418,8 @@ inline void gate_up_gemv_n2x_f16(const __global half* weight, __global half* y,
sum_all1 = sub_group_reduce_add(sum_all1);
if (id_local == 0) {
if (silu) {
- y[n] *= sum_all0 / (1 + exp(-sum_all0));
- y[n + 1] *= sum_all1 / (1 + exp(-sum_all1));
+ y[n] *= MOE_GATE_ACT(sum_all0);
+ y[n + 1] *= MOE_GATE_ACT(sum_all1);
} else {
y[n] = sum_all0;
y[n + 1] = sum_all1;
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
index 97b3cf06544..a9c464e8b5c 100644
--- 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
@@ -10,10 +10,12 @@
#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"
@@ -42,23 +44,32 @@ FuseMOE3GemmCompressed::FuseMOE3GemmCompressed() {
#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 matmul = wrap_type<ov::op::v0::MatMul>({hidden_state_reshape, ANY}, consumers_count(1));
+ 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>({matmul}, consumers_count(1));
+ 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)});
- auto sm_slice = optional<ov::op::v8::Slice>({sm_norm, ANY, ANY, ANY, ANY});
+
+ // 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>({matmul});
+ 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});
@@ -153,11 +164,10 @@ FuseMOE3GemmCompressed::FuseMOE3GemmCompressed() {
if (!has_shared_expert) {
config.num_shared_expert = 0;
}
- // When Optional<Reshape> is absent, the optional pattern is NOT in the map.
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(matmul),
+ pattern_map.at(routing_matmul),
pattern_map.at(gate_wei_m),
pattern_map.at(gate_scale_m),
pattern_map.at(gate_zp_m),
@@ -193,6 +203,31 @@ FuseMOE3GemmCompressed::FuseMOE3GemmCompressed() {
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);
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 ab86fe910c1..48137795595 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
@@ -48,12 +48,14 @@ using MoECompressedParams = std::tuple<MoeTestShapeParams,
int, // group_size
size_t, // gate_idx (2-GEMM only)
bool, // force_gather_matmul
- MoEActivationType>; // gate activation type (GEMM3 only)
+ MoEActivationType, // gate activation type (GEMM3 only)
+ bool, // use_per_expert_scale (GEMM3+SOFTMAX only)
+ bool>; // use_layernorm_multiply (gemma4 pattern)
class MoECompressedFusionTest : public testing::WithParamInterface<MoECompressedParams>, virtual public ov::test::SubgraphBaseTest {
public:
static std::string getTestCaseName(const testing::TestParamInfo<MoECompressedParams>& info) {
- const auto& [moe_params, pattern_type, routing_type, wp, dp, sp, dm, ds, rd, gs, gi, fgm, act] = info.param;
+ const auto& [moe_params, pattern_type, routing_type, wp, dp, sp, dm, ds, rd, gs, gi, fgm, act, pes, lnm] = info.param;
std::ostringstream result;
result << "IS=" << ov::test::utils::partialShape2str({moe_params.data_shape.first}) << "_";
result << "TS=";
@@ -73,13 +75,15 @@ public:
result << "GS=" << gs << "_";
result << "GI=" << gi << "_";
result << "FGM=" << fgm << "_";
- result << "act=" << (act == MoEActivationType::GELU ? "GELU" : "SWISH");
+ result << "act=" << (act == MoEActivationType::GELU ? "GELU" : act == MoEActivationType::GELU_ERF ? "GELU_ERF" : "SWISH") << "_";
+ result << "PES=" << pes << "_";
+ result << "LNM=" << lnm;
return result.str();
}
protected:
void SetUp() override {
- const auto& [moe_params, pattern_type, routing_type, wp, dp, sp, dm, ds, rd, gs, gi, fgm, act] = GetParam();
+ const auto& [moe_params, pattern_type, routing_type, wp, dp, sp, dm, ds, rd, gs, gi, fgm, act, pes, lnm] = GetParam();
if (fgm) {
set_disable_moe_opt();
}
@@ -113,9 +117,13 @@ protected:
rd, // reshape_on_decompression
gs, // group_size
routing_type,
- act); // activation_type
+ act, // activation_type
+ pes, // use_per_expert_scale
+ lnm); // use_layernorm_multiply
} else {
ASSERT_TRUE(act == MoEActivationType::SWISH) << "2-GEMM pattern only supports Swish activation";
+ ASSERT_TRUE(pes == false) << "2-GEMM pattern doesn't support per-expert scale";
+ ASSERT_TRUE(lnm == false) << "2-GEMM pattern doesn't support layernorm multiply";
function = ov::test::initMoE2GeMMSubgraph(shape_params,
ov::element::f32, // data_precision
wp, // weights_precision
@@ -147,10 +155,7 @@ protected:
ov::test::SubgraphBaseTest::validate();
const auto pattern_type = std::get<1>(GetParam());
const auto force_gather_matmul = std::get<11>(GetParam());
- const auto activation_type = std::get<12>(GetParam());
- // Gelu activation is not supported by the fused kernel -> always falls back to gather_matmul.
- const bool use_gather_matmul = force_gather_matmul || activation_type == MoEActivationType::GELU;
- if (use_gather_matmul) {
+ 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);
} else {
@@ -207,6 +212,13 @@ const std::vector<MoeTestShapeParams> moe_params_smoke = {
4, // number_of_experts
256 // intermediate_size
},
+ {
+ // large hidden
+ {{-1, -1, 2048}, {{1, 4, 2048}, {1, 1, 2048}}}, // prefill + decode
+ 4, // topk
+ 8, // number_of_experts
+ 512 // intermediate_size
+ },
};
// Compressed weights — full GatherMatmul → MOECompressed → FuseMOE3GemmCompressed pipeline.
@@ -232,7 +244,9 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoE3GemmCompressedFusion,
::testing::Values(128),
::testing::Values(size_t{0}), // gate_idx unused for GEMM3
::testing::Values(false), // force_gather_matmul
- ::testing::Values(MoEActivationType::SWISH)),
+ ::testing::Values(MoEActivationType::SWISH),
+ ::testing::Values(false), // use_per_expert_scale
+ ::testing::Values(false)), // use_layernorm_multiply
MoECompressedFusionTest::getTestCaseName);
// GPT-OSS 2-GEMM pattern (combined gate/up MatMul + Slice/Clamp/Add/Swish).
@@ -251,7 +265,9 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoE2GemmCompressedFusion,
::testing::Values(128),
::testing::ValuesIn(gate_idx_values),
::testing::Values(false), // force_gather_matmul
- ::testing::Values(MoEActivationType::SWISH)),
+ ::testing::Values(MoEActivationType::SWISH),
+ ::testing::Values(false), // use_per_expert_scale
+ ::testing::Values(false)), // use_layernorm_multiply
MoECompressedFusionTest::getTestCaseName);
// MoEGatherMatmulTest: alias for MoECompressedFusionTest with force_gather_matmul=true.
@@ -272,7 +288,9 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoEGatherMatmul,
::testing::Values(128),
::testing::Values(size_t{0}), // gate_idx unused for GEMM3
::testing::Values(true), // force_gather_matmul
- ::testing::Values(MoEActivationType::SWISH)),
+ ::testing::Values(MoEActivationType::SWISH),
+ ::testing::Values(false), // use_per_expert_scale
+ ::testing::Values(false)), // use_layernorm_multiply
MoEGatherMatmulTest::getTestCaseName);
// 2-GEMM unfused: covers GatherMatmul OCL clamp/bias/swiglu compile path.
@@ -290,16 +308,17 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoE2GemmGatherMatmul,
::testing::Values(128),
::testing::ValuesIn(gate_idx_values),
::testing::Values(true), // force_gather_matmul
- ::testing::Values(MoEActivationType::SWISH)),
+ ::testing::Values(MoEActivationType::SWISH),
+ ::testing::Values(false), // use_per_expert_scale
+ ::testing::Values(false)), // use_layernorm_multiply
MoEGatherMatmulTest::getTestCaseName);
-// GEMM3 + Gelu (GeGLU): GPU fused kernel does not support gelu, so the model is executed
-// via 3 GatherMatmul ops even without force_gather_matmul.
+// 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,
MoECompressedFusionTest,
::testing::Combine(::testing::ValuesIn(moe_params_smoke),
::testing::Values(MoePatternType::GEMM3),
- ::testing::ValuesIn(routing_types),
+ ::testing::Values(MoERoutingType::SOFTMAX),
::testing::Values(ov::element::u4), // weights_precision
::testing::Values(ov::element::f16), // decompression_precision
::testing::Values(ov::element::f16), // scale_precision
@@ -309,7 +328,9 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoE3GemmGeluCompressed,
::testing::Values(128),
::testing::Values(size_t{0}), // gate_idx unused for GEMM3
::testing::Values(false), // force_gather_matmul
- ::testing::Values(MoEActivationType::GELU)),
+ ::testing::Values(MoEActivationType::GELU, MoEActivationType::GELU_ERF),
+ ::testing::Values(true, false), // use_per_expert_scale
+ ::testing::Values(true, false)), // use_layernorm_multiply
MoECompressedFusionTest::getTestCaseName);
} // namespace
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
index 418c81a9278..419650fd47e 100644
--- 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
@@ -39,8 +39,12 @@ 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 */>;
+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:
@@ -60,25 +64,51 @@ public:
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 → 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) {
+// 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);
- auto norm = std::make_shared<ov::op::v1::Divide>(topk_node->output(0), reduce_sum);
+ 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_node->output(1)};
+ return {unsqueeze_moe, topk_indices};
}
// Sigmoid+bias routing: Sigmoid → Add → TopK → Convert → GatherElements → ReduceSum → Add(eps) → Divide
@@ -122,10 +152,11 @@ static std::pair<ov::Output<ov::Node>, ov::Output<ov::Node>> build_sigmoid_routi
}
TEST_P(FuseMOE3GemmCompressedTest, CompareFunctions) {
- const auto& [routing_type, reshape_on_moe_input, with_routed_scale] = GetParam();
+ const auto& [routing_type, reshape_on_moe_input, with_routed_scale, activation_type] = GetParam();
constexpr float routed_scale_value = 2.5f;
- // routed_scaling_factor only applies to the SIGMOID_BIAS branch.
- ASSERT_TRUE(!with_routed_scale || routing_type == MoERoutingType::SIGMOID_BIAS);
+ // 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;
@@ -140,20 +171,27 @@ TEST_P(FuseMOE3GemmCompressedTest, CompareFunctions) {
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>(element::f16, Shape{batch, seq_len, hidden_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(element::f16, Shape{hidden_size, num_experts}, {0.2});
- auto routing_weights = std::make_shared<ov::op::v0::MatMul>(hidden_states_reshape, routers);
-
- // Build post-GatherMatmul routing (no ScatterElementsUpdate)
- std::optional<float> scale_opt;
- if (with_routed_scale) {
- scale_opt = routed_scale_value;
+ 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)
- : build_sigmoid_routing_for_fuse_test(routing_weights, element::f16, num_experts, top_k, scale_opt);
+ ? 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.
@@ -169,6 +207,7 @@ TEST_P(FuseMOE3GemmCompressedTest, CompareFunctions) {
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;
@@ -187,11 +226,19 @@ TEST_P(FuseMOE3GemmCompressedTest, CompareFunctions) {
}
manager.register_pass<FuseMOE3GemmCompressed>();
{
- auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{batch, seq_len, hidden_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(element::f16, Shape{hidden_size, num_experts}, {0.2});
- auto routing_weights = std::make_shared<ov::op::v0::MatMul>(hidden_states_reshape, routers);
+ 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});
@@ -200,11 +247,14 @@ TEST_P(FuseMOE3GemmCompressedTest, CompareFunctions) {
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});
+ // 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;
@@ -220,29 +270,39 @@ TEST_P(FuseMOE3GemmCompressedTest, CompareFunctions) {
OPENVINO_THROW("Unsupported routing type");
}
- ov::OutputVector args{hidden_states_reshape, routing_weights, wei_gate, scale_gate, zp_gate, wei_up, scale_up, zp_up, wei_down, scale_down, zp_down};
+ // 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(element::f16, Shape{1, num_experts}, {0.1f});
+ 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(element::f16, Shape{1, 1}, {1e-6f});
+ 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, MOE3GemmFusedCompressed takes reshaped input from routing subgraph,
- // so the transformation inserts a reshape-back to restore the original shape. The reshape-back is
- // emitted before the post-op Multiply in the callback, so mirror that order here.
- if (!reshape_on_moe_input) {
+ // 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);
}
- // The transformation re-applies the absorbed routed_scaling_factor as a post-op Multiply.
- // Scale is already f16, so no Convert insertion is expected.
- if (with_routed_scale) {
- auto post_scale = op::v0::Constant::create(element::f16, Shape{1, 1}, {routed_scale_value});
- result = std::make_shared<ov::op::v1::Multiply>(result, post_scale);
+ // 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});
@@ -251,16 +311,10 @@ TEST_P(FuseMOE3GemmCompressedTest, CompareFunctions) {
INSTANTIATE_TEST_SUITE_P(smoke,
FuseMOE3GemmCompressedTest,
- ::testing::ValuesIn(std::vector<FuseMOE3GemmCompressedTestParams>{
- // {routing_type, reshape_on_moe_input, with_routed_scale}
- {MoERoutingType::SOFTMAX, false, false},
- {MoERoutingType::SOFTMAX, true, false},
- {MoERoutingType::SIGMOID_BIAS, false, false},
- {MoERoutingType::SIGMOID_BIAS, true, false},
- // trinity-mini afmoe: SIGMOID_BIAS + extra Multiply(routed_scaling_factor)
- {MoERoutingType::SIGMOID_BIAS, false, true},
- {MoERoutingType::SIGMOID_BIAS, true, true},
- }),
+ ::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) {
diff --git a/src/tests/test_utils/common_test_utils/include/common_test_utils/node_builders/moe_builders.hpp b/src/tests/test_utils/common_test_utils/include/common_test_utils/node_builders/moe_builders.hpp
index 80b8caaa6fc..10676c33d15 100644
--- a/src/tests/test_utils/common_test_utils/include/common_test_utils/node_builders/moe_builders.hpp
+++ b/src/tests/test_utils/common_test_utils/include/common_test_utils/node_builders/moe_builders.hpp
@@ -31,15 +31,20 @@ enum class MoERoutingType {
};
enum class MoEActivationType {
- SWISH, ///< Swish gate activation (SwiGLU)
- GELU, ///< Gelu gate activation (GeGLU)
+ SWISH, ///< Swish gate activation (SwiGLU)
+ GELU, ///< Gelu gate activation with Tanh approximation (GeGLU-Tanh)
+ GELU_ERF, ///< Gelu gate activation with ERF (exact) formula (GeGLU-ERF)
};
/// Softmax branch:
/// routing_weights -> Softmax -> TopK -> ReduceSum -> Divide (norm)
+/// [-> Multiply(norm, Gather(per_expert_scale, topk_idx)) when use_per_expert_scale=true]
/// -> ScatterElementsUpdate -> Transpose -> Reshape -> Unsqueeze
-std::pair<ov::Output<ov::Node>, ov::Output<ov::Node>>
-build_softmax_routing_subgraph(const ov::Output<ov::Node>& routing_weights, size_t number_of_experts, size_t topk);
+std::pair<ov::Output<ov::Node>, ov::Output<ov::Node>> build_softmax_routing_subgraph(
+ const ov::Output<ov::Node>& routing_weights,
+ size_t number_of_experts,
+ size_t topk,
+ bool use_per_expert_scale = false);
/// Sigmoid+bias branch:
/// routing_weights -> Sigmoid -> Add(bias) -> TopK -> Convert(i32)
@@ -76,7 +81,9 @@ std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(
const std::optional<bool> reshape_on_decompression = std::nullopt,
const std::optional<int> decompression_group_size = std::nullopt,
MoERoutingType routing_type = MoERoutingType::SOFTMAX,
- MoEActivationType activation_type = MoEActivationType::SWISH);
+ MoEActivationType activation_type = MoEActivationType::SWISH,
+ bool use_per_expert_scale = false,
+ bool use_layernorm_multiply = false);
} // namespace test
} // namespace ov
diff --git a/src/tests/test_utils/common_test_utils/src/node_builders/moe_builders.cpp b/src/tests/test_utils/common_test_utils/src/node_builders/moe_builders.cpp
index 383de88531a..bb7a38092b0 100644
--- a/src/tests/test_utils/common_test_utils/src/node_builders/moe_builders.cpp
+++ b/src/tests/test_utils/common_test_utils/src/node_builders/moe_builders.cpp
@@ -44,8 +44,11 @@
namespace ov {
namespace test {
-std::pair<ov::Output<ov::Node>, ov::Output<ov::Node>>
-build_softmax_routing_subgraph(const ov::Output<ov::Node>& routing_weights, size_t number_of_experts, size_t topk) {
+std::pair<ov::Output<ov::Node>, ov::Output<ov::Node>> build_softmax_routing_subgraph(
+ const ov::Output<ov::Node>& routing_weights,
+ size_t number_of_experts,
+ size_t topk,
+ bool use_per_expert_scale) {
using namespace ov::op;
auto router_softmax = std::make_shared<v8::Softmax>(routing_weights, 1);
@@ -61,6 +64,15 @@ build_softmax_routing_subgraph(const ov::Output<ov::Node>& routing_weights, size
auto scatter_w = ov::Output<ov::Node>{std::make_shared<v1::Divide>(router_topk->output(0), reduce_sm)};
auto topk_idx = router_topk->output(1);
+ if (use_per_expert_scale) {
+ const auto elem_type = routing_weights.get_element_type();
+ auto pes_data = ov::test::utils::InputGenerateData(0.5, 2, 100, 42);
+ auto per_expert_scale_const = ov::test::utils::make_constant(elem_type, ov::Shape{number_of_experts}, pes_data);
+ auto gather_axis = v0::Constant::create(ov::element::i32, ov::Shape{}, {0});
+ auto gathered_scales = std::make_shared<v8::Gather>(per_expert_scale_const, topk_idx, gather_axis);
+ scatter_w = std::make_shared<v1::Multiply>(scatter_w, gathered_scales);
+ }
+
auto shapeof = std::make_shared<v3::ShapeOf>(topk_idx);
auto gather = std::make_shared<v8::Gather>(shapeof,
v0::Constant::create(ov::element::i64, ov::Shape{}, {0}),
@@ -462,7 +474,9 @@ std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(
const std::optional<bool> reshape_on_decompression,
const std::optional<int> decompression_group_size,
MoERoutingType routing_type,
- MoEActivationType activation_type) {
+ MoEActivationType activation_type,
+ bool use_per_expert_scale,
+ bool use_layernorm_multiply) {
// Use parameters from shape_params - static shapes only
const auto& input_shape = moe_params.data_shape;
const size_t intermediate_size = moe_params.intermediate_size;
@@ -478,6 +492,14 @@ std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(
auto input = std::make_shared<ov::op::v0::Parameter>(data_precision, input_shape);
ov::Output<ov::Node> input_data = input;
+ // Gemma4 pattern: layernorm Multiply sits between Parameter and Reshape.
+ // The fused MOE's hidden_states input must be the Multiply output, not the Parameter.
+ if (use_layernorm_multiply) {
+ auto ln_data = ov::test::utils::InputGenerateData(0.5, 2, 100, 99);
+ auto ln_scale = ov::test::utils::make_constant(data_precision, ov::Shape{1, 1, hidden_size}, ln_data);
+ input_data = std::make_shared<ov::op::v1::Multiply>(input_data, ln_scale);
+ }
+
// Expert processing path - use -1 for dynamic reshape like in reference
auto experts_reshape = std::make_shared<ov::op::v1::Reshape>(
input_data,
@@ -519,10 +541,12 @@ std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(
gate_matmul->set_friendly_name("GateMatMul");
- // Apply gate activation (Swish for SwiGLU, Gelu for GeGLU)
+ // Apply gate activation (Swish for SwiGLU, Tanh-approximated Gelu for GeGLU, ERF Gelu for GeGLU-ERF)
std::shared_ptr<ov::Node> gate_act;
if (activation_type == MoEActivationType::GELU) {
- gate_act = std::make_shared<ov::op::v7::Gelu>(gate_matmul);
+ gate_act = std::make_shared<ov::op::v7::Gelu>(gate_matmul, ov::op::GeluApproximationMode::TANH);
+ } else if (activation_type == MoEActivationType::GELU_ERF) {
+ gate_act = std::make_shared<ov::op::v7::Gelu>(gate_matmul, ov::op::GeluApproximationMode::ERF);
} else {
gate_act = std::make_shared<ov::op::v4::Swish>(gate_matmul);
}
@@ -577,14 +601,23 @@ std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(
reshape_on_decompression,
decompression_group_size);
- auto router_matmul = std::make_shared<ov::op::v0::MatMul>(experts_reshape, router_weights_moe3, false, true);
+ // Gemma-4 style: the router uses a separately RMSNorm-scaled hidden state (different node
+ // from the expert path's experts_reshape).
+ ov::Output<ov::Node> router_input = experts_reshape;
+ if (use_per_expert_scale) {
+ auto pes_data = ov::test::utils::InputGenerateData(0.5, 2, 100, 42);
+ auto router_norm_scale = ov::test::utils::make_constant(data_precision, ov::Shape{1, hidden_size}, pes_data);
+ router_input = std::make_shared<ov::op::v1::Multiply>(experts_reshape, router_norm_scale);
+ }
+ auto router_matmul = std::make_shared<ov::op::v0::MatMul>(router_input, router_weights_moe3, false, true);
std::pair<ov::Output<ov::Node>, ov::Output<ov::Node>> routing_outputs;
switch (routing_type) {
case MoERoutingType::SOFTMAX:
- routing_outputs = build_softmax_routing_subgraph(router_matmul, number_of_experts, topk);
+ routing_outputs = build_softmax_routing_subgraph(router_matmul, number_of_experts, topk, use_per_expert_scale);
break;
case MoERoutingType::SIGMOID_BIAS:
+ OPENVINO_ASSERT(!use_per_expert_scale, "Per-expert scale is only supported for SOFTMAX routing");
routing_outputs = build_sigmoid_bias_routing_subgraph(router_matmul, data_precision, number_of_experts, topk);
break;
default: