Skip to content

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

[GPU] qwen3.5/qwen3-next to fuse shared expert into sparse experts computation (#34816)

River Lib03947e49eb5
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.hpp
index 4ea9749da1b..3ad0044dbb6 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
@@ -24,6 +24,7 @@ public:
size_t hidden_size = 0;
size_t inter_size = 0;
size_t num_expert = 0;
+ size_t num_shared_expert = 0;
size_t top_k = 0;
// numeric_limits<size_t>::max() means per_channel compression (single group).
// other non-zero value means group compression with this given group_size.
diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_3gemm_fused_compressed.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_3gemm_fused_compressed.hpp
index 50112003954..b1c430d1850 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,8 +42,33 @@ 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)
+ // shape [num_experts, hidden_size, group_num, 1]
+ // 11: routing_bias (optional, SIGMOID_BIAS only; dummy placeholder for SOFTMAX+shared) -
+ // [1, num_experts] routing bias for sigmoid routing
+ // 12: routing_eps (optional, SIGMOID_BIAS only; dummy placeholder for SOFTMAX+shared) -
+ // scalar epsilon for normalization (read at kernel compile time)
+ //
+ // Options for shared experts (if config.num_shared_expert > 0, always starting at index 13):
+ // 13: shared_gate_weight - shared expert weights for first projection,
+ // shape [1, inter_size, group_num, group_size]
+ // 14: shared_gate_scale - shared expert scale for first projection,
+ // shape [1, inter_size, group_num, 1]
+ // 15: shared_gate_zp - shared expert zp for first projection,
+ // shape [1, inter_size, group_num, 1]
+ // 16: shared_up_weight - shared expert weights for second projection,
+ // shape [1, inter_size, group_num, group_size]
+ // 17: shared_up_scale - shared expert scale for second projection,
+ // shape [1, inter_size, group_num, 1]
+ // 18: shared_up_zp - shared expert zp for second projection,
+ // shape [1, inter_size, group_num, 1]
+ // 19: shared_down_weight - shared expert weights for final projection,
+ // shape [1, hidden_size, group_num, group_size]
+ // 20: shared_down_scale - shared expert scale for final projection,
+ // shape [1, hidden_size, group_num, 1]
+ // 21: shared_down_zp - shared expert zp for final projection,
+ // shape [1, hidden_size, group_num, 1]
+ // 22: shared_gate_gate_weight - shared expert gate weight for gating,
+ // shape [hidden_size]
//
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.hpp
index 75021e8848b..a3b749021c1 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
@@ -42,8 +42,23 @@ enum class MOE3GemmInputIndex : uint8_t {
WEIGHT_2 = 8,
SCALE_2 = 9,
ZP_2 = 10,
+ // Sigmoid routing (optional, always at index 11-12)
+ // For SOFTMAX routing without shared expert these are absent.
+ // For SOFTMAX routing with shared expert, dummy placeholders fill these slots.
ROUTING_BIAS = 11,
- ROUTING_EPS = 12
+ ROUTING_EPS = 12,
+ // Shared expert inputs (optional, when num_shared_expert > 0)
+ // Always start at index 13 regardless of routing type.
+ SHARED_GATE_WEIGHT = 13,
+ SHARED_GATE_SCALE = 14,
+ SHARED_GATE_ZP = 15,
+ SHARED_UP_WEIGHT = 16,
+ SHARED_UP_SCALE = 17,
+ SHARED_UP_ZP = 18,
+ SHARED_DOWN_WEIGHT = 19,
+ SHARED_DOWN_SCALE = 20,
+ SHARED_DOWN_ZP = 21,
+ SHARED_GATE_GATE_WEIGHT = 22
};
struct moe_3gemm_config {
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_gen_micro.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_gen_micro.cpp
index c773ccd60a4..1d98e6ca0df 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_gen_micro.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_gen_micro.cpp
@@ -329,11 +329,6 @@ DispatchDataFunc MoE3GemmMicroGenerator::get_dispatch_data_func() const {
OPENVINO_THROW("Unsupported input tensor shape size: ", input_layout.get_shape().size());
}
- auto cur_moe = params.typed_desc<moe_3gemm_fused_compressed>();
- const auto& config = cur_moe->_config;
- n = n * config.top_k;
- GPU_DEBUG_TRACE_DETAIL << "\t n = " << n << std::endl;
-
const auto& experts_weight_shape = experts_weight_layout.get_shape();
size_t m = experts_weight_shape[1];
size_t k = experts_weight_shape.size() == 4 ? experts_weight_shape[2] * experts_weight_shape[3] : experts_weight_shape[2];
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.cpp
index e2958afa97b..6e7d6eb148a 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
@@ -168,6 +168,8 @@ struct onednn_matmul {
with_bin_mul_per_row_sum,
with_silu,
with_silu_bin_mul,
+ with_sigmoid,
+ with_bin_mul_sum,
};
int bin_post_id = -1;
bool bin_per_row = false;
@@ -184,6 +186,14 @@ struct onednn_matmul {
bin_post_id = 0;
post_op_bin_mul(true);
}
+ if (t == type::with_bin_mul_sum) {
+ bin_post_id = 0;
+ post_op_bin_mul(false);
+ post_op_sum();
+ }
+ if (t == type::with_sigmoid) {
+ postops.append_eltwise(dnnl::algorithm::eltwise_logistic, 1.0f, 0.0f);
+ }
if (t == type::with_bin_mul_per_row) {
bin_post_id = 0;
bin_per_row = true;
@@ -705,14 +715,22 @@ static void add_common_consts(const RuntimeParams& params, JitConstants& jit) {
class MoE3GemmSwigluMLPGateUp : public KernelGenerator {
public:
- MoE3GemmSwigluMLPGateUp() : KernelGenerator("moe_3gemm_swiglu_mlp", "gate_up") {}
+ MoE3GemmSwigluMLPGateUp(bool disable_shared_experts = false)
+ : KernelGenerator("moe_3gemm_swiglu_mlp", "gate_up"),
+ _disable_shared_experts(disable_shared_experts) {}
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>();
add_common_consts(params, jit);
jit.make("GATE_UP_ENABLE", 1);
-
+ if (!_disable_shared_experts && desc->_config.num_shared_expert > 0 &&
+ params.input_layouts.size() > static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_WEIGHT)) {
+ jit.make("SHARED_EXPERT_ENABLE", 1);
+ } else {
+ jit.make("SHARED_EXPERT_ENABLE", 0);
+ }
return jit;
}
@@ -724,17 +742,29 @@ protected:
[[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {
return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {}};
}
+
+private:
+ bool _disable_shared_experts;
};
class MoE3GemmSwigluMLPDown : public KernelGenerator {
public:
- MoE3GemmSwigluMLPDown() : KernelGenerator("moe_3gemm_swiglu_mlp", "down") {}
+ MoE3GemmSwigluMLPDown(bool disable_shared_experts = false)
+ : KernelGenerator("moe_3gemm_swiglu_mlp", "down"),
+ _disable_shared_experts(disable_shared_experts) {}
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>();
add_common_consts(params, jit);
jit.make("DOWN_ENABLE", 1);
+ if (!_disable_shared_experts && desc->_config.num_shared_expert > 0 &&
+ params.input_layouts.size() > static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_WEIGHT)) {
+ jit.make("SHARED_EXPERT_ENABLE", 1);
+ } else {
+ jit.make("SHARED_EXPERT_ENABLE", 0);
+ }
return jit;
}
@@ -746,17 +776,29 @@ protected:
[[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {
return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {}};
}
+
+private:
+ bool _disable_shared_experts;
};
class MoE3GemmSwigluMLPReduce : public KernelGenerator {
public:
- MoE3GemmSwigluMLPReduce() : KernelGenerator("moe_3gemm_swiglu_mlp", "reduce") {}
+ MoE3GemmSwigluMLPReduce(bool disable_shared_experts = false)
+ : KernelGenerator("moe_3gemm_swiglu_mlp", "reduce"),
+ _disable_shared_experts(disable_shared_experts) {}
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>();
add_common_consts(params, jit);
jit.make("REDUCE_ENABLE", 1);
+ if (!_disable_shared_experts && desc->_config.num_shared_expert > 0 &&
+ params.input_layouts.size() > static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_WEIGHT)) {
+ jit.make("SHARED_EXPERT_ENABLE", 1);
+ } else {
+ jit.make("SHARED_EXPERT_ENABLE", 0);
+ }
return jit;
}
@@ -768,6 +810,9 @@ protected:
[[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {
return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {}};
}
+
+private:
+ bool _disable_shared_experts;
};
dnnl::memory convert2dnnl(const memory::ptr& ptr, const std::vector<int64_t>& dim, dnnl::memory::format_tag tag, int64_t offset = 0) {
@@ -823,6 +868,11 @@ public:
memory::ptr scale[3];
memory::ptr zp[3];
memory::ptr bias[3];
+
+ // Shared expert: Gate, Up, Down, ScalarGate
+ memory::ptr shared_weight[4];
+ memory::ptr shared_scale[4];
+ memory::ptr shared_zp[4];
} moe_fusion_weights;
struct scratch_buffers {
@@ -852,9 +902,17 @@ public:
std::vector<std::vector<dnnl_weights>> _dnnl_weights;
int _hidden_size;
int _intermediate_size;
+ int _shared_intermediate_size;
int _gate_up_group_size;
int _down_group_size;
+ bool _has_shared_expert = false;
+ // Shared expert primitives
+ std::shared_ptr<onednn_linear> _shared_gate_proj;
+ std::shared_ptr<onednn_linear> _shared_up_proj;
+ std::shared_ptr<onednn_linear> _shared_down_proj;
+ std::shared_ptr<onednn_linear> _shared_gate_gate_proj; // The scalar gate for shared expert
+
moe_3gemm_swiglu_opt_impl() : PrimitiveImplOCL(moe_3gemm_swiglu_opt::get_type_info_static()) {}
moe_3gemm_swiglu_opt_impl(const program_node& node, const RuntimeParams& params) : moe_3gemm_swiglu_opt_impl() {
if (m_rt_params == nullptr) {
@@ -995,6 +1053,128 @@ public:
}
}
+ void init_shared_primitives(cldnn::engine& engine, const struct moe_fusion_weights_base_addr& addr, int batch) {
+ if (_shared_gate_proj && _shared_gate_proj->m_batch == batch)
+ return;
+
+ if (!addr.shared_weight[0]) {
+ _has_shared_expert = false;
+ return;
+ }
+
+ _shared_intermediate_size = static_cast<int>(addr.shared_weight[0]->get_layout().count() / _hidden_size);
+ auto eng = engine.get_onednn_engine();
+ using t = onednn_matmul::type;
+
+ // 1. Up (Standard Linear)
+ auto up_w_dt = convert_data_type(addr.shared_weight[1]->get_layout().data_type);
+ auto up_w = convert2dnnl(addr.shared_weight[1], {_hidden_size, _shared_intermediate_size}, dnnl::memory::format_tag::ba);
+ auto up_s = addr.shared_scale[1]
+ ? convert2dnnl(addr.shared_scale[1], {_hidden_size / _gate_up_group_size, _shared_intermediate_size}, dnnl::memory::format_tag::ab)
+ : dnnl::memory();
+ auto up_z = addr.shared_zp[1]
+ ? convert2dnnl(addr.shared_zp[1], {_hidden_size / _gate_up_group_size, _shared_intermediate_size}, dnnl::memory::format_tag::ab)
+ : dnnl::memory();
+ _shared_up_proj = std::make_shared<onednn_linear>(onednn_linear::create(eng,
+ dnnl::memory::data_type::f16,
+ up_w_dt,
+ batch,
+ _hidden_size,
+ _shared_intermediate_size,
+ _gate_up_group_size,
+ t::none,
+ up_w,
+ up_s,
+ up_z));
+
+ // 2. Gate (SiLU + BinMul)
+ auto gate_w_dt = convert_data_type(addr.shared_weight[0]->get_layout().data_type);
+ auto gate_w = convert2dnnl(addr.shared_weight[0], {_hidden_size, _shared_intermediate_size}, dnnl::memory::format_tag::ba);
+ auto gate_s = addr.shared_scale[0]
+ ? convert2dnnl(addr.shared_scale[0], {_hidden_size / _gate_up_group_size, _shared_intermediate_size}, dnnl::memory::format_tag::ab)
+ : dnnl::memory();
+ auto gate_z = addr.shared_zp[0]
+ ? convert2dnnl(addr.shared_zp[0], {_hidden_size / _gate_up_group_size, _shared_intermediate_size}, dnnl::memory::format_tag::ab)
+ : dnnl::memory();
+ _shared_gate_proj = std::make_shared<onednn_linear>(onednn_linear::create(eng,
+ dnnl::memory::data_type::f16,
+ gate_w_dt,
+ batch,
+ _hidden_size,
+ _shared_intermediate_size,
+ _gate_up_group_size,
+ t::with_silu_bin_mul,
+ gate_w,
+ gate_s,
+ gate_z));
+
+ // 3. Scalar Gate (Sigmoid)
+ // It is very small weight with shape of [Hidden, 1], and not need to keep compressed, so KeepMOE3GemmConstPrecision will not keep its precision and
+ // ConvertPrecision will convert to f16. So Scalar gate is [Hidden, 1], f16 weights, no scale/zp for now
+ dnnl::memory sg_w;
+ dnnl::memory::data_type sg_w_dt = dnnl::memory::data_type::f16;
+ if (addr.shared_weight[3]) {
+ sg_w_dt = convert_data_type(addr.shared_weight[3]->get_layout().data_type);
+ sg_w = convert2dnnl(addr.shared_weight[3], {_hidden_size, 1}, dnnl::memory::format_tag::ba);
+ }
+
+ if (sg_w) {
+ _shared_gate_gate_proj = std::make_shared<onednn_linear>(
+ onednn_linear::
+ create(eng, dnnl::memory::data_type::f16, sg_w_dt, batch, _hidden_size, 1, -1, t::with_sigmoid, sg_w, dnnl::memory(), dnnl::memory()));
+ }
+
+ // 4. Down (BinMul + Sum)
+ auto down_w_dt = convert_data_type(addr.shared_weight[2]->get_layout().data_type);
+ auto down_w = convert2dnnl(addr.shared_weight[2], {_shared_intermediate_size, _hidden_size}, dnnl::memory::format_tag::ba);
+ auto down_s = addr.shared_scale[2]
+ ? convert2dnnl(addr.shared_scale[2], {_shared_intermediate_size / _down_group_size, _hidden_size}, dnnl::memory::format_tag::ab)
+ : dnnl::memory();
+ auto down_z = addr.shared_zp[2]
+ ? convert2dnnl(addr.shared_zp[2], {_shared_intermediate_size / _down_group_size, _hidden_size}, dnnl::memory::format_tag::ab)
+ : dnnl::memory();
+ _shared_down_proj = std::make_shared<onednn_linear>(onednn_linear::create(eng,
+ dnnl::memory::data_type::f16,
+ down_w_dt,
+ batch,
+ _shared_intermediate_size,
+ _hidden_size,
+ _down_group_size,
+ t::with_bin_mul_sum,
+ down_w,
+ down_s,
+ down_z));
+ }
+
+ void execute_shared_expert(dnnl::stream& stream, int batch, memory::ptr input_mem, memory::ptr output_mem, scratch_buffers& scratch) {
+ if (!_shared_gate_proj || !_shared_up_proj || !_shared_down_proj || !_shared_gate_gate_proj) {
+ return;
+ }
+
+ auto input_dnnl = convert2dnnl(input_mem, {batch, _hidden_size}, dnnl::memory::format_tag::ab);
+ auto output_dnnl = convert2dnnl(output_mem, {batch, _hidden_size}, dnnl::memory::format_tag::ab);
+
+ auto up_mem_dnnl = convert2dnnl(scratch.up, {batch, _shared_intermediate_size}, dnnl::memory::format_tag::ab);
+ auto gate_mem_dnnl = convert2dnnl(scratch.gate, {batch, _shared_intermediate_size}, dnnl::memory::format_tag::ab);
+ // Reuse routing weights or topk_weights buffer as temp for scalar gate [Batch, 1]
+ // This buffer is usually [Batch, MaxTopK]. Check if big enough. Batch=1 -> TopK. Batch>1 -> Batch*TopK.
+ // We only use [Batch, 1] part.
+ auto scalar_gate_mem = scratch.topk_weights;
+ auto scalar_gate_dnnl = convert2dnnl(scalar_gate_mem, {batch, 1}, dnnl::memory::format_tag::ab);
+
+ // 1. Up Proj
+ _shared_up_proj->forward(stream, batch, input_dnnl, up_mem_dnnl, dnnl::memory());
+
+ // 2. Gate Proj (Fused with SiLU and BinMul(up))
+ _shared_gate_proj->forward(stream, batch, input_dnnl, gate_mem_dnnl, up_mem_dnnl);
+
+ // 3. Scalar Gate Proj (Fused with Sigmoid)
+ _shared_gate_gate_proj->forward(stream, batch, input_dnnl, scalar_gate_dnnl, dnnl::memory());
+
+ // 4. Down Proj (Fused with BinMul(Scalar) and Sum)
+ _shared_down_proj->forward(stream, batch, gate_mem_dnnl, output_dnnl, scalar_gate_dnnl);
+ }
+
void load(BinaryInputBuffer& ib) override {
PrimitiveImplOCL::load(ib);
const kernel_impl_params* impl_params = reinterpret_cast<kernel_impl_params*>(ib.getKernelImplParams());
@@ -1020,16 +1200,17 @@ public:
auto hidden_states_layout = params.input_layouts[0];
auto token_num = get_seq_len(hidden_states_layout);
auto data_type = hidden_states_layout.data_type;
+ bool has_shared_expert = params.input_layouts.size() > static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_WEIGHT);
std::vector<BufferDescriptor> internal_buffers;
// softmax+topk
layout layout_topk_id(ov::Shape{token_num, max_topk}, data_types::u32, cldnn::format::bfyx);
- layout layout_topk_weights(ov::Shape{token_num, max_topk}, data_type, cldnn::format::bfyx);
+ layout layout_topk_weights(ov::Shape{token_num, max_topk + (has_shared_expert ? 1 : 0)}, data_type, cldnn::format::bfyx);
internal_buffers.emplace_back(layout_topk_id, true); // 0: topk_id
internal_buffers.emplace_back(layout_topk_weights, true); // 1: topk_weights
// To support micro_gemm, prefill need to allocate max_topk * token_num for input data of micro_gemm
- auto max_batch = max_topk * token_num;
+ auto max_batch = has_shared_expert ? (max_topk + 1) * token_num : max_topk * token_num;
layout layout_gateup_out(ov::Shape{max_batch, static_cast<size_t>(config.inter_size)}, data_type, cldnn::format::bfyx);
layout layout_down_out(ov::Shape{max_batch, static_cast<size_t>(config.hidden_size)}, data_type, cldnn::format::bfyx);
internal_buffers.emplace_back(layout_gateup_out, true); // 2: up output
@@ -1039,7 +1220,7 @@ public:
// scratch.gate = gate(scratch.x) * scratch.up
// scratch.y = down(scratch.gate) * routing_weights
internal_buffers.emplace_back(layout_down_out, true); // 4: up/gate input, scratch.x has same layout with down output
- layout routing_layout(ov::Shape{token_num * max_topk}, data_type, cldnn::format::bfyx);
+ layout routing_layout(ov::Shape{max_batch}, data_type, cldnn::format::bfyx);
internal_buffers.emplace_back(routing_layout, true); // 5: routing_weights
internal_buffers.emplace_back(layout_gateup_out, true); // 6: gate output, scratch.gate has same layout with up
// expert masks for gpu
@@ -1099,6 +1280,28 @@ public:
scratch.moe_fusion_wei_addr.weight[2] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::WEIGHT_2));
scratch.moe_fusion_wei_addr.scale[2] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SCALE_2));
scratch.moe_fusion_wei_addr.zp[2] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::ZP_2));
+
+ // shared expert
+ size_t dep_count = instance.dependencies().size();
+ if (dep_count >= static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_GATE_WEIGHT) + 1) {
+ // Gate
+ scratch.moe_fusion_wei_addr.shared_weight[0] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_WEIGHT));
+ scratch.moe_fusion_wei_addr.shared_scale[0] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_SCALE));
+ scratch.moe_fusion_wei_addr.shared_zp[0] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_ZP));
+
+ // Up
+ scratch.moe_fusion_wei_addr.shared_weight[1] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_UP_WEIGHT));
+ scratch.moe_fusion_wei_addr.shared_scale[1] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_UP_SCALE));
+ scratch.moe_fusion_wei_addr.shared_zp[1] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_UP_ZP));
+
+ // Down
+ scratch.moe_fusion_wei_addr.shared_weight[2] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_DOWN_WEIGHT));
+ scratch.moe_fusion_wei_addr.shared_scale[2] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_DOWN_SCALE));
+ scratch.moe_fusion_wei_addr.shared_zp[2] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_DOWN_ZP));
+
+ // Scalar Gate - f16
+ scratch.moe_fusion_wei_addr.shared_weight[3] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_GATE_WEIGHT));
+ }
}
void get_expert_mask_from_gpu(const MOE3GemmFusedCompressed::Config& config, memory::ptr mem, stream& stream, expert_mask_cpu& expert_mask) {
@@ -1229,7 +1432,6 @@ public:
return std::make_tuple(mem, layout);
}
- bool print_wei = false;
cldnn::event::ptr exec_single_token(const std::vector<cldnn::event::ptr>& events,
typed_primitive_inst<moe_3gemm_fused_compressed>& instance,
scratch_buffers& scratch) {
@@ -1240,7 +1442,6 @@ public:
auto batch_mem_ptr = scratch.topk_id;
auto [hidden_states_mem_ptr, hidden_states_layout] = get_input_info(instance, static_cast<size_t>(MOE3GemmInputIndex::HIDDEN_STATES));
auto routing_mem_ptr = scratch.topk_weights;
-
_hidden_size = static_cast<int>(cur_moe->_config.hidden_size);
_intermediate_size = static_cast<int>(cur_moe->_config.inter_size);
@@ -1263,30 +1464,64 @@ public:
const auto& mlp_down_zp_mem = scratch.moe_fusion_wei_addr.zp[2];
event::ptr ret;
+ size_t compute_experts = static_cast<size_t>(max_topk);
+ Stage* stage_gate_up = mlp_gate_up.get();
+ Stage* stage_down = mlp_down.get();
+ Stage* stage_reduce = mlp_reduce.get();
+
+ std::vector<memory::ptr> extra_args_gate_up;
+ std::vector<memory::ptr> extra_args_down;
+
+ if (_has_shared_expert) {
+ compute_experts += 1;
+
+ extra_args_gate_up = {scratch.moe_fusion_wei_addr.shared_weight[0],
+ scratch.moe_fusion_wei_addr.shared_scale[0],
+ scratch.moe_fusion_wei_addr.shared_zp[0],
+ scratch.moe_fusion_wei_addr.shared_weight[1],
+ scratch.moe_fusion_wei_addr.shared_scale[1],
+ scratch.moe_fusion_wei_addr.shared_zp[1],
+ scratch.moe_fusion_wei_addr.shared_weight[3],
+ routing_mem_ptr};
+
+ extra_args_down = {scratch.moe_fusion_wei_addr.shared_weight[2],
+ scratch.moe_fusion_wei_addr.shared_scale[2],
+ scratch.moe_fusion_wei_addr.shared_zp[2]};
+ }
{
// scratch.up = up(x) * silu(gate(x))
- auto ret_event = execute_stage(
- events,
- instance,
- *mlp_gate_up,
- {batch_mem_ptr, mlp_gate_wei_mem, mlp_gate_scale_mem, mlp_gate_zp_mem, mlp_up_wei_mem, mlp_up_scale_mem, mlp_up_zp_mem, hidden_states_mem_ptr},
- {scratch.up},
- {static_cast<size_t>(max_topk), subgroup_size, static_cast<size_t>(_intermediate_size / N_BLOCK)},
- {1, subgroup_size, SUBGROUP_NUM});
+ std::vector<memory::ptr> args_gate_up =
+ {batch_mem_ptr, mlp_gate_wei_mem, mlp_gate_scale_mem, mlp_gate_zp_mem, mlp_up_wei_mem, mlp_up_scale_mem, mlp_up_zp_mem};
+ if (_has_shared_expert)
+ args_gate_up.insert(args_gate_up.end(), extra_args_gate_up.begin(), extra_args_gate_up.end());
+ args_gate_up.push_back(hidden_states_mem_ptr);
+
+ auto ret_event = execute_stage(events,
+ instance,
+ *stage_gate_up,
+ args_gate_up,
+ {scratch.up},
+ {compute_experts, subgroup_size, static_cast<size_t>(_intermediate_size / N_BLOCK)},
+ {1, subgroup_size, SUBGROUP_NUM});
// scratch.y = down(scratch.up) * weight[expert_no]
+ std::vector<memory::ptr> args_down = {batch_mem_ptr, mlp_down_wei_mem, mlp_down_scale_mem, mlp_down_zp_mem};
+ if (_has_shared_expert)
+ args_down.insert(args_down.end(), extra_args_down.begin(), extra_args_down.end());
+ args_down.push_back(scratch.up);
+ args_down.push_back(routing_mem_ptr);
ret_event = execute_stage({ret_event},
instance,
- *mlp_down,
- {batch_mem_ptr, mlp_down_wei_mem, mlp_down_scale_mem, mlp_down_zp_mem, scratch.up, routing_mem_ptr},
+ *stage_down,
+ args_down,
{scratch.y},
- {static_cast<size_t>(max_topk), subgroup_size, static_cast<size_t>(_hidden_size / N_BLOCK)},
+ {compute_experts, subgroup_size, static_cast<size_t>(_hidden_size / N_BLOCK)},
{1, subgroup_size, SUBGROUP_NUM});
// final = sum(scratch.y)
ret = execute_stage({ret_event},
instance,
- *mlp_reduce,
+ *stage_reduce,
{scratch.y},
{final_hidden_states_mem_ptr},
{static_cast<size_t>(1), static_cast<size_t>(_hidden_size)},
@@ -1770,6 +2005,17 @@ public:
auto& cur_net = instance.get_network();
auto& stream = cur_net.get_stream();
cldnn::event::ptr ret_env = nullptr;
+ _has_shared_expert = (config.num_shared_expert > 0);
+
+ if (_has_shared_expert) {
+ if (config.num_shared_expert > 1) {
+ OPENVINO_THROW("num_shared_expert=", config.num_shared_expert, " is not supported yet, only support 0 or 1");
+ }
+ auto shared_expert_weight_layout = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_WEIGHT))->get_layout();
+ auto hidden_size = static_cast<int>(cur_moe->_config.hidden_size);
+ _shared_intermediate_size = static_cast<int>(shared_expert_weight_layout.count() / hidden_size);
+ OPENVINO_ASSERT(_shared_intermediate_size == _intermediate_size, "Shared expert _intermediate_size should be same with moe experts");
+ }
auto [hidden_states_mem_ptr, hidden_states_layout] = get_input_info(instance, static_cast<size_t>(MOE3GemmInputIndex::HIDDEN_STATES));
size_t token_num = get_seq_len(hidden_states_layout);
@@ -1785,7 +2031,7 @@ public:
*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},
+ {token_num, lws_size},
{1, lws_size},
instance.needs_completion_event());
} else if (config.routing_type == ov::intel_gpu::op::MOECompressed::RoutingType::SIGMOID_BIAS) {
@@ -1796,7 +2042,7 @@ public:
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},
+ {token_num, lws_size},
{1, lws_size},
instance.needs_completion_event());
} else {
@@ -1809,9 +2055,9 @@ public:
return exec_single_token({topk_event}, instance, scratch);
}
+ auto final_hidden_states_mem_ptr = instance.output_memory_ptr(0);
// onednn path will accumulate to the output
if (!use_micro_gemm_prefill) {
- auto final_hidden_states_mem_ptr = instance.output_memory_ptr(0);
final_hidden_states_mem_ptr->fill(stream, false);
}
const bool use_gpu_mask_gen = use_gpu_mask_gen_prefill;
@@ -1828,6 +2074,17 @@ public:
} else {
ret_env = exec_prefill_onednn({topk_event}, stream, instance, scratch);
}
+
+ if (_has_shared_expert) {
+ auto& engine = instance.get_network().get_engine();
+ init_shared_primitives(engine, scratch.moe_fusion_wei_addr, static_cast<int>(token_num));
+ // execute_shared_expert will read the output of moe_gemm_down, so it should be after ret_env is ready, but it doesn't need to wait for ret_env to
+ // be ready, since execute_shared_expert will be serialized with the following kernels by onednn stream, just make sure ret_env is submitted before
+ // execute_shared_expert.
+ // if (ret_env)
+ // ret_env->wait();
+ execute_shared_expert(stream.get_onednn_stream(), static_cast<int>(token_num), hidden_states_mem_ptr, final_hidden_states_mem_ptr, scratch);
+ }
// Wait for the final event to be ready
// ret_env->wait();
return ret_env;
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_3gemm_swiglu_mlp.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_3gemm_swiglu_mlp.cl
index d29dfe7cfbc..561156abf67 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_3gemm_swiglu_mlp.cl
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_3gemm_swiglu_mlp.cl
@@ -231,7 +231,7 @@ inline void gate_up_gemv_n2x_f16(const __global half* weight, __global half* y,
half4 sum1;
half8 a = as_half8(intel_sub_group_block_read_us8((const __global ushort*)x2 + gk * FAKE_GROUP_SIZE));
half8 b = as_half8(intel_sub_group_block_read_us8((const __global ushort*)B + gk * FAKE_GROUP_SIZE));
- half8 b2= as_half8(intel_sub_group_block_read_us8((const __global ushort*)(B + K + gk * FAKE_GROUP_SIZE)));
+ half8 b2 = as_half8(intel_sub_group_block_read_us8((const __global ushort*)(B + K + gk * FAKE_GROUP_SIZE)));
sum0.s0 = fma(a.s0, b.s0, 0);
sum0.s1 = fma(a.s1, b.s1, 0);
@@ -253,7 +253,7 @@ inline void gate_up_gemv_n2x_f16(const __global half* weight, __global half* y,
sum1.s2 = fma(a.s6, b2.s6, sum1.s2);
sum1.s3 = fma(a.s7, b2.s7, sum1.s3);
- sum_all0 += sum0[0] + sum0[1] + sum0[2] + sum0[3] ;
+ sum_all0 += sum0[0] + sum0[1] + sum0[2] + sum0[3];
sum_all1 += sum1[0] + sum1[1] + sum1[2] + sum1[3];
# endif
}
@@ -272,19 +272,37 @@ inline void gate_up_gemv_n2x_f16(const __global half* weight, __global half* y,
}
}
-__attribute__((intel_reqd_sub_group_size(SUBGROUP_SIZE))) KERNEL(mlp_gate_up)(const __global int* expert_list,
- const __global MOE_WEI_DT* gate_weight_addr,
- const __global MOE_SCALE_DT* gate_scale_addr,
- const __global MOE_ZP_DT* gate_zp_addr,
- const __global MOE_WEI_DT* up_weight_addr,
- const __global MOE_SCALE_DT* up_scale_addr,
- const __global MOE_ZP_DT* up_zp_addr,
- __global MOE_DTYPE* x, // [1, HIDDEN_SIZE]
- __global MOE_DTYPE* y) { // [MAX_TOPK, INTERMEDIATE_SIZE]
+__attribute__((intel_reqd_sub_group_size(SUBGROUP_SIZE))) KERNEL(mlp_gate_up)(
+ const __global int* expert_list,
+ const __global MOE_WEI_DT* gate_weight_addr,
+ const __global MOE_SCALE_DT* gate_scale_addr,
+ const __global MOE_ZP_DT* gate_zp_addr,
+ const __global MOE_WEI_DT* up_weight_addr,
+ const __global MOE_SCALE_DT* up_scale_addr,
+ const __global MOE_ZP_DT* up_zp_addr,
+# if SHARED_EXPERT_ENABLE
+ const __global MOE_WEI_DT* shared_gate_weight,
+ const __global MOE_SCALE_DT* shared_gate_scale,
+ const __global MOE_ZP_DT* shared_gate_zp,
+ const __global MOE_WEI_DT* shared_up_weight,
+ const __global MOE_SCALE_DT* shared_up_scale,
+ const __global MOE_ZP_DT* shared_up_zp,
+ const __global half* shared_gate_gate_weight, // [HIDDEN_SIZE] (assuming no scale/zp for now, or pre-dequantized)
+ __global MOE_DTYPE* routing_weights, // Input routing weights, will append shared gate result at end
+# endif
+ __global MOE_DTYPE* x, // [1, HIDDEN_SIZE]
+ __global MOE_DTYPE* y) { // [MAX_TOPK (+1 if shared), INTERMEDIATE_SIZE]
// global: [expert, SUBGROUP_SIZE, N//N_BLOCK],[1, SUBGROUP_SIZE, SUBGROUP_NUM]
int expert_no = get_global_id(0);
y += expert_no * INTERMEDIATE_SIZE;
+ // Check if we are processing the Shared Expert
+# if SHARED_EXPERT_ENABLE
+ bool is_shared = (expert_no == MAX_TOPK); // Assuming global size was increased by 1
+# else
+ bool is_shared = false;
+# endif
+
# if WEIGHT_COMPRESSEION_DT == 0
const int expert_wei_size = INTERMEDIATE_SIZE * HIDDEN_SIZE / 2;
const int expert_scale_size = INTERMEDIATE_SIZE * HIDDEN_SIZE / GATE_UP_GROUP_SIZE;
@@ -296,16 +314,39 @@ __attribute__((intel_reqd_sub_group_size(SUBGROUP_SIZE))) KERNEL(mlp_gate_up)(co
# endif
int expert_id = expert_list[expert_no];
-
// gate, [HIDDEN_SIZE, INTERMEDIATE_SIZE]
- __global MOE_WEI_DT* gate_weight = (__global MOE_WEI_DT*)(gate_weight_addr + expert_id * expert_wei_size);
- __global MOE_SCALE_DT* gate_scale = (__global MOE_SCALE_DT*)(gate_scale_addr + expert_id * expert_scale_size);
- __global MOE_ZP_DT* gate_zp = (__global MOE_ZP_DT*)(gate_zp_addr + expert_id * expert_zp_size);
-
+ __global MOE_WEI_DT* gate_weight;
+ __global MOE_SCALE_DT* gate_scale;
+ __global MOE_ZP_DT* gate_zp;
// up, [HIDDEN_SIZE, INTERMEDIATE_SIZE]
- __global MOE_WEI_DT* up_weight = (__global MOE_WEI_DT*)(up_weight_addr + expert_id * expert_wei_size);
- __global MOE_SCALE_DT* up_scale = (__global MOE_SCALE_DT*)(up_scale_addr + expert_id * expert_scale_size);
- __global MOE_ZP_DT* up_zp = (__global MOE_ZP_DT*)(up_zp_addr + expert_id * expert_zp_size);
+ __global MOE_WEI_DT* up_weight;
+ __global MOE_SCALE_DT* up_scale;
+ __global MOE_ZP_DT* up_zp;
+
+ if (!is_shared) {
+ expert_id = expert_list[expert_no];
+ // gate, [HIDDEN_SIZE, INTERMEDIATE_SIZE]
+ gate_weight = (__global MOE_WEI_DT*)(gate_weight_addr + expert_id * expert_wei_size);
+ gate_scale = (__global MOE_SCALE_DT*)(gate_scale_addr + expert_id * expert_scale_size);
+ gate_zp = (__global MOE_ZP_DT*)(gate_zp_addr + expert_id * expert_zp_size);
+
+ // up, [HIDDEN_SIZE, INTERMEDIATE_SIZE]
+ up_weight = (__global MOE_WEI_DT*)(up_weight_addr + expert_id * expert_wei_size);
+ up_scale = (__global MOE_SCALE_DT*)(up_scale_addr + expert_id * expert_scale_size);
+ up_zp = (__global MOE_ZP_DT*)(up_zp_addr + expert_id * expert_zp_size);
+ }
+# if SHARED_EXPERT_ENABLE
+ else {
+ // Use shared expert pointers directly
+ // [HIDDEN_SIZE, SHARED_INTERMEDIATE_SIZE] - assume layout/size match sparse experts for now
+ gate_weight = (__global MOE_WEI_DT*)shared_gate_weight;
+ gate_scale = (__global MOE_SCALE_DT*)shared_gate_scale;
+ gate_zp = (__global MOE_ZP_DT*)shared_gate_zp;
+ up_weight = (__global MOE_WEI_DT*)shared_up_weight;
+ up_scale = (__global MOE_SCALE_DT*)shared_up_scale;
+ up_zp = (__global MOE_ZP_DT*)shared_up_zp;
+ }
+# endif
# if GATE_UP_GROUP_SIZE % FAKE_GROUP_SIZE != 0
if (get_sub_group_id() == 0 && get_sub_group_local_id() == 0) {
@@ -316,6 +357,9 @@ __attribute__((intel_reqd_sub_group_size(SUBGROUP_SIZE))) KERNEL(mlp_gate_up)(co
__local half x2[HIDDEN_SIZE];
__local float xg_sum[HIDDEN_SIZE / FAKE_GROUP_SIZE];
+# if SHARED_EXPERT_ENABLE
+ __local float shared_gate_partial[SUBGROUP_NUM]; // one slot per subgroup for scalar gate reduction
+# endif
# if WEIGHT_COMPRESSEION_DT == 0
//# interleaving x into x2
@@ -363,6 +407,42 @@ __attribute__((intel_reqd_sub_group_size(SUBGROUP_SIZE))) KERNEL(mlp_gate_up)(co
barrier(CLK_LOCAL_MEM_FENCE);
+# if SHARED_EXPERT_ENABLE
+ // Compute scalar gate for shared expert using all threads in the workgroup.
+ // Only the N-block-0 workgroup writes routing_weights[MAX_TOPK]; other N-block workgroups
+ // skip this entirely to avoid redundant work and races.
+ if (is_shared && get_group_id(2) == 0) {
+ // Step 1: every thread accumulates a partial dot product over its slice of HIDDEN_SIZE.
+ // With num_sg subgroups * SUBGROUP_SIZE threads, each thread handles ~14 elements
+ // (HIDDEN_SIZE=3584 / 256 threads) instead of one thread doing all 3584.
+ float gate_val = 0.0f;
+ int thread_id = id_sg * SUBGROUP_SIZE + id_local;
+ int total_threads = num_sg * SUBGROUP_SIZE;
+ for (int i = thread_id; i < HIDDEN_SIZE; i += total_threads) {
+ gate_val += (float)x[i] * (float)shared_gate_gate_weight[i];
+ }
+
+ // Step 2: intra-subgroup reduction.
+ gate_val = sub_group_reduce_add(gate_val);
+
+ // Step 3: store per-subgroup partial to SLM.
+ if (id_local == 0) {
+ shared_gate_partial[id_sg] = gate_val;
+ }
+ barrier(CLK_LOCAL_MEM_FENCE);
+
+ // Step 4: subgroup 0 does final cross-subgroup reduction and writes sigmoid result.
+ if (id_sg == 0) {
+ float final_val = (id_local < num_sg) ? shared_gate_partial[id_local] : 0.0f;
+ final_val = sub_group_reduce_add(final_val);
+ if (id_local == 0) {
+ routing_weights[MAX_TOPK] = (MOE_DTYPE)(1.0f / (1.0f + exp(-final_val)));
+ }
+ }
+ }
+ // routing_weights[MAX_TOPK] is consumed by the next kernel (mlp_down) — no barrier needed here.
+# endif
+
# if WEIGHT_COMPRESSEION_DT == 0
gate_up_gemv_n2x_u4(up_weight, up_scale, up_zp, y, INTERMEDIATE_SIZE, HIDDEN_SIZE, x2, xg_sum, false);
gate_up_gemv_n2x_u4(gate_weight, gate_scale, gate_zp, y, INTERMEDIATE_SIZE, HIDDEN_SIZE, x2, xg_sum, true);
@@ -627,6 +707,11 @@ __attribute__((intel_reqd_sub_group_size(SUBGROUP_SIZE))) KERNEL(mlp_down)(const
const __global MOE_WEI_DT* down_weight_addr,
const __global MOE_SCALE_DT* down_scale_addr,
const __global MOE_ZP_DT* down_zp_addr,
+# if SHARED_EXPERT_ENABLE
+ const __global MOE_WEI_DT* shared_down_weight,
+ const __global MOE_SCALE_DT* shared_down_scale,
+ const __global MOE_ZP_DT* shared_down_zp,
+# endif
const __global MOE_DTYPE* x, // [MAX_TOPK, INTERMEDIATE_SIZE]
__global MOE_DTYPE* routing_weights, // [MAX_TOPK]
__global MOE_DTYPE* y) { // [MAX_TOPK, HIDDEN_SIZE]
@@ -635,6 +720,12 @@ __attribute__((intel_reqd_sub_group_size(SUBGROUP_SIZE))) KERNEL(mlp_down)(const
x += expert_no * INTERMEDIATE_SIZE;
y += expert_no * HIDDEN_SIZE;
+# if SHARED_EXPERT_ENABLE
+ bool is_shared = (expert_no == MAX_TOPK);
+# else
+ bool is_shared = false;
+# endif
+
# if WEIGHT_COMPRESSEION_DT == 0
const int expert_wei_size = INTERMEDIATE_SIZE * HIDDEN_SIZE / 2;
const int expert_scale_size = INTERMEDIATE_SIZE * HIDDEN_SIZE / DOWN_GROUP_SIZE;
@@ -647,9 +738,24 @@ __attribute__((intel_reqd_sub_group_size(SUBGROUP_SIZE))) KERNEL(mlp_down)(const
int expert_id = expert_list[expert_no];
// down, [INTERMEDIATE_SIZE, HIDDEN_SIZE]
- __global MOE_WEI_DT* weight = (__global MOE_WEI_DT*)(down_weight_addr + expert_id * expert_wei_size);
- __global MOE_SCALE_DT* scales = (__global MOE_SCALE_DT*)(down_scale_addr + expert_id * expert_scale_size);
- __global MOE_ZP_DT* zps = (__global MOE_ZP_DT*)(down_zp_addr + expert_id * expert_zp_size);
+ __global MOE_WEI_DT* weight;
+ __global MOE_SCALE_DT* scales;
+ __global MOE_ZP_DT* zps;
+
+ if (!is_shared) {
+ expert_id = expert_list[expert_no];
+ // down, [INTERMEDIATE_SIZE, HIDDEN_SIZE]
+ weight = (__global MOE_WEI_DT*)(down_weight_addr + expert_id * expert_wei_size);
+ scales = (__global MOE_SCALE_DT*)(down_scale_addr + expert_id * expert_scale_size);
+ zps = (__global MOE_ZP_DT*)(down_zp_addr + expert_id * expert_zp_size);
+ }
+# if SHARED_EXPERT_ENABLE
+ else {
+ weight = (__global MOE_WEI_DT*)shared_down_weight;
+ scales = (__global MOE_SCALE_DT*)shared_down_scale;
+ zps = (__global MOE_ZP_DT*)shared_down_zp;
+ }
+# endif
int N = HIDDEN_SIZE;
int K = INTERMEDIATE_SIZE;
@@ -716,11 +822,16 @@ __attribute__((intel_reqd_sub_group_size(SUBGROUP_SIZE))) KERNEL(mlp_down)(const
__attribute__((intel_reqd_sub_group_size(SUBGROUP_SIZE))) KERNEL(mlp_reduce)(const __global MOE_DTYPE* x, // [MAX_TOPK, HIDDEN_SIZE]
__global MOE_DTYPE* y) { // [1, HIDDEN_SIZE]
int n = get_global_id(1);
- half sum[MAX_TOPK] = {0};
- __attribute__((opencl_unroll_hint(MAX_TOPK))) for (int i = 0; i < MAX_TOPK; i++) {
+# if SHARED_EXPERT_ENABLE
+# define REDUCE_COUNT (MAX_TOPK + 1)
+# else
+# define REDUCE_COUNT MAX_TOPK
+# endif
+ half sum[REDUCE_COUNT] = {0};
+ __attribute__((opencl_unroll_hint(REDUCE_COUNT))) for (int i = 0; i < REDUCE_COUNT; i++) {
sum[i] = as_half(intel_sub_group_block_read_us((const __global ushort*)(x + i * HIDDEN_SIZE + n)));
}
- for (int i = 1; i < MAX_TOPK; i++) {
+ for (int i = 1; i < REDUCE_COUNT; i++) {
sum[0] += sum[i];
}
intel_sub_group_block_write_us((__global ushort*)(y + n), as_ushort(sum[0]));
diff --git a/src/plugins/intel_gpu/src/plugin/ops/moe.cpp b/src/plugins/intel_gpu/src/plugin/ops/moe.cpp
index 16c32d9a539..532d08412b4 100644
--- a/src/plugins/intel_gpu/src/plugin/ops/moe.cpp
+++ b/src/plugins/intel_gpu/src/plugin/ops/moe.cpp
@@ -1,22 +1,22 @@
// Copyright (C) 2018-2026 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
-#include "openvino/op/constant.hpp"
#include "openvino/op/moe.hpp"
-#include "intel_gpu/op/moe_compressed.hpp"
-#include "intel_gpu/plugin/program_builder.hpp"
+
+#include <intel_gpu/primitives/eltwise.hpp>
+#include <intel_gpu/primitives/moe_gather.hpp>
+#include <intel_gpu/primitives/moe_scatter_reduction.hpp>
+#include <intel_gpu/primitives/swiglu.hpp>
+#include <limits>
+
#include "intel_gpu/op/moe_3gemm_fused_compressed.hpp"
+#include "intel_gpu/op/moe_compressed.hpp"
#include "intel_gpu/plugin/common_utils.hpp"
#include "intel_gpu/plugin/program_builder.hpp"
#include "intel_gpu/primitives/moe_3gemm_fused_compressed.hpp"
#include "intel_gpu/primitives/moe_gemm.hpp"
#include "intel_gpu/primitives/moe_mask_gen.hpp"
-#include <intel_gpu/primitives/moe_scatter_reduction.hpp>
-#include <intel_gpu/primitives/moe_gather.hpp>
-#include <intel_gpu/primitives/swiglu.hpp>
-#include <intel_gpu/primitives/eltwise.hpp>
-
-#include <limits>
+#include "openvino/op/constant.hpp"
namespace ov {
namespace op {
@@ -53,7 +53,35 @@ 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]
- const size_t expected_inputs = config.routing_type == op::MOECompressed::RoutingType::SIGMOID_BIAS ? 13 : 11;
+ /// 11: routing_bias (optional, SIGMOID_BIAS only; dummy placeholder for SOFTMAX+shared) -
+ /// [1, num_experts] routing bias for sigmoid routing
+ /// 12: routing_eps (optional, SIGMOID_BIAS only; dummy placeholder for SOFTMAX+shared) -
+ /// scalar epsilon for normalization
+ ///
+ /// Options for shared experts (if config.num_shared_expert > 0, always starting at index 13):
+ /// 13: shared_gate_weight - shared expert weights for first projection,
+ /// shape [1, inter_size, group_num, group_size]
+ /// 14: shared_gate_scale - shared expert scale for first projection,
+ /// shape [1, inter_size, group_num, 1]
+ /// 15: shared_gate_zp - shared expert zp for first projection,
+ /// shape [1, inter_size, group_num, 1]
+ /// 16: shared_up_weight - shared expert weights for second projection,
+ /// shape [1, inter_size, group_num, group_size]
+ /// 17: shared_up_scale - shared expert scale for second projection,
+ /// shape [1, inter_size, group_num, 1]
+ /// 18: shared_up_zp - shared expert zp for second projection,
+ /// shape [1, inter_size, group_num, 1]
+ /// 19: shared_down_weight - shared expert weights for final projection,
+ /// shape [1, hidden_size, group_num, group_size]
+ /// 20: shared_down_scale - shared expert scale for final projection,
+ /// shape [1, hidden_size, group_num, 1]
+ /// 21: shared_down_zp - shared expert zp for final projection,
+ /// shape [1, hidden_size, group_num, 1]
+ /// 22: shared_gate_gate_weight - shared expert gate weight for gating,
+ /// shape [hidden_size]
+ const size_t expected_inputs = config.num_shared_expert > 0 ? 23
+ : config.routing_type == op::MOECompressed::RoutingType::SIGMOID_BIAS ? 13
+ : 11;
validate_inputs_count(op, {expected_inputs});
const std::string layerName = layer_type_name_ID(op);
@@ -95,7 +123,7 @@ static void CreateMOECompressedOp(ProgramBuilder& p, const std::shared_ptr<ov::o
// shape [num_experts, hidden_size, group_num, 1]
// Use moe_3gemm_fused_compressed to replace it.
- } else {
+ } else {
// Create GEMM2_BIAS_SWIGLU_CLAMP specific primitives
// input0 : input {#tokens, hidden_size}
// input1 : topk_weight {#tokens, num_experts_per_token}
@@ -113,15 +141,15 @@ static void CreateMOECompressedOp(ProgramBuilder& p, const std::shared_ptr<ov::o
// moe_gemm_down + bias
// moe_scatter_reduce
std::string prim_name_base = layer_type_name_ID(op);
- auto moe_mask_gen_name = prim_name_base + "_moe_mask_gen";
- auto moe_mask_gen_reshape_name = prim_name_base + "_moe_mask_gen_reshape";
- auto moe_gather_name = prim_name_base + "_moe_gather";
- auto moe_bias_up_name = prim_name_base + "_moe_bias_up";
- auto moe_gemm_up_name = prim_name_base + "_moe_gemm_up";
- auto moe_swiglu_name = prim_name_base + "_moe_swiglu";
- auto moe_gemm_down_name = prim_name_base + "_moe_gemm_down";
- auto moe_bias_down_name = prim_name_base + "_moe_bias_down";
- auto moe_scatter_reduce_name = prim_name_base + "_moe_scatter_reduce";
+ auto moe_mask_gen_name = prim_name_base + "_moe_mask_gen";
+ auto moe_mask_gen_reshape_name = prim_name_base + "_moe_mask_gen_reshape";
+ auto moe_gather_name = prim_name_base + "_moe_gather";
+ auto moe_bias_up_name = prim_name_base + "_moe_bias_up";
+ auto moe_gemm_up_name = prim_name_base + "_moe_gemm_up";
+ auto moe_swiglu_name = prim_name_base + "_moe_swiglu";
+ auto moe_gemm_down_name = prim_name_base + "_moe_gemm_down";
+ auto moe_bias_down_name = prim_name_base + "_moe_bias_down";
+ auto moe_scatter_reduce_name = prim_name_base + "_moe_scatter_reduce";
auto moe_mask_gen_prim = cldnn::moe_mask_gen(moe_mask_gen_name,
input_infos[2], // topk indices
static_cast<int32_t>(config.num_expert),
@@ -142,11 +170,10 @@ static void CreateMOECompressedOp(ProgramBuilder& p, const std::shared_ptr<ov::o
p.add_primitive(*op, moe_gather_prim);
std::vector<cldnn::input_info> moe_gemm_up_inputs = {
input_info(moe_gather_name), // topk_weight
- input_infos[3], // compressed_weights_input_up
+ input_infos[3], // compressed_weights_input_up
input_info(moe_mask_gen_reshape_name, moe_mask_gen_reshape::MoEMaskGenReshapeOutputIdx::EXPERTS_ID),
input_info(moe_mask_gen_reshape_name, moe_mask_gen_reshape::MoEMaskGenReshapeOutputIdx::EXPERTS_INFO_START_IDX),
- input_info(moe_mask_gen_reshape_name, moe_mask_gen_reshape::MoEMaskGenReshapeOutputIdx::TOKENS_LENS_PER_EXPERT)
- };
+ input_info(moe_mask_gen_reshape_name, moe_mask_gen_reshape::MoEMaskGenReshapeOutputIdx::TOKENS_LENS_PER_EXPERT)};
size_t down_idx = 0;
if (config.has_zp) {
moe_gemm_up_inputs.push_back(input_infos[6]); // bias_up
@@ -173,14 +200,14 @@ static void CreateMOECompressedOp(ProgramBuilder& p, const std::shared_ptr<ov::o
// TODO : update for each new pattern
auto moe_swiglu_prim = cldnn::swiglu(moe_swiglu_name,
input_info(moe_gemm_up_name),
- 2, // axis
- 2, // glu_stride
+ 2, // axis
+ 2, // glu_stride
ov::op::internal::GLU::GluType::Swish,
- 0, // gate idx
- -config.expert_alpha, // clamp_min
- config.expert_alpha, // clamp_max
- config.expert_beta, // swish beta
- 1.0f, // up_add_val
+ 0, // gate idx
+ -config.expert_alpha, // clamp_min
+ config.expert_alpha, // clamp_max
+ config.expert_beta, // swish beta
+ 1.0f, // up_add_val
cldnn::tensor());
p.add_primitive(*op, moe_swiglu_prim);
std::vector<cldnn::input_info> moe_gemm_down_inputs = {
@@ -203,15 +230,16 @@ static void CreateMOECompressedOp(ProgramBuilder& p, const std::shared_ptr<ov::o
auto moe_gemm_down = cldnn::moe_gemm(moe_gemm_down_name, moe_gemm_down_inputs, config);
moe_gemm_down.has_bias = true;
p.add_primitive(*op, moe_gemm_down);
- auto moe_scatter_reduce_prim = cldnn::moe_scatter_reduction(moe_scatter_reduce_name,
- input_info(moe_gemm_down_name),
- input_infos[2],
- input_infos[1],
- input_info(moe_mask_gen_reshape_name, moe_mask_gen_reshape::MoEMaskGenReshapeOutputIdx::TOKENS_PER_EXPERT),
- input_info(moe_mask_gen_reshape_name, moe_mask_gen_reshape::MoEMaskGenReshapeOutputIdx::EXPERTS_INFO_START_IDX),
- input_info(moe_mask_gen_reshape_name, moe_mask_gen_reshape::MoEMaskGenReshapeOutputIdx::TOKENS_LENS_PER_EXPERT),
- input_info(moe_mask_gen_reshape_name, moe_mask_gen_reshape::MoEMaskGenReshapeOutputIdx::EXPERTS_ID),
- config);
+ auto moe_scatter_reduce_prim =
+ cldnn::moe_scatter_reduction(moe_scatter_reduce_name,
+ input_info(moe_gemm_down_name),
+ input_infos[2],
+ input_infos[1],
+ input_info(moe_mask_gen_reshape_name, moe_mask_gen_reshape::MoEMaskGenReshapeOutputIdx::TOKENS_PER_EXPERT),
+ input_info(moe_mask_gen_reshape_name, moe_mask_gen_reshape::MoEMaskGenReshapeOutputIdx::EXPERTS_INFO_START_IDX),
+ input_info(moe_mask_gen_reshape_name, moe_mask_gen_reshape::MoEMaskGenReshapeOutputIdx::TOKENS_LENS_PER_EXPERT),
+ input_info(moe_mask_gen_reshape_name, moe_mask_gen_reshape::MoEMaskGenReshapeOutputIdx::EXPERTS_ID),
+ config);
p.add_primitive(*op, moe_scatter_reduce_prim);
}
}
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/convert_moe_to_compressed.cpp b/src/plugins/intel_gpu/src/plugin/transformations/convert_moe_to_compressed.cpp
index 1dc49a611b7..54d8f9de0ab 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations/convert_moe_to_compressed.cpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations/convert_moe_to_compressed.cpp
@@ -12,6 +12,9 @@
#include "openvino/core/rt_info.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/convert.hpp"
+#include "openvino/op/swish.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/add.hpp"
#include "openvino/op/moe.hpp"
#include "openvino/op/multiply.hpp"
#include "openvino/op/reshape.hpp"
@@ -19,9 +22,11 @@
#include "openvino/op/slice.hpp"
#include "openvino/op/softmax.hpp"
#include "openvino/op/subtract.hpp"
+#include "openvino/op/sigmoid.hpp"
#include "openvino/op/topk.hpp"
#include "openvino/op/transpose.hpp"
#include "openvino/op/unsqueeze.hpp"
+#include "openvino/pass/pattern/op/or.hpp"
#include "openvino/pass/pattern/op/optional.hpp"
#include "openvino/pass/pattern/op/pattern.hpp"
#include "openvino/pass/pattern/op/wrap_type.hpp"
@@ -87,7 +92,8 @@ namespace ov::intel_gpu {
auto gemm3_reshape_ungroup_##SUFFIX = [](const ov::Output<ov::Node>& output) {\
auto in_ps = output.get_node()->get_input_partial_shape(0);\
auto out_ps = output.get_node()->get_output_partial_shape(0);\
- return in_ps.rank().is_static() && out_ps.rank().is_static() && (in_ps.size() == 4 && out_ps.size() == 3);\
+ return in_ps.rank().is_static() && out_ps.rank().is_static() &&\
+ ((in_ps.size() == 4 && out_ps.size() == 3) || (in_ps.size() == 3 && out_ps.size() == 2));\
};\
\
auto gemm3_reshape_const_m_##SUFFIX = wrap_type<ov::op::v0::Constant>();\
@@ -123,16 +129,63 @@ ConvertMOEToMOECompressed::ConvertMOEToMOECompressed(bool is_pa) {
MOE_COMPRESSED_WEIGHT_GEMM3_PATTERN(up);
MOE_COMPRESSED_WEIGHT_GEMM3_PATTERN(down);
+ // shared expert pattern
+ MOE_COMPRESSED_WEIGHT_GEMM3_PATTERN(shared_gate);
+ MOE_COMPRESSED_WEIGHT_GEMM3_PATTERN(shared_up);
+ MOE_COMPRESSED_WEIGHT_GEMM3_PATTERN(shared_down);
+
auto hidden_states_m = any_input();
auto routing_weights_m = any_input();
auto topk_m = any_input();
- auto moe_root_gemm3 =
+ auto moe_root_gemm3_no_shared_expert_bare =
wrap_type<ov::op::internal::MOE>({hidden_states_m, routing_weights_m, topk_m, gemm3_convert_m_gate, gemm3_convert_m_up, gemm3_convert_m_down},
[](const ov::Output<ov::Node>& output) {
auto moe = ov::as_type_ptr<ov::op::internal::MOE>(output.get_node_shared_ptr());
return moe && moe->get_config().expert_type == ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU;
});
+
+ auto moe_root_gemm3_no_shared_expert =
+ wrap_type<ov::op::internal::MOE>({hidden_states_m, routing_weights_m, topk_m, gemm3_convert_m_gate, gemm3_convert_m_up, gemm3_convert_m_down},
+ [](const ov::Output<ov::Node>& output) {
+ auto moe = ov::as_type_ptr<ov::op::internal::MOE>(output.get_node_shared_ptr());
+ if (!moe || moe->get_config().expert_type != ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU) return false;
+ for (auto& tg : output.get_target_inputs()) {
+ if (ov::is_type<ov::op::v1::Add>(tg.get_node())) {
+ auto add = tg.get_node();
+ // Check both Add inputs; follow through Reshape to detect shared expert
+ for (size_t i = 0; i < add->get_input_size(); i++) {
+ auto n = add->get_input_node_ptr(i);
+ if (n && ov::is_type<ov::op::v1::Reshape>(n))
+ n = n->get_input_node_ptr(0);
+ if (n && ov::is_type<ov::op::v1::Multiply>(n)) return false;
+ }
+ }
+ }
+ return true;
+ });
+
+ // Shared expert uses a separate hidden_states input because in the actual model,
+ // MOE's hidden_states is the node BEFORE a Reshape (matmul_experts_fusion extracts input_value(0)),
+ // while shared expert MatMuls take the node AFTER that Reshape.
+ auto shared_hidden_states_m = any_input();
+ auto shared_gate_m = wrap_type<ov::op::v0::MatMul>({shared_hidden_states_m, gemm3_convert_m_shared_gate});
+ auto shared_swish_m = wrap_type<ov::op::v4::Swish>({shared_gate_m});
+ auto shared_up_m = wrap_type<ov::op::v0::MatMul>({shared_hidden_states_m, gemm3_convert_m_shared_up});
+ auto shared_mul_m = wrap_type<ov::op::v1::Multiply>({shared_swish_m, shared_up_m});
+ auto shared_down_m = wrap_type<ov::op::v0::MatMul>({shared_mul_m, gemm3_convert_m_shared_down});
+
+ auto shared_gate_gate_wei_m = any_input();
+ auto shared_gate_gate_m = wrap_type<ov::op::v0::MatMul>({shared_hidden_states_m, shared_gate_gate_wei_m});
+ auto shared_gate_sigmoid_m = wrap_type<ov::op::v0::Sigmoid>({shared_gate_gate_m});
+ auto shared_expert_gated_m = wrap_type<ov::op::v1::Multiply>({shared_gate_sigmoid_m, shared_down_m});
+ auto shared_expert_m = std::make_shared<ov::pass::pattern::op::Or>(OutputVector{shared_down_m, shared_expert_gated_m});
+ auto shared_expert_reshaped_m = optional<ov::op::v1::Reshape>({shared_expert_m, any_input()});
+
+ auto add_1 = wrap_type<ov::op::v1::Add>({moe_root_gemm3_no_shared_expert_bare, shared_expert_reshaped_m});
+ auto add_2 = wrap_type<ov::op::v1::Add>({shared_expert_reshaped_m, moe_root_gemm3_no_shared_expert_bare});
+ auto moe_root_gemm3_shared_expert = std::make_shared<ov::pass::pattern::op::Or>(OutputVector{add_1, add_2});
+ auto moe_root_gemm3 = std::make_shared<ov::pass::pattern::op::Or>(OutputVector{moe_root_gemm3_no_shared_expert, moe_root_gemm3_shared_expert});
// gemm3 pattern finished
// =========================================================================================
// gemm2 pattern start
@@ -174,8 +227,14 @@ ConvertMOEToMOECompressed::ConvertMOEToMOECompressed(bool is_pa) {
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 = ov::as_type_ptr<ov::op::internal::MOE>(pattern_map.at(moe_root).get_node_shared_ptr());
- if (!moe || transformation_callback(moe)) {
+ auto root_node = pattern_map.at(moe_root).get_node_shared_ptr();
+ std::shared_ptr<ov::op::internal::MOE> moe;
+ if (auto add_op = ov::as_type_ptr<ov::op::v1::Add>(root_node)) {
+ moe = ov::as_type_ptr<ov::op::internal::MOE>(pattern_map.count(moe_root_gemm3_no_shared_expert_bare) ? pattern_map.at(moe_root_gemm3_no_shared_expert_bare).get_node_shared_ptr() : pattern_map.at(moe_root_gemm3_no_shared_expert).get_node_shared_ptr());
+ } else {
+ moe = ov::as_type_ptr<ov::op::internal::MOE>(root_node);
+ }
+ if (!moe || transformation_callback(root_node)) {
return false;
}
if (moe->get_config().expert_type == ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU) {
@@ -192,7 +251,9 @@ ConvertMOEToMOECompressed::ConvertMOEToMOECompressed(bool is_pa) {
} else {
OPENVINO_THROW("Moe weight shape must be 3D or 4D.");
}
- OutputVector args(12);
+ bool has_shared_expert = pattern_map.count(gemm3_compressed_weights_m_shared_gate) > 0;
+
+ OutputVector args(has_shared_expert ? 22 : 12);
args[0] = pattern_map.at(hidden_states_m);
args[1] = pattern_map.at(routing_weights_m);
args[2] = pattern_map.at(topk_m);
@@ -223,10 +284,47 @@ ConvertMOEToMOECompressed::ConvertMOEToMOECompressed(bool is_pa) {
args[10] = pattern_map.at(gemm3_scale_m_down);
args[11] = pattern_map.at(gemm3_zp_m_down);
}
+
+ if (has_shared_expert) {
+ args[12] = pattern_map.at(gemm3_compressed_weights_m_shared_gate);
+ if (group_compressed) {
+ MOE_COMPRESSED_WEIGHT_GEMM3(shared_gate);
+ args[13] = gemm3_transpose_scale_shared_gate;
+ args[14] = gemm3_transpose_zp_shared_gate;
+ } else {
+ args[13] = pattern_map.at(gemm3_scale_m_shared_gate);
+ args[14] = pattern_map.at(gemm3_zp_m_shared_gate);
+ }
+ args[15] = pattern_map.at(gemm3_compressed_weights_m_shared_up);
+ if (group_compressed) {
+ MOE_COMPRESSED_WEIGHT_GEMM3(shared_up);
+ args[16] = gemm3_transpose_scale_shared_up;
+ args[17] = gemm3_transpose_zp_shared_up;
+ } else {
+ args[16] = pattern_map.at(gemm3_scale_m_shared_up);
+ args[17] = pattern_map.at(gemm3_zp_m_shared_up);
+ }
+ args[18] = pattern_map.at(gemm3_compressed_weights_m_shared_down);
+ if (group_compressed) {
+ MOE_COMPRESSED_WEIGHT_GEMM3(shared_down);
+ args[19] = gemm3_transpose_scale_shared_down;
+ args[20] = gemm3_transpose_zp_shared_down;
+ } else {
+ args[19] = pattern_map.at(gemm3_scale_m_shared_down);
+ args[20] = pattern_map.at(gemm3_zp_m_shared_down);
+ }
+ if (pattern_map.count(shared_gate_gate_wei_m)) {
+ args[21] = pattern_map.at(shared_gate_gate_wei_m);
+ } else {
+ size_t hidden_size = group_compressed ? weight_shape[2] * weight_shape[3] : weight_shape[2];
+ args[21] = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{hidden_size}, std::vector<float>(hidden_size, 0.0f));
+ }
+ }
ov::intel_gpu::op::MOECompressed::Config config(moe->get_config());
config.hidden_size = group_compressed ? weight_shape[2] * weight_shape[3] : weight_shape[2];
config.inter_size = weight_shape[1];
config.num_expert = weight_shape[0];
+ config.num_shared_expert = has_shared_expert ? 1 : 0;
config.group_size = group_compressed ? weight_shape[3] : std::numeric_limits<size_t>::max();
auto topk_shape = pattern_map.at(topk_m).get_partial_shape();
if (!topk_shape[1].is_static()) {
@@ -247,7 +345,13 @@ ConvertMOEToMOECompressed::ConvertMOEToMOECompressed(bool is_pa) {
moe_compressed->set_friendly_name(moe->get_friendly_name());
ov::copy_runtime_info(moe, moe_compressed);
}
- ov::replace_node(moe, moe_compressed);
+ if (has_shared_expert) {
+ moe_compressed->set_friendly_name(root_node->get_friendly_name());
+ ov::copy_runtime_info(root_node, moe_compressed);
+ ov::replace_node(root_node, moe_compressed);
+ } else {
+ ov::replace_node(moe, moe_compressed);
+ }
} else if (moe->get_config().expert_type == ov::op::internal::MOE::Expert_type::GEMM2_BIAS_SWIGLU_CLAMP) {
OutputVector args;
auto topk_indice_node = pattern_map.at(topk_indices_gemm2_m);
@@ -300,9 +404,9 @@ ConvertMOEToMOECompressed::ConvertMOEToMOECompressed(bool is_pa) {
}
args.push_back(pattern_map.at(bias_down_gemm2_m));
auto moe_compressed = std::make_shared<ov::intel_gpu::op::MOECompressed>(args, config);
- moe_compressed->set_friendly_name(moe->get_friendly_name());
- ov::copy_runtime_info(moe, moe_compressed);
- ov::replace_node(moe, moe_compressed);
+ moe_compressed->set_friendly_name(root_node->get_friendly_name());
+ ov::copy_runtime_info(root_node, moe_compressed);
+ ov::replace_node(root_node, moe_compressed);
} else {
OPENVINO_THROW("Unsupported MOE expert type in ConvertMOEToMOECompressed");
}
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_3gemm_compressed.cpp b/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_3gemm_compressed.cpp
index faf854e6d05..3e2181291b3 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
@@ -122,9 +122,35 @@ FuseMOE3GemmCompressed::FuseMOE3GemmCompressed() {
down_wei_m,
down_scale_m,
down_zp_m};
- auto moe_compressed_m = wrap_type<ov::intel_gpu::op::MOECompressed>(moe_inputs);
+ auto moe_compressed_no_shared_m = wrap_type<ov::intel_gpu::op::MOECompressed>(moe_inputs);
+
+ // ── Shared expert weights ───────────────────────────────────────────
+ auto shared_gate_wei_m = wrap_const();
+ auto shared_gate_scale_m = ANY;
+ auto shared_gate_zp_m = ANY;
+ auto shared_up_wei_m = wrap_const();
+ auto shared_up_scale_m = ANY;
+ auto shared_up_zp_m = ANY;
+ auto shared_down_wei_m = wrap_const();
+ auto shared_down_scale_m = ANY;
+ auto shared_down_zp_m = ANY;
+
+ ov::OutputVector moe_inputs_shared = moe_inputs;
+ moe_inputs_shared.push_back(shared_gate_wei_m);
+ moe_inputs_shared.push_back(shared_gate_scale_m);
+ moe_inputs_shared.push_back(shared_gate_zp_m);
+ moe_inputs_shared.push_back(shared_up_wei_m);
+ moe_inputs_shared.push_back(shared_up_scale_m);
+ moe_inputs_shared.push_back(shared_up_zp_m);
+ moe_inputs_shared.push_back(shared_down_wei_m);
+ moe_inputs_shared.push_back(shared_down_scale_m);
+ moe_inputs_shared.push_back(shared_down_zp_m);
+ auto shared_gate_gate_wei_m = ANY;
+ moe_inputs_shared.push_back(shared_gate_gate_wei_m);
+ auto moe_compressed_shared_m = wrap_type<ov::intel_gpu::op::MOECompressed>(moe_inputs_shared);
+
+ auto moe_compressed_m = std::make_shared<ov::pass::pattern::op::Or>(OutputVector{moe_compressed_no_shared_m, moe_compressed_shared_m});
#undef ANY
-
ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](ov::pass::pattern::Matcher& m) {
const auto& pattern_map = m.get_pattern_value_map();
@@ -134,8 +160,16 @@ FuseMOE3GemmCompressed::FuseMOE3GemmCompressed() {
}
auto config = moe_compressed->get_config();
+ bool has_shared_expert = pattern_map.count(shared_gate_wei_m) > 0;
+ if (!has_shared_expert) {
+ config.num_shared_expert = 0;
+ }
+ // When Optional<Reshape> is absent, the optional pattern is NOT in the map.
+ auto hs_reshaped = pattern_map.count(hidden_state_reshape)
+ ? pattern_map.at(hidden_state_reshape)
+ : pattern_map.at(hidden_state_m);
OutputVector args{
- pattern_map.at(hidden_state_reshape),
+ hs_reshaped,
pattern_map.at(matmul),
pattern_map.at(gate_wei_m),
pattern_map.at(gate_scale_m),
@@ -151,6 +185,25 @@ FuseMOE3GemmCompressed::FuseMOE3GemmCompressed() {
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;
+ } else if (has_shared_expert) {
+ // SOFTMAX + shared expert: insert dummy placeholders at indices 11-12
+ // so that shared expert inputs always start at index 13.
+ auto dummy_bias = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{1}, {0.0f});
+ auto dummy_eps = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{1}, {0.0f});
+ args.push_back(dummy_bias);
+ args.push_back(dummy_eps);
+ }
+ if (has_shared_expert) {
+ args.push_back(pattern_map.at(shared_gate_wei_m));
+ args.push_back(pattern_map.at(shared_gate_scale_m));
+ args.push_back(pattern_map.at(shared_gate_zp_m));
+ args.push_back(pattern_map.at(shared_up_wei_m));
+ args.push_back(pattern_map.at(shared_up_scale_m));
+ args.push_back(pattern_map.at(shared_up_zp_m));
+ args.push_back(pattern_map.at(shared_down_wei_m));
+ args.push_back(pattern_map.at(shared_down_scale_m));
+ args.push_back(pattern_map.at(shared_down_zp_m));
+ args.push_back(pattern_map.at(shared_gate_gate_wei_m));
}
std::shared_ptr<ov::Node> moe_router_fused = std::make_shared<ov::intel_gpu::op::MOE3GemmFusedCompressed>(args, config);
@@ -158,7 +211,7 @@ FuseMOE3GemmCompressed::FuseMOE3GemmCompressed() {
// 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)) {
+ if (moe_compressed->input_value(0) != hs_reshaped) {
auto hidden_state_shape = std::make_shared<ov::op::v3::ShapeOf>(pattern_map.at(hidden_state_m));
moe_router_fused = std::make_shared<ov::op::v1::Reshape>(moe_router_fused, hidden_state_shape, false);
ov::copy_runtime_info(moe_compressed, {hidden_state_shape, moe_router_fused});
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/keep_moe_3gemm_const_precision.cpp b/src/plugins/intel_gpu/src/plugin/transformations/keep_moe_3gemm_const_precision.cpp
index 365c643c70b..6648ffa0547 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
@@ -32,7 +32,26 @@ KeepMOE3GemmConstPrecision::KeepMOE3GemmConstPrecision() {
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});
+ // Shared expert weights
+ auto sh_gate_wei_m = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::u4));
+ auto sh_gate_zp_m = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::u4));
+ auto sh_up_wei_m = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::u4));
+ auto sh_up_zp_m = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::u4));
+ auto sh_down_wei_m = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::u4));
+ auto sh_down_zp_m = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::u4));
+
+ // Softmax + shared expert: 23 inputs (indices 11-12 are dummy placeholders)
+ auto moe_softmax_shared_m = wrap_type<ov::intel_gpu::op::MOE3GemmFusedCompressed>(
+ {any_input(), any_input(), wei_0_m, any_input(), zp_0_m, wei_1_m, any_input(), zp_1_m, wei_2_m, any_input(),
+ zp_2_m, any_input(), any_input(), sh_gate_wei_m, any_input(), sh_gate_zp_m, sh_up_wei_m, any_input(), sh_up_zp_m, sh_down_wei_m, any_input(), sh_down_zp_m, any_input()});
+
+ // SigmoidBias + shared expert: 23 inputs (indices 11-12 are routing_bias/eps)
+ auto moe_sigmoid_shared_m = wrap_type<ov::intel_gpu::op::MOE3GemmFusedCompressed>(
+ {any_input(), any_input(), wei_0_m, any_input(), zp_0_m, wei_1_m, any_input(), zp_1_m, wei_2_m, any_input(),
+ zp_2_m, any_input(), any_input(), sh_gate_wei_m, any_input(), sh_gate_zp_m, sh_up_wei_m, any_input(), sh_up_zp_m, sh_down_wei_m, any_input(), sh_down_zp_m, any_input()});
+
+ auto moe_3gemm_fused_compressed_m = std::make_shared<ov::pass::pattern::op::Or>(
+ OutputVector{moe_softmax_m, moe_sigmoid_m, moe_softmax_shared_m, moe_sigmoid_shared_m});
ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](ov::pass::pattern::Matcher& m) {
const auto& pattern_map = m.get_pattern_value_map();
@@ -41,12 +60,24 @@ KeepMOE3GemmConstPrecision::KeepMOE3GemmConstPrecision() {
return false;
}
- ov::enable_keep_const_precision(pattern_map.at(wei_0_m).get_node_shared_ptr());
- ov::enable_keep_const_precision(pattern_map.at(wei_1_m).get_node_shared_ptr());
- ov::enable_keep_const_precision(pattern_map.at(wei_2_m).get_node_shared_ptr());
- ov::enable_keep_const_precision(pattern_map.at(zp_0_m).get_node_shared_ptr());
- ov::enable_keep_const_precision(pattern_map.at(zp_1_m).get_node_shared_ptr());
- ov::enable_keep_const_precision(pattern_map.at(zp_2_m).get_node_shared_ptr());
+ auto enable_if_present = [&](const std::shared_ptr<Node>& pattern_node) {
+ if (pattern_map.count(pattern_node)) {
+ ov::enable_keep_const_precision(pattern_map.at(pattern_node).get_node_shared_ptr());
+ }
+ };
+
+ enable_if_present(wei_0_m);
+ enable_if_present(wei_1_m);
+ enable_if_present(wei_2_m);
+ enable_if_present(zp_0_m);
+ enable_if_present(zp_1_m);
+ enable_if_present(zp_2_m);
+ enable_if_present(sh_gate_wei_m);
+ enable_if_present(sh_gate_zp_m);
+ enable_if_present(sh_up_wei_m);
+ enable_if_present(sh_up_zp_m);
+ enable_if_present(sh_down_wei_m);
+ enable_if_present(sh_down_zp_m);
return true;
};
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/op/moe_3gemm_fused_compressed.cpp b/src/plugins/intel_gpu/src/plugin/transformations/op/moe_3gemm_fused_compressed.cpp
index 3dcdb139e35..ea64fa5e994 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
@@ -12,7 +12,9 @@ MOE3GemmFusedCompressed::MOE3GemmFusedCompressed(const OutputVector& args, const
}
void MOE3GemmFusedCompressed::validate_and_infer_types() {
- const size_t expected_inputs = m_config.routing_type == MOECompressed::RoutingType::SIGMOID_BIAS ? 13 : 11;
+ const size_t expected_inputs = m_config.num_shared_expert > 0 ? 23
+ : m_config.routing_type == MOECompressed::RoutingType::SIGMOID_BIAS ? 13
+ : 11;
OPENVINO_ASSERT(get_input_size() == expected_inputs,
"MOECompressed: expected ",
expected_inputs,
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.cpp
index 40e66b7c4f1..72fec1aa33d 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
@@ -35,6 +35,7 @@ bool MOECompressed::visit_attributes(ov::AttributeVisitor& visitor) {
visitor.on_attribute("hidden_size", m_config.hidden_size);
visitor.on_attribute("inter_size", m_config.inter_size);
visitor.on_attribute("num_expert", m_config.num_expert);
+ visitor.on_attribute("num_shared_expert", m_config.num_shared_expert);
visitor.on_attribute("top_k", m_config.top_k);
visitor.on_attribute("group_size", m_config.group_size);
visitor.on_attribute("out_type", m_config.out_type);
diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cpp
index 025fabb3a59..a4ac651bcc5 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
@@ -30,6 +30,7 @@ struct Moe3GemmConfig {
size_t top_k;
size_t group_size;
bool is_u4;
+ bool has_shared_expert = false;
};
struct Moe3GemmReference {
@@ -116,13 +117,19 @@ struct Moe3GemmReference {
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) {
+ const std::vector<float>& w2_data,
+ const std::vector<float>& s_gate_data = {},
+ const std::vector<float>& s_up_data = {},
+ const std::vector<float>& s_down_data = {},
+ const std::vector<float>& s_gate_scalar_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 * config.hidden_size, 0);
+ std::vector<ov::float16> output(batch_size * seq_len * hidden_size, 0);
for (size_t b = 0; b < batch_size; ++b) {
for (size_t s = 0; s < seq_len; ++s) {
@@ -163,6 +170,48 @@ struct Moe3GemmReference {
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);
+
+ // Shared Expert
+ if (config.has_shared_expert) {
+ std::vector<float> shared_gate(inter_size);
+ std::vector<float> shared_up(inter_size);
+ float shared_scalar_gate = 0.0f;
+
+ // Compute scalar gate
+ for (size_t j = 0; j < hidden_size; ++j) {
+ float x = static_cast<float>(hidden_states[b * seq_len * hidden_size + s * hidden_size + j]);
+ shared_scalar_gate += x * s_gate_scalar_data[j];
+ }
+ shared_scalar_gate = 1.0f / (1.0f + std::exp(-shared_scalar_gate));
+
+ // 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]);
+ gate_val += x_val * s_gate_data[j * inter_size + i];
+ up_val += x_val * s_up_data[j * inter_size + i];
+ }
+ shared_gate[i] = gate_val;
+ shared_up[i] = up_val;
+ }
+
+ std::vector<float> shared_act(inter_size);
+ for (size_t i = 0; i < inter_size; ++i) {
+ float silu = shared_gate[i] / (1.0f + std::exp(-shared_gate[i]));
+ shared_act[i] = silu * shared_up[i];
+ }
+
+ // Compute out = act @ s_down * scalar_gate
+ for (size_t j = 0; j < hidden_size; ++j) {
+ float out_val = 0.0f;
+ for (size_t i = 0; i < inter_size; ++i) {
+ out_val += shared_act[i] * s_down_data[i * hidden_size + j];
+ }
+ output[b * seq_len * hidden_size + s * hidden_size + j] += static_cast<ov::float16>(out_val * shared_scalar_gate);
+ }
+ }
}
}
return output;
@@ -467,6 +516,253 @@ INSTANTIATE_TEST_SUITE_P(smoke,
class moe_3gemm_compressed_gpu_u4 : public ::testing::TestWithParam<cldnn::MOE3GemmFusedCompressed::RoutingType> {};
+class moe_3gemm_compressed_gpu_shared_random : public ::testing::TestWithParam<Moe3GemmTestParams> {};
+
+TEST_P(moe_3gemm_compressed_gpu_shared_random, moe_accuracy_test_shared_expert_random) {
+ auto param = GetParam();
+ auto& engine = get_test_engine();
+ if (!engine.get_device_info().supports_immad) {
+ return;
+ }
+
+ tests::random_generator rg(GET_SUITE_NAME);
+ Moe3GemmConfig config;
+ config.batch_size = 1;
+ config.seq_len = param.seq_len;
+ config.hidden_size = param.hidden_size;
+ config.inter_size = param.inter_size;
+ config.num_experts = param.num_experts;
+ config.top_k = param.top_k;
+ config.group_size = param.group_size;
+ config.is_u4 = param.is_u4;
+ config.has_shared_expert = true;
+
+ Moe3GemmReference ref(config, rg);
+
+ // Generate random data
+ auto hidden_states = rg.generate_random_1d<ov::float16>(config.batch_size * config.seq_len * config.hidden_size, -1.0f, 1.0f, 1000);
+ auto routing_weights = rg.generate_random_1d<ov::float16>(config.batch_size * config.seq_len * config.num_experts, 0.0f, 1.0f, 1000);
+
+ auto w0_data = rg.generate_random_1d<float>(config.num_experts * config.hidden_size * config.inter_size, -1.0f, 0.0f, 1000);
+ auto w1_data = rg.generate_random_1d<float>(config.num_experts * config.hidden_size * config.inter_size, -1.0f, 0.0f, 1000);
+ auto w2_data = rg.generate_random_1d<float>(config.num_experts * config.inter_size * config.hidden_size, -1.0f, 0.0f, 1000);
+
+ // Shared Expert Data
+ auto s_gate_data = rg.generate_random_1d<float>(config.hidden_size * config.inter_size, -1.0f, 0.0f, 1000);
+ auto s_up_data = rg.generate_random_1d<float>(config.hidden_size * config.inter_size, -1.0f, 0.0f, 1000); // [hidden, inter]
+ auto s_down_data = rg.generate_random_1d<float>(config.inter_size * config.hidden_size, -1.0f, 0.0f, 1000); // [inter, hidden]
+ auto s_gate_scalar_data = rg.generate_random_1d<float>(config.hidden_size, -1.0f, 0.0f, 1000);
+
+ for (size_t i = 0; i < config.num_experts * config.hidden_size * config.inter_size; ++i) {
+ w0_data[i] /= 7.0f;
+ w1_data[i] /= 11.0f;
+ w2_data[i] /= 7.0f;
+ if (i < config.hidden_size * config.inter_size) {
+ s_gate_data[i] /= 7.0f;
+ s_up_data[i] /= 11.0f;
+ s_down_data[i] /= 7.0f;
+ }
+ }
+
+ // Quantize Experts
+ auto [w0_q, w0_scale, w0_zp] = ref.quantize(w0_data, config.num_experts, config.hidden_size, config.inter_size, config.group_size);
+ auto [w1_q, w1_scale, w1_zp] = ref.quantize(w1_data, config.num_experts, config.hidden_size, config.inter_size, config.group_size);
+ auto [w2_q, w2_scale, w2_zp] = ref.quantize(w2_data, config.num_experts, config.inter_size, config.hidden_size, config.group_size);
+
+ // Quantize Shared Experts (Treat as 1 expert)
+ auto [s_gate_q, s_gate_scale, s_gate_zp] = ref.quantize(s_gate_data, 1, config.hidden_size, config.inter_size, config.group_size);
+ auto [s_up_q, s_up_scale, s_up_zp] = ref.quantize(s_up_data, 1, config.hidden_size, config.inter_size, config.group_size);
+ auto [s_down_q, s_down_scale, s_down_zp] = ref.quantize(s_down_data, 1, config.inter_size, config.hidden_size, config.group_size);
+
+ auto w0_q_packed = ref.pack(w0_q);
+ auto w0_zp_packed = ref.pack(w0_zp);
+ auto w1_q_packed = ref.pack(w1_q);
+ auto w1_zp_packed = ref.pack(w1_zp);
+ auto w2_q_packed = ref.pack(w2_q);
+ auto w2_zp_packed = ref.pack(w2_zp);
+
+ auto s_gate_q_packed = ref.pack(s_gate_q);
+ auto s_gate_zp_packed = ref.pack(s_gate_zp);
+ auto s_up_q_packed = ref.pack(s_up_q);
+ auto s_up_zp_packed = ref.pack(s_up_zp);
+ auto s_down_q_packed = ref.pack(s_down_q);
+ auto s_down_zp_packed = ref.pack(s_down_zp);
+
+ // Create tensors
+ auto create_weight_tensor = [&](const std::vector<uint8_t>& values, int64_t b, int64_t f, int64_t y, int64_t x) {
+ auto dt = config.is_u4 ? data_types::u4 : data_types::u8;
+ auto mem = engine.allocate_memory({dt, format::bfyx, {b, f, y, x}});
+ set_values(mem, values);
+ get_test_stream().finish();
+ return mem;
+ };
+
+ auto create_zp_tensor = [&](const std::vector<uint8_t>& values, int64_t b, int64_t f, int64_t y, int64_t x) {
+ auto dt = config.is_u4 ? data_types::u4 : data_types::u8;
+ auto mem = engine.allocate_memory({dt, format::bfyx, {b, f, y, x}});
+ set_values(mem, values);
+ get_test_stream().finish();
+ return mem;
+ };
+
+ auto create_f16_tensor = [&](const std::vector<ov::float16>& values, int64_t b, int64_t f, int64_t y, int64_t x) {
+ auto mem = engine.allocate_memory({data_types::f16, format::bfyx, {b, f, y, x}});
+ set_values(mem, values);
+ get_test_stream().finish();
+ return mem;
+ };
+
+ // For Scalar Gate Weights - assuming 1D tensor [hidden_size]
+ auto create_scalar_gate_tensor = [&](const std::vector<float>& values) {
+ std::vector<ov::float16> fp16_values;
+ for(float v : values) fp16_values.push_back(static_cast<ov::float16>(v));
+ // Shape: [hidden_size]
+ auto mem = engine.allocate_memory({data_types::f16, format::bfyx, {1, 1, 1, static_cast<int64_t>(values.size())}});
+ set_values(mem, fp16_values);
+ get_test_stream().finish();
+ 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);
+
+ size_t group_num = config.hidden_size / config.group_size;
+ size_t group_num2 = config.inter_size / config.group_size;
+
+ // Expert Weights
+ auto w0_weight_mem = create_weight_tensor(w0_q_packed, config.num_experts, config.inter_size, config.group_size, group_num);
+ auto w0_scale_mem = create_f16_tensor(w0_scale, config.num_experts, group_num, 1, config.inter_size);
+ auto w0_zp_mem = create_zp_tensor(w0_zp_packed, config.num_experts, group_num, 1, config.inter_size);
+
+ auto w1_weight_mem = create_weight_tensor(w1_q_packed, config.num_experts, config.inter_size, config.group_size, group_num);
+ auto w1_scale_mem = create_f16_tensor(w1_scale, config.num_experts, group_num, 1, config.inter_size);
+ auto w1_zp_mem = create_zp_tensor(w1_zp_packed, config.num_experts, group_num, 1, config.inter_size);
+
+ auto w2_weight_mem = create_weight_tensor(w2_q_packed, config.num_experts, config.hidden_size, config.group_size, group_num2);
+ auto w2_scale_mem = create_f16_tensor(w2_scale, config.num_experts, group_num2, 1, config.hidden_size);
+ auto w2_zp_mem = create_zp_tensor(w2_zp_packed, config.num_experts, group_num2, 1, config.hidden_size);
+
+ // Shared Expert Weights (num_experts = 1)
+ // create_weight_tensor(values, b, f, y, x) -> b=1, f=inter_size, y=group_size, x=group_num
+ auto s_gate_weight_mem = create_weight_tensor(s_gate_q_packed, 1, config.inter_size, config.group_size, group_num);
+ auto s_gate_scale_mem = create_f16_tensor(s_gate_scale, 1, group_num, 1, config.inter_size);
+ auto s_gate_zp_mem = create_zp_tensor(s_gate_zp_packed, 1, group_num, 1, config.inter_size);
+
+ auto s_up_weight_mem = create_weight_tensor(s_up_q_packed, 1, config.inter_size, config.group_size, group_num);
+ auto s_up_scale_mem = create_f16_tensor(s_up_scale, 1, group_num, 1, config.inter_size);
+ auto s_up_zp_mem = create_zp_tensor(s_up_zp_packed, 1, group_num, 1, config.inter_size);
+
+ // down: b=1, f=hidden_size, y=group_num2, x=group_size
+ auto s_down_weight_mem = create_weight_tensor(s_down_q_packed, 1, config.hidden_size, config.group_size, group_num2);
+ auto s_down_scale_mem = create_f16_tensor(s_down_scale, 1, group_num2, 1, config.hidden_size);
+ auto s_down_zp_mem = create_zp_tensor(s_down_zp_packed, 1, group_num2, 1, config.hidden_size);
+
+ auto s_gate_scalar_mem = create_scalar_gate_tensor(s_gate_scalar_data);
+
+ // Build topology
+ topology topology;
+ topology.add(input_layout("hidden_states", hidden_states_mem->get_layout()));
+ topology.add(input_layout("routing_weights", routing_weights_mem->get_layout()));
+
+ topology.add(data("w0_weight", w0_weight_mem));
+ topology.add(data("w0_scale", w0_scale_mem));
+ topology.add(data("w0_zp", w0_zp_mem));
+ topology.add(data("w1_weight", w1_weight_mem));
+ topology.add(data("w1_scale", w1_scale_mem));
+ topology.add(data("w1_zp", w1_zp_mem));
+ topology.add(data("w2_weight", w2_weight_mem));
+ topology.add(data("w2_scale", w2_scale_mem));
+ topology.add(data("w2_zp", w2_zp_mem));
+
+ // Add shared inputs
+ // Insert dummy routing_bias/eps placeholders at indices 11-12 (SOFTMAX + shared expert)
+ auto dummy_bias_mem = engine.allocate_memory({data_types::f16, format::bfyx, {1, 1, 1, 1}});
+ set_values(dummy_bias_mem, {ov::float16(0.0f)});
+ get_test_stream().finish();
+ auto dummy_eps_mem = engine.allocate_memory({data_types::f16, format::bfyx, {1, 1, 1, 1}});
+ set_values(dummy_eps_mem, {ov::float16(0.0f)});
+ get_test_stream().finish();
+ topology.add(data("dummy_routing_bias", dummy_bias_mem));
+ topology.add(data("dummy_routing_eps", dummy_eps_mem));
+
+ topology.add(data("s_gate_weight", s_gate_weight_mem));
+ topology.add(data("s_gate_scale", s_gate_scale_mem));
+ topology.add(data("s_gate_zp", s_gate_zp_mem));
+ topology.add(data("s_up_weight", s_up_weight_mem));
+ topology.add(data("s_up_scale", s_up_scale_mem));
+ topology.add(data("s_up_zp", s_up_zp_mem));
+ topology.add(data("s_down_weight", s_down_weight_mem));
+ topology.add(data("s_down_scale", s_down_scale_mem));
+ topology.add(data("s_down_zp", s_down_zp_mem));
+ topology.add(data("s_gate_scalar", s_gate_scalar_mem));
+
+ cldnn::MOE3GemmFusedCompressed::Config moe_config;
+ moe_config.hidden_size = config.hidden_size;
+ moe_config.inter_size = config.inter_size;
+ moe_config.num_expert = config.num_experts;
+ moe_config.top_k = config.top_k;
+ moe_config.group_size = config.group_size;
+ moe_config.out_type = data_types::f16;
+ moe_config.num_shared_expert = 1;
+ // has_batch_dim default is 0.
+
+ // Create Primitive with extended inputs
+ auto moe_prim = moe_3gemm_fused_compressed("moe_3gemm_fused_compressed",
+ {input_info("hidden_states"),
+ input_info("routing_weights"),
+ input_info("w0_weight"),
+ input_info("w0_scale"),
+ input_info("w0_zp"),
+ input_info("w1_weight"),
+ input_info("w1_scale"),
+ input_info("w1_zp"),
+ input_info("w2_weight"),
+ input_info("w2_scale"),
+ input_info("w2_zp"),
+ // Dummy placeholders for routing_bias/eps (indices 11-12)
+ input_info("dummy_routing_bias"),
+ input_info("dummy_routing_eps"),
+ // Shared Expert Inputs (indices 13-22)
+ input_info("s_gate_weight"),
+ input_info("s_gate_scale"),
+ input_info("s_gate_zp"),
+ input_info("s_up_weight"),
+ input_info("s_up_scale"),
+ input_info("s_up_zp"),
+ input_info("s_down_weight"),
+ input_info("s_down_scale"),
+ input_info("s_down_zp"),
+ input_info("s_gate_scalar")
+ },
+ moe_config);
+
+ topology.add(moe_prim);
+
+ network network(engine, topology, get_test_default_config(engine));
+ network.set_input_data("hidden_states", hidden_states_mem);
+ network.set_input_data("routing_weights", routing_weights_mem);
+
+ auto outputs = network.execute();
+ auto output_prim = outputs.begin()->second.get_memory();
+ 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_softmax(hidden_states, routing_weights, w0_data, w1_data, w2_data,
+ s_gate_data, s_up_data, s_down_data, s_gate_scalar_data);
+
+ // Check accuracy
+ for (size_t i = 0; i < ref_output.size(); ++i) {
+ EXPECT_NEAR(static_cast<float>(output_ptr[i]), static_cast<float>(ref_output[i]), 0.5f);
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(smoke,
+ moe_3gemm_compressed_gpu_shared_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}));
+
TEST_P(moe_3gemm_compressed_gpu_u4, moe_accuracy_test_u4) {
auto routing_type = GetParam();
auto& engine = get_test_engine();
@@ -536,7 +832,6 @@ TEST_P(moe_3gemm_compressed_gpu_u4, moe_accuracy_test_u4) {
// Input 11: w2_zp [num_experts, hidden_size, group_num, 1]
auto w2_zp = create_u4_tensor(w2_zp_data, num_experts, hidden_size, group_num2, 1);
- // Input 3: w0_weight [num_experts, inter_size, group_num, group_size]
// Build topology
topology topology;
diff --git a/src/plugins/intel_gpu/tests/unit/transformations/convert_moe_to_compressed_test.cpp b/src/plugins/intel_gpu/tests/unit/transformations/convert_moe_to_compressed_test.cpp
index b9ed4a9a382..7a63ee1d23c 100644
--- a/src/plugins/intel_gpu/tests/unit/transformations/convert_moe_to_compressed_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/transformations/convert_moe_to_compressed_test.cpp
@@ -20,6 +20,13 @@
#include "openvino/op/transpose.hpp"
#include "openvino/op/variadic_split.hpp"
#include "plugin/transformations/convert_moe_to_compressed.hpp"
+#include "openvino/op/swish.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/add.hpp"
+
+#include "openvino/op/sigmoid.hpp"
using namespace testing;
using namespace ov::intel_gpu;
@@ -153,6 +160,217 @@ INSTANTIATE_TEST_SUITE_P(smoke,
ConvertMOEToMOE3GemmCompressedTest,
Values(element::f16, element::f32),
ConvertMOEToMOE3GemmCompressedTest::get_test_case_name);
+
+TEST_F(TransformationTestsF, ConvertMOEToMOE3GemmSharedExpertCompressedTest) {
+ disable_rt_info_check();
+ {
+ // tokens:32, hidden_size:2048, iter_size:768, experts:128, topk:8
+ auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{32, 2048});
+ auto routing_weights = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{128, 1, 32, 1});
+ auto routing_idx = std::make_shared<ov::op::v0::Parameter>(element::i32, Shape{32, 8});
+
+ // Gate projection
+ auto wei_gate = op::v0::Constant::create(element::u4, Shape{128, 768, 16, 128}, {1});
+ auto zp_gate = op::v0::Constant::create(element::u4, Shape{128, 768, 16, 1}, {0});
+ auto scale_gate = op::v0::Constant::create(element::f16, Shape{128, 768, 16, 1}, {0.01f});
+ auto reshape_const_gate = op::v0::Constant::create(element::i32, Shape{3}, {128, 768, 2048});
+
+ auto w_gate_f16 = std::make_shared<op::v0::Convert>(wei_gate, element::f16);
+ auto zp_gate_f16 = std::make_shared<op::v0::Convert>(zp_gate, element::f16);
+ auto sub_gate = std::make_shared<op::v1::Subtract>(w_gate_f16, zp_gate_f16);
+ auto mul_gate = std::make_shared<op::v1::Multiply>(sub_gate, scale_gate);
+ auto reshape_gate = std::make_shared<op::v1::Reshape>(mul_gate, reshape_const_gate, false);
+ auto convert_gate = std::make_shared<op::v0::Convert>(reshape_gate, element::f32);
+
+ // Up projection
+ auto wei_up = op::v0::Constant::create(element::u4, Shape{128, 768, 16, 128}, {1});
+ auto zp_up = op::v0::Constant::create(element::u4, Shape{128, 768, 16, 1}, {0});
+ auto scale_up = op::v0::Constant::create(element::f16, Shape{128, 768, 16, 1}, {0.01f});
+ auto reshape_const_up = op::v0::Constant::create(element::i32, Shape{3}, {128, 768, 2048});
+
+ auto w_up_f16 = std::make_shared<op::v0::Convert>(wei_up, element::f16);
+ auto zp_up_f16 = std::make_shared<op::v0::Convert>(zp_up, element::f16);
+ auto sub_up = std::make_shared<op::v1::Subtract>(w_up_f16, zp_up_f16);
+ auto mul_up = std::make_shared<op::v1::Multiply>(sub_up, scale_up);
+ auto reshape_up = std::make_shared<op::v1::Reshape>(mul_up, reshape_const_up, false);
+ auto convert_up = std::make_shared<op::v0::Convert>(reshape_up, element::f32);
+
+ // Down projection
+ auto wei_down = op::v0::Constant::create(element::u4, Shape{128, 2048, 6, 128}, {1});
+ auto zp_down = op::v0::Constant::create(element::u4, Shape{128, 2048, 6, 1}, {0});
+ auto scale_down = op::v0::Constant::create(element::f16, Shape{128, 2048, 6, 1}, {0.01f});
+ auto reshape_const_down = op::v0::Constant::create(element::i32, Shape{3}, {128, 2048, 768});
+
+ auto wei_down_f16 = std::make_shared<op::v0::Convert>(wei_down, element::f16);
+ auto zp_down_f16 = std::make_shared<op::v0::Convert>(zp_down, element::f16);
+ auto sub_down = std::make_shared<op::v1::Subtract>(wei_down_f16, zp_down_f16);
+ auto mul_down = std::make_shared<op::v1::Multiply>(sub_down, scale_down);
+ auto reshape_down = std::make_shared<op::v1::Reshape>(mul_down, reshape_const_down, false);
+ auto convert_down = std::make_shared<op::v0::Convert>(reshape_down, element::f32);
+
+ // Shared expert Gate projection (separate weights, 3D without num_experts dim)
+ auto sh_wei_gate = op::v0::Constant::create(element::u4, Shape{768, 16, 128}, {2});
+ auto sh_zp_gate = op::v0::Constant::create(element::u4, Shape{768, 16, 1}, {1});
+ auto sh_scale_gate = op::v0::Constant::create(element::f16, Shape{768, 16, 1}, {0.02f});
+ auto sh_reshape_const_gate = op::v0::Constant::create(element::i32, Shape{2}, {768, 2048});
+ auto sh_w_gate_f16 = std::make_shared<op::v0::Convert>(sh_wei_gate, element::f16);
+ auto sh_zp_gate_f16 = std::make_shared<op::v0::Convert>(sh_zp_gate, element::f16);
+ auto sh_sub_gate = std::make_shared<op::v1::Subtract>(sh_w_gate_f16, sh_zp_gate_f16);
+ auto sh_mul_gate = std::make_shared<op::v1::Multiply>(sh_sub_gate, sh_scale_gate);
+ auto sh_reshape_gate = std::make_shared<op::v1::Reshape>(sh_mul_gate, sh_reshape_const_gate, false);
+ auto sh_convert_gate = std::make_shared<op::v0::Convert>(sh_reshape_gate, element::f32);
+
+ // Shared expert Up projection (separate weights, 3D without num_experts dim)
+ auto sh_wei_up = op::v0::Constant::create(element::u4, Shape{768, 16, 128}, {2});
+ auto sh_zp_up = op::v0::Constant::create(element::u4, Shape{768, 16, 1}, {1});
+ auto sh_scale_up = op::v0::Constant::create(element::f16, Shape{768, 16, 1}, {0.02f});
+ auto sh_reshape_const_up = op::v0::Constant::create(element::i32, Shape{2}, {768, 2048});
+ auto sh_w_up_f16 = std::make_shared<op::v0::Convert>(sh_wei_up, element::f16);
+ auto sh_zp_up_f16 = std::make_shared<op::v0::Convert>(sh_zp_up, element::f16);
+ auto sh_sub_up = std::make_shared<op::v1::Subtract>(sh_w_up_f16, sh_zp_up_f16);
+ auto sh_mul_up = std::make_shared<op::v1::Multiply>(sh_sub_up, sh_scale_up);
+ auto sh_reshape_up = std::make_shared<op::v1::Reshape>(sh_mul_up, sh_reshape_const_up, false);
+ auto sh_convert_up = std::make_shared<op::v0::Convert>(sh_reshape_up, element::f32);
+
+ // Shared expert Down projection (separate weights, 3D without num_experts dim)
+ auto sh_wei_down = op::v0::Constant::create(element::u4, Shape{2048, 6, 128}, {2});
+ auto sh_zp_down = op::v0::Constant::create(element::u4, Shape{2048, 6, 1}, {1});
+ auto sh_scale_down = op::v0::Constant::create(element::f16, Shape{2048, 6, 1}, {0.02f});
+ auto sh_reshape_const_down = op::v0::Constant::create(element::i32, Shape{2}, {2048, 768});
+ auto sh_w_down_f16 = std::make_shared<op::v0::Convert>(sh_wei_down, element::f16);
+ auto sh_zp_down_f16 = std::make_shared<op::v0::Convert>(sh_zp_down, element::f16);
+ auto sh_sub_down = std::make_shared<op::v1::Subtract>(sh_w_down_f16, sh_zp_down_f16);
+ auto sh_mul_down = std::make_shared<op::v1::Multiply>(sh_sub_down, sh_scale_down);
+ auto sh_reshape_down = std::make_shared<op::v1::Reshape>(sh_mul_down, sh_reshape_const_down, false);
+ auto sh_convert_down = std::make_shared<op::v0::Convert>(sh_reshape_down, element::f32);
+
+ // Construct MOE node
+ ov::op::internal::MOE::Config config;
+ config.expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU;
+ auto hidden_states_f32 = std::make_shared<ov::op::v0::Convert>(hidden_states, element::f32);
+ auto moe = std::make_shared<ov::op::internal::MOE>(
+ ov::OutputVector{hidden_states_f32, routing_weights, routing_idx, convert_gate, convert_up, convert_down}, config);
+
+ // In the actual model (Qwen3-Next), shared expert MatMuls use hidden_states
+ // from a different node (after a Reshape) than MOE's hidden_states input.
+ // matmul_experts_fusion extracts input_value(0) of the Reshape as MOE's hidden_states,
+ // while the shared expert MatMuls take the Reshape output directly.
+ auto reshape_const_hs = op::v0::Constant::create(element::i64, Shape{2}, {32, 2048});
+ auto hidden_states_reshaped = std::make_shared<ov::op::v1::Reshape>(hidden_states_f32, reshape_const_hs, false);
+
+ // Shared expert computation (using separate weights and reshaped hidden_states)
+ auto shared_gate_m = std::make_shared<ov::op::v0::MatMul>(hidden_states_reshaped, sh_convert_gate, false, true);
+ auto shared_swish_m = std::make_shared<ov::op::v4::Swish>(shared_gate_m);
+ auto shared_up_m = std::make_shared<ov::op::v0::MatMul>(hidden_states_reshaped, sh_convert_up, false, true);
+ auto shared_mul_m = std::make_shared<ov::op::v1::Multiply>(shared_swish_m, shared_up_m);
+ auto shared_down_m = std::make_shared<ov::op::v0::MatMul>(shared_mul_m, sh_convert_down, false, true);
+ auto shared_gate_gate_wei_m = std::make_shared<ov::op::v0::Constant>(element::f32, Shape{2048, 1}, std::vector<float>(2048, 1.0f));
+ auto shared_gate_gate_m = std::make_shared<ov::op::v0::MatMul>(hidden_states_reshaped, shared_gate_gate_wei_m);
+ auto shared_gate_sigmoid_m = std::make_shared<ov::op::v0::Sigmoid>(shared_gate_gate_m);
+ auto shared_expert_gated_m = std::make_shared<ov::op::v1::Multiply>(shared_gate_sigmoid_m, shared_down_m);
+
+ // In the actual model, there's a Reshape between the gated shared expert output and the Add
+ auto reshape_const_output = op::v0::Constant::create(element::i64, Shape{2}, {32, 2048});
+ auto shared_expert_reshaped = std::make_shared<ov::op::v1::Reshape>(shared_expert_gated_m, reshape_const_output, false);
+
+ auto add_m = std::make_shared<ov::op::v1::Add>(shared_expert_reshaped, moe);
+
+ model = std::make_shared<ov::Model>(add_m, ov::ParameterVector{hidden_states, routing_weights, routing_idx});
+ manager.register_pass<ConvertMOEToMOECompressed>(0);
+ }
+ {
+ // Inputs
+ auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{32, 2048});
+ auto routing_weights = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{128, 1, 32, 1});
+ auto routing_idx = std::make_shared<ov::op::v0::Parameter>(element::i32, Shape{32, 8});
+
+ // Gate and up projection
+ auto reshape_const_gate_up = op::v0::Constant::create(element::i32, Shape{3}, {128, 768, 16});
+ auto transpose_const_gate_up = op::v0::Constant::create(element::i32, Shape{3}, {0, 2, 1});
+
+ auto wei_gate = op::v0::Constant::create(element::u4, Shape{128, 768, 16, 128}, {1});
+ auto zp_gate = op::v0::Constant::create(element::u4, Shape{128, 768, 16, 1}, {0});
+ auto scale_gate = op::v0::Constant::create(element::f16, Shape{128, 768, 16, 1}, {0.01f});
+ auto zp_reshape_gate = std::make_shared<op::v1::Reshape>(zp_gate, reshape_const_gate_up, false);
+ auto zp_transpose_gate = std::make_shared<ov::op::v1::Transpose>(zp_reshape_gate, transpose_const_gate_up);
+ auto scale_reshape_gate = std::make_shared<op::v1::Reshape>(scale_gate, reshape_const_gate_up, false);
+ auto scale_transpose_gate = std::make_shared<ov::op::v1::Transpose>(scale_reshape_gate, transpose_const_gate_up);
+
+ auto wei_up = op::v0::Constant::create(element::u4, Shape{128, 768, 16, 128}, {1});
+ auto zp_up = op::v0::Constant::create(element::u4, Shape{128, 768, 16, 1}, {0});
+ auto scale_up = op::v0::Constant::create(element::f16, Shape{128, 768, 16, 1}, {0.01f});
+ auto zp_reshape_up = std::make_shared<op::v1::Reshape>(zp_up, reshape_const_gate_up, false);
+ auto zp_transpose_up = std::make_shared<ov::op::v1::Transpose>(zp_reshape_up, transpose_const_gate_up);
+ auto scale_reshape_up = std::make_shared<op::v1::Reshape>(scale_up, reshape_const_gate_up, false);
+ auto scale_transpose_up = std::make_shared<ov::op::v1::Transpose>(scale_reshape_up, transpose_const_gate_up);
+
+ // Down projection
+ auto wei_down = op::v0::Constant::create(element::u4, Shape{128, 2048, 6, 128}, {1});
+ auto zp_down = op::v0::Constant::create(element::u4, Shape{128, 2048, 6, 1}, {0});
+ auto scale_down = op::v0::Constant::create(element::f16, Shape{128, 2048, 6, 1}, {0.01f});
+ auto reshape_const_down = op::v0::Constant::create(element::i32, Shape{3}, {128, 2048, 6});
+ auto transpose_const_down = op::v0::Constant::create(element::i32, Shape{3}, {0, 2, 1});
+ auto zp_reshape_down = std::make_shared<op::v1::Reshape>(zp_down, reshape_const_down, false);
+ auto zp_transpose_down = std::make_shared<ov::op::v1::Transpose>(zp_reshape_down, transpose_const_down);
+ auto scale_reshape_down = std::make_shared<op::v1::Reshape>(scale_down, reshape_const_down, false);
+ auto scale_transpose_down = std::make_shared<ov::op::v1::Transpose>(scale_reshape_down, transpose_const_down);
+
+ // Shared expert weights (3D without num_experts dim, separate from MOE expert weights)
+ auto sh_reshape_const_gate_up = op::v0::Constant::create(element::i32, Shape{2}, {768, 16});
+ auto sh_transpose_const_gate_up = op::v0::Constant::create(element::i32, Shape{2}, {1, 0});
+
+ auto sh_wei_gate = op::v0::Constant::create(element::u4, Shape{768, 16, 128}, {2});
+ auto sh_zp_gate = op::v0::Constant::create(element::u4, Shape{768, 16, 1}, {1});
+ auto sh_scale_gate = op::v0::Constant::create(element::f16, Shape{768, 16, 1}, {0.02f});
+ auto sh_zp_reshape_gate = std::make_shared<op::v1::Reshape>(sh_zp_gate, sh_reshape_const_gate_up, false);
+ auto sh_zp_transpose_gate = std::make_shared<ov::op::v1::Transpose>(sh_zp_reshape_gate, sh_transpose_const_gate_up);
+ auto sh_scale_reshape_gate = std::make_shared<op::v1::Reshape>(sh_scale_gate, sh_reshape_const_gate_up, false);
+ auto sh_scale_transpose_gate = std::make_shared<ov::op::v1::Transpose>(sh_scale_reshape_gate, sh_transpose_const_gate_up);
+
+ auto sh_wei_up = op::v0::Constant::create(element::u4, Shape{768, 16, 128}, {2});
+ auto sh_zp_up = op::v0::Constant::create(element::u4, Shape{768, 16, 1}, {1});
+ auto sh_scale_up = op::v0::Constant::create(element::f16, Shape{768, 16, 1}, {0.02f});
+ auto sh_zp_reshape_up = std::make_shared<op::v1::Reshape>(sh_zp_up, sh_reshape_const_gate_up, false);
+ auto sh_zp_transpose_up = std::make_shared<ov::op::v1::Transpose>(sh_zp_reshape_up, sh_transpose_const_gate_up);
+ auto sh_scale_reshape_up = std::make_shared<op::v1::Reshape>(sh_scale_up, sh_reshape_const_gate_up, false);
+ auto sh_scale_transpose_up = std::make_shared<ov::op::v1::Transpose>(sh_scale_reshape_up, sh_transpose_const_gate_up);
+
+ auto sh_reshape_const_down = op::v0::Constant::create(element::i32, Shape{2}, {2048, 6});
+ auto sh_transpose_const_down = op::v0::Constant::create(element::i32, Shape{2}, {1, 0});
+ auto sh_wei_down = op::v0::Constant::create(element::u4, Shape{2048, 6, 128}, {2});
+ auto sh_zp_down = op::v0::Constant::create(element::u4, Shape{2048, 6, 1}, {1});
+ auto sh_scale_down = op::v0::Constant::create(element::f16, Shape{2048, 6, 1}, {0.02f});
+ auto sh_zp_reshape_down = std::make_shared<op::v1::Reshape>(sh_zp_down, sh_reshape_const_down, false);
+ auto sh_zp_transpose_down = std::make_shared<ov::op::v1::Transpose>(sh_zp_reshape_down, sh_transpose_const_down);
+ auto sh_scale_reshape_down = std::make_shared<op::v1::Reshape>(sh_scale_down, sh_reshape_const_down, false);
+ auto sh_scale_transpose_down = std::make_shared<ov::op::v1::Transpose>(sh_scale_reshape_down, sh_transpose_const_down);
+
+ ov::intel_gpu::op::MOECompressed::Config config;
+ config.hidden_size = 2048;
+ config.inter_size = 768;
+ config.num_expert = 128;
+ config.num_shared_expert = 1;
+ config.top_k = 8;
+ config.group_size = 128;
+ config.out_type = ov::element::f16;
+ auto hidden_states_f32 = std::make_shared<ov::op::v0::Convert>(hidden_states, element::f32);
+ auto shared_gate_gate_wei_m = std::make_shared<ov::op::v0::Constant>(element::f32, Shape{2048, 1}, std::vector<float>(2048, 1.0f));
+ std::shared_ptr<ov::Node> moe_compressed = std::make_shared<ov::intel_gpu::op::MOECompressed>(
+ ov::OutputVector{hidden_states_f32, routing_weights, routing_idx,
+ wei_gate, scale_transpose_gate, zp_transpose_gate,
+ wei_up, scale_transpose_up, zp_transpose_up,
+ wei_down, scale_transpose_down, zp_transpose_down,
+ sh_wei_gate, sh_scale_transpose_gate, sh_zp_transpose_gate,
+ sh_wei_up, sh_scale_transpose_up, sh_zp_transpose_up,
+ sh_wei_down, sh_scale_transpose_down, sh_zp_transpose_down,
+ shared_gate_gate_wei_m}, config);
+ // MOECompressed outputs f16, but the input model outputs f32 (Add of f32 MOE + f32 shared expert),
+ // so the transformation inserts a Convert(f16->f32) to preserve the original output type.
+ moe_compressed = std::make_shared<ov::op::v0::Convert>(moe_compressed, element::f32);
+ model_ref = std::make_shared<ov::Model>(moe_compressed, ov::ParameterVector{hidden_states, routing_weights, routing_idx});
+ }
+}
+
} // namespace intel_gpu
} // namespace test
} // namespace ov
diff --git a/src/plugins/intel_gpu/tests/unit/transformations/fuse_moe_3gemm_compressed_test.cpp b/src/plugins/intel_gpu/tests/unit/transformations/fuse_moe_3gemm_compressed_test.cpp
index ab9a898da7a..ed908864f36 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
@@ -57,10 +57,11 @@ TEST_P(FuseMOE3GemmCompressedTest, CompareFunctions) {
auto routing_weights = std::make_shared<ov::op::v0::MatMul>(hidden_states_reshape, routers);
// 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 routing_pair = routing_type == MoERoutingType::SOFTMAX
+ ? build_softmax_routing_subgraph(routing_weights, 128, 8)
+ : build_sigmoid_bias_routing_subgraph(routing_weights, element::f16, 128, 8);
+ auto unsqueeze_moe = routing_pair.first;
+ auto topk_indices = routing_pair.second;
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});
@@ -153,6 +154,108 @@ INSTANTIATE_TEST_SUITE_P(smoke,
::testing::Values(false, true)),
FuseMOE3GemmCompressedTest::get_test_case_name);
+TEST_F(TransformationTestsF, FuseMOE3GemmSharedExpertCompressedTest) {
+ {
+ // tokens:32, hidden_size:2048, iter_size:768, experts:128, topk:8
+ auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{32, 2048});
+ 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, routers);
+
+ auto routing_pair = build_softmax_routing_subgraph(routing_weights, 128, 8);
+ auto unsqueeze_moe = routing_pair.first;
+ auto topk_indices = routing_pair.second;
+
+ // weight
+ 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});
+ auto wei_up = op::v0::Constant::create(element::u4, Shape{128, 768, 16, 128}, {1});
+ auto scale_up = op::v0::Constant::create(element::f16, Shape{128, 16, 768}, {0.01f});
+ auto zp_up = op::v0::Constant::create(element::u4, Shape{128, 16, 768, 16}, {0});
+ auto wei_down = op::v0::Constant::create(element::u4, Shape{128, 2048, 6, 128}, {1});
+ auto scale_down = op::v0::Constant::create(element::f16, Shape{128, 6, 2048}, {0.01f});
+ auto zp_down = op::v0::Constant::create(element::u4, Shape{128, 6, 2048}, {0});
+
+ // Shared expert weights (single shared expert: leading dimension 1)
+ auto sh_wei_gate = op::v0::Constant::create(element::u4, Shape{1, 768, 16, 128}, {2});
+ auto sh_scale_gate = op::v0::Constant::create(element::f16, Shape{1, 16, 768}, {0.02f});
+ auto sh_zp_gate = op::v0::Constant::create(element::u4, Shape{1, 16, 768}, {0});
+ auto sh_wei_up = op::v0::Constant::create(element::u4, Shape{1, 768, 16, 128}, {2});
+ auto sh_scale_up = op::v0::Constant::create(element::f16, Shape{1, 16, 768}, {0.02f});
+ auto sh_zp_up = op::v0::Constant::create(element::u4, Shape{1, 16, 768, 16}, {0});
+ auto sh_wei_down = op::v0::Constant::create(element::u4, Shape{1, 2048, 6, 128}, {2});
+ auto sh_scale_down = op::v0::Constant::create(element::f16, Shape{1, 6, 2048}, {0.02f});
+ auto sh_zp_down = op::v0::Constant::create(element::u4, Shape{1, 6, 2048}, {0});
+ auto sh_gate_gate_wei = op::v0::Constant::create(element::f16, Shape{2048, 1}, {0.5f});
+
+ ov::intel_gpu::op::MOECompressed::Config config;
+ config.hidden_size = 2048;
+ config.inter_size = 768;
+ config.num_expert = 128;
+ config.num_shared_expert = 1;
+ config.group_size = 128;
+ config.top_k = 8;
+ config.out_type = ov::element::f16;
+ auto moe_compressed = std::make_shared<ov::intel_gpu::op::MOECompressed>(
+ ov::OutputVector{hidden_states, unsqueeze_moe, topk_indices,
+ wei_gate, scale_gate, zp_gate, wei_up, scale_up, zp_up, wei_down, scale_down, zp_down,
+ sh_wei_gate, sh_scale_gate, sh_zp_gate, sh_wei_up, sh_scale_up, sh_zp_up,
+ sh_wei_down, sh_scale_down, sh_zp_down, sh_gate_gate_wei}, config);
+ model = std::make_shared<ov::Model>(moe_compressed, ov::ParameterVector{hidden_states});
+ manager.register_pass<FuseMOE3GemmCompressed>();
+ }
+ {
+ // tokens:32, hidden_size:2048, iter_size:768, experts:128, topk:8
+ auto hidden_states = std::make_shared<ov::op::v0::Parameter>(element::f16, Shape{32, 2048});
+ 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, routers);
+
+ // MOE expert weights
+ 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});
+ auto wei_up = op::v0::Constant::create(element::u4, Shape{128, 768, 16, 128}, {1});
+ auto scale_up = op::v0::Constant::create(element::f16, Shape{128, 16, 768}, {0.01f});
+ auto zp_up = op::v0::Constant::create(element::u4, Shape{128, 16, 768, 16}, {0});
+ auto wei_down = op::v0::Constant::create(element::u4, Shape{128, 2048, 6, 128}, {1});
+ auto scale_down = op::v0::Constant::create(element::f16, Shape{128, 6, 2048}, {0.01f});
+ auto zp_down = op::v0::Constant::create(element::u4, Shape{128, 6, 2048}, {0});
+
+ // Shared expert weights (single shared expert: leading dimension 1)
+ auto sh_wei_gate = op::v0::Constant::create(element::u4, Shape{1, 768, 16, 128}, {2});
+ auto sh_scale_gate = op::v0::Constant::create(element::f16, Shape{1, 16, 768}, {0.02f});
+ auto sh_zp_gate = op::v0::Constant::create(element::u4, Shape{1, 16, 768}, {0});
+ auto sh_wei_up = op::v0::Constant::create(element::u4, Shape{1, 768, 16, 128}, {2});
+ auto sh_scale_up = op::v0::Constant::create(element::f16, Shape{1, 16, 768}, {0.02f});
+ auto sh_zp_up = op::v0::Constant::create(element::u4, Shape{1, 16, 768, 16}, {0});
+ auto sh_wei_down = op::v0::Constant::create(element::u4, Shape{1, 2048, 6, 128}, {2});
+ auto sh_scale_down = op::v0::Constant::create(element::f16, Shape{1, 6, 2048}, {0.02f});
+ auto sh_zp_down = op::v0::Constant::create(element::u4, Shape{1, 6, 2048}, {0});
+ auto sh_gate_gate_wei = op::v0::Constant::create(element::f16, Shape{2048, 1}, {0.5f});
+
+ // Dummy placeholders for SOFTMAX + shared expert (indices 11-12)
+ auto dummy_bias = op::v0::Constant::create(element::f16, Shape{1}, {0.0f});
+ auto dummy_eps = op::v0::Constant::create(element::f16, Shape{1}, {0.0f});
+
+ ov::intel_gpu::op::MOECompressed::Config config;
+ config.hidden_size = 2048;
+ config.inter_size = 768;
+ config.num_expert = 128;
+ config.num_shared_expert = 1;
+ 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, routing_weights,
+ wei_gate, scale_gate, zp_gate, wei_up, scale_up, zp_up, wei_down, scale_down, zp_down,
+ dummy_bias, dummy_eps,
+ sh_wei_gate, sh_scale_gate, sh_zp_gate, sh_wei_up, sh_scale_up, sh_zp_up,
+ sh_wei_down, sh_scale_down, sh_zp_down, sh_gate_gate_wei}, config);
+
+ model_ref = std::make_shared<ov::Model>(moe_3gemm_fused_compressed, ov::ParameterVector{hidden_states});
+ }
+}
+
} // namespace intel_gpu
} // namespace test
} // namespace ov