OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[Transformations] MoE 3 Gemm pattern: Gelu activation support (#35618)
Vladislav Golubevd814408d6f9b
diff --git a/src/common/transformations/src/transformations/common_optimizations/convert_tiled_moe_block_to_gather_matmuls.cpp b/src/common/transformations/src/transformations/common_optimizations/convert_tiled_moe_block_to_gather_matmuls.cppindex c06b6740a19..ff7d4bac8e8 100644--- a/src/common/transformations/src/transformations/common_optimizations/convert_tiled_moe_block_to_gather_matmuls.cpp+++ b/src/common/transformations/src/transformations/common_optimizations/convert_tiled_moe_block_to_gather_matmuls.cpp@@ -12,6 +12,7 @@#include "openvino/op/add.hpp"#include "openvino/op/clamp.hpp"#include "openvino/op/constant.hpp"+#include "openvino/op/gelu.hpp"#include "openvino/op/matmul.hpp"#include "openvino/op/minimum.hpp"#include "openvino/op/multiply.hpp"@@ -35,6 +36,7 @@ namespace v0 = ov::op::v0;namespace v1 = ov::op::v1;namespace v3 = ov::op::v3;namespace v4 = ov::op::v4;+namespace v7 = ov::op::v7;namespace v8 = ov::op::v8;namespace v12 = ov::op::v12;@@ -137,7 +139,7 @@ struct MOE3GEMMPatternNodes {MOE3GEMMPatternNodes build_3gemm_pattern() {MOE3GEMMPatternNodes p;- p.experts_input = pattern::wrap_type<v1::Reshape>({pattern::any_input(), pattern::any_input()});+ p.experts_input = pattern::any_input();p.tile = pattern::wrap_type<v0::Tile>({p.experts_input, pattern::any_input()}, pattern::consumers_count(1));p.after_tile_reshape = pattern::wrap_type<v1::Reshape>({p.tile, pattern::any_input()}, pattern::consumers_count(2));@@ -145,7 +147,7 @@ MOE3GEMMPatternNodes build_3gemm_pattern() {p.gate_matmul = pattern::wrap_type<v0::MatMul>({p.after_tile_reshape, pattern::any_input()},pattern::consumers_count(1) && pattern::attrs_match({{"transpose_a", false}, {"transpose_b", true}}));- p.swish = pattern::wrap_type<v4::Swish>({p.gate_matmul}, pattern::consumers_count(1));+ p.swish = pattern::wrap_type<v4::Swish, v7::Gelu>({p.gate_matmul}, pattern::consumers_count(1));// Second GEMM (up_projection)p.up_matmul = pattern::wrap_type<v0::MatMul>({p.after_tile_reshape, pattern::any_input()},diff --git a/src/common/transformations/tests/common_optimizations/convert_tiled_moe_block_to_gather_matmuls_test.cpp b/src/common/transformations/tests/common_optimizations/convert_tiled_moe_block_to_gather_matmuls_test.cppindex cf3abbf5883..6565590cc60 100644--- a/src/common/transformations/tests/common_optimizations/convert_tiled_moe_block_to_gather_matmuls_test.cpp+++ b/src/common/transformations/tests/common_optimizations/convert_tiled_moe_block_to_gather_matmuls_test.cpp@@ -19,6 +19,7 @@#include "openvino/op/concat.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/divide.hpp"+#include "openvino/op/gelu.hpp"#include "openvino/op/matmul.hpp"#include "openvino/op/minimum.hpp"#include "openvino/op/multiply.hpp"@@ -57,6 +58,8 @@ inline std::ostream& operator<<(std::ostream& os, const MoEType& type) {}}+enum class GateActivationType { SWISH, GELU };+enum class AdditionalConsumersMode { NO, MATMULS, AFTER_MATMULS, REDUCE };inline std::ostream& operator<<(std::ostream& os, const AdditionalConsumersMode& mode) {@@ -80,6 +83,8 @@ using ConvertTiledMoeBlockToGatherMatmulsParams = std::tuple<MoEType,bool, // skip_unsqueezebool, // matmul_transpose_bAdditionalConsumersMode, // additional_consumers_mode+ bool, // use_gelu_gate (3GeMM only)+ bool, // norm_before_tile (3GeMM only)bool>; // transformation_should_be_appliedinline std::shared_ptr<ov::Node> build_matmul_weights(const ov::Shape& weights_shape,@@ -461,7 +466,10 @@ inline std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(bool use_scatter_v12,bool use_broadcast_v3,bool skip_unsqueeze,bool matmul_transpose_b,- AdditionalConsumersMode additional_consumers_mode) {+ AdditionalConsumersMode additional_consumers_mode,+ GateActivationType gate_activation = GateActivationType::SWISH,+ bool norm_before_tile = false,+ bool use_normalized_router = true) {// Fixed values that don't affect pass behaviorconst ov::PartialShape input_shape = {-1, -1, 256};const size_t topk = 4;@@ -481,8 +489,15 @@ inline std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(bool use_scatter_v12,std::vector<int64_t>{-1, static_cast<int64_t>(hidden_size)}), // -1 flattens batch*seq_lenfalse);+ // Optional normalization scaling (e.g. RMS-norm) before tile+ std::shared_ptr<ov::Node> tile_input = experts_reshape;+ if (norm_before_tile) {+ auto scale_const = ov::op::v0::Constant::create(data_precision, ov::Shape{}, {0.7071f});+ tile_input = std::make_shared<ov::op::v1::Multiply>(experts_reshape, scale_const);+ }+auto tile = std::make_shared<ov::op::v0::Tile>(- experts_reshape,+ tile_input,ov::op::v0::Constant::create(ov::element::i64,ov::Shape{2},std::vector<int64_t>{static_cast<int64_t>(number_of_experts), 1}));@@ -507,7 +522,13 @@ inline std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(bool use_scatter_v12,gate_matmul->set_friendly_name("GateMatMul");- auto swish = std::make_shared<ov::op::v4::Swish>(gate_matmul);+ // Gate activation: Swish (SwiGLU) or Gelu (GeGLU)+ std::shared_ptr<ov::Node> gate_act;+ if (gate_activation == GateActivationType::GELU) {+ gate_act = std::make_shared<ov::op::v7::Gelu>(gate_matmul);+ } else {+ gate_act = std::make_shared<ov::op::v4::Swish>(gate_matmul);+ }auto up_weights = build_matmul_weights(ov::Shape{number_of_experts, hidden_size, intermediate_size},weights_precision,seed++,@@ -517,7 +538,7 @@ inline std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(bool use_scatter_v12,up_matmul->set_friendly_name("UpMatMul");- auto swiglu = std::make_shared<ov::op::v1::Multiply>(swish, up_matmul);+ auto swiglu = std::make_shared<ov::op::v1::Multiply>(gate_act, up_matmul);auto down_weights = build_matmul_weights(ov::Shape{number_of_experts, intermediate_size, hidden_size},weights_precision,@@ -534,29 +555,44 @@ inline std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(bool use_scatter_v12,auto reshape_2nd_consumer_router_matmul =std::make_shared<ov::op::v0::MatMul>(experts_reshape, router_weights, false, matmul_transpose_b);- auto router_softmax = std::make_shared<ov::op::v1::Softmax>(reshape_2nd_consumer_router_matmul, 1);-- auto router_topk_values_and_indices =- std::make_shared<ov::op::v11::TopK>(router_softmax,- ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {topk}),- -1,- ov::op::v11::TopK::Mode::MAX,- ov::op::v11::TopK::SortType::SORT_VALUES,- ov::element::i64);-- auto router_topk_values_reduce = std::make_shared<ov::op::v1::ReduceSum>(- router_topk_values_and_indices->output(0),- ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{-1}),- true);- auto router_topk_values_normalization =- std::make_shared<ov::op::v1::Divide>(router_topk_values_and_indices->output(0), router_topk_values_reduce);- auto router_topk_indices = router_topk_values_and_indices->output(1);+ // Router: normalized (softmax + topk normalization) or simple (raw TopK values)+ ov::Output<ov::Node> router_topk_indices;+ ov::Output<ov::Node> chosen_experts;+ if (use_normalized_router) {+ auto router_softmax = std::make_shared<ov::op::v1::Softmax>(reshape_2nd_consumer_router_matmul, 1);++ auto router_topk_values_and_indices =+ std::make_shared<ov::op::v11::TopK>(router_softmax,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {topk}),+ -1,+ ov::op::v11::TopK::Mode::MAX,+ ov::op::v11::TopK::SortType::SORT_VALUES,+ ov::element::i64);++ auto router_topk_values_reduce = std::make_shared<ov::op::v1::ReduceSum>(+ router_topk_values_and_indices->output(0),+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{-1}),+ true);+ auto router_topk_values_normalization =+ std::make_shared<ov::op::v1::Divide>(router_topk_values_and_indices->output(0), router_topk_values_reduce);+ router_topk_indices = router_topk_values_and_indices->output(1);+ chosen_experts = router_topk_values_normalization;+ } else {+ auto router_topk_values_and_indices =+ std::make_shared<ov::op::v11::TopK>(reshape_2nd_consumer_router_matmul,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {topk}),+ -1,+ ov::op::v11::TopK::Mode::MAX,+ ov::op::v11::TopK::SortType::SORT_VALUES,+ ov::element::i64);+ router_topk_indices = router_topk_values_and_indices->output(1);+ chosen_experts = router_topk_values_and_indices->output(0);+ }const auto number_of_experts_const =ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {static_cast<int64_t>(number_of_experts)});- auto zero_const =- ov::op::v0::Constant::create(router_topk_values_normalization->get_output_element_type(0), ov::Shape{1}, {0});+ auto zero_const = ov::op::v0::Constant::create(chosen_experts.get_element_type(), ov::Shape{1}, {0});auto first_topk_dim = ov::op::util::node_to_get_shape_value_of_indices_from_shape_source(router_topk_indices, {0});auto bcast_target_shape =std::make_shared<ov::op::v0::Concat>(ov::OutputVector{first_topk_dim, number_of_experts_const}, 0);@@ -573,13 +609,13 @@ inline std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(bool use_scatter_v12,scatter_elements_update = std::make_shared<ov::op::v12::ScatterElementsUpdate>(broadcast_zero,router_topk_indices,- router_topk_values_normalization,+ chosen_experts,ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{1}));} else {scatter_elements_update = std::make_shared<ov::op::v3::ScatterElementsUpdate>(broadcast_zero,router_topk_indices,- router_topk_values_normalization,+ chosen_experts,ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{1}));}@@ -631,14 +667,19 @@ inline std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(bool use_scatter_v12,auto final_reshape = std::make_shared<ov::op::v1::Reshape>(reduce_sum, final_reshape_const, true);ov::ParameterVector params = {input};- ov::ResultVector results = {std::make_shared<ov::op::v0::Result>(final_reshape)};+ ov::ResultVector results;+ if (use_normalized_router) {+ results.push_back(std::make_shared<ov::op::v0::Result>(final_reshape));+ } else {+ results.push_back(std::make_shared<ov::op::v0::Result>(reduce_sum));+ }if (additional_consumers_mode == AdditionalConsumersMode::MATMULS) {results.push_back(std::make_shared<ov::op::v0::Result>(gate_matmul));results.push_back(std::make_shared<ov::op::v0::Result>(up_matmul));results.push_back(std::make_shared<ov::op::v0::Result>(down_matmul));} else if (additional_consumers_mode == AdditionalConsumersMode::AFTER_MATMULS) {- results.push_back(std::make_shared<ov::op::v0::Result>(swish));+ results.push_back(std::make_shared<ov::op::v0::Result>(gate_act));results.push_back(std::make_shared<ov::op::v0::Result>(swiglu));} else if (additional_consumers_mode == AdditionalConsumersMode::REDUCE) {results.push_back(std::make_shared<ov::op::v0::Result>(reduce_sum));@@ -647,10 +688,14 @@ inline std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(bool use_scatter_v12,return std::make_shared<ov::Model>(results, params);}-inline std::shared_ptr<ov::Model> initMoE3GeMMSubgraphRef(bool use_scatter_v12,- bool use_broadcast_v3,- bool skip_unsqueeze,- bool matmul_transpose_b) {+inline std::shared_ptr<ov::Model> initMoE3GeMMSubgraphRef(+ bool use_scatter_v12,+ bool use_broadcast_v3,+ bool skip_unsqueeze,+ bool matmul_transpose_b,+ GateActivationType gate_activation = GateActivationType::SWISH,+ bool norm_before_tile = false,+ bool use_normalized_router = true) {// Fixed values that don't affect pass behaviorconst ov::PartialShape input_shape = {-1, -1, 256};const size_t topk = 4;@@ -670,33 +715,58 @@ inline std::shared_ptr<ov::Model> initMoE3GeMMSubgraphRef(bool use_scatter_v12,std::vector<int64_t>{-1, static_cast<int64_t>(hidden_size)}),false);+ // The transformation captures experts_input (the Tile's direct predecessor) and unsqueezes it.+ // When norm_before_tile=true, experts_input is the norm_multiply node, not experts_reshape.+ std::shared_ptr<ov::Node> experts_input = experts_reshape;+ if (norm_before_tile) {+ auto scale_const = ov::op::v0::Constant::create(data_precision, ov::Shape{}, {0.7071f});+ experts_input = std::make_shared<ov::op::v1::Multiply>(experts_reshape, scale_const);+ }+auto unsqueeze_experts =- std::make_shared<ov::op::v0::Unsqueeze>(experts_reshape,+ std::make_shared<ov::op::v0::Unsqueeze>(experts_input,ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0}));+ // Router weights always use seed=4 (4th in the source model's seed sequence)auto router_weights =build_matmul_weights(ov::Shape{hidden_size, number_of_experts}, weights_precision, 4, matmul_transpose_b);auto reshape_2nd_consumer_router_matmul =std::make_shared<ov::op::v0::MatMul>(experts_reshape, router_weights, false, matmul_transpose_b);- auto router_softmax = std::make_shared<ov::op::v1::Softmax>(reshape_2nd_consumer_router_matmul, 1);-- auto router_topk_values_and_indices =- std::make_shared<ov::op::v11::TopK>(router_softmax,- ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {topk}),- -1,- ov::op::v11::TopK::Mode::MAX,- ov::op::v11::TopK::SortType::SORT_VALUES,- ov::element::i64);-- auto router_topk_values_reduce = std::make_shared<ov::op::v1::ReduceSum>(- router_topk_values_and_indices->output(0),- ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{-1}),- true);- auto router_topk_values_normalization =- std::make_shared<ov::op::v1::Divide>(router_topk_values_and_indices->output(0), router_topk_values_reduce);- auto router_topk_indices = router_topk_values_and_indices->output(1);+ // Router: normalized (softmax + normalization) or simple (raw TopK values)+ ov::Output<ov::Node> router_topk_indices;+ ov::Output<ov::Node> chosen_experts;+ if (use_normalized_router) {+ auto router_softmax = std::make_shared<ov::op::v1::Softmax>(reshape_2nd_consumer_router_matmul, 1);++ auto router_topk_values_and_indices =+ std::make_shared<ov::op::v11::TopK>(router_softmax,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {topk}),+ -1,+ ov::op::v11::TopK::Mode::MAX,+ ov::op::v11::TopK::SortType::SORT_VALUES,+ ov::element::i64);++ auto router_topk_values_reduce = std::make_shared<ov::op::v1::ReduceSum>(+ router_topk_values_and_indices->output(0),+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{-1}),+ true);+ auto router_topk_values_normalization =+ std::make_shared<ov::op::v1::Divide>(router_topk_values_and_indices->output(0), router_topk_values_reduce);+ router_topk_indices = router_topk_values_and_indices->output(1);+ chosen_experts = router_topk_values_normalization;+ } else {+ auto router_topk_values_and_indices =+ std::make_shared<ov::op::v11::TopK>(reshape_2nd_consumer_router_matmul,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {topk}),+ -1,+ ov::op::v11::TopK::Mode::MAX,+ ov::op::v11::TopK::SortType::SORT_VALUES,+ ov::element::i64);+ router_topk_indices = router_topk_values_and_indices->output(1);+ chosen_experts = router_topk_values_and_indices->output(0);+ }// Note: we need to use different seed to avoid the exact weights generation for the MatMuls with the same shapeint seed = 1;@@ -707,7 +777,13 @@ inline std::shared_ptr<ov::Model> initMoE3GeMMSubgraphRef(bool use_scatter_v12,auto gate_gathered_mm = std::make_shared<GatherMatmul>(unsqueeze_experts, gate_weights, router_topk_indices);- auto swish = std::make_shared<ov::op::v4::Swish>(gate_gathered_mm);+ // Gate activation: Swish (SwiGLU) or Gelu (GeGLU)+ std::shared_ptr<ov::Node> gate_act;+ if (gate_activation == GateActivationType::GELU) {+ gate_act = std::make_shared<ov::op::v7::Gelu>(gate_gathered_mm);+ } else {+ gate_act = std::make_shared<ov::op::v4::Swish>(gate_gathered_mm);+ }auto up_weights = build_matmul_weights(ov::Shape{number_of_experts, hidden_size, intermediate_size},weights_precision,@@ -716,7 +792,7 @@ inline std::shared_ptr<ov::Model> initMoE3GeMMSubgraphRef(bool use_scatter_v12,auto up_gathered_mm = std::make_shared<GatherMatmul>(unsqueeze_experts, up_weights, router_topk_indices);- auto swiglu = std::make_shared<ov::op::v1::Multiply>(swish, up_gathered_mm);+ auto swiglu = std::make_shared<ov::op::v1::Multiply>(gate_act, up_gathered_mm);auto down_weights = build_matmul_weights(ov::Shape{number_of_experts, intermediate_size, hidden_size},weights_precision,@@ -725,8 +801,9 @@ inline std::shared_ptr<ov::Model> initMoE3GeMMSubgraphRef(bool use_scatter_v12,auto down_gathered_mm = std::make_shared<GatherMatmul>(swiglu, down_weights, router_topk_indices);+ // The transformation replaces the scatter chain with transpose + unsqueeze of chosen_expertsauto router_transpose = std::make_shared<ov::op::v1::Transpose>(- router_topk_values_normalization,+ chosen_experts,ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{1, 0}));auto router_unsqueeze =@@ -759,13 +836,17 @@ inline std::shared_ptr<ov::Model> initMoE3GeMMSubgraphRef(bool use_scatter_v12,auto final_reshape = std::make_shared<ov::op::v1::Reshape>(reduce_sum, slice_shape, true);- auto final_reshape_const = ov::op::v0::Constant::create(ov::element::i64,- ov::Shape{2},- std::vector<int64_t>{0, static_cast<int64_t>(hidden_size)});- auto original_final_reshape = std::make_shared<ov::op::v1::Reshape>(final_reshape, final_reshape_const, true);-ov::ParameterVector params = {input};- return std::make_shared<ov::Model>(ov::OutputVector{original_final_reshape}, params);+ if (use_normalized_router) {+ auto final_reshape_const =+ ov::op::v0::Constant::create(ov::element::i64,+ ov::Shape{2},+ std::vector<int64_t>{0, static_cast<int64_t>(hidden_size)});+ auto original_final_reshape = std::make_shared<ov::op::v1::Reshape>(final_reshape, final_reshape_const, true);+ return std::make_shared<ov::Model>(ov::OutputVector{original_final_reshape}, params);+ } else {+ return std::make_shared<ov::Model>(ov::OutputVector{final_reshape}, params);+ }}class ConvertTiledMoeBlockToGatherMatmulsTest : public TransformationTestsF,@@ -778,12 +859,16 @@ public:skip_unsqueeze,matmul_transpose_b,additional_consumers_mode,+ use_gelu_gate,+ norm_before_tile,should_be_applied] = obj.param;std::ostringstream result;result << "MoEType_" << moe_type << "_ScatterV" << (use_scatter_v12 ? "12" : "3") << "_BroadcastV"<< (use_broadcast_v3 ? "3" : "1") << "_SkipUnsqueeze_" << (skip_unsqueeze ? "true" : "false")<< "_MatMulTransposeB_" << (matmul_transpose_b ? "true" : "false") << "_AdditionalConsumers_"- << additional_consumers_mode << "_shouldBeApplied_" << (should_be_applied ? "true" : "false");+ << additional_consumers_mode << "_GeluGate_" << (use_gelu_gate ? "true" : "false") << "_NormBeforeTile_"+ << (norm_before_tile ? "true" : "false") << "_shouldBeApplied_"+ << (should_be_applied ? "true" : "false");return result.str();}@@ -796,8 +881,18 @@ protected:skip_unsqueeze,matmul_transpose_b,additional_consumers_mode,+ use_gelu_gate,+ norm_before_tile,should_be_applied] = this->GetParam();+ // 3GeMM-only params must be false for MoE2GeMM+ ASSERT_FALSE(moe_type == MoEType::MoE2GeMM && use_gelu_gate) << "use_gelu_gate must be false for MoE2GeMM";+ ASSERT_FALSE(moe_type == MoEType::MoE2GeMM && norm_before_tile)+ << "norm_before_tile must be false for MoE2GeMM";++ const auto gate_act = use_gelu_gate ? GateActivationType::GELU : GateActivationType::SWISH;+ const bool use_normalized_router = !use_gelu_gate && !norm_before_tile;+switch (moe_type) {case MoEType::MoE2GeMM:model = initMoE2GeMMSubgraph(use_scatter_v12,@@ -811,7 +906,10 @@ protected:use_broadcast_v3,skip_unsqueeze,matmul_transpose_b,- additional_consumers_mode);+ additional_consumers_mode,+ gate_act,+ norm_before_tile,+ use_normalized_router);break;default:OPENVINO_THROW("Unexpected MoEType value");@@ -826,8 +924,13 @@ protected:initMoE2GeMMSubgraphRef(use_scatter_v12, use_broadcast_v3, skip_unsqueeze, matmul_transpose_b);break;case MoEType::MoE3GeMM:- model_ref =- initMoE3GeMMSubgraphRef(use_scatter_v12, use_broadcast_v3, skip_unsqueeze, matmul_transpose_b);+ model_ref = initMoE3GeMMSubgraphRef(use_scatter_v12,+ use_broadcast_v3,+ skip_unsqueeze,+ matmul_transpose_b,+ gate_act,+ norm_before_tile,+ use_normalized_router);break;default:OPENVINO_THROW("Unexpected MoEType value");@@ -851,6 +954,21 @@ INSTANTIATE_TEST_SUITE_P(ConvertTiledMoeBlockToGatherMatmulsTest_positive_cases,::testing::ValuesIn(skip_unsqueeze_versions),::testing::Values(true),::testing::Values(AdditionalConsumersMode::NO),+ ::testing::Values(false),+ ::testing::Values(false),+ ::testing::Values(true)),+ ConvertTiledMoeBlockToGatherMatmulsTest::getTestCaseName);++INSTANTIATE_TEST_SUITE_P(ConvertTiledMoeBlockToGatherMatmulsTest_3gemm_specific_positive_cases,+ ConvertTiledMoeBlockToGatherMatmulsTest,+ ::testing::Combine(::testing::Values(MoEType::MoE3GeMM),+ ::testing::ValuesIn(scatter_versions),+ ::testing::ValuesIn(broadcast_versions),+ ::testing::ValuesIn(skip_unsqueeze_versions),+ ::testing::Values(true),+ ::testing::Values(AdditionalConsumersMode::NO),+ ::testing::Values(false, true),+ ::testing::Values(false, true),::testing::Values(true)),ConvertTiledMoeBlockToGatherMatmulsTest::getTestCaseName);@@ -862,6 +980,8 @@ INSTANTIATE_TEST_SUITE_P(ConvertTiledMoeBlockToGatherMatmulsTest_negative_cases_::testing::ValuesIn(skip_unsqueeze_versions),::testing::Values(false),::testing::Values(AdditionalConsumersMode::NO),+ ::testing::Values(false),+ ::testing::Values(false),::testing::Values(false)),ConvertTiledMoeBlockToGatherMatmulsTest::getTestCaseName);@@ -875,6 +995,8 @@ INSTANTIATE_TEST_SUITE_P(ConvertTiledMoeBlockToGatherMatmulsTest_negative_cases_::testing::Values(AdditionalConsumersMode::MATMULS,AdditionalConsumersMode::AFTER_MATMULS,AdditionalConsumersMode::REDUCE),+ ::testing::Values(false),+ ::testing::Values(false),::testing::Values(false)),ConvertTiledMoeBlockToGatherMatmulsTest::getTestCaseName);} // namespacediff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/moe.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/moe.cppindex 68b657accc1..7a1e7e9da95 100644--- a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/moe.cpp+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/moe.cpp@@ -32,6 +32,17 @@ inline std::ostream& operator<<(std::ostream& os, const MoEType& type) {}}+inline std::ostream& operator<<(std::ostream& os, const MoEActivationType& type) {+ switch (type) {+ case MoEActivationType::SWISH:+ return os << "SWISH";+ case MoEActivationType::GELU:+ return os << "GELU";+ default:+ OPENVINO_THROW("Unsupported MoEActivationType");+ }+}+struct MoeTestShapeParams {InputShape data_shape;size_t topk;@@ -40,14 +51,16 @@ struct MoeTestShapeParams {};using MoeTestParams = std::tuple<MoeTestShapeParams,- MoEType, // MoE builder type- ov::AnyMap>; // additional config+ MoEType, // MoE builder type+ MoEActivationType, // gate activation type (3GeMM only)+ ov::AnyMap>; // additional configusing MoeCompressedWeightsTestParams = std::tuple<MoeTestShapeParams,- MoEType, // MoE builder type- ov::test::ElementType, // weights precision- ov::test::ElementType, // decompression precision- ov::test::ElementType, // scale precision+ MoEType, // MoE builder type+ MoEActivationType, // gate activation type (3GeMM only)+ ov::test::ElementType, // weights precision+ ov::test::ElementType, // decompression precision+ ov::test::ElementType, // scale precisionov::test::utils::DecompressionType, // decompression multiply typeov::test::utils::DecompressionType, // decompression subtract typebool, // reshape on decompression constants@@ -82,8 +95,11 @@ public:return result.str();}static std::string getTestCaseName(const testing::TestParamInfo<MoeTestParams>& obj) {- const auto& [moe_params, moe_type, additional_config] = obj.param;- return generateBaseMoeTestName(moe_params, moe_type, additional_config);+ const auto& [moe_params, moe_type, activation_type, additional_config] = obj.param;+ std::ostringstream result;+ result << generateBaseMoeTestName(moe_params, moe_type, additional_config);+ result << "_act=" << activation_type;+ return result.str();}static size_t get_expected_gather_mm_count(MoEType moe_type) {@@ -112,7 +128,7 @@ public:protected:void SetUp() override {targetDevice = ov::test::utils::DEVICE_CPU;- const auto& [moe_params, moe_type, additional_config] = GetParam();+ const auto& [moe_params, moe_type, activation_type, additional_config] = GetParam();configuration.insert(additional_config.begin(), additional_config.end());init_input_shapes({moe_params.data_shape});@@ -130,9 +146,21 @@ protected:}if (moe_type == MoEType::MoE2GeMM) {+ ASSERT_TRUE(activation_type == MoEActivationType::SWISH) << "MoE2GeMM only supports SWISH activation";function = initMoE2GeMMSubgraph(shape_params, ov::element::f32, ov::element::f32);} else if (moe_type == MoEType::MoE3GeMM) {- function = initMoE3GeMMSubgraph(shape_params, ov::element::f32, ov::element::f32);+ function = initMoE3GeMMSubgraph(shape_params,+ ov::element::f32,+ ov::element::f32,+ false,+ std::nullopt,+ std::nullopt,+ std::nullopt,+ std::nullopt,+ std::nullopt,+ std::nullopt,+ MoERoutingType::SOFTMAX,+ activation_type);} else {OPENVINO_THROW("Unsupported MoEType");}@@ -153,6 +181,7 @@ public:static std::string getTestCaseName(const testing::TestParamInfo<MoeCompressedWeightsTestParams>& obj) {const auto& [moe_params,moe_type,+ activation_type,weights_precision,decompression_precision,scale_precision,@@ -164,6 +193,7 @@ public:use_matmul_decompression_impl] = obj.param;std::ostringstream result;result << MoESubgraphTest::generateBaseMoeTestName(moe_params, moe_type, additional_config) << "_";+ result << "act=" << activation_type << "_";result << "_WP=" << weights_precision << "_";result << "DP=" << decompression_precision << "_";result << "SP=" << scale_precision << "_";@@ -184,6 +214,7 @@ protected:const auto& [moe_params,moe_type,+ activation_type,weights_precision,decompression_precision,scale_precision,@@ -210,6 +241,7 @@ protected:}if (moe_type == MoEType::MoE2GeMM) {+ ASSERT_TRUE(activation_type == MoEActivationType::SWISH) << "MoE2GeMM only supports SWISH activation";function = initMoE2GeMMSubgraph(shape_params,ov::element::f32,weights_precision,@@ -230,7 +262,9 @@ protected:decompression_multiply_type,decompression_subtract_type,reshape_on_decompression,- decompression_group_size);+ decompression_group_size,+ MoERoutingType::SOFTMAX,+ activation_type);} else {OPENVINO_THROW("Unsupported MoEType");}@@ -259,8 +293,8 @@ protected:const size_t expected_gather_mm_count = MoESubgraphTest::get_expected_gather_mm_count(moe_type);EXPECT_EQ(gather_mm_nodes.size(), expected_gather_mm_count);- const ov::element::Type compressed_weights_precision = std::get<2>(test_param);- const bool use_matmul_decompression_impl = std::get<10>(test_param);+ const ov::element::Type compressed_weights_precision = std::get<3>(test_param);+ const bool use_matmul_decompression_impl = std::get<11>(test_param);for (const auto& gather_mm_node : gather_mm_nodes) {const auto& expected_weights_precision = use_matmul_decompression_impl? compressed_weights_precision@@ -315,6 +349,15 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoESubgraph_basic,MoESubgraphTest,::testing::Combine(::testing::ValuesIn(moe_params_smoke),::testing::ValuesIn(moe_types),+ ::testing::Values(MoEActivationType::SWISH),+ ::testing::ValuesIn(generate_additional_config())),+ MoESubgraphTest::getTestCaseName);++INSTANTIATE_TEST_SUITE_P(smoke_MoESubgraph_3gemm_gelu,+ MoESubgraphTest,+ ::testing::Combine(::testing::ValuesIn(moe_params_smoke),+ ::testing::Values(MoEType::MoE3GeMM),+ ::testing::Values(MoEActivationType::GELU),::testing::ValuesIn(generate_additional_config())),MoESubgraphTest::getTestCaseName);@@ -328,6 +371,23 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoeCompressedWeights,MoECompressedWeightsSubgraphTest,::testing::Combine(::testing::ValuesIn(moe_params_smoke),::testing::ValuesIn(moe_types),+ ::testing::Values(MoEActivationType::SWISH),+ ::testing::ValuesIn(weights_precisions),+ ::testing::ValuesIn(decompression_precisions),+ ::testing::Values(ov::element::f32),+ ::testing::Values(ov::test::utils::DecompressionType::full),+ ::testing::Values(ov::test::utils::DecompressionType::full),+ ::testing::Values(false), // reshape on decompression+ ::testing::Values(16), // decompression group size+ ::testing::ValuesIn(generate_additional_config()),+ ::testing::Values(true)), // use_matmul_decompression_impl+ MoECompressedWeightsSubgraphTest::getTestCaseName);++INSTANTIATE_TEST_SUITE_P(smoke_MoeCompressedWeights_3gemm_gelu,+ MoECompressedWeightsSubgraphTest,+ ::testing::Combine(::testing::ValuesIn(moe_params_smoke),+ ::testing::Values(MoEType::MoE3GeMM),+ ::testing::Values(MoEActivationType::GELU),::testing::ValuesIn(weights_precisions),::testing::ValuesIn(decompression_precisions),::testing::Values(ov::element::f32),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.cppindex 754898f729d..ab86fe910c1 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@@ -9,6 +9,7 @@namespace {using ov::test::InputShape;+using ov::test::MoEActivationType;using ov::test::MoERoutingType;enum class MoePatternType { GEMM3, GEMM2 };@@ -45,12 +46,14 @@ using MoECompressedParams = std::tuple<MoeTestShapeParams,ov::test::utils::DecompressionType, // subtract typebool, // reshape_on_decompressionint, // group_size- size_t>; // gate_idx (2-GEMM only)+ size_t, // gate_idx (2-GEMM only)+ bool, // force_gather_matmul+ MoEActivationType>; // gate activation type (GEMM3 only)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] = info.param;+ const auto& [moe_params, pattern_type, routing_type, wp, dp, sp, dm, ds, rd, gs, gi, fgm, act] = info.param;std::ostringstream result;result << "IS=" << ov::test::utils::partialShape2str({moe_params.data_shape.first}) << "_";result << "TS=";@@ -68,12 +71,18 @@ public:result << "DS=" << ds << "_";result << "RD=" << rd << "_";result << "GS=" << gs << "_";- result << "GI=" << gi;+ result << "GI=" << gi << "_";+ result << "FGM=" << fgm << "_";+ result << "act=" << (act == MoEActivationType::GELU ? "GELU" : "SWISH");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();+ if (fgm) {+ set_disable_moe_opt();+ }targetDevice = ov::test::utils::DEVICE_GPU;// MoE fusion (and the GatherMatmul-based fallback) is gated on supports_immad.const auto caps = core->get_property(targetDevice, ov::device::capabilities);@@ -85,8 +94,6 @@ protected:abs_threshold = 1.0;rel_threshold = 0.01;- const auto& [moe_params, pattern_type, routing_type, wp, dp, sp, dm, ds, rd, gs, gi] = GetParam();-// INSTANTIATE blocks below never produce GEMM2 + non-softmax; fail loudly if that ever changes.if (pattern_type == MoePatternType::GEMM2 && routing_type != MoERoutingType::SOFTMAX) {FAIL() << "2-GEMM pattern with non-softmax routing must not be instantiated";@@ -105,8 +112,10 @@ protected:ds, // decompression_subtract_typerd, // reshape_on_decompressiongs, // group_size- routing_type);+ routing_type,+ act); // activation_type} else {+ ASSERT_TRUE(act == MoEActivationType::SWISH) << "2-GEMM pattern only supports Swish activation";function = ov::test::initMoE2GeMMSubgraph(shape_params,ov::element::f32, // data_precisionwp, // weights_precision@@ -137,10 +146,43 @@ protected:void validate() override {ov::test::SubgraphBaseTest::validate();const auto pattern_type = std::get<1>(GetParam());- // GEMM3 → single fused moe_3gemm_fused_compressed; GEMM2 → gate_up + down = 2 moe_gemm ops.- ov::test::CheckNumberOfNodesWithType(compiledModel,- pattern_type == MoePatternType::GEMM3 ? "moe_3gemm_fused_compressed" : "moe_gemm",- pattern_type == MoePatternType::GEMM3 ? 1 : 2);+ 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) {+ // 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 {+ // GEMM3 → single fused moe_3gemm_fused_compressed; GEMM2 → gate_up + down = 2 moe_gemm ops.+ ov::test::CheckNumberOfNodesWithType(compiledModel,+ pattern_type == MoePatternType::GEMM3 ? "moe_3gemm_fused_compressed" : "moe_gemm",+ pattern_type == MoePatternType::GEMM3 ? 1 : 2);+ }+ }++ void TearDown() override {+ ov::test::SubgraphBaseTest::TearDown();+ if (std::get<11>(GetParam())) {+ unset_disable_moe_opt();+ }+ }++private:+ static void set_disable_moe_opt() {+#ifdef _WIN32+ _putenv_s("OV_GPU_DISABLE_MOE_OPT", "1");+#else+ ::setenv("OV_GPU_DISABLE_MOE_OPT", "1", 1);+#endif+ }++ static void unset_disable_moe_opt() {+#ifdef _WIN32+ _putenv_s("OV_GPU_DISABLE_MOE_OPT", "");+#else+ ::unsetenv("OV_GPU_DISABLE_MOE_OPT");+#endif}};@@ -188,7 +230,9 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoE3GemmCompressedFusion,::testing::Values(ov::test::utils::DecompressionType::full),::testing::Values(true), // reshape_on_decompression::testing::Values(128),- ::testing::Values(size_t{0})), // gate_idx unused for GEMM3+ ::testing::Values(size_t{0}), // gate_idx unused for GEMM3+ ::testing::Values(false), // force_gather_matmul+ ::testing::Values(MoEActivationType::SWISH)),MoECompressedFusionTest::getTestCaseName);// GPT-OSS 2-GEMM pattern (combined gate/up MatMul + Slice/Clamp/Add/Swish).@@ -205,50 +249,13 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoE2GemmCompressedFusion,::testing::Values(ov::test::utils::DecompressionType::full),::testing::Values(true), // reshape_on_decompression::testing::Values(128),- ::testing::ValuesIn(gate_idx_values)),+ ::testing::ValuesIn(gate_idx_values),+ ::testing::Values(false), // force_gather_matmul+ ::testing::Values(MoEActivationType::SWISH)),MoECompressedFusionTest::getTestCaseName);-// MOE fusion disabled — exercises GatherMatmulCompressed directly.-// disable_moe_opt is a debug option; only honored via env var, not properties.-class MoEGatherMatmulTest : public MoECompressedFusionTest {-protected:- static void set_disable_moe_opt() {-#ifdef _WIN32- _putenv_s("OV_GPU_DISABLE_MOE_OPT", "1");-#else- ::setenv("OV_GPU_DISABLE_MOE_OPT", "1", 1);-#endif- }-- static void unset_disable_moe_opt() {-#ifdef _WIN32- _putenv_s("OV_GPU_DISABLE_MOE_OPT", "");-#else- ::unsetenv("OV_GPU_DISABLE_MOE_OPT");-#endif- }-- void SetUp() override {- set_disable_moe_opt();- MoECompressedFusionTest::SetUp();- }-- void TearDown() override {- MoECompressedFusionTest::TearDown();- unset_disable_moe_opt();- }-- void validate() override {- ov::test::SubgraphBaseTest::validate();- const auto pattern_type = std::get<1>(GetParam());- // 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);- }-};--TEST_P(MoEGatherMatmulTest, Inference) {- run();-}+// MoEGatherMatmulTest: alias for MoECompressedFusionTest with force_gather_matmul=true.+using MoEGatherMatmulTest = MoECompressedFusionTest;// u8 excluded: GatherMatmul prefill micro-kernel for u8 is not selectable yet.INSTANTIATE_TEST_SUITE_P(smoke_MoEGatherMatmul,@@ -263,7 +270,9 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoEGatherMatmul,::testing::Values(ov::test::utils::DecompressionType::full),::testing::Values(true), // reshape_on_decompression::testing::Values(128),- ::testing::Values(size_t{0})), // gate_idx unused for GEMM3+ ::testing::Values(size_t{0}), // gate_idx unused for GEMM3+ ::testing::Values(true), // force_gather_matmul+ ::testing::Values(MoEActivationType::SWISH)),MoEGatherMatmulTest::getTestCaseName);// 2-GEMM unfused: covers GatherMatmul OCL clamp/bias/swiglu compile path.@@ -279,7 +288,28 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoE2GemmGatherMatmul,::testing::Values(ov::test::utils::DecompressionType::full),::testing::Values(true), // reshape_on_decompression::testing::Values(128),- ::testing::ValuesIn(gate_idx_values)),+ ::testing::ValuesIn(gate_idx_values),+ ::testing::Values(true), // force_gather_matmul+ ::testing::Values(MoEActivationType::SWISH)),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.+INSTANTIATE_TEST_SUITE_P(smoke_MoE3GemmGeluCompressed,+ MoECompressedFusionTest,+ ::testing::Combine(::testing::ValuesIn(moe_params_smoke),+ ::testing::Values(MoePatternType::GEMM3),+ ::testing::ValuesIn(routing_types),+ ::testing::Values(ov::element::u4), // weights_precision+ ::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(true), // reshape_on_decompression+ ::testing::Values(128),+ ::testing::Values(size_t{0}), // gate_idx unused for GEMM3+ ::testing::Values(false), // force_gather_matmul+ ::testing::Values(MoEActivationType::GELU)),+ MoECompressedFusionTest::getTestCaseName);+} // namespacediff --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.hppindex 7d6307653cd..80b8caaa6fc 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@@ -30,6 +30,11 @@ enum class MoERoutingType {SIGMOID_BIAS, ///< Sigmoid -> Add(bias) -> TopK routing};+enum class MoEActivationType {+ SWISH, ///< Swish gate activation (SwiGLU)+ GELU, ///< Gelu gate activation (GeGLU)+};+/// Softmax branch:/// routing_weights -> Softmax -> TopK -> ReduceSum -> Divide (norm)/// -> ScatterElementsUpdate -> Transpose -> Reshape -> Unsqueeze@@ -70,7 +75,8 @@ std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(const std::optional<ov::test::utils::DecompressionType> decompression_subtract_type = std::nullopt,const std::optional<bool> reshape_on_decompression = std::nullopt,const std::optional<int> decompression_group_size = std::nullopt,- MoERoutingType routing_type = MoERoutingType::SOFTMAX);+ MoERoutingType routing_type = MoERoutingType::SOFTMAX,+ MoEActivationType activation_type = MoEActivationType::SWISH);} // namespace test} // namespace ovdiff --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.cppindex e2a1ad01f6d..383de88531a 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@@ -21,6 +21,7 @@#include "openvino/op/divide.hpp"#include "openvino/op/gather.hpp"#include "openvino/op/gather_elements.hpp"+#include "openvino/op/gelu.hpp"#include "openvino/op/matmul.hpp"#include "openvino/op/minimum.hpp"#include "openvino/op/multiply.hpp"@@ -460,7 +461,8 @@ std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(const std::optional<ov::test::utils::DecompressionType> decompression_subtract_type,const std::optional<bool> reshape_on_decompression,const std::optional<int> decompression_group_size,- MoERoutingType routing_type) {+ MoERoutingType routing_type,+ MoEActivationType activation_type) {// Use parameters from shape_params - static shapes onlyconst auto& input_shape = moe_params.data_shape;const size_t intermediate_size = moe_params.intermediate_size;@@ -517,8 +519,13 @@ std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(gate_matmul->set_friendly_name("GateMatMul");- // Apply Swish activation directly to gate- auto swish = std::make_shared<ov::op::v4::Swish>(gate_matmul);+ // Apply gate activation (Swish for SwiGLU, Gelu for GeGLU)+ std::shared_ptr<ov::Node> gate_act;+ if (activation_type == MoEActivationType::GELU) {+ gate_act = std::make_shared<ov::op::v7::Gelu>(gate_matmul);+ } else {+ gate_act = std::make_shared<ov::op::v4::Swish>(gate_matmul);+ }// Second GEMM (up_projection)auto up_weights = build_matmul_weights(ov::Shape{number_of_experts, hidden_size, intermediate_size},@@ -537,8 +544,8 @@ std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(up_matmul->set_friendly_name("UpMatMul");- // Join: Multiply (SwiGLU)- auto swiglu = std::make_shared<ov::op::v1::Multiply>(swish, up_matmul);+ // Join: Multiply (SwiGLU or GeGLU)+ auto swiglu = std::make_shared<ov::op::v1::Multiply>(gate_act, up_matmul);// Third GEMM (down_projection)auto down_weights_moe3 = build_matmul_weights(ov::Shape{number_of_experts, intermediate_size, hidden_size},