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
[GPU] MOE3GemmCompressed: added Sigmoid routing type support (#34356)
Vladislav Golubevb3175eb70da7
diff --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 b1e1db5afa0..2db2907441c 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@@ -8,9 +8,9 @@#include <sstream>#include <vector>+#include "common_test_utils/node_builders/moe_builders.hpp"#include "common_test_utils/subgraph_builders/weights_decompression_builders.hpp"#include "shared_test_classes/base/ov_subgraph.hpp"-#include "shared_test_classes/subgraph/moe_builders.hpp"#include "shared_test_classes/subgraph/weights_decompression_params.hpp"#include "utils/cpu_test_utils.hpp"#include "utils/fusing_test_utils.hpp"@@ -32,11 +32,18 @@ inline std::ostream& operator<<(std::ostream& os, const MoEType& type) {}}-using MoeTestParams = std::tuple<MoePatternParams,+struct MoeTestShapeParams {+ InputShape data_shape;+ size_t topk;+ size_t number_of_experts;+ size_t intermediate_size;+};++using MoeTestParams = std::tuple<MoeTestShapeParams,MoEType, // MoE builder typeov::AnyMap>; // additional config-using MoeCompressedWeightsTestParams = std::tuple<MoePatternParams,+using MoeCompressedWeightsTestParams = std::tuple<MoeTestShapeParams,MoEType, // MoE builder typeov::test::ElementType, // weights precisionov::test::ElementType, // decompression precision@@ -52,7 +59,7 @@ class MoESubgraphTest : public testing::WithParamInterface<MoeTestParams>,virtual public SubgraphBaseTest,public CpuTestWithFusing {public:- static std::string generateBaseMoeTestName(const MoePatternParams& moe_params,+ static std::string generateBaseMoeTestName(const MoeTestShapeParams& moe_params,const MoEType& moe_type,const ov::AnyMap& additional_config) {std::ostringstream result;@@ -105,10 +112,14 @@ public:protected:void SetUp() override {targetDevice = ov::test::utils::DEVICE_CPU;- const auto& [shape_params, moe_type, additional_config] = GetParam();+ const auto& [moe_params, moe_type, additional_config] = GetParam();configuration.insert(additional_config.begin(), additional_config.end());- init_input_shapes({shape_params.data_shape});+ init_input_shapes({moe_params.data_shape});+ const MoePatternParams shape_params{moe_params.data_shape.first,+ moe_params.topk,+ moe_params.number_of_experts,+ moe_params.intermediate_size};inType = outType = ov::element::f32;auto itr = configuration.find(ov::hint::inference_precision.name());@@ -171,7 +182,7 @@ protected:rel_threshold = 5e-4f;abs_threshold = 5e-4f;- const auto& [shape_params,+ const auto& [moe_params,moe_type,weights_precision,decompression_precision,@@ -184,7 +195,11 @@ protected:use_matmul_decompression_impl] = GetParam();configuration.insert(additional_config.begin(), additional_config.end());- init_input_shapes({shape_params.data_shape});+ init_input_shapes({moe_params.data_shape});+ const MoePatternParams shape_params{moe_params.data_shape.first,+ moe_params.topk,+ moe_params.number_of_experts,+ moe_params.intermediate_size};inType = outType = ov::element::f32;auto itr = configuration.find(ov::hint::inference_precision.name());@@ -270,7 +285,7 @@ TEST_P(MoECompressedWeightsSubgraphTest, CompareWithRefs) {namespace {const std::vector<MoEType> moe_types = {MoEType::MoE2GeMM, MoEType::MoE3GeMM};-const std::vector<MoePatternParams> moe_params_smoke = {+const std::vector<MoeTestShapeParams> moe_params_smoke = {{{{-1, -1, 256}, {{2, 15, 256}, {2, 1, 256}, {3, 8, 256}}}, // data_shape,// seq_len=dynamic, hidden_size=256diff --git a/src/plugins/intel_gpu/include/intel_gpu/op/moe_3gemm_fused_compressed.hpp b/src/plugins/intel_gpu/include/intel_gpu/op/moe_3gemm_fused_compressed.hppindex 32368244603..78751af50f0 100644--- a/src/plugins/intel_gpu/include/intel_gpu/op/moe_3gemm_fused_compressed.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/op/moe_3gemm_fused_compressed.hpp@@ -37,9 +37,13 @@ public:/// shape [num_experts, hidden_size, group_num, 1]/// 10: w2_zp - expert zp for final projection for compressed experts,/// shape [num_experts, hidden_size, group_num, 1]+ /// 11: routing_bias (optional, SIGMOID_BIAS only) - [1, num_experts] routing bias for sigmoid routing+ /// 12: routing_eps (optional, SIGMOID_BIAS only) - scalar epsilon for normalization (read at kernel compile time)/// \param config Configuration for the MOE 3GEMM SWIGLU fused operationMOE3GemmFusedCompressed(const OutputVector& args, const MOECompressed::Config config);+ void validate_and_infer_types() override;+std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& new_args) const override;};diff --git a/src/plugins/intel_gpu/include/intel_gpu/op/moe_compressed.hpp b/src/plugins/intel_gpu/include/intel_gpu/op/moe_compressed.hppindex 89636d08664..4ea9749da1b 100644--- a/src/plugins/intel_gpu/include/intel_gpu/op/moe_compressed.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/op/moe_compressed.hpp@@ -4,8 +4,9 @@#pragma once-#include "openvino/op/op.hpp"+#include "openvino/core/attribute_adapter.hpp"#include "openvino/op/moe.hpp"+#include "openvino/op/op.hpp"namespace ov::intel_gpu::op {@@ -17,6 +18,8 @@ public:MOECompressed() = default;MOECompressed(const OutputVector& args) : MOE(args) {}+ enum class RoutingType { SOFTMAX, SIGMOID_BIAS };+struct Config : public MOE::Config {size_t hidden_size = 0;size_t inter_size = 0;@@ -30,6 +33,7 @@ public:size_t has_batch_dim = 0;bool has_zp = false;ov::element::Type out_type = ov::element::dynamic;+ RoutingType routing_type = RoutingType::SOFTMAX;Config() = default;Config(const MOE::Config& moe_config) : MOE::Config(moe_config) {}};@@ -68,8 +72,21 @@ public:void validate_and_infer_types() override;std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& new_args) const override;-private:+protected:Config m_config;};+std::ostream& operator<<(std::ostream& s, const MOECompressed::RoutingType& type);+} // namespace ov::intel_gpu::op++namespace ov {+template <>+class AttributeAdapter<ov::intel_gpu::op::MOECompressed::RoutingType> : public EnumAttributeAdapterBase<ov::intel_gpu::op::MOECompressed::RoutingType> {+public:+ AttributeAdapter(ov::intel_gpu::op::MOECompressed::RoutingType& value) : EnumAttributeAdapterBase<ov::intel_gpu::op::MOECompressed::RoutingType>(value) {}++ OPENVINO_RTTI("AttributeAdapter<ov::intel_gpu::op::MOECompressed::RoutingType>");+ ~AttributeAdapter() override = default;+};+} // namespace ovdiff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_3gemm_fused_compressed.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_3gemm_fused_compressed.hppindex f907610c179..50112003954 100644--- a/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_3gemm_fused_compressed.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_3gemm_fused_compressed.hpp@@ -42,6 +42,8 @@ struct moe_3gemm_fused_compressed : public primitive_base<moe_3gemm_fused_compre// 9: w2_scale - expert scale for final projection for compressed experts,// shape [num_experts, hidden_size, group_num, 1]// 10: w2_zp - expert zp for final projection for compressed experts,+ // 11: routing_bias (optional, SIGMOID_BIAS only) - [1, num_experts] routing bias for sigmoid routing+ // 12: routing_eps (optional, SIGMOID_BIAS only) - scalar epsilon for normalization (read at kernel compile time)//moe_3gemm_fused_compressed(const primitive_id& id, const std::vector<input_info>& inputs, const MOE3GemmFusedCompressed::Config& config): primitive_base(id, inputs, 1, {optional_data_type()}),diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_base.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_base.hppindex ed011addca1..75021e8848b 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_base.hpp+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_base.hpp@@ -41,7 +41,9 @@ enum class MOE3GemmInputIndex : uint8_t {ZP_1 = 7,WEIGHT_2 = 8,SCALE_2 = 9,- ZP_2 = 10+ ZP_2 = 10,+ ROUTING_BIAS = 11,+ ROUTING_EPS = 12};struct moe_3gemm_config {diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.cppindex 1b7c24c8286..e2958afa97b 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@@ -365,6 +365,33 @@ protected:}};+class MoE3GemmSwigluSigmoidBiasTopK : public KernelGenerator {+public:+ MoE3GemmSwigluSigmoidBiasTopK() : KernelGenerator("moe_3gemm_swiglu_fuse", "sigmoid_bias_topk") {}++protected:+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = KernelGenerator::get_jit_constants(params);+ auto desc = params.typed_desc<moe_3gemm_fused_compressed>();+ jit.make("SIGMOID_BIAS_TOPK_ENABLE", 1);+ jit.make("TOP_K", desc->_config.top_k);+ jit.make("VALUE_NUM", desc->_config.num_expert);+ jit.make("MOE_DTYPE", params.get_input_layout(0).data_type == ov::element::f16 ? "half" : "float");+ jit.make("MOE_DTYPE_SIZE", params.get_input_layout(0).data_type == ov::element::f16 ? 2 : 4);+ return jit;+ }++ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& params) const override {+ Arguments args;++ return args;+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {}};+ }+};+class MoE3GemmSwigluGather : public KernelGenerator {public:MoE3GemmSwigluGather() : KernelGenerator("moe_3gemm_swiglu_fuse", "gather") {}@@ -431,7 +458,7 @@ protected:static size_t get_seq_len(cldnn::layout& layout) {auto shape = layout.get_shape();size_t seq_len = static_cast<size_t>(shape[0]);- if (shape.size() == 4) {+ if (shape.size() >= 3) {seq_len = static_cast<size_t>(shape[0] * shape[1]);}return seq_len;@@ -754,6 +781,7 @@ class moe_3gemm_swiglu_opt_impl : public PrimitiveImplOCL {public:DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::ocl::MoE3GemmSwigluImpl)Stage::Ptr softmax_topk = make_stage<MoE3GemmSwigluSoftMaxTopK>();+ Stage::Ptr sigmoid_bias_topk = make_stage<MoE3GemmSwigluSigmoidBiasTopK>();Stage::Ptr gather = make_stage<MoE3GemmSwigluGather>();Stage::Ptr scatter = make_stage<MoE3GemmSwigluScatter>();Stage::Ptr mlp_gate_up = make_stage<MoE3GemmSwigluMLPGateUp>();@@ -871,7 +899,14 @@ public:}// Don't change the order of stages- add_stage(softmax_topk, params);+ auto routing_type = node.as<moe_3gemm_fused_compressed>().get_primitive()->_config.routing_type;+ if (routing_type == ov::intel_gpu::op::MOECompressed::RoutingType::SOFTMAX) {+ add_stage(softmax_topk, params);+ } else if (routing_type == ov::intel_gpu::op::MOECompressed::RoutingType::SIGMOID_BIAS) {+ add_stage(sigmoid_bias_topk, params);+ } else {+ OPENVINO_THROW("Unsupported routing type for moe_3gemm_swiglu_opt_impl: ", static_cast<int>(routing_type));+ }add_stage(gather, params);add_stage(scatter, params);add_stage(mlp_gate_up, params);@@ -1741,16 +1776,32 @@ public:scratch_buffers scratch;prepare_internal_buffers(instance, scratch, token_num);- // softmax+topk+ // routing: softmax+topk or sigmoid+bias+topkauto lws_size = config.num_expert;- auto topk_event = execute_stage(events,- instance,- *softmax_topk,- {instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::ROUTING_WEIGHTS))},- {scratch.topk_id, scratch.topk_weights},- {static_cast<size_t>(token_num), lws_size},- {1, lws_size},- instance.needs_completion_event());+ cldnn::event::ptr topk_event;+ if (config.routing_type == ov::intel_gpu::op::MOECompressed::RoutingType::SOFTMAX) {+ topk_event = execute_stage(events,+ instance,+ *softmax_topk,+ {instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::ROUTING_WEIGHTS))},+ {scratch.topk_id, scratch.topk_weights},+ {static_cast<size_t>(token_num), lws_size},+ {1, lws_size},+ instance.needs_completion_event());+ } else if (config.routing_type == ov::intel_gpu::op::MOECompressed::RoutingType::SIGMOID_BIAS) {+ topk_event = execute_stage(events,+ instance,+ *sigmoid_bias_topk,+ {instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::ROUTING_WEIGHTS)),+ instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::ROUTING_BIAS)),+ instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::ROUTING_EPS))},+ {scratch.topk_id, scratch.topk_weights},+ {static_cast<size_t>(token_num), lws_size},+ {1, lws_size},+ instance.needs_completion_event());+ } else {+ OPENVINO_THROW("Unsupported routing type ", static_cast<int>(config.routing_type));+ }// Single token is a special case, we don't need to do gather/scatter,// and we can apply optimal kernels against memory bound to improve performance.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.clindex ad0abdda0c9..980dc17c77d 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@@ -22,7 +22,13 @@ KERNEL(softmax_topk)(__local MOE_DTYPE local_output[TOP_K];__local uint local_index[TOP_K];+#if MOE_DTYPE_SIZE == 2MOE_DTYPE in_value = as_half(intel_sub_group_block_read_us((const __global ushort*)(input)));+#elif MOE_DTYPE_SIZE == 4+ MOE_DTYPE in_value = as_float(intel_sub_group_block_read((const __global uint*)(input)));+#else+# error "softmax_topk: unsupported MOE_DTYPE_SIZE"+#endiflocal_input[sort_index] = in_value;barrier(CLK_LOCAL_MEM_FENCE);@@ -65,6 +71,95 @@ KERNEL(softmax_topk)(}}+#elif SIGMOID_BIAS_TOPK_ENABLE++KERNEL(sigmoid_bias_topk)(+ const __global MOE_DTYPE* input, // routing logits [input_batch, num_experts]+ const __global MOE_DTYPE* bias, // routing bias [1, num_experts] or [num_experts]+ const __global MOE_DTYPE* eps_ptr, // routing epsilon scalar [1]+ __global uint* output_index, // [input_batch, TOP_K]+ __global MOE_DTYPE* output // [input_batch, TOP_K]+) {+ // gws [batch, num_experts]+ const uint batch = (uint)get_global_id(0);+ const uint sort_index = (uint)get_global_id(1);+ const uint sort_cnt = (uint)get_global_size(1); // num_experts++ input += batch * sort_cnt + sort_index;++ __local MOE_DTYPE local_sigmoid[VALUE_NUM]; // raw sigmoid values+ __local MOE_DTYPE local_selection[VALUE_NUM]; // sigmoid + bias (for sorting)+ __local MOE_DTYPE local_output[TOP_K];+ __local uint local_index[TOP_K];++ // Compute sigmoid+#if MOE_DTYPE_SIZE == 2+ MOE_DTYPE in_value = as_half(intel_sub_group_block_read_us((const __global ushort*)(input)));+#elif MOE_DTYPE_SIZE == 4+ MOE_DTYPE in_value = as_float(intel_sub_group_block_read((const __global uint*)(input)));+#else+# error "sigmoid_bias_topk: unsupported MOE_DTYPE_SIZE"+#endif+ MOE_DTYPE sigmoid_val = (MOE_DTYPE)(1.0f / (1.0f + native_exp(-(float)in_value)));++ // Add bias for selection (determines which experts are chosen)+ MOE_DTYPE bias_val = bias[sort_index];+ MOE_DTYPE selection_val = sigmoid_val + bias_val;++ local_sigmoid[sort_index] = sigmoid_val;+ local_selection[sort_index] = selection_val;+ barrier(CLK_LOCAL_MEM_FENCE);++ // Sort by selection_val (sigmoid + bias) to find top-K+ uint sort_position = 0;+ uint actual_topk = (TOP_K < sort_cnt) ? TOP_K : sort_cnt;++ __attribute__((opencl_unroll_hint(8)))+ for(uint i = 0; i < sort_index; i++) {+ MOE_DTYPE value = local_selection[i];+ if(value >= selection_val) {+ sort_position++;+ }+ }++ __attribute__((opencl_unroll_hint(8)))+ for(uint i = sort_index; i < sort_cnt; i++) {+ MOE_DTYPE value = local_selection[i];+ if(value > selection_val) {+ sort_position++;+ }+ }++ // Store raw sigmoid values (NOT sigmoid+bias) for the top-K experts+ if (sort_position < actual_topk) {+ local_output[sort_position] = local_sigmoid[sort_index];+ local_index[sort_position] = sort_index;+ }+ barrier(CLK_LOCAL_MEM_FENCE);++ // Normalize: weights / (sum + eps)+ if(sort_position == 0) {+ float sum_weights = 0.0f;+ for(uint i = 0; i < actual_topk; i++) {+ sum_weights += (float)local_output[i];+ }+ sum_weights += (float)eps_ptr[0]; // epsilon to avoid division by zero++ output_index += batch * TOP_K;+ output += batch * TOP_K;++ for(uint i = 0; i < actual_topk; i++) {+ output[i] = (MOE_DTYPE)((float)local_output[i] / sum_weights);+ output_index[i] = local_index[i];+ }+ // Zero out remaining positions if TOP_K > actual_topk+ for(uint i = actual_topk; i < TOP_K; i++) {+ output[i] = (MOE_DTYPE)0.0f;+ output_index[i] = 0;+ }+ }+}+#elif GATHER_ENABLE__attribute__((intel_reqd_sub_group_size(SUBGROUP_SIZE)))KERNEL (gather_2d_ref)(diff --git a/src/plugins/intel_gpu/src/plugin/ops/moe.cpp b/src/plugins/intel_gpu/src/plugin/ops/moe.cppindex 805f65f449d..16c32d9a539 100644--- a/src/plugins/intel_gpu/src/plugin/ops/moe.cpp+++ b/src/plugins/intel_gpu/src/plugin/ops/moe.cpp@@ -53,7 +53,8 @@ static void CreateMOE3GemmFusedCompressedOp(ProgramBuilder& p, const std::shared/// shape [num_experts, hidden_size, group_num, 1]/// 10: w2_zp - expert zp for final projection for compressed experts,/// shape [num_experts, hidden_size, group_num, 1]- validate_inputs_count(op, {11});+ const size_t expected_inputs = config.routing_type == op::MOECompressed::RoutingType::SIGMOID_BIAS ? 13 : 11;+ validate_inputs_count(op, {expected_inputs});const std::string layerName = layer_type_name_ID(op);const cldnn::moe_3gemm_fused_compressed moe(layerName, inputs, config);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.cppindex 0ac2fe79f53..faf854e6d05 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@@ -6,8 +6,8 @@#include <memory>-#include "intel_gpu/op/moe_compressed.hpp"#include "intel_gpu/op/moe_3gemm_fused_compressed.hpp"+#include "intel_gpu/op/moe_compressed.hpp"#include "openvino/core/graph_util.hpp"#include "openvino/core/node.hpp"#include "openvino/core/rt_info.hpp"@@ -19,12 +19,14 @@#include "openvino/op/convert.hpp"#include "openvino/op/divide.hpp"#include "openvino/op/gather.hpp"+#include "openvino/op/gather_elements.hpp"#include "openvino/op/matmul.hpp"#include "openvino/op/multiply.hpp"#include "openvino/op/reduce_sum.hpp"#include "openvino/op/reshape.hpp"#include "openvino/op/scatter_elements_update.hpp"#include "openvino/op/shape_of.hpp"+#include "openvino/op/sigmoid.hpp"#include "openvino/op/slice.hpp"#include "openvino/op/softmax.hpp"#include "openvino/op/subtract.hpp"@@ -45,57 +47,83 @@#include "openvino/pass/pattern/op/wrap_type.hpp"namespace ov::intel_gpu {-using namespace ov::pass;-using namespace ov::pass::pattern;-FuseMOE3GemmCompressed::FuseMOE3GemmCompressed() {- auto hidden_state_m = any_input();- auto routers_m = any_input();- auto hidden_state_reshape_m = wrap_type<ov::op::v1::Reshape>({hidden_state_m, any_input()});- auto router_matmul_m = wrap_type<ov::op::v0::MatMul>({hidden_state_reshape_m, routers_m}, consumers_count(1));- auto softmax_m = wrap_type<ov::op::v8::Softmax>({router_matmul_m}, consumers_count(1));- auto topk_m = wrap_type<ov::op::v11::TopK>({softmax_m, any_input()});- topk_m->set_output_size(2);- // idx output- auto topk_idx_m = optional<ov::op::v0::Convert>({topk_m->output(1)});-- // weight output- auto reduce_sum_m = wrap_type<ov::op::v1::ReduceSum>({topk_m->output(0), any_input()}, consumers_count(1));- auto norm_m = wrap_type<ov::op::v1::Divide>({topk_m->output(0), reduce_sum_m->output(0)}, consumers_count(1));-- auto bc_m = wrap_type<ov::op::v3::Broadcast>({any_input(), any_input()});- auto shape_of_m = wrap_type<ov::op::v3::ShapeOf>({topk_idx_m}, consumers_count(1));- auto norm_slice = optional<ov::op::v8::Slice>({norm_m, any_input(), shape_of_m, any_input(), any_input()}, consumers_count(1));-- auto scatter_m = wrap_type<ov::op::v12::ScatterElementsUpdate>({bc_m, topk_idx_m, norm_m | norm_slice, any_input()}, consumers_count(1));-- auto transpose_m = wrap_type<ov::op::v1::Transpose>({scatter_m, any_input()}, consumers_count(1));- auto reshape_m = wrap_type<ov::op::v1::Reshape>({transpose_m, any_input()}, consumers_count(1));- auto unsqueeze_moe_m = wrap_type<ov::op::v0::Unsqueeze>({reshape_m, any_input()}, consumers_count(1));-- auto gate_wei_m = wrap_type<ov::op::v0::Constant>();- auto gate_scale_m = any_input();- auto gate_zp_m = any_input();- auto up_wei_m = wrap_type<ov::op::v0::Constant>();- auto up_scale_m = any_input();- auto up_zp_m = any_input();- auto down_wei_m = wrap_type<ov::op::v0::Constant>();- auto down_scale_m = any_input();- auto down_zp_m = any_input();-- // moe compressed- auto moe_compressed_m = wrap_type<ov::intel_gpu::op::MOECompressed>({hidden_state_reshape_m | hidden_state_m,- unsqueeze_moe_m->output(0),- topk_idx_m->output(0),- gate_wei_m->output(0),- gate_scale_m->output(0),- gate_zp_m->output(0),- up_wei_m->output(0),- up_scale_m->output(0),- up_zp_m->output(0),- down_wei_m->output(0),- down_scale_m->output(0),- down_zp_m->output(0)});+ using namespace ov::pass::pattern;+ using namespace ov::pass;+#define ANY any_input()++ auto hidden_state_m = ANY;+ 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));++ // ── Softmax routing branch ──────────────────────────────────────────+ auto sm_softmax = wrap_type<ov::op::v8::Softmax>({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_bc = wrap_type<ov::op::v3::Broadcast>({ANY, ANY});++ // Optional slice on normalized weights (covers Qwen3-next pattern)+ auto sm_shape_of = wrap_type<ov::op::v3::ShapeOf>({sm_convert_topk}, consumers_count(1));+ auto sm_norm_slice = optional<ov::op::v8::Slice>({sm_norm, ANY, sm_shape_of, ANY, ANY}, consumers_count(1));++ // ── Sigmoid+bias routing branch ─────────────────────────────────────+ auto sig_sigmoid = wrap_type<ov::op::v0::Sigmoid>({matmul});+ auto sig_routing_bias = ANY;+ auto sig_add = wrap_type<ov::op::v1::Add>({sig_sigmoid, sig_routing_bias}, consumers_count(1));+ auto sig_topk = wrap_type<ov::op::v11::TopK>({sig_add, ANY});+ sig_topk->set_output_size(2);++ auto sig_convert_topk = optional<ov::op::v0::Convert>({sig_topk->output(1)});+ auto sig_gather_el = wrap_type<ov::op::v6::GatherElements>({sig_sigmoid, sig_convert_topk});+ auto sig_reduce = wrap_type<ov::op::v1::ReduceSum>({sig_gather_el, ANY}, consumers_count(1));++ // Note: only scalar eps is supported for now+ auto sig_eps_value = wrap_type<ov::op::v0::Constant>([](const ov::Output<ov::Node>& output) {+ return ov::shape_size(output.get_shape()) == 1;+ });+ auto sig_add_eps = wrap_type<ov::op::v1::Add>({sig_reduce, sig_eps_value}, consumers_count(1));+ auto sig_norm = wrap_type<ov::op::v1::Divide>({sig_gather_el, sig_add_eps}, consumers_count(1));+ auto sig_slice = wrap_type<ov::op::v8::Slice>({sig_norm, ANY, ANY, ANY, ANY}, consumers_count(1));+ auto sig_bc = wrap_type<ov::op::v3::Broadcast>({ANY, ANY}, consumers_count(1));++ auto topk_idces = sm_convert_topk | sig_convert_topk;+ auto scatter = wrap_type<ov::op::v12::ScatterElementsUpdate>({sm_bc | sig_bc, topk_idces, sm_norm_slice | sig_slice, ANY}, consumers_count(1));++ // ── Shared tail: scatter → transpose → reshape → unsqueeze ──────────+ auto transpose = wrap_type<ov::op::v1::Transpose>({scatter, ANY}, consumers_count(1));+ auto reshape = wrap_type<ov::op::v1::Reshape>({transpose, ANY}, consumers_count(1));+ auto unsqueeze_moe = wrap_type<ov::op::v0::Unsqueeze>({reshape, ANY}, consumers_count(1));++ // ── Common: hidden state + compressed weights + MOECompressed ───────+ auto gate_wei_m = wrap_const();+ auto gate_scale_m = ANY;+ auto gate_zp_m = ANY;+ auto up_wei_m = wrap_const();+ auto up_scale_m = ANY;+ auto up_zp_m = ANY;+ auto down_wei_m = wrap_const();+ auto down_scale_m = ANY;+ auto down_zp_m = ANY;++ ov::OutputVector moe_inputs = {hidden_state_reshape | hidden_state_m,+ unsqueeze_moe,+ topk_idces,+ gate_wei_m,+ gate_scale_m,+ gate_zp_m,+ up_wei_m,+ up_scale_m,+ up_zp_m,+ down_wei_m,+ down_scale_m,+ down_zp_m};+ auto moe_compressed_m = wrap_type<ov::intel_gpu::op::MOECompressed>(moe_inputs);+#undef ANYov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](ov::pass::pattern::Matcher& m) {const auto& pattern_map = m.get_pattern_value_map();@@ -105,21 +133,31 @@ FuseMOE3GemmCompressed::FuseMOE3GemmCompressed() {return false;}- OutputVector args(11);- args[0] = pattern_map.at(hidden_state_reshape_m);- args[1] = pattern_map.at(router_matmul_m);- args[2] = pattern_map.at(gate_wei_m);- args[3] = pattern_map.at(gate_scale_m);- args[4] = pattern_map.at(gate_zp_m);- args[5] = pattern_map.at(up_wei_m);- args[6] = pattern_map.at(up_scale_m);- args[7] = pattern_map.at(up_zp_m);- args[8] = pattern_map.at(down_wei_m);- args[9] = pattern_map.at(down_scale_m);- args[10] = pattern_map.at(down_zp_m);-- std::shared_ptr<ov::op::Op> moe_router_fused = std::make_shared<ov::intel_gpu::op::MOE3GemmFusedCompressed>(args, moe_compressed->get_config());+ auto config = moe_compressed->get_config();+ OutputVector args{+ pattern_map.at(hidden_state_reshape),+ pattern_map.at(matmul),+ pattern_map.at(gate_wei_m),+ pattern_map.at(gate_scale_m),+ pattern_map.at(gate_zp_m),+ pattern_map.at(up_wei_m),+ pattern_map.at(up_scale_m),+ pattern_map.at(up_zp_m),+ pattern_map.at(down_wei_m),+ pattern_map.at(down_scale_m),+ pattern_map.at(down_zp_m),+ };+ if (pattern_map.count(sig_routing_bias)) {+ args.push_back(pattern_map.at(sig_routing_bias));+ args.push_back(pattern_map.at(sig_eps_value));+ config.routing_type = ov::intel_gpu::op::MOECompressed::RoutingType::SIGMOID_BIAS;+ }++ std::shared_ptr<ov::Node> moe_router_fused = std::make_shared<ov::intel_gpu::op::MOE3GemmFusedCompressed>(args, config);ov::copy_runtime_info(moe_compressed, moe_router_fused);++ // If MOECompressed's first input was the original (un-reshaped) hidden state+ // but the fused op works on the flattened 2D input, reshape the output back.if (moe_compressed->input_value(0) == pattern_map.at(hidden_state_m)) {auto hidden_state_shape = std::make_shared<ov::op::v3::ShapeOf>(pattern_map.at(hidden_state_m));moe_router_fused = std::make_shared<ov::op::v1::Reshape>(moe_router_fused, hidden_state_shape, false);@@ -132,7 +170,7 @@ FuseMOE3GemmCompressed::FuseMOE3GemmCompressed() {return true;};- auto m = std::make_shared<ov::pass::pattern::Matcher>(moe_compressed_m, "FuseMOE3GemmCompressed");+ auto m = std::make_shared<Matcher>(moe_compressed_m, "FuseMOE3GemmCompressed");this->register_matcher(m, callback);}diff --git a/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_3gemm_compressed.hpp b/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_3gemm_compressed.hppindex e71e6fde985..d47793619c0 100644--- a/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_3gemm_compressed.hpp+++ b/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_3gemm_compressed.hpp@@ -4,12 +4,13 @@#pragma once-#include "openvino/pass/graph_rewrite.hpp"+#include "openvino/pass/matcher_pass.hpp"namespace ov::intel_gpu {-// Fuse subgraph between router and MOECompressed into MOE3GemmFusedCompressed operation.-class FuseMOE3GemmCompressed: public ov::pass::MatcherPass {+// Fuse routing subgraph + MOECompressed into MOE3GemmFusedCompressed.+// Handles both Softmax and Sigmoid+bias routing patterns via pattern::op::Or.+class FuseMOE3GemmCompressed : public ov::pass::MatcherPass {public:OPENVINO_MATCHER_PASS_RTTI("FuseMOE3GemmCompressed");FuseMOE3GemmCompressed();diff --git a/src/plugins/intel_gpu/src/plugin/transformations/keep_moe_3gemm_const_precision.cpp b/src/plugins/intel_gpu/src/plugin/transformations/keep_moe_3gemm_const_precision.cppindex 42af0afb34d..365c643c70b 100644--- a/src/plugins/intel_gpu/src/plugin/transformations/keep_moe_3gemm_const_precision.cpp+++ b/src/plugins/intel_gpu/src/plugin/transformations/keep_moe_3gemm_const_precision.cpp@@ -7,6 +7,7 @@#include <memory>#include "intel_gpu/op/moe_3gemm_fused_compressed.hpp"+#include "openvino/pass/pattern/op/or.hpp"#include "openvino/pass/pattern/op/pattern.hpp"#include "openvino/pass/pattern/op/wrap_type.hpp"#include "transformations/rt_info/keep_const_precision.hpp"@@ -22,14 +23,20 @@ KeepMOE3GemmConstPrecision::KeepMOE3GemmConstPrecision() {auto zp_0_m = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::u4));auto zp_1_m = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::u4));auto zp_2_m = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::u4));- auto moe_3gemm_fused_compressed_m = wrap_type<ov::intel_gpu::op::MOE3GemmFusedCompressed>(++ // Softmax routing: 11 inputs (no routing_bias)+ auto moe_softmax_m = wrap_type<ov::intel_gpu::op::MOE3GemmFusedCompressed>({any_input(), any_input(), wei_0_m, any_input(), zp_0_m, wei_1_m, any_input(), zp_1_m, wei_2_m, any_input(), zp_2_m});+ // SigmoidBias routing: 13 inputs (routing_bias at index 11, routing_eps at index 12)+ auto moe_sigmoid_m = wrap_type<ov::intel_gpu::op::MOE3GemmFusedCompressed>(+ {any_input(), any_input(), wei_0_m, any_input(), zp_0_m, wei_1_m, any_input(), zp_1_m, wei_2_m, any_input(), zp_2_m, any_input(), any_input()});++ auto moe_3gemm_fused_compressed_m = std::make_shared<ov::pass::pattern::op::Or>(OutputVector{moe_softmax_m, moe_sigmoid_m});+ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](ov::pass::pattern::Matcher& m) {const auto& pattern_map = m.get_pattern_value_map();-- auto moe_3gemm_fused_compressed =- ov::as_type_ptr<ov::intel_gpu::op::MOE3GemmFusedCompressed>(pattern_map.at(moe_3gemm_fused_compressed_m).get_node_shared_ptr());+ auto moe_3gemm_fused_compressed = ov::as_type_ptr<ov::intel_gpu::op::MOE3GemmFusedCompressed>(m.get_match_root());if (!moe_3gemm_fused_compressed || transformation_callback(moe_3gemm_fused_compressed)) {return false;}diff --git a/src/plugins/intel_gpu/src/plugin/transformations/op/moe_3gemm_fused_compressed.cpp b/src/plugins/intel_gpu/src/plugin/transformations/op/moe_3gemm_fused_compressed.cppindex 27a52b80fe4..3dcdb139e35 100644--- a/src/plugins/intel_gpu/src/plugin/transformations/op/moe_3gemm_fused_compressed.cpp+++ b/src/plugins/intel_gpu/src/plugin/transformations/op/moe_3gemm_fused_compressed.cpp@@ -11,6 +11,26 @@ MOE3GemmFusedCompressed::MOE3GemmFusedCompressed(const OutputVector& args, constconstructor_validate_and_infer_types();}+void MOE3GemmFusedCompressed::validate_and_infer_types() {+ const size_t expected_inputs = m_config.routing_type == MOECompressed::RoutingType::SIGMOID_BIAS ? 13 : 11;+ OPENVINO_ASSERT(get_input_size() == expected_inputs,+ "MOECompressed: expected ",+ expected_inputs,+ " inputs for routing type ",+ m_config.routing_type,+ ", got ",+ get_input_size());++ if (m_config.routing_type == MOECompressed::RoutingType::SIGMOID_BIAS) {+ // Input 12 is routing_eps — must be a scalar+ OPENVINO_ASSERT(ov::shape_size(get_input_partial_shape(12).to_shape()) == 1,+ "MOE3GemmFusedCompressed: routing_eps (input 12) must be scalar, got shape ",+ get_input_partial_shape(12));+ }++ MOECompressed::validate_and_infer_types();+}+std::shared_ptr<ov::Node> MOE3GemmFusedCompressed::clone_with_new_inputs(const ov::OutputVector& new_args) const {check_new_args_count(this, new_args);diff --git a/src/plugins/intel_gpu/src/plugin/transformations/op/moe_compressed.cpp b/src/plugins/intel_gpu/src/plugin/transformations/op/moe_compressed.cppindex d29007e7649..40e66b7c4f1 100644--- a/src/plugins/intel_gpu/src/plugin/transformations/op/moe_compressed.cpp+++ b/src/plugins/intel_gpu/src/plugin/transformations/op/moe_compressed.cpp@@ -6,7 +6,7 @@namespace ov::intel_gpu::op {-MOECompressed::MOECompressed(const OutputVector& args, const Config& config) : MOE(args), m_config(config) {+MOECompressed::MOECompressed(const OutputVector& args, const Config& config) : MOE(args, config), m_config(config) {constructor_validate_and_infer_types();}@@ -38,7 +38,27 @@ bool MOECompressed::visit_attributes(ov::AttributeVisitor& visitor) {visitor.on_attribute("top_k", m_config.top_k);visitor.on_attribute("group_size", m_config.group_size);visitor.on_attribute("out_type", m_config.out_type);+ visitor.on_attribute("routing_type", m_config.routing_type);return true;}+std::ostream& operator<<(std::ostream& s, const MOECompressed::RoutingType& type) {+ return s << as_string(type);+}+} // namespace ov::intel_gpu::op++namespace ov {++template <>+EnumNames<ov::intel_gpu::op::MOECompressed::RoutingType>& EnumNames<ov::intel_gpu::op::MOECompressed::RoutingType>::get() {+ static auto enum_names =+ EnumNames<ov::intel_gpu::op::MOECompressed::RoutingType>("MOECompressed::RoutingType",+ {+ {"softmax", ov::intel_gpu::op::MOECompressed::RoutingType::SOFTMAX},+ {"sigmoid_bias", ov::intel_gpu::op::MOECompressed::RoutingType::SIGMOID_BIAS},+ });+ return enum_names;+}++} // namespace ovdiff --git a/src/plugins/intel_gpu/tests/functional/shared_tests_instances/skip_tests_config.cpp b/src/plugins/intel_gpu/tests/functional/shared_tests_instances/skip_tests_config.cppindex 23fe4726fce..e31bddb35a9 100644--- a/src/plugins/intel_gpu/tests/functional/shared_tests_instances/skip_tests_config.cpp+++ b/src/plugins/intel_gpu/tests/functional/shared_tests_instances/skip_tests_config.cpp@@ -245,6 +245,8 @@ const std::vector<std::regex>& disabled_test_patterns() {} else {// CVS-172342patterns.push_back(std::regex(R"(.*smoke_MatMulCompressedWeights_3D_weight.*)"));+ // MoE patterns are not supported on the platforms without immad (fusion transformation are disabled)+ patterns.push_back(std::regex(R"(.*smoke_MoE3GemmCompressedFusion.*)"));}return patterns;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.cppnew file mode 100644index 00000000000..e252a538a01--- /dev/null+++ b/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/moe.cpp@@ -0,0 +1,151 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "common_test_utils/node_builders/moe_builders.hpp"+#include "common_test_utils/ov_tensor_utils.hpp"+#include "openvino/runtime/exec_model_info.hpp"+#include "shared_test_classes/base/ov_subgraph.hpp"++namespace {+using ov::test::InputShape;+using ov::test::MoERoutingType;++struct MoeTestShapeParams {+ InputShape data_shape;+ size_t topk;+ size_t number_of_experts;+ size_t intermediate_size;+};++static const char* routing_type_str(MoERoutingType rt) {+ switch (rt) {+ case MoERoutingType::SOFTMAX: return "Softmax";+ case MoERoutingType::SIGMOID_BIAS: return "SigmoidBias";+ default: OPENVINO_THROW("Unsupported MoERoutingType");+ }+}++using MoE3GemmCompressedParams = std::tuple<MoeTestShapeParams,+ MoERoutingType,+ ov::element::Type, // weights_precision+ ov::element::Type, // decompression_precision+ ov::element::Type, // scale_precision+ ov::test::utils::DecompressionType, // multiply type+ ov::test::utils::DecompressionType, // subtract type+ bool, // reshape_on_decompression+ int>; // group_size++class MoE3GemmCompressedFusionTest : public testing::WithParamInterface<MoE3GemmCompressedParams>, virtual public ov::test::SubgraphBaseTest {+public:+ static std::string getTestCaseName(const testing::TestParamInfo<MoE3GemmCompressedParams>& info) {+ const auto& [moe_params, routing_type, wp, dp, sp, dm, ds, rd, gs] = info.param;+ std::ostringstream result;+ result << "IS=" << ov::test::utils::partialShape2str({moe_params.data_shape.first}) << "_";+ result << "TS=";+ for (const auto& s : moe_params.data_shape.second)+ result << ov::test::utils::vec2str(s) << ",";+ result << "topk=" << moe_params.topk << "_";+ result << "experts=" << moe_params.number_of_experts << "_";+ result << "inter=" << moe_params.intermediate_size << "_";+ result << "routing=" << routing_type_str(routing_type) << "_";+ result << "WP=" << wp << "_";+ result << "DP=" << dp << "_";+ result << "SP=" << sp << "_";+ result << "DM=" << dm << "_";+ result << "DS=" << ds << "_";+ result << "RD=" << rd << "_";+ result << "GS=" << gs;+ return result.str();+ }++protected:+ void SetUp() override {+ targetDevice = ov::test::utils::DEVICE_GPU;+ inType = outType = inference_precision = ov::element::f16;++ const auto& [moe_params, routing_type, wp, dp, sp, dm, ds, rd, gs] = GetParam();+ init_input_shapes({moe_params.data_shape});+ const ov::test::MoePatternParams shape_params{moe_params.data_shape.first, moe_params.topk, moe_params.number_of_experts, moe_params.intermediate_size};++ function = ov::test::initMoE3GeMMSubgraph(shape_params,+ ov::element::f32, // data_precision+ wp, // weights_precision+ true, // use_weight_decompression+ dp, // decompression_precision+ sp, // scale_precision+ dm, // decompression_multiply_type+ ds, // decompression_subtract_type+ rd, // reshape_on_decompression+ gs, // group_size+ routing_type);+ }++ void generate_inputs(const std::vector<ov::Shape>& target_input_static_shapes) override {+ inputs.clear();+ const auto& params = function->get_parameters();+ ASSERT_EQ(params.size(), 1);+ inputs.insert({params[0],+ ov::test::utils::create_and_fill_tensor(params[0]->get_element_type(),+ target_input_static_shapes[0],+ ov::test::utils::InputGenerateData(0.125f, 2, 8, 1234))});+ }++ void validate() override {+ ov::test::SubgraphBaseTest::validate();+ auto runtime_model = compiledModel.get_runtime_model();+ ASSERT_TRUE(runtime_model != nullptr) << "Runtime model should not be null";+ bool moe_found = false;+ for (const auto& op : runtime_model->get_ordered_ops()) {+ auto layer_type = op->get_rt_info().at(ov::exec_model_info::LAYER_TYPE).as<std::string>();+ if (layer_type == std::string("moe_3gemm_fused_compressed")) {+ moe_found = true;+ }+ }+ ASSERT_TRUE(moe_found) << "moe_3gemm_fused_compressed op is not found";+ }+};++TEST_P(MoE3GemmCompressedFusionTest, Inference) {+ run();+}++const std::vector<MoERoutingType> routing_types = {MoERoutingType::SOFTMAX, MoERoutingType::SIGMOID_BIAS};++const std::vector<MoeTestShapeParams> moe_params_smoke = {+ {+ {{-1, -1, 256}, {{2, 15, 256}, {2, 1, 256}, {3, 8, 256}}}, // data_shape,+ // seq_len=dynamic, hidden_size=256+ 4, // topk+ 8, // number_of_experts+ 512 // intermediate_size+ },+ {+ {{-1, -1, 128}, {{1, 32, 128}, {1, 1, 128}, {1, 16, 128}}}, // Different seq length+ 2, // topk+ 4, // number_of_experts+ 256 // intermediate_size+ },+};++// Compressed weights – covers the full FuseVectorizedMOE3GEMM + ConvertMOEToMOECompressed ++// FuseMOE3GemmCompressed pipeline that runs in production.+const std::vector<ov::element::Type> weights_precisions = {+ ov::element::u8,+ ov::element::u4,+};++INSTANTIATE_TEST_SUITE_P(smoke_MoE3GemmCompressedFusion,+ MoE3GemmCompressedFusionTest,+ ::testing::Combine(::testing::ValuesIn(moe_params_smoke),+ ::testing::ValuesIn(routing_types),+ ::testing::ValuesIn(weights_precisions),+ ::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)),+ MoE3GemmCompressedFusionTest::getTestCaseName);++} // namespacediff --git a/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cppindex 2d4cc89b2a7..025fabb3a59 100644--- a/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cpp+++ b/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cpp@@ -1,5 +1,7 @@// Copyright (C) 2018-2026 Intel Corporation// SPDX-License-Identifier: Apache-2.0+//+#include <algorithm>#include <cmath>#include <intel_gpu/primitives/data.hpp>@@ -110,19 +112,17 @@ struct Moe3GemmReference {return {q_data, scales, zps};}- std::vector<ov::float16> run_reference(const std::vector<ov::float16>& hidden_states,- const std::vector<ov::float16>& routing_weights,- const std::vector<float>& w0_data,- const std::vector<float>& w1_data,- const std::vector<float>& w2_data) {+ std::vector<ov::float16> run_reference_softmax(const std::vector<ov::float16>& hidden_states,+ const std::vector<ov::float16>& routing_weights,+ const std::vector<float>& w0_data,+ const std::vector<float>& w1_data,+ const std::vector<float>& w2_data) {size_t batch_size = config.batch_size;size_t seq_len = config.seq_len;- size_t hidden_size = config.hidden_size;- size_t inter_size = config.inter_size;size_t num_experts = config.num_experts;size_t top_k = config.top_k;- std::vector<ov::float16> output(batch_size * seq_len * hidden_size, 0);+ std::vector<ov::float16> output(batch_size * seq_len * config.hidden_size, 0);for (size_t b = 0; b < batch_size; ++b) {for (size_t s = 0; s < seq_len; ++s) {@@ -154,67 +154,131 @@ struct Moe3GemmReference {return a.first > b.first;});- // Normalize weights+ // Normalize top-k weightsfloat sum_weights = 0.0f;- for (size_t k = 0; k < top_k; ++k) {+ for (size_t k = 0; k < top_k; ++k)sum_weights += expert_weights[k].first;- }- for (size_t k = 0; k < top_k; ++k) {- size_t expert_idx = expert_weights[k].second;- float weight = expert_weights[k].first / sum_weights;-- std::vector<float> gate(inter_size);- std::vector<float> up(inter_size);-- // Compute gate and up- for (size_t i = 0; i < inter_size; ++i) {- float gate_val = 0.0f;- float up_val = 0.0f;- for (size_t j = 0; j < hidden_size; ++j) {- float x_val = static_cast<float>(hidden_states[b * seq_len * hidden_size + s * hidden_size + j]);-- // w0_data is Row-Major: [num_experts, hidden_size, inter_size]- size_t w0_cols = inter_size;- size_t w0_r = expert_idx * hidden_size + j;- float w0_val = w0_data[w0_r * w0_cols + i];- gate_val += x_val * w0_val;-- // w1_data is Row-Major: [num_experts, hidden_size, inter_size]- size_t w1_cols = inter_size;- size_t w1_r = expert_idx * hidden_size + j;- float w1_val = w1_data[w1_r * w1_cols + i];- up_val += x_val * w1_val;- }- gate[i] = gate_val;- up[i] = up_val;- }+ std::vector<std::pair<float, size_t>> top_k_normalized(top_k);+ for (size_t k = 0; k < top_k; ++k)+ top_k_normalized[k] = {expert_weights[k].first / sum_weights, expert_weights[k].second};+ apply_top_k_experts(b, s, hidden_states, w0_data, w1_data, w2_data, top_k_normalized, output);+ }+ }+ return output;+ }- // SwiGLU- std::vector<float> act(inter_size);- for (size_t i = 0; i < inter_size; ++i) {- float silu = gate[i] / (1.0f + std::exp(-gate[i]));- act[i] = silu * up[i];- }+ std::vector<ov::float16> run_reference_sigmoid(const std::vector<ov::float16>& hidden_states,+ const std::vector<ov::float16>& routing_logits,+ const std::vector<ov::float16>& routing_bias,+ ov::float16 epsilon,+ const std::vector<float>& w0_data,+ const std::vector<float>& w1_data,+ const std::vector<float>& w2_data) {+ size_t batch_size = config.batch_size;+ size_t seq_len = config.seq_len;+ size_t num_experts = config.num_experts;+ size_t top_k = config.top_k;- // Compute out = act @ w2- for (size_t j = 0; j < hidden_size; ++j) {- float out_val = 0.0f;- for (size_t i = 0; i < inter_size; ++i) {- // w2_data is Row-Major: [num_experts, inter_size, hidden_size]- size_t w2_cols = hidden_size;- size_t w2_r = expert_idx * inter_size + i;- float w2_val = w2_data[w2_r * w2_cols + j];-- out_val += act[i] * w2_val;- }- output[b * seq_len * hidden_size + s * hidden_size + j] += static_cast<ov::float16>(out_val * weight);- }+ std::vector<ov::float16> output(batch_size * seq_len * config.hidden_size, 0);++ for (size_t b = 0; b < batch_size; ++b) {+ for (size_t s = 0; s < seq_len; ++s) {+ // Apply sigmoid to logits+ std::vector<float> sigmoid_scores(num_experts);+ for (size_t e = 0; e < num_experts; ++e) {+ float logit = static_cast<float>(routing_logits[b * seq_len * num_experts + s * num_experts + e]);+ sigmoid_scores[e] = 1.0f / (1.0f + std::exp(-logit));+ }++ // Add bias and select top-k by (sigmoid + bias)+ std::vector<std::pair<float, size_t>> expert_weights;+ for (size_t e = 0; e < num_experts; ++e) {+ float score = sigmoid_scores[e] + static_cast<float>(routing_bias[e]);+ expert_weights.push_back({score, e});}+ std::partial_sort(expert_weights.begin(),+ expert_weights.begin() + top_k,+ expert_weights.end(),+ [](const std::pair<float, size_t>& a, const std::pair<float, size_t>& b) {+ return a.first > b.first;+ });++ // Gather sigmoid scores at top-k indices and normalize+ float sum_weights = 0.0f;+ for (size_t k = 0; k < top_k; ++k)+ sum_weights += sigmoid_scores[expert_weights[k].second];+ sum_weights += static_cast<float>(epsilon);++ std::vector<std::pair<float, size_t>> top_k_normalized(top_k);+ for (size_t k = 0; k < top_k; ++k)+ top_k_normalized[k] = {sigmoid_scores[expert_weights[k].second] / sum_weights, expert_weights[k].second};+ apply_top_k_experts(b, s, hidden_states, w0_data, w1_data, w2_data, top_k_normalized, output);}}return output;}++private:+ void apply_top_k_experts(size_t b,+ size_t s,+ const std::vector<ov::float16>& hidden_states,+ const std::vector<float>& w0_data,+ const std::vector<float>& w1_data,+ const std::vector<float>& w2_data,+ const std::vector<std::pair<float, size_t>>& top_k_normalized,+ std::vector<ov::float16>& output) {+ const size_t hidden_size = config.hidden_size;+ const size_t inter_size = config.inter_size;++ for (const auto& [weight, expert_idx] : top_k_normalized) {+ std::vector<float> gate(inter_size);+ std::vector<float> up(inter_size);++ // Compute gate and up+ for (size_t i = 0; i < inter_size; ++i) {+ float gate_val = 0.0f;+ float up_val = 0.0f;+ for (size_t j = 0; j < hidden_size; ++j) {+ float x_val = static_cast<float>(hidden_states[b * config.seq_len * hidden_size + s * hidden_size + j]);++ // w0_data is Row-Major: [num_experts, hidden_size, inter_size]+ size_t w0_cols = inter_size;+ size_t w0_r = expert_idx * hidden_size + j;+ float w0_val = w0_data[w0_r * w0_cols + i];+ gate_val += x_val * w0_val;++ // w1_data is Row-Major: [num_experts, hidden_size, inter_size]+ size_t w1_cols = inter_size;+ size_t w1_r = expert_idx * hidden_size + j;+ float w1_val = w1_data[w1_r * w1_cols + i];+ up_val += x_val * w1_val;+ }+ gate[i] = gate_val;+ up[i] = up_val;+ }++ // SwiGLU+ std::vector<float> act(inter_size);+ for (size_t i = 0; i < inter_size; ++i) {+ float silu = gate[i] / (1.0f + std::exp(-gate[i]));+ act[i] = silu * up[i];+ }++ // Compute out = act @ w2+ for (size_t j = 0; j < hidden_size; ++j) {+ float out_val = 0.0f;+ for (size_t i = 0; i < inter_size; ++i) {+ // w2_data is Row-Major: [num_experts, inter_size, hidden_size]+ size_t w2_cols = hidden_size;+ size_t w2_r = expert_idx * inter_size + i;+ float w2_val = w2_data[w2_r * w2_cols + j];+ out_val += act[i] * w2_val;+ }+ output[b * config.seq_len * hidden_size + s * hidden_size + j] += static_cast<ov::float16>(out_val * weight);+ }+ }+ }};struct Moe3GemmTestParams {@@ -227,13 +291,13 @@ struct Moe3GemmTestParams {size_t group_size;};-class moe_3gemm_compressed_gpu_random : public ::testing::TestWithParam<Moe3GemmTestParams> {};+class moe_3gemm_compressed_gpu_random : public ::testing::TestWithParam<std::tuple<cldnn::MOE3GemmFusedCompressed::RoutingType, Moe3GemmTestParams>> {};TEST_P(moe_3gemm_compressed_gpu_random, moe_accuracy_test_random) {- auto param = GetParam();+ const auto& [routing_type, param] = GetParam();auto& engine = get_test_engine();if (!engine.get_device_info().supports_immad) {- return;+ GTEST_SKIP() << "No immad support";}tests::random_generator rg(GET_SUITE_NAME);@@ -296,8 +360,18 @@ TEST_P(moe_3gemm_compressed_gpu_random, moe_accuracy_test_random) {return mem;};- auto hidden_states_mem = create_f16_tensor(hidden_states, config.batch_size, config.seq_len, config.hidden_size, 1);- auto routing_weights_mem = create_f16_tensor(routing_weights, config.batch_size, config.seq_len, config.num_experts, 1);+ auto create_f16_tensor_3d = [&](const std::vector<ov::float16>& values, int64_t d0, int64_t d1, int64_t d2) {+ auto mem = engine.allocate_memory(layout{ov::PartialShape{d0, d1, d2}, data_types::f16, format::bfyx});+ set_values(mem, values);+ get_test_stream().finish();+ return mem;+ };++ auto hidden_states_mem = create_f16_tensor_3d(hidden_states, config.batch_size, config.seq_len, config.hidden_size);+ auto routing_weights_mem = create_f16_tensor_3d(routing_weights, config.batch_size, config.seq_len, config.num_experts);+ auto routing_bias_data = rg.generate_random_1d<ov::float16>(config.num_experts, -0.5f, 0.5f, 1000);+ auto routing_bias_mem = create_f16_tensor(routing_bias_data, 1, 1, 1, config.num_experts);+ ov::float16 routing_eps_val = ov::float16(1e-6f);size_t group_num = config.hidden_size / config.group_size;size_t group_num2 = config.inter_size / config.group_size;@@ -335,20 +409,30 @@ TEST_P(moe_3gemm_compressed_gpu_random, moe_accuracy_test_random) {moe_config.top_k = config.top_k;moe_config.group_size = config.group_size;moe_config.out_type = data_types::f16;+ moe_config.routing_type = routing_type;++ std::vector<input_info> moe_inputs{input_info("hidden_states"),+ input_info("routing_weights"),+ input_info("w0_weight"),+ input_info("w0_scale"),+ input_info("w0_zp"),+ input_info("w1_weight"),+ input_info("w1_scale"),+ input_info("w1_zp"),+ input_info("w2_weight"),+ input_info("w2_scale"),+ input_info("w2_zp")};+ if (routing_type == cldnn::MOE3GemmFusedCompressed::RoutingType::SIGMOID_BIAS) {+ topology.add(data("routing_bias", routing_bias_mem));+ moe_inputs.push_back(input_info("routing_bias"));+ auto routing_eps_mem = engine.allocate_memory({data_types::f16, format::bfyx, {1, 1, 1, 1}});+ set_values(routing_eps_mem, {routing_eps_val});+ get_test_stream().finish();+ topology.add(data("routing_eps", routing_eps_mem));+ moe_inputs.push_back(input_info("routing_eps"));+ }- auto moe_prim = moe_3gemm_fused_compressed("moe_3gemm_fused_compressed",- {input_info("hidden_states"),- input_info("routing_weights"),- input_info("w0_weight"),- input_info("w0_scale"),- input_info("w0_zp"),- input_info("w1_weight"),- input_info("w1_scale"),- input_info("w1_zp"),- input_info("w2_weight"),- input_info("w2_scale"),- input_info("w2_zp")},- moe_config);+ auto moe_prim = moe_3gemm_fused_compressed("moe_3gemm_fused_compressed", moe_inputs, moe_config);topology.add(moe_prim);@@ -361,23 +445,33 @@ TEST_P(moe_3gemm_compressed_gpu_random, moe_accuracy_test_random) {get_test_stream().flush();cldnn::mem_lock<ov::float16, mem_lock_type::read> output_ptr(output_prim, get_test_stream());- auto ref_output = ref.run_reference(hidden_states, routing_weights, w0_data, w1_data, w2_data);+ auto ref_output = routing_type == cldnn::MOE3GemmFusedCompressed::RoutingType::SIGMOID_BIAS+ ? ref.run_reference_sigmoid(hidden_states, routing_weights, routing_bias_data, routing_eps_val, w0_data, w1_data, w2_data)+ : ref.run_reference_softmax(hidden_states, routing_weights, w0_data, w1_data, w2_data);+ // SigmoidBias routing performs all routing math (sigmoid, bias, normalization) in f16 on the kernel side,+ // while the reference uses f32, leading to slightly larger numerical divergence than Softmax.+ const float tolerance = routing_type == cldnn::MOE3GemmFusedCompressed::RoutingType::SIGMOID_BIAS ? 0.2f : 0.1f;for (size_t i = 0; i < ref_output.size(); ++i) {- ASSERT_NEAR(static_cast<float>(output_ptr[i]), static_cast<float>(ref_output[i]), 0.1f);+ ASSERT_NEAR(static_cast<float>(output_ptr[i]), static_cast<float>(ref_output[i]), tolerance);}}INSTANTIATE_TEST_SUITE_P(smoke,moe_3gemm_compressed_gpu_random,- ::testing::Values(Moe3GemmTestParams{1, true, 128, 256, 4, 2, 128},- Moe3GemmTestParams{16, true, 128, 256, 4, 2, 128},- Moe3GemmTestParams{1, false, 128, 256, 4, 2, 128},- Moe3GemmTestParams{16, false, 128, 256, 4, 2, 128}));+ ::testing::Combine(::testing::Values(cldnn::MOE3GemmFusedCompressed::RoutingType::SOFTMAX,+ cldnn::MOE3GemmFusedCompressed::RoutingType::SIGMOID_BIAS),+ ::testing::Values(Moe3GemmTestParams{1, true, 128, 256, 4, 2, 128},+ Moe3GemmTestParams{16, true, 128, 256, 4, 2, 128},+ Moe3GemmTestParams{1, false, 128, 256, 4, 2, 128},+ Moe3GemmTestParams{16, false, 128, 256, 4, 2, 128})));++class moe_3gemm_compressed_gpu_u4 : public ::testing::TestWithParam<cldnn::MOE3GemmFusedCompressed::RoutingType> {};-TEST(moe_3gemm_compressed_gpu, moe_accuracy_test_u4) {+TEST_P(moe_3gemm_compressed_gpu_u4, moe_accuracy_test_u4) {+ auto routing_type = GetParam();auto& engine = get_test_engine();if (!engine.get_device_info().supports_immad) {- return;+ GTEST_SKIP() << "No immad support";}const size_t batch_size = 1;@@ -403,11 +497,19 @@ TEST(moe_3gemm_compressed_gpu, moe_accuracy_test_u4) {get_test_stream().finish();return mem;};- // Input 0: hidden_states [batch_size, seq_len, hidden_size]- auto hidden_states = create_f16_tensor(hidden_states_data, batch_size, seq_len, hidden_size, 1);++ auto create_f16_tensor_3d = [&](const std::vector<ov::float16>& values, int64_t d0, int64_t d1, int64_t d2) {+ auto mem = engine.allocate_memory(layout{ov::PartialShape{d0, d1, d2}, data_types::f16, format::bfyx});+ set_values(mem, values);+ get_test_stream().finish();+ return mem;+ };++ auto hidden_states = create_f16_tensor_3d(hidden_states_data, batch_size, seq_len, hidden_size);// Input 1: routing_weights [batch_size, seq_len, num_experts]- auto routing_weights = create_f16_tensor(router_weights_data, batch_size, seq_len, num_experts, 1);+ auto routing_weights = create_f16_tensor_3d(router_weights_data, batch_size, seq_len, num_experts);+ auto routing_bias = create_f16_tensor(routing_bias_data, 1, 1, 1, num_experts);// Input 3: w0_weight [num_experts, inter_size, group_num, group_size]auto w0_weight = create_u4_tensor(w0_weights_data, num_experts, inter_size, group_num, group_size);@@ -461,29 +563,38 @@ TEST(moe_3gemm_compressed_gpu, moe_accuracy_test_u4) {config.top_k = top_k;config.group_size = group_size;config.out_type = data_types::f16;+ config.routing_type = routing_type;++ std::vector<input_info> moe_inputs{input_info("hidden_states"),+ input_info("routing_weights"),+ input_info("w0_weight"),+ input_info("w0_scale"),+ input_info("w0_zp"),+ input_info("w1_weight"),+ input_info("w1_scale"),+ input_info("w1_zp"),+ input_info("w2_weight"),+ input_info("w2_scale"),+ input_info("w2_zp")};+ if (routing_type == cldnn::MOE3GemmFusedCompressed::RoutingType::SIGMOID_BIAS) {+ topology.add(data("routing_bias", routing_bias));+ moe_inputs.push_back(input_info("routing_bias"));+ auto routing_eps_mem = engine.allocate_memory({data_types::f16, format::bfyx, {1, 1, 1, 1}});+ set_values(routing_eps_mem, {ov::float16(1e-6f)});+ get_test_stream().finish();+ topology.add(data("routing_eps", routing_eps_mem));+ moe_inputs.push_back(input_info("routing_eps"));+ }// Create MOECompressed primitive- auto moe_prim = moe_3gemm_fused_compressed("moe_3gemm_fused_compressed",- {input_info("hidden_states"),- input_info("routing_weights"),- input_info("w0_weight"),- input_info("w0_scale"),- input_info("w0_zp"),- input_info("w1_weight"),- input_info("w1_scale"),- input_info("w1_zp"),- input_info("w2_weight"),- input_info("w2_scale"),- input_info("w2_zp")},- config);-- topology.add(moe_prim);+ topology.add(moe_3gemm_fused_compressed("moe_3gemm_fused_compressed", moe_inputs, config));// Create and execute networknetwork network(engine, topology, get_test_default_config(engine));network.set_input_data("hidden_states", hidden_states);network.set_input_data("routing_weights", routing_weights);+ // Verify output shape should be [batch_size, seq_len, hidden_size]auto outputs = network.execute();ASSERT_EQ(outputs.size(), size_t(1));ASSERT_EQ(outputs.begin()->first, "moe_3gemm_fused_compressed");@@ -492,12 +603,16 @@ TEST(moe_3gemm_compressed_gpu, moe_accuracy_test_u4) {get_test_stream().flush();cldnn::mem_lock<ov::float16, mem_lock_type::read> output_ptr(output_prim, get_test_stream());- // Verify output shape should be [batch_size, seq_len, hidden_size]auto output_layout = output_prim->get_layout();EXPECT_EQ(output_layout.batch(), batch_size);EXPECT_EQ(output_layout.feature(), seq_len);+ const auto& output_reference = routing_type == cldnn::MOE3GemmFusedCompressed::RoutingType::SIGMOID_BIAS ? output_ref_sigmoid_bias : output_ref_softmax;for (size_t i = 0; i < batch_size * seq_len * hidden_size; ++i) {- EXPECT_NEAR(static_cast<float>(output_ptr[i]), static_cast<float>(output_ref[i]), 1e-3f);+ EXPECT_NEAR(static_cast<float>(output_ptr[i]), static_cast<float>(output_reference[i]), 1e-3f);}-}\ No newline at end of file+}++INSTANTIATE_TEST_SUITE_P(smoke,+ moe_3gemm_compressed_gpu_u4,+ ::testing::Values(cldnn::MOE3GemmFusedCompressed::RoutingType::SOFTMAX, cldnn::MOE3GemmFusedCompressed::RoutingType::SIGMOID_BIAS));\ No newline at end of filediff --git a/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_test_data.h b/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_test_data.hindex b6acb5c3cdd..f09187772cf 100644--- a/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_test_data.h+++ b/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_test_data.h@@ -1,3 +1,7 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+#include <intel_gpu/primitives/data.hpp>#include <numeric>#include <vector>@@ -27,6 +31,12 @@ std::vector<ov::float16> router_weights_data = {0.6982421875,-0.344970703125,};+std::vector<ov::float16> routing_bias_data = {+ 0.1f,+ -0.2f,+ 0.3f,+ -0.1f,+};std::vector<uint8_t> w0_weights_data = {0, 1, 32, 0, 2, 1, 33, 2, 0, 33, 33, 16, 33, 18, 18, 34, 33, 16, 32, 0, 2, 2, 16, 18, 16, 1, 34, 16, 2, 17, 33, 16, 1, 0, 18, 34, 16, 18, 0,0, 16, 17, 18, 32, 16, 18, 1, 33, 1, 0, 33, 33, 1, 0, 33, 34, 16, 2, 2, 33, 32, 16, 2, 32, 1, 1, 17, 1, 34, 17, 32, 2, 17, 0, 32, 34, 0, 34,@@ -2695,7 +2705,7 @@ std::vector<uint8_t> w2_zp_data = {32, 32, 17, 1, 0, 33, 33, 17, 18, 18, 34, 17, 32, 0, 17, 32, 1, 1, 17, 18, 32, 16, 16, 16, 18, 34, 18, 16, 17, 32, 17, 17, 34, 0,};-ov::float16 output_ref[128] = {+ov::float16 output_ref_softmax[128] = {0.153564453125,0.0797119140625,0.0118408203125,@@ -2824,4 +2834,135 @@ ov::float16 output_ref[128] = {-0.164794921875,-0.25732421875,0.07373046875,+};++ov::float16 output_ref_sigmoid_bias[128] = {+ 0.140137,+ 0.0834351,+ 0.0233765,+ -0.195801,+ 0.0799561,+ -0.0205994,+ -0.0327148,+ -0.133545,+ 0.0275574,+ 0.0119095,+ -0.0194855,+ -0.181274,+ -0.265869,+ -0.0134277,+ 0.107422,+ 0,+ 0.0968018,+ -0.0708008,+ -0.0913696,+ 0.0765381,+ 0.0195465,+ 0.367188,+ -0.0648804,+ -0.00517273,+ 0.044281,+ 0.0308838,+ 0.303223,+ 0.133057,+ -0.0641479,+ 0,+ 0.038208,+ 0.0584412,+ -0.142944,+ -0.00142574,+ 0.0592651,+ 0.264648,+ -0.00340843,+ 0.0576172,+ 0.423828,+ 0.213379,+ 0.286377,+ -0.0353699,+ -0.260742,+ 0.21167,+ -0.0206604,+ 0.0333252,+ -0.166992,+ -0.0209198,+ 0.239014,+ 0.193359,+ -0.014679,+ -0.228149,+ 0.0567322,+ 0.381348,+ 0.0984497,+ 0.13208,+ 0.0779419,+ 0.0571594,+ -0.0310822,+ 0.0808716,+ 0.208252,+ -0.346436,+ -0.0372925,+ -0.00139618,+ 0.225098,+ -0.0685425,+ -0.0270844,+ -0.01651,+ 0.176025,+ -0.0938721,+ 0.0750122,+ 0.000518799,+ -0.0255127,+ -0.0859375,+ 0.122559,+ 0.267578,+ 0.0698242,+ -0.185059,+ -0.0984497,+ 0.167114,+ 0.131836,+ 0.44165,+ 0.0180054,+ -0.0799561,+ 0.025238,+ 0.065979,+ 0.0792847,+ 0.137939,+ 0.151367,+ -0.0610962,+ -0.157471,+ 0.0775146,+ -0.120422,+ 0.0212402,+ 0.182495,+ 0,+ 0.20459,+ -0.220703,+ 0,+ -0.139038,+ -0.0322876,+ 0.0542603,+ -0.0875244,+ -0.178345,+ -0.0153809,+ 0.00948334,+ -0.276855,+ 0.0940552,+ 0.0739746,+ 0.0549011,+ 0.022583,+ 0.193115,+ 0.206421,+ 0.278076,+ 0.266113,+ -0.0126953,+ 0.455566,+ -0.19812,+ 0.131226,+ -0.160645,+ -0.136719,+ 0.365479,+ -0.076416,+ -0.0355225,+ -0.189697,+ -0.18457,+ -0.251465,+ 0.0783691,};\ No newline at end of filediff --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.cppindex a4deed264de..ab9a898da7a 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@@ -7,25 +7,12 @@#include "common_test_utils/ov_test_utils.hpp"#include "intel_gpu/op/moe_compressed.hpp"#include "intel_gpu/op/moe_3gemm_fused_compressed.hpp"-#include "openvino/op/broadcast.hpp"-#include "openvino/op/concat.hpp"#include "openvino/op/constant.hpp"-#include "openvino/op/convert.hpp"-#include "openvino/op/divide.hpp"-#include "openvino/op/gather.hpp"#include "openvino/op/matmul.hpp"-#include "openvino/op/multiply.hpp"-#include "openvino/op/reduce_sum.hpp"#include "openvino/op/reshape.hpp"-#include "openvino/op/scatter_elements_update.hpp"#include "openvino/op/shape_of.hpp"-#include "openvino/op/slice.hpp"-#include "openvino/op/softmax.hpp"-#include "openvino/op/subtract.hpp"-#include "openvino/op/topk.hpp"-#include "openvino/op/transpose.hpp"-#include "openvino/op/unsqueeze.hpp"#include "plugin/transformations/fuse_moe_3gemm_compressed.hpp"+#include "common_test_utils/node_builders/moe_builders.hpp"using namespace testing;using namespace ov::intel_gpu;@@ -33,57 +20,48 @@ using namespace ov::intel_gpu;namespace ov {namespace test {namespace intel_gpu {-TEST_F(TransformationTestsF, FuseMOE3GemmCompressedTest) {++using namespace ov::test;++using FuseMOE3GemmCompressedTestParams = std::tuple<MoERoutingType, bool /* reshape_on_moe_input */>;++class FuseMOE3GemmCompressedTest : public TransformationTestsF,+ public ::testing::WithParamInterface<FuseMOE3GemmCompressedTestParams> {+public:+ static std::string get_test_case_name(const ::testing::TestParamInfo<FuseMOE3GemmCompressedTestParams>& info) {+ std::string name;+ switch (std::get<0>(info.param)) {+ case MoERoutingType::SOFTMAX:+ name = "Softmax";+ break;+ case MoERoutingType::SIGMOID_BIAS:+ name = "SigmoidBias";+ break;+ default:+ OPENVINO_THROW("Unsupported routing type");+ }+ if (std::get<1>(info.param))+ name += "_ReshapeOnMoeInput";+ return name;+ }+};++TEST_P(FuseMOE3GemmCompressedTest, CompareFunctions) {+ const auto& [routing_type, reshape_on_moe_input] = GetParam();{- // tokens:32, hidden_size:2048, iter_size:768, experts:128, topk:8+ // tokens:32, hidden_size:2048, inter_size:768, experts:128, topk:8auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{4, 8, 2048});auto flatten_shape = op::v0::Constant::create(element::i32, Shape{2}, {32, 2048});auto hidden_states_reshape = std::make_shared<ov::op::v1::Reshape>(hidden_states, flatten_shape, false);auto routers = op::v0::Constant::create(element::f16, Shape{2048, 128}, {0.2});auto routing_weights = std::make_shared<ov::op::v0::MatMul>(hidden_states_reshape, routers);- auto softmax = std::make_shared<ov::op::v8::Softmax>(routing_weights, 1);- auto k = op::v0::Constant::create(element::i32, Shape{}, {8});- auto topk = std::make_shared<ov::op::v11::TopK>(softmax, k, 1,- ov::op::v11::TopK::Mode::MAX, ov::op::v11::TopK::SortType::SORT_VALUES);-- // weight output- auto reduce_axis = op::v0::Constant::create(element::i64, Shape{1}, {1});- auto reduce_sum = std::make_shared<ov::op::v1::ReduceSum>(topk->output(0), reduce_axis->output(0), true);- auto norm = std::make_shared<ov::op::v1::Divide>(topk->output(0), reduce_sum->output(0));-- // 32- auto shape_of = std::make_shared<ov::op::v3::ShapeOf>(topk->output(1)); // [2]{32, 8}- auto gather_idx = op::v0::Constant::create(element::i64, Shape{}, {0});- auto gather_axis = op::v0::Constant::create(element::i64, Shape{}, {0});- auto gather = std::make_shared<ov::op::v8::Gather>(shape_of, gather_idx, gather_axis); // scalar: 32- auto const_unsqueeze = op::v0::Constant::create(element::i64, Shape{1}, {0});- auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(gather, const_unsqueeze); // [1]{32}-- // 128- auto const0 = op::v0::Constant::create(element::i64, Shape{}, {128});- auto const1 = op::v0::Constant::create(element::i64, Shape{1}, {0});- auto unsqueeze1 = std::make_shared<ov::op::v0::Unsqueeze>(const0, const1); // [1]{128}- auto concat = std::make_shared<ov::op::v0::Concat>(OutputVector{unsqueeze, unsqueeze1}, 0); // [2]{32,128}- auto const3 = op::v0::Constant::create(element::i64, Shape{1}, {1});- auto concat1 = std::make_shared<ov::op::v0::Concat>(OutputVector{unsqueeze1, unsqueeze, const3}, 0);-- // [32, 128]- auto zero = op::v0::Constant::create(element::f16, Shape{1}, {0});- auto bc = std::make_shared<ov::op::v3::Broadcast>(zero, concat);- auto scatter_axis = op::v0::Constant::create(element::i64, Shape{1}, {1});- auto scatter = std::make_shared<ov::op::v12::ScatterElementsUpdate>(bc, // [32, 128]- topk->output(1), // [32, 8]- norm, // [32, 8]- scatter_axis, // [1]- ov::op::v12::ScatterElementsUpdate::Reduction::SUM);- auto transpose_shape = op::v0::Constant::create(element::i64, Shape{2}, {1, 0});- auto transpose = std::make_shared<ov::op::v1::Transpose>(scatter, transpose_shape); // [128, 32]- auto reshape = std::make_shared<ov::op::v1::Reshape>(transpose, concat1, false);- auto unsqueeze_const = op::v0::Constant::create(element::i64, Shape{1}, {3});- auto unsqueeze_moe = std::make_shared<ov::op::v0::Unsqueeze>(reshape, unsqueeze_const); // [128, 1, 32, 1]-- // weight+ // tokens:32, num_experts:128, topk:8+ auto [unsqueeze_moe, topk_indices] =+ routing_type == MoERoutingType::SOFTMAX+ ? build_softmax_routing_subgraph(routing_weights, 128, 8)+ : build_sigmoid_bias_routing_subgraph(routing_weights, element::f16, 128, 8);+auto wei_gate = op::v0::Constant::create(element::u4, Shape{128, 768, 16, 128}, {1});auto scale_gate = op::v0::Constant::create(element::f16, Shape{128, 16, 768}, {0.01f});auto zp_gate = op::v0::Constant::create(element::u4, Shape{128, 16, 768}, {0});@@ -101,21 +79,26 @@ TEST_F(TransformationTestsF, FuseMOE3GemmCompressedTest) {config.group_size = 128;config.top_k = 8;config.out_type = ov::element::f16;++ // When reshape_on_moe_input is true, MOECompressed gets the flattened 2D hidden_states_reshape;+ // otherwise it gets the original 3D hidden_states.+ auto moe_input_0 = reshape_on_moe_input+ ? ov::Output<ov::Node>(hidden_states_reshape)+ : ov::Output<ov::Node>(hidden_states);auto moe_compressed = std::make_shared<ov::intel_gpu::op::MOECompressed>(- ov::OutputVector{hidden_states_reshape, unsqueeze_moe, topk->output(1),+ ov::OutputVector{moe_input_0, unsqueeze_moe, topk_indices,wei_gate, scale_gate, zp_gate, wei_up, scale_up, zp_up, wei_down, scale_down, zp_down}, config);model = std::make_shared<ov::Model>(moe_compressed, ov::ParameterVector{hidden_states});- manager.register_pass<FuseMOE3GemmCompressed>();}+ manager.register_pass<FuseMOE3GemmCompressed>();{- // tokens:32, hidden_size:2048, iter_size:768, experts:128, topk:8+ // tokens:32, hidden_size:2048, inter_size:768, experts:128, topk:8auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{4, 8, 2048});auto flatten_shape = op::v0::Constant::create(element::i32, Shape{2}, {32, 2048});auto hidden_states_reshape = std::make_shared<ov::op::v1::Reshape>(hidden_states, flatten_shape, false);auto routers = op::v0::Constant::create(element::f16, Shape{2048, 128}, {0.2});auto routing_weights = std::make_shared<ov::op::v0::MatMul>(hidden_states_reshape, routers);- // weightauto wei_gate = op::v0::Constant::create(element::u4, Shape{128, 768, 16, 128}, {1});auto scale_gate = op::v0::Constant::create(element::f16, Shape{128, 16, 768}, {0.01f});auto zp_gate = op::v0::Constant::create(element::u4, Shape{128, 16, 768}, {0});@@ -133,122 +116,43 @@ TEST_F(TransformationTestsF, FuseMOE3GemmCompressedTest) {config.group_size = 128;config.top_k = 8;config.out_type = ov::element::f16;- auto moe_3gemm_fused_compressed = std::make_shared<ov::intel_gpu::op::MOE3GemmFusedCompressed>(- ov::OutputVector{hidden_states_reshape, routing_weights,- wei_gate, scale_gate, zp_gate, wei_up, scale_up, zp_up, wei_down, scale_down, zp_down}, config);-- model_ref = std::make_shared<ov::Model>(moe_3gemm_fused_compressed, ov::ParameterVector{hidden_states});+ if (routing_type == MoERoutingType::SOFTMAX) {+ config.routing_type = ov::intel_gpu::op::MOECompressed::RoutingType::SOFTMAX;+ } else if (routing_type == MoERoutingType::SIGMOID_BIAS) {+ config.routing_type = ov::intel_gpu::op::MOECompressed::RoutingType::SIGMOID_BIAS;+ } else {+ 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};+ if (routing_type == MoERoutingType::SIGMOID_BIAS) {+ auto routing_bias = op::v0::Constant::create(element::f16, Shape{1, 128}, {0.1f});+ args.push_back(routing_bias);+ auto routing_eps = op::v0::Constant::create(element::f16, 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.+ if (!reshape_on_moe_input) {+ 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);+ }++ model_ref = std::make_shared<ov::Model>(result, ov::ParameterVector{hidden_states});}}-TEST_F(TransformationTestsF, FuseMOE3GemmCompressedTest1) {- {- // tokens:32, hidden_size:2048, iter_size:512, experts:512, topk:10- auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{4, 8, 2048});- auto flatten_shape = op::v0::Constant::create(element::i32, Shape{2}, {32, 2048});- auto hidden_states_reshape = std::make_shared<ov::op::v1::Reshape>(hidden_states, flatten_shape, false);- auto routers = op::v0::Constant::create(element::f16, Shape{2048, 512}, {0.2});- // [32, 512]- auto routing_weights = std::make_shared<ov::op::v0::MatMul>(hidden_states_reshape, routers);-- auto softmax = std::make_shared<ov::op::v8::Softmax>(routing_weights, 1);- auto k = op::v0::Constant::create(element::i64, Shape{}, {10});- // [32, 10]- auto topk = std::make_shared<ov::op::v11::TopK>(softmax, k, 1,- ov::op::v11::TopK::Mode::MAX, ov::op::v11::TopK::SortType::SORT_VALUES);-- // weight output- auto reduce_axis = op::v0::Constant::create(element::i64, Shape{1}, {1});- auto reduce_sum = std::make_shared<ov::op::v1::ReduceSum>(topk->output(0), reduce_axis->output(0), true);- auto norm = std::make_shared<ov::op::v1::Divide>(topk->output(0), reduce_sum->output(0));-- // index- auto topk_indices_i32 = std::make_shared<ov::op::v0::Convert>(topk->output(1), ov::element::i32);- auto shape_of = std::make_shared<ov::op::v3::ShapeOf>(topk_indices_i32);-- auto slice = std::make_shared<ov::op::v8::Slice>(norm,- op::v0::Constant::create(element::i32, Shape{2}, {0, 0}),- shape_of,- op::v0::Constant::create(element::i32, Shape{2}, {1, 1}),- op::v0::Constant::create(element::i32, Shape{2}, {0, 1}));-- auto zero = op::v0::Constant::create(element::f16, Shape{1}, {0});- auto router_shape = op::v0::Constant::create(element::i64, Shape{2}, {32, 512});- auto bc = std::make_shared<ov::op::v3::Broadcast>(zero, router_shape);- auto scatter_axis = op::v0::Constant::create(element::i64, Shape{1}, {1});- auto scatter = std::make_shared<ov::op::v12::ScatterElementsUpdate>(bc,- topk_indices_i32,- slice,- scatter_axis);- // [512, 32]- auto transpose_shape = op::v0::Constant::create(element::i64, Shape{2}, {1, 0});- auto transpose = std::make_shared<ov::op::v1::Transpose>(scatter, transpose_shape);- // [512, 4, 8]- auto router_shape_transpose = op::v0::Constant::create(element::i64, Shape{3}, {512, 4, 8});- auto reshape = std::make_shared<ov::op::v1::Reshape>(transpose, router_shape_transpose, false);- // [512, 4, 8, 1]- auto unsqueeze_const = op::v0::Constant::create(element::i64, Shape{1}, {3});- auto unsqueeze_moe = std::make_shared<ov::op::v0::Unsqueeze>(reshape, unsqueeze_const);-- // weight- auto wei_gate = op::v0::Constant::create(element::u4, Shape{512, 512, 16, 128}, {1});- auto scale_gate = op::v0::Constant::create(element::f16, Shape{512, 16, 512}, {0.01f});- auto zp_gate = op::v0::Constant::create(element::u4, Shape{512, 16, 512}, {0});- auto wei_up = op::v0::Constant::create(element::u4, Shape{512, 512, 16, 128}, {1});- auto scale_up = op::v0::Constant::create(element::f16, Shape{512, 16, 512}, {0.01f});- auto zp_up = op::v0::Constant::create(element::u4, Shape{512, 16, 512}, {0});- auto wei_down = op::v0::Constant::create(element::u4, Shape{512, 2048, 4, 128}, {1});- auto scale_down = op::v0::Constant::create(element::f16, Shape{512, 4, 2048}, {0.01f});- auto zp_down = op::v0::Constant::create(element::u4, Shape{512, 4, 2048}, {0});-- ov::intel_gpu::op::MOECompressed::Config config;- config.hidden_size = 2048;- config.inter_size = 512;- config.num_expert = 512;- config.group_size = 128;- config.top_k = 10;- config.out_type = ov::element::f16;- auto moe_compressed = std::make_shared<ov::intel_gpu::op::MOECompressed>(- ov::OutputVector{hidden_states, unsqueeze_moe, topk->output(1),- wei_gate, scale_gate, zp_gate, wei_up, scale_up, zp_up, wei_down, scale_down, zp_down}, config);- model = std::make_shared<ov::Model>(moe_compressed, ov::ParameterVector{hidden_states});- manager.register_pass<FuseMOE3GemmCompressed>();- }- {- // tokens:32, hidden_size:2048, inter_size:512, experts:512, topk:10- auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{4, 8, 2048});- auto flatten_shape = op::v0::Constant::create(element::i32, Shape{2}, {32, 2048});- auto hidden_states_reshape = std::make_shared<ov::op::v1::Reshape>(hidden_states, flatten_shape, false);- auto routers = op::v0::Constant::create(element::f16, Shape{2048, 512}, {0.2});- auto routing_weights = std::make_shared<ov::op::v0::MatMul>(hidden_states_reshape, routers);-- // weight- auto wei_gate = op::v0::Constant::create(element::u4, Shape{512, 512, 16, 128}, {1});- auto scale_gate = op::v0::Constant::create(element::f16, Shape{512, 16, 512}, {0.01f});- auto zp_gate = op::v0::Constant::create(element::u4, Shape{512, 16, 512}, {0});- auto wei_up = op::v0::Constant::create(element::u4, Shape{512, 512, 16, 128}, {1});- auto scale_up = op::v0::Constant::create(element::f16, Shape{512, 16, 512}, {0.01f});- auto zp_up = op::v0::Constant::create(element::u4, Shape{512, 16, 512}, {0});- auto wei_down = op::v0::Constant::create(element::u4, Shape{512, 2048, 4, 128}, {1});- auto scale_down = op::v0::Constant::create(element::f16, Shape{512, 4, 2048}, {0.01f});- auto zp_down = op::v0::Constant::create(element::u4, Shape{512, 4, 2048}, {0});+INSTANTIATE_TEST_SUITE_P(smoke,+ FuseMOE3GemmCompressedTest,+ ::testing::Combine(+ ::testing::Values(MoERoutingType::SOFTMAX, MoERoutingType::SIGMOID_BIAS),+ ::testing::Values(false, true)),+ FuseMOE3GemmCompressedTest::get_test_case_name);- ov::intel_gpu::op::MOECompressed::Config config;- config.hidden_size = 2048;- config.inter_size = 512;- config.num_expert = 512;- config.group_size = 128;- config.top_k = 10;- config.out_type = ov::element::f16;- auto moe_3gemm_fused_compressed = std::make_shared<ov::intel_gpu::op::MOE3GemmFusedCompressed>(- ov::OutputVector{hidden_states_reshape, routing_weights,- wei_gate, scale_gate, zp_gate, wei_up, scale_up, zp_up, wei_down, scale_down, zp_down}, config);- auto hidden_state_shape = std::make_shared<ov::op::v3::ShapeOf>(hidden_states);- auto reshape_back = std::make_shared<ov::op::v1::Reshape>(moe_3gemm_fused_compressed->output(0), hidden_state_shape, false);-- model_ref = std::make_shared<ov::Model>(reshape_back, ov::ParameterVector{hidden_states});- }-}} // namespace intel_gpu} // namespace test} // namespace ovdiff --git a/src/tests/functional/plugin/shared/include/shared_test_classes/subgraph/moe_builders.hpp b/src/tests/functional/plugin/shared/include/shared_test_classes/subgraph/moe_builders.hppdeleted file mode 100644index f5fcf0e582f..00000000000--- a/src/tests/functional/plugin/shared/include/shared_test_classes/subgraph/moe_builders.hpp+++ /dev/null@@ -1,49 +0,0 @@-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#pragma once--#include <iostream>-#include <memory>-#include <optional>-#include "openvino/core/model.hpp"-#include "openvino/core/type/element_type.hpp"-#include "shared_test_classes/base/ov_subgraph.hpp"-#include "shared_test_classes/subgraph/weights_decompression_params.hpp"-#include "common_test_utils/subgraph_builders/weights_decompression_builders.hpp"--namespace ov {-namespace test {--struct MoePatternParams {- ov::test::InputShape data_shape;- size_t topk;- size_t number_of_experts;- size_t intermediate_size;-};--std::shared_ptr<ov::Model> initMoE2GeMMSubgraph(const MoePatternParams& moe_params,- const ov::element::Type data_precision,- const ov::element::Type weights_precision,- const bool use_weight_decompression = false,- const std::optional<ov::element::Type> decompression_precision = std::nullopt,- const std::optional<ov::element::Type> scale_precision = std::nullopt,- const std::optional<ov::test::utils::DecompressionType> decompression_multiply_type = std::nullopt,- 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);--std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(const MoePatternParams& moe_params,- const ov::element::Type data_precision,- const ov::element::Type weights_precision,- const bool use_weight_decompression = false,- const std::optional<ov::element::Type> decompression_precision = std::nullopt,- const std::optional<ov::element::Type> scale_precision = std::nullopt,- const std::optional<ov::test::utils::DecompressionType> decompression_multiply_type = std::nullopt,- 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);--} // namespace test-} // namespace ov\ No newline at end of filediff --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.hppnew file mode 100644index 00000000000..9996f8508a9--- /dev/null+++ b/src/tests/test_utils/common_test_utils/include/common_test_utils/node_builders/moe_builders.hpp@@ -0,0 +1,74 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <memory>+#include <optional>+#include <utility>+#include <vector>++#include "common_test_utils/subgraph_builders/weights_decompression_builders.hpp"+#include "openvino/core/model.hpp"+#include "openvino/core/node_output.hpp"+#include "openvino/core/partial_shape.hpp"+#include "openvino/core/shape.hpp"++namespace ov {+namespace test {++struct MoePatternParams {+ ov::PartialShape data_shape;+ size_t topk;+ size_t number_of_experts;+ size_t intermediate_size;+};++enum class MoERoutingType {+ SOFTMAX, ///< Softmax -> TopK -> normalize routing+ SIGMOID_BIAS, ///< Sigmoid -> Add(bias) -> TopK routing+};++/// Softmax branch:+/// routing_weights -> Softmax -> TopK -> ReduceSum -> Divide (norm)+/// -> 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);++/// Sigmoid+bias branch:+/// routing_weights -> Sigmoid -> Add(bias) -> TopK -> Convert(i32)+/// -> GatherElements -> normalize -> ScatterElementsUpdate -> Transpose -> Reshape -> Unsqueeze+std::pair<ov::Output<ov::Node>, ov::Output<ov::Node>> build_sigmoid_bias_routing_subgraph(+ const ov::Output<ov::Node>& routing_weights,+ ov::element::Type data_precision,+ size_t number_of_experts,+ size_t topk);++std::shared_ptr<ov::Model> initMoE2GeMMSubgraph(+ const MoePatternParams& moe_params,+ const ov::element::Type data_precision,+ const ov::element::Type weights_precision,+ const bool use_weight_decompression = false,+ const std::optional<ov::element::Type> decompression_precision = std::nullopt,+ const std::optional<ov::element::Type> scale_precision = std::nullopt,+ const std::optional<ov::test::utils::DecompressionType> decompression_multiply_type = std::nullopt,+ 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);++std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(+ const MoePatternParams& moe_params,+ const ov::element::Type data_precision,+ const ov::element::Type weights_precision,+ const bool use_weight_decompression = false,+ const std::optional<ov::element::Type> decompression_precision = std::nullopt,+ const std::optional<ov::element::Type> scale_precision = std::nullopt,+ const std::optional<ov::test::utils::DecompressionType> decompression_multiply_type = std::nullopt,+ 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);++} // namespace test+} // namespace ovdiff --git a/src/tests/functional/plugin/shared/src/subgraph/moe_builders.cpp b/src/tests/test_utils/common_test_utils/src/node_builders/moe_builders.cppsimilarity index 68%rename from src/tests/functional/plugin/shared/src/subgraph/moe_builders.cpprename to src/tests/test_utils/common_test_utils/src/node_builders/moe_builders.cppindex 965fc85293f..76ab3d3a6ee 100644--- a/src/tests/functional/plugin/shared/src/subgraph/moe_builders.cpp+++ b/src/tests/test_utils/common_test_utils/src/node_builders/moe_builders.cpp@@ -2,7 +2,7 @@// SPDX-License-Identifier: Apache-2.0//-#include "shared_test_classes/subgraph/moe_builders.hpp"+#include "common_test_utils/node_builders/moe_builders.hpp"#include <limits>#include <memory>@@ -17,8 +17,10 @@#include "openvino/op/clamp.hpp"#include "openvino/op/concat.hpp"#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"#include "openvino/op/divide.hpp"#include "openvino/op/gather.hpp"+#include "openvino/op/gather_elements.hpp"#include "openvino/op/matmul.hpp"#include "openvino/op/minimum.hpp"#include "openvino/op/multiply.hpp"@@ -28,6 +30,7 @@#include "openvino/op/result.hpp"#include "openvino/op/scatter_elements_update.hpp"#include "openvino/op/shape_of.hpp"+#include "openvino/op/sigmoid.hpp"#include "openvino/op/slice.hpp"#include "openvino/op/softmax.hpp"#include "openvino/op/swish.hpp"@@ -35,12 +38,145 @@#include "openvino/op/topk.hpp"#include "openvino/op/transpose.hpp"#include "openvino/op/unsqueeze.hpp"-#include "shared_test_classes/subgraph/weights_decompression_params.hpp"#include "transformations/utils/utils.hpp"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) {+ using namespace ov::op;++ auto router_softmax = std::make_shared<v8::Softmax>(routing_weights, 1);++ auto k_const = v0::Constant::create(ov::element::i32, ov::Shape{}, {static_cast<int32_t>(topk)});+ auto router_topk =+ std::make_shared<v11::TopK>(router_softmax, k_const, 1, v11::TopK::Mode::MAX, v11::TopK::SortType::SORT_VALUES);++ auto reduce_sm =+ std::make_shared<v1::ReduceSum>(router_topk->output(0),+ v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{1}),+ true);+ 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);++ 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}),+ v0::Constant::create(ov::element::i64, ov::Shape{}, {0}));+ auto unsq_seq =+ std::make_shared<v0::Unsqueeze>(gather,+ v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{0}));++ auto ne_scalar = v0::Constant::create(ov::element::i64, ov::Shape{}, {static_cast<int64_t>(number_of_experts)});+ auto unsq_ne =+ std::make_shared<v0::Unsqueeze>(ne_scalar,+ v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{0}));++ ov::OutputVector bcast_vec{unsq_seq, unsq_ne};+ auto bcast_shape = std::make_shared<v0::Concat>(bcast_vec, 0);++ auto one = v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{1});+ ov::OutputVector reshape_vec{unsq_ne, unsq_seq, one};+ auto reshape_shape = std::make_shared<v0::Concat>(reshape_vec, 0);++ auto zero = v0::Constant::create(scatter_w.get_element_type(), ov::Shape{1}, {0});+ auto bcast = std::make_shared<v3::Broadcast>(zero, bcast_shape);+ auto scatter = std::make_shared<v12::ScatterElementsUpdate>(+ bcast,+ topk_idx,+ scatter_w,+ v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{1}));+ auto transp = std::make_shared<v1::Transpose>(+ scatter,+ v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{1, 0}));+ auto reshape = std::make_shared<v1::Reshape>(transp, reshape_shape, false);+ auto unsqueeze_moe = ov::Output<ov::Node>{+ std::make_shared<v0::Unsqueeze>(reshape,+ v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{3}))};++ return {unsqueeze_moe, topk_idx};+}++std::pair<ov::Output<ov::Node>, ov::Output<ov::Node>> build_sigmoid_bias_routing_subgraph(+ const ov::Output<ov::Node>& routing_weights,+ ov::element::Type data_precision,+ size_t number_of_experts,+ size_t topk) {+ using namespace ov::op;++ auto sigmoid = std::make_shared<v0::Sigmoid>(routing_weights);+ auto bias_test_data = ov::test::utils::InputGenerateData(0., 1, 100);+ auto bias = ov::test::utils::make_constant(data_precision, ov::Shape{1, number_of_experts}, bias_test_data);+ auto sig_add = std::make_shared<v1::Add>(sigmoid, bias);++ auto router_topk =+ std::make_shared<v11::TopK>(sig_add,+ v0::Constant::create(ov::element::i64, ov::Shape{}, {static_cast<int64_t>(topk)}),+ -1,+ v11::TopK::Mode::MAX,+ v11::TopK::SortType::SORT_VALUES,+ ov::element::i64);++ auto convert_topk = std::make_shared<v0::Convert>(router_topk->output(1), ov::element::i32);+ auto topk_idx = ov::Output<ov::Node>{convert_topk};++ auto gather_el = std::make_shared<v6::GatherElements>(sigmoid, convert_topk, 1);+ auto reduce =+ std::make_shared<v1::ReduceSum>(gather_el,+ v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{1}),+ true);+ auto eps = v0::Constant::create(data_precision, ov::Shape{1, 1}, {1e-6f});+ auto add_eps = std::make_shared<v1::Add>(reduce, eps);+ auto norm = std::make_shared<v1::Divide>(gather_el, add_eps);++ auto sl_stop = std::make_shared<v3::ShapeOf>(convert_topk, ov::element::i32);+ auto scatter_w = ov::Output<ov::Node>{+ std::make_shared<v8::Slice>(norm,+ v0::Constant::create(ov::element::i32, ov::Shape{2}, std::vector<int32_t>{0, 0}),+ sl_stop,+ v0::Constant::create(ov::element::i32, ov::Shape{2}, std::vector<int32_t>{1, 1}),+ v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{0, 1}))};++ auto shapeof = std::make_shared<v3::ShapeOf>(convert_topk, ov::element::i64);+ auto gather = std::make_shared<v8::Gather>(shapeof,+ v0::Constant::create(ov::element::i64, ov::Shape{}, {0}),+ v0::Constant::create(ov::element::i64, ov::Shape{}, {0}));+ auto unsq_seq =+ std::make_shared<v0::Unsqueeze>(gather,+ v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{0}));++ auto ne_scalar = v0::Constant::create(ov::element::i64, ov::Shape{}, {static_cast<int64_t>(number_of_experts)});+ auto unsq_ne =+ std::make_shared<v0::Unsqueeze>(ne_scalar,+ v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{0}));++ ov::OutputVector bcast_vec{unsq_seq, unsq_ne};+ auto bcast_shape = std::make_shared<v0::Concat>(bcast_vec, 0);++ auto zero = v0::Constant::create(scatter_w.get_element_type(), ov::Shape{1}, {0});+ auto bcast = std::make_shared<v3::Broadcast>(zero, bcast_shape);+ auto scatter = std::make_shared<v12::ScatterElementsUpdate>(+ bcast,+ topk_idx,+ scatter_w,+ v0::Constant::create(ov::element::i64, ov::Shape{}, std::vector<int64_t>{1}));+ auto transp = std::make_shared<v1::Transpose>(+ scatter,+ v0::Constant::create(ov::element::i32, ov::Shape{2}, std::vector<int32_t>{1, 0}));++ auto one = v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{1});+ ov::OutputVector reshape_vec{unsq_ne, one, unsq_seq};+ auto reshape_shape = std::make_shared<v0::Concat>(reshape_vec, 0);+ auto reshape = std::make_shared<v1::Reshape>(transp, reshape_shape, false);++ auto unsqueeze_moe = ov::Output<ov::Node>{+ std::make_shared<v0::Unsqueeze>(reshape,+ v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{3}))};++ return {unsqueeze_moe, topk_idx};+}+std::shared_ptr<ov::Node> build_matmul_weights(const ov::Shape& weights_shape,const ov::element::Type& weights_precision,@@ -58,9 +194,13 @@ std::shared_ptr<ov::Node> build_matmul_weights(// since MoE matmuls are supported only in case of transpose_b=trueauto transposed_weights_shape = weights_shape;std::swap(*transposed_weights_shape.rbegin(), *(transposed_weights_shape.rbegin() + 1));- return ov::test::utils::make_constant(weights_precision,- transposed_weights_shape,- utils::InputGenerateData(0, 10, 1, seed));+ std::shared_ptr<ov::Node> weights = ov::test::utils::make_constant(weights_precision,+ transposed_weights_shape,+ utils::InputGenerateData(0, 10, 1, seed));+ if (weights_precision != data_precision) {+ weights = std::make_shared<ov::op::v0::Convert>(weights, data_precision);+ }+ return weights;} else {OPENVINO_ASSERT(decompression_precision.has_value(),"decompression_precision must be set when use_weight_decompression is true");@@ -101,7 +241,7 @@ std::shared_ptr<ov::Model> initMoE2GeMMSubgraph(const std::optional<bool> reshape_on_decompression,const std::optional<int> decompression_group_size) {// Use parameters from shape_params - static shapes only- const auto& data_shape = moe_params.data_shape;+ const auto& input_shape = moe_params.data_shape;const size_t intermediate_size = moe_params.intermediate_size;const size_t topk = moe_params.topk;const size_t number_of_experts = moe_params.number_of_experts;@@ -110,8 +250,6 @@ std::shared_ptr<ov::Model> initMoE2GeMMSubgraph(const auto expert_beta = 7.0f;constexpr int64_t fusion_factor = 2; // property of GPT-OSS-- const auto& input_shape = data_shape.first;// Create input parameter with dynamic shape - batch and hidden_size are fixed, seq_len is dynamicauto input = std::make_shared<ov::op::v0::Parameter>(data_precision, input_shape);@@ -309,25 +447,26 @@ std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(const std::optional<ov::test::utils::DecompressionType> decompression_multiply_type,const std::optional<ov::test::utils::DecompressionType> decompression_subtract_type,const std::optional<bool> reshape_on_decompression,- const std::optional<int> decompression_group_size) {+ const std::optional<int> decompression_group_size,+ MoERoutingType routing_type) {// Use parameters from shape_params - static shapes only- const auto& data_shape = moe_params.data_shape;+ const auto& input_shape = moe_params.data_shape;const size_t intermediate_size = moe_params.intermediate_size;const size_t topk = moe_params.topk;const size_t number_of_experts = moe_params.number_of_experts;const auto expert_alpha = 1.702f;+ const auto input_rank = static_cast<size_t>(input_shape.rank().get_length());+ OPENVINO_ASSERT(input_rank >= 2 && input_shape[input_rank - 1].is_static());+ const auto hidden_size = static_cast<size_t>(input_shape[input_rank - 1].get_length());- const auto& input_shape = data_shape.first;- // Create input parameter with dynamic shape - batch and hidden_size are fixed, seq_len is dynamic+ // Create input parameterauto input = std::make_shared<ov::op::v0::Parameter>(data_precision, input_shape);-- OPENVINO_ASSERT(input_shape[2].is_static());- const auto hidden_size = static_cast<size_t>(input_shape[2].get_length());+ ov::Output<ov::Node> input_data = input;// Expert processing path - use -1 for dynamic reshape like in referenceauto experts_reshape = std::make_shared<ov::op::v1::Reshape>(- input,+ input_data,ov::op::v0::Constant::create(ov::element::i64,ov::Shape{2},@@ -419,61 +558,41 @@ std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(reshape_on_decompression,decompression_group_size);- auto reshape_2nd_consumer_router_matmul =- std::make_shared<ov::op::v0::MatMul>(experts_reshape, router_weights_moe3, false, true);-- 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);+ auto router_matmul = std::make_shared<ov::op::v0::MatMul>(experts_reshape, 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);+ break;+ case MoERoutingType::SIGMOID_BIAS:+ routing_outputs = build_sigmoid_bias_routing_subgraph(router_matmul, data_precision, number_of_experts, topk);+ break;+ default:+ OPENVINO_THROW("Unsupported MoERoutingType");+ }+ auto [unsqueeze_routing_weights, router_topk_indices] = routing_outputs;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 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);- auto broadcast_zero = std::make_shared<ov::op::v3::Broadcast>(zero_const, bcast_target_shape);-- auto scatter_elements_update = std::make_shared<ov::op::v12::ScatterElementsUpdate>(- broadcast_zero,- router_topk_indices,- router_topk_values_normalization,- ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{1}));-- auto router_transpose = std::make_shared<ov::op::v1::Transpose>(- scatter_elements_update,- ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{1, 0}));-auto minus_one = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{-1});- const auto router_shape =- std::make_shared<ov::op::v0::Concat>(ov::OutputVector{number_of_experts_const, first_topk_dim, minus_one}, 0);+ auto one_const = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{1});- auto router_reshape = std::make_shared<ov::op::v1::Reshape>(router_transpose, router_shape, true);+ auto first_topk_dim_for_reshape =+ ov::op::util::node_to_get_shape_value_of_indices_from_shape_source(router_topk_indices, {0});- auto unsqueeze_routing_weights = std::make_shared<ov::op::v0::Unsqueeze>(- router_reshape,- ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{3}));+ auto last_in_dim = ov::op::util::node_to_get_shape_value_of_indices_from_shape_source(input, {input_rank - 1});- auto last_in_dim = ov::op::util::node_to_get_shape_value_of_indices_from_shape_source(input, {2});- auto end_shape = std::make_shared<ov::op::v0::Concat>(- ov::OutputVector{number_of_experts_const, first_topk_dim, minus_one, last_in_dim},- 0);+ // Softmax: end_reshape [ne, seq, 1, hidden] matched by mul with [ne, seq, 1, 1]+ // Sigmoid: end_reshape [ne, 1, seq, hidden] matched by mul with [ne, 1, seq, 1]+ std::shared_ptr<ov::op::v0::Concat> end_shape;+ if (routing_type == MoERoutingType::SOFTMAX) {+ ov::OutputVector end_dims{number_of_experts_const, first_topk_dim_for_reshape, minus_one, last_in_dim};+ end_shape = std::make_shared<ov::op::v0::Concat>(end_dims, 0);+ } else {+ ov::OutputVector end_dims{number_of_experts_const, one_const, first_topk_dim_for_reshape, last_in_dim};+ end_shape = std::make_shared<ov::op::v0::Concat>(end_dims, 0);+ }auto end_reshape = std::make_shared<ov::op::v1::Reshape>(down_matmul, end_shape, true);auto mul3 = std::make_shared<ov::op::v1::Multiply>(end_reshape, unsqueeze_routing_weights);@@ -483,10 +602,11 @@ std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{0}),false);- // Note: here we imitate a real model scenario with special zero value- 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)});+ // Flatten any leading dimensions to [batch*seq, hidden] regardless of routing type+ auto final_reshape_const =+ ov::op::v0::Constant::create(ov::element::i64,+ ov::Shape{2},+ std::vector<int64_t>{-1, static_cast<int64_t>(hidden_size)});auto final_reshape = std::make_shared<ov::op::v1::Reshape>(reduce_sum, final_reshape_const, true);ov::ParameterVector params = {input};